TExcelTAD
Home › Monorepo Builds: Bazel (+ Buck2 & Pants) › A Polyglot Target Graph

A Polyglot Target Graph

The point of one build system for every language is that the dependency graph crosses language boundaries. A Python tool that runs a C++ binary, a Go service and a Java library live in one graph, so Bazel knows that a change to the C++ code must rerun the Python tool's tests, and that it doesn't affect the Go service at all.

The repository

text
MODULE.bazel           rules_cc, rules_python, rules_go, rules_java + Go SDK
cc/checksum/           cc_library "checksum" + cc_binary "checksum_cli" + cc_test
tools/report/          py_binary "report" that runs //cc/checksum:checksum_cli (a data dependency) + py_test
services/pricer/       go_library + go_binary + go_test
java/com/example/fmt/  java_library + java_binary

There are two ways for one language to use another in Bazel:

Mechanism Example here When
data dependency: the other target's output is in your runfiles and you run or read it the Python tool executes the C++ CLI tools, fixtures, binaries called as subprocesses
build-time dependency: a rule consumes the other target's output while building a genrule that runs a C++ tool to generate a .py file, cc_library linked into a Python extension or Go via cgo code generation, native extensions

The genrule lesson shows the second one; this lesson uses the first.

Build and test everything

bash · try it yourself
mkdir ws && cd ws
cat > MODULE.bazel <<'EOF'
module(name = "poly")
bazel_dep(name = "rules_cc", version = "0.2.27")
bazel_dep(name = "rules_python", version = "2.4.5")
bazel_dep(name = "rules_go", version = "0.65.0")
bazel_dep(name = "rules_java", version = "9.9.0")
go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk")
go_sdk.download(version = "1.27.3")
EOF
mkdir -p cc/checksum tools/report services/pricer java/com/example/fmt
# --- C++: a checksum library, a CLI and a test
cat > cc/checksum/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test")
cc_library(name = "checksum", srcs = ["checksum.cc"], hdrs = ["checksum.h"])
cc_binary(name = "checksum_cli", srcs = ["cli.cc"], deps = [":checksum"], visibility = ["//tools:__subpackages__"])
cc_test(name = "checksum_test", size = "small", srcs = ["checksum_test.cc"], deps = [":checksum"])
EOF
printf '#pragma once\n#include <string>\nunsigned checksum(const std::string& s);\n' > cc/checksum/checksum.h
cat > cc/checksum/checksum.cc <<'EOF'
#include "cc/checksum/checksum.h"
unsigned checksum(const std::string& s) {
  unsigned h = 7;
  for (unsigned char c : s) h = h * 31 + c;
  return h % 10007;
}
EOF
printf '#include <cstdio>\n#include "cc/checksum/checksum.h"\nint main(int argc, char** argv) { std::printf("%%u\\n", checksum(argc > 1 ? argv[1] : "")); }\n' > cc/checksum/cli.cc
printf '#include "cc/checksum/checksum.h"\nint main() { return checksum("abc") == checksum("abc") && checksum("abc") != checksum("abd") ? 0 : 1; }\n' > cc/checksum/checksum_test.cc
# --- Python: a report tool that runs the C++ CLI from its runfiles
cat > tools/report/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")
py_library(name = "lib", srcs = ["lib.py"], data = ["//cc/checksum:checksum_cli"], deps = ["@rules_python//python/runfiles"])
py_binary(name = "report", srcs = ["report.py"], deps = [":lib"])
py_test(name = "lib_test", size = "small", srcs = ["lib_test.py"], deps = [":lib"])
EOF
cat > tools/report/lib.py <<'EOF'
import subprocess
from python.runfiles import runfiles

_CLI = runfiles.Create().Rlocation("_main/cc/checksum/checksum_cli")

def checksum(text):
    return int(subprocess.run([_CLI, text], capture_output=True, text=True, check=True).stdout)
