TExcelTAD

Providers & depsets

Rules talk to each other through providers: structs a target returns from its implementation, which targets that depend on it can read. CcInfo carries headers, defines and libraries from C++ libraries to binaries; JavaInfo carries jars; DefaultInfo carries default outputs and runfiles. Your own rules can define their own.

python
SchemaInfo = provider(
    doc = "A schema file and the schemas it depends on.",
    fields = {
        "schema": "File: this target's schema",
        "transitive_schemas": "depset of File: this schema and every dependency's",
    },
)

A dependent reads it with dep[SchemaInfo], and an attribute can demand it with attr.label_list(providers = [SchemaInfo]), so that a wrong dependency is an error at analysis time.

depsets: transitive data without the quadratic blow-up

The natural way to collect "my files plus all my dependencies' files" is list concatenation. In a deep graph that copies the same lists at every level: quadratic time and memory. A depset is an immutable DAG of sets that shares structure between targets:

python
depset(direct = [ctx.file.schema], transitive = [d[SchemaInfo].transitive_schemas for d in ctx.attr.deps])

Creating it costs only the direct items plus pointers to the children; it's flattened (.to_list()) only when an action really needs the full list, ideally inside ctx.actions.args(), which flattens lazily at execution time. order can be "default", "postorder", "preorder" or "topological" (dependencies after dependents, what linkers want).

Here is the idea as a runnable model, comparing what list concatenation and a shared DAG store for a chain of 2,000 libraries:

python · try it yourself
class Depset:
    """A tiny depset: direct items + pointers to child depsets (shared, never copied)."""
    def __init__(self, direct, transitive=()):
        self.direct, self.transitive = list(direct), list(transitive)

    def to_list(self):
        """Postorder (dependencies first), each item once; iterative, like Bazel's own walk."""
        seen, out, done = set(), [], set()
        stack = [(self, False)]
        while stack:
            node, expanded = stack.pop()
            if expanded:
                for x in node.direct:
                    if x not in seen:
                        seen.add(x)
                        out.append(x)
            elif id(node) not in done:
                done.add(id(node))
                stack.append((node, True))
                for child in reversed(node.transitive):
                    stack.append((child, False))
        return out

N = 2000
lists, sets = [], []
list_cells = depset_cells = 0
for i in range(N):
    prev_list = lists[-1] if lists else []
    lists.append(prev_list + [f"lib{i}.h"])          # copy everything below
    list_cells += len(lists[-1])
    sets.append(Depset([f"lib{i}.h"], [sets[-1]] if sets else []))
    depset_cells += 1 + (1 if i else 0)             # one item + one pointer

print("headers seen by the top library:", len(sets[-1].to_list()))
print("same order as the list version:", sets[-1].to_list() == lists[-1])
print(f"list concatenation stored {list_cells:,} entries")
print(f"depsets stored {depset_cells:,} entries")
headers seen by the top library: 2000
same order as the list version: True
list concatenation stored 2,001,000 entries
depsets stored 3,999 entries

That's the reason CcInfo keeps headers in depsets: a binary at the top of a large C++ graph sees tens of thousands of headers, and each library in between only adds its own.

A provider in action

Two rules: schema_library collects schema files transitively through SchemaInfo, and schema_bundle concatenates the whole closure into one file:

bash · try it yourself
mkdir ws && cd ws
echo 'module(name = "providers_demo")' > MODULE.bazel
mkdir -p build_defs schemas/common schemas/orders
touch build_defs/BUILD.bazel
cat > build_defs/schema.bzl <<'EOF'
SchemaInfo = provider(
    doc = "A schema file and its transitive closure.",
    fields = ["schema", "transitive_schemas"],
)

def _schema_library_impl(ctx):
    transitive = depset(
        direct = [ctx.file.src],
        transitive = [dep[SchemaInfo].transitive_schemas for dep in ctx.attr.deps],
        order = "postorder",
    )
    return [
        SchemaInfo(schema = ctx.file.src, transitive_schemas = transitive),
        DefaultInfo(files = depset([ctx.file.src])),
    ]