EOF
printf 'import sys\nfrom tools.report.lib import checksum\nfor word in sys.argv[1:]:\n    print(f"{word:>8} {checksum(word):5}")\n' > tools/report/report.py
printf 'import unittest\nfrom tools.report.lib import checksum\nclass T(unittest.TestCase):\n    def test_stable(self):\n        self.assertEqual(checksum("abc"), checksum("abc"))\nunittest.main()\n' > tools/report/lib_test.py
# --- Go: a small service package
cat > services/pricer/BUILD.bazel <<'EOF'
load("@rules_go//go:def.bzl", "go_binary", "go_library", "go_test")
go_library(name = "pricer_lib", srcs = ["price.go"], importpath = "example.com/poly/pricer")
go_binary(name = "pricer", srcs = ["main.go"], deps = [":pricer_lib"])
go_test(name = "pricer_test", size = "small", srcs = ["price_test.go"], embed = [":pricer_lib"])
EOF
printf 'package pricer\n\nfunc Discount(cents int) int { return cents * 9 / 10 }\n' > services/pricer/price.go
printf 'package pricer\n\nimport "testing"\n\nfunc TestDiscount(t *testing.T) {\n\tif Discount(1000) != 900 {\n\t\tt.Fatal("bad discount")\n\t}\n}\n' > services/pricer/price_test.go
printf 'package main\n\nimport (\n\t"fmt"\n\n\t"example.com/poly/pricer"\n)\n\nfunc main() { fmt.Println("discounted:", pricer.Discount(2500)) }\n' > services/pricer/main.go
# --- Java: a formatting library and a binary
cat > java/com/example/fmt/BUILD.bazel <<'EOF'
load("@rules_java//java:defs.bzl", "java_binary", "java_library")
java_library(name = "fmt", srcs = ["Fmt.java"])
java_binary(name = "demo", srcs = ["Demo.java"], main_class = "com.example.fmt.Demo", deps = [":fmt"])
EOF
printf 'package com.example.fmt;\npublic final class Fmt {\n  public static String box(String s) { return "[" + s + "]"; }\n}\n' > java/com/example/fmt/Fmt.java
printf 'package com.example.fmt;\npublic class Demo {\n  public static void main(String[] a) { System.out.println(Fmt.box("java")); }\n}\n' > java/com/example/fmt/Demo.java

bazel build //... 2>&1 | grep -E '^INFO: (Analyzed|[0-9]+ process)'
bazel test //... 2>&1 | grep -E 'PASSED|FAILED|Executed'
bazel run //tools/report -- bazel build graph 2>/dev/null
bazel run //services/pricer 2>/dev/null
bazel run //java/com/example/fmt:demo 2>/dev/null
INFO: Analyzed 11 targets (135 packages loaded, 12282 targets configured).
INFO: 73 processes: 48 internal, 23 processwrapper-sandbox, 2 worker.
//cc/checksum:checksum_test                                              PASSED in 0.0s
//services/pricer:pricer_test                                            PASSED in 0.0s
//tools/report:lib_test                                                  PASSED in 0.4s
Executed 3 out of 3 tests: 3 tests pass.
   bazel  3726
   build  3012
   graph   520
discounted: 2250
[java]

One bazel build //... built all four languages with their own toolchains: GCC for C++, the hermetic CPython, Go 1.27.3 and the remote JDK. One bazel test //... ran every test.

What a change rebuilds

Now change the C++ checksum and run all tests again. Bazel reruns only the tests whose inputs changed:

bash · try it yourself
mkdir ws && cd ws
cat > MODULE.bazel <<'EOF'
bazel_dep(name = "rules_cc", version = "0.2.27")
bazel_dep(name = "rules_python", version = "2.4.5")
EOF
mkdir -p cc/checksum tools/report textutil
cat > cc/checksum/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test")
cc_library(name = "checksum", srcs = ["checksum.cc"], hdrs = ["checksum.h"])
cc_binary(name = "checksum_cli", srcs = ["cli.cc"], deps = [":checksum"], visibility = ["//visibility:public"])
cc_test(name = "checksum_test", size = "small", srcs = ["checksum_test.cc"], deps = [":checksum"])
EOF
printf '#pragma once\n#include <string>\nunsigned checksum(const std::string& s);\n' > cc/checksum/checksum.h
printf '#include "cc/checksum/checksum.h"\nunsigned checksum(const std::string& s) {\n  unsigned h = 7;\n  for (unsigned char c : s) h = h * 31 + c;\n  return h %% 10007;\n}\n' > cc/checksum/checksum.cc
printf '#include <cstdio>\n#include "cc/checksum/checksum.h"\nint main(int argc, char** argv) { std::printf("%%u\\n", checksum(argc > 1 ? argv[1] : "")); }\n' > cc/checksum/cli.cc
printf '#include "cc/checksum/checksum.h"\nint main() { return checksum("abc") != checksum("abd") ? 0 : 1; }\n' > cc/checksum/checksum_test.cc
cat > tools/report/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_test")
py_test(name = "cli_test", size = "small", srcs = ["cli_test.py"], data = ["//cc/checksum:checksum_cli"], deps = ["@rules_python//python/runfiles"])
EOF
printf 'import subprocess, unittest\nfrom python.runfiles import runfiles\ncli = runfiles.Create().Rlocation("_main/cc/checksum/checksum_cli")\nclass T(unittest.TestCase):\n    def test_runs(self):\n        self.assertTrue(subprocess.run([cli, "x"], capture_output=True, text=True).stdout.strip().isdigit())\nunittest.main()\n' > tools/report/cli_test.py
cat > textutil/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_test")
py_test(name = "upper_test", size = "small", srcs = ["upper_test.py"])
EOF
printf 'import unittest\nclass T(unittest.TestCase):\n    def test_upper(self):\n        self.assertEqual("a".upper(), "A")\nunittest.main()\n' > textutil/upper_test.py
bazel test //... 2>&1 | grep -E 'PASSED|FAILED'
echo "== edit checksum.cc"
sed -i 's/h \* 31/h * 37/' cc/checksum/checksum.cc
bazel test //... 2>&1 | grep -E 'PASSED|FAILED|Executed'
//cc/checksum:checksum_test                                              PASSED in 0.0s
//textutil:upper_test                                                    PASSED in 0.3s
//tools/report:cli_test                                                  PASSED in 0.4s
== edit checksum.cc
//textutil:upper_test                                           (cached) PASSED in 0.3s
//cc/checksum:checksum_test                                              PASSED in 0.0s
//tools/report:cli_test                                                  PASSED in 0.4s
Executed 2 out of 3 tests: 3 tests pass.