schema_library = rule(
    implementation = _schema_library_impl,
    attrs = {
        "src": attr.label(allow_single_file = [".schema"], mandatory = True),
        "deps": attr.label_list(providers = [SchemaInfo]),
    },
)

def _schema_bundle_impl(ctx):
    files = ctx.attr.root[SchemaInfo].transitive_schemas
    out = ctx.actions.declare_file(ctx.label.name + ".bundle")
    args = ctx.actions.args()
    args.add(out)
    args.add_all(files)                      # flattened lazily, at execution time
    ctx.actions.run_shell(
        inputs = files,
        outputs = [out],
        arguments = [args],
        command = 'out=$1; shift; for f in "$@"; do echo "-- $f"; cat "$f"; done > "$out"',
        mnemonic = "SchemaBundle",
    )
    return [DefaultInfo(files = depset([out]))]

schema_bundle = rule(
    implementation = _schema_bundle_impl,
    attrs = {"root": attr.label(providers = [SchemaInfo], mandatory = True)},
)
EOF
cat > schemas/common/BUILD.bazel <<'EOF'
load("//build_defs:schema.bzl", "schema_library")
schema_library(name = "money", src = "money.schema", visibility = ["//visibility:public"])
schema_library(name = "address", src = "address.schema", visibility = ["//visibility:public"])
EOF
echo "money: cents int" > schemas/common/money.schema
echo "address: street, city" > schemas/common/address.schema
cat > schemas/orders/BUILD.bazel <<'EOF'
load("//build_defs:schema.bzl", "schema_bundle", "schema_library")
schema_library(name = "order", src = "order.schema", deps = ["//schemas/common:money", "//schemas/common:address"])
schema_bundle(name = "all", root = ":order")
genrule(name = "not_a_schema", outs = ["x.schema"], cmd = "touch $@")
schema_library(name = "broken", src = "order.schema", deps = [":not_a_schema"])
EOF
echo "order: id, total money, ship_to address" > schemas/orders/order.schema
bazel build //schemas/orders:all 2>/dev/null
cat bazel-bin/schemas/orders/all.bundle
echo "== a dependency without SchemaInfo"
bazel build //schemas/orders:broken 2>&1 | grep -A1 "^ERROR" | head -2 | sed 's#/home/learner/ws/##'
-- schemas/common/money.schema
money: cents int
-- schemas/common/address.schema
address: street, city
-- schemas/orders/order.schema
order: id, total money, ship_to address
== a dependency without SchemaInfo
ERROR: schemas/orders/BUILD.bazel:5:15: in deps attribute of schema_library rule //schemas/orders:broken: '//schemas/orders:not_a_schema' does not have mandatory providers: 'SchemaInfo'
ERROR: schemas/orders/BUILD.bazel:5:15: Analysis of target '//schemas/orders:broken' (config: 0a96350) failed

postorder put the dependencies before the schema that uses them, the order a code generator or linker needs. And providers = [SchemaInfo] turned a meaningless dependency into a clear analysis-time error instead of a confusing failure later.

Built-in providers worth knowing

Provider Carries
DefaultInfo files (what bazel build builds), runfiles, executable
OutputGroupInfo named extra output groups, built with --output_groups=name (e.g. compilation_outputs)
CcInfo C++ compilation context (headers, includes, defines) and linking context
JavaInfo, PyInfo, GoInfo the language's compile/run information
InstrumentedFilesInfo which files coverage should instrument
RunEnvironmentInfo environment variables for bazel run/bazel test

To make your rule usable by existing ones, return their providers: a rule that generates C++ code can return a CcInfo (built with cc_common) so cc_binary can depend on it directly.

Test yourself

What is a provider?

  1. A remote cache
  2. A struct a target returns that its dependents can read
  3. A module in the BCR
  4. A toolchain

Why use a depset instead of concatenating lists of transitive files?

  1. depsets are sorted
  2. They share structure, avoiding quadratic copying in deep graphs; flattening is deferred
  3. Lists can't hold files
  4. depsets are mutable

What does attr.label_list(providers = [SchemaInfo]) enforce?

  1. Nothing at build time
  2. Every dependency in the attribute must return SchemaInfo, checked during analysis
  3. The files must end in .schema
  4. The deps are built first