(cached) PASSED means Bazel didn't run the test: its inputs (the test binary, its runfiles, its environment) were identical to a previous successful run, so the result came from the cache. The C++ test and the Python test reran, because the C++ CLI is in the Python test's runfiles; upper_test didn't. On a CI system with a remote cache, this is what makes bazel test //... affordable on every commit.

Seeing the graph

bazel cquery (the configured query, see its lesson) can draw the cross-language edges. --noimplicit_deps hides the toolchain and rule-internal dependencies, and filter("^//", …) keeps only targets in our own repository:

bash · try it yourself
mkdir ws && cd ws
cat > MODULE.bazel <<'EOF'
bazel_dep(name = "rules_cc", version = "0.2.27")
bazel_dep(name = "rules_python", version = "2.4.5")
EOF
mkdir -p cc/checksum tools/report
cat > cc/checksum/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
cc_library(name = "checksum", srcs = ["checksum.cc"], hdrs = ["checksum.h"])
cc_binary(name = "checksum_cli", srcs = ["cli.cc"], deps = [":checksum"], visibility = ["//visibility:public"])
EOF
cat > tools/report/BUILD.bazel <<'EOF'
load("@rules_python//python:defs.bzl", "py_binary", "py_library")
py_library(name = "lib", srcs = ["lib.py"], data = ["//cc/checksum:checksum_cli"])
py_binary(name = "report", srcs = ["report.py"], deps = [":lib"])
EOF
touch cc/checksum/checksum.cc cc/checksum/checksum.h cc/checksum/cli.cc tools/report/lib.py tools/report/report.py
bazel cquery --noimplicit_deps 'filter("^//", kind(rule, deps(//tools/report)))' --output=graph 2>/dev/null
digraph mygraph {
  node [shape=box];
  "//tools/report:report (0a96350)"
  "//tools/report:report (0a96350)" -> "//tools/report:lib (0a96350)"
  "//tools/report:lib (0a96350)"
  "//tools/report:lib (0a96350)" -> "//cc/checksum:checksum_cli (0a96350)"
  "//cc/checksum:checksum_cli (0a96350)"
  "//cc/checksum:checksum_cli (0a96350)" -> "//cc/checksum:checksum (0a96350)"
  "//cc/checksum:checksum (0a96350)"
}

The (0a96350) after each label is the short id of the build configuration the target was analyzed in. Paste the digraph text into any Graphviz viewer (or dot -Tsvg) to get a picture. Every edge is a declared dependency; there is no other way for code in one target to use another.

Test yourself

The Python tool runs the C++ CLI as a subprocess. How is that dependency declared?

  1. It isn't; Python finds the binary on PATH
  2. As a data dependency, so the CLI is in the Python target's runfiles
  3. With deps on a cc_library
  4. In MODULE.bazel

What does (cached) PASSED mean in bazel test output?

  1. The test was skipped because it's flaky
  2. The test's inputs were unchanged, so Bazel reused the previous result instead of running it
  3. The test ran on a remote machine
  4. The test passed twice

After editing a C++ source used only by the C++ CLI, which tests rerun?

  1. All tests
  2. Only tests whose inputs (directly or through runfiles) include something rebuilt
  3. Only C++ tests
  4. None until bazel clean