4.12.2 Rule Extension API: parent + ctx.super()
extraSometimes the rule you need almost exists. py_wheel from rules_python builds the wheel you want, but only for the module's current Python version. cc_binary links your program, but you want its debug symbols as a named output. You do not own those rules, so you cannot edit them. A rule extension declares a new rule that is the upstream rule plus one narrow change. rule(parent = upstream_rule, ...) inherits the parent's public attributes and advertised providers, and the child's implementation calls ctx.super() to run the parent's implementation for the same target.1,2 The API first appeared in Bazel 7 behind --experimental_rule_extension_api, which turned on by default in Bazel 8, and it is still experimental.3,4 In Bazel 9.1.0 that flag is still on by default, and it also gates 4.12.3 Subrules.5
Four Ways To Change A Rule You Do Not Own
The extension API exists because the older options each cost something.6
Fork or patch the ruleset. You get full control, and you also own every upstream merge from then on.
Wrap the rule in a macro. A macro runs in the Loading phase, so it can only choose attribute values and declare more targets (4.1.1 Macro vs Rule Decision Framework). It cannot give the upstream target an incoming transition, add an aspect to one of the rule's attributes, or change what the target returns. The workarounds add hidden targets. One real workaround pairs every swift_library with an ios_build_test target only to get a platform transition, and those extra targets then show up in every query.7
Write a wrapper rule. A new rule depends on the upstream target, often through an attribute with a transition, and returns something based on it. It works, but one idea is now two targets, and the wrapper must forward the inner target's providers by hand or downstream rules lose them.8
Extend the rule. The extension is one rule, and each use of it is one target. Because the child is declared with rule(), it has the analysis-time powers a macro lacks: an incoming cfg, label attributes overridden to carry aspects, and control over the returned providers.1
| Macro | Wrapper rule | Extension | |
|---|---|---|---|
| Targets per use | Upstream target plus any helpers | Wrapper plus upstream target | One |
| Puts the upstream target in a new configuration | No | Yes, through a transition on the edge to it | Yes, through the target's own cfg |
| Aspect on an existing attribute | No | No | Yes, through a label override |
| Change returned providers | No | Yes, by forwarding them manually | Yes, by editing the list |
Subrules are a related tool, but they answer a different question. An extension says the new rule is a py_wheel with one change, so it should stay usable wherever a py_wheel is. A subrule says a rule has a reusable piece of implementation, such as a lint step, that unrelated rules can call. That HAS-A case is 4.12.3 Subrules.9
the child inherits the supported target surface
Bazel merges attrs, fragments, constraints, and exec groups into the child rule definition
metadata merging does not run it. The child must call ctx.super()
None permits extension. False blocks it. An allowlist restricts callers.
must be a Starlark rule symbol, not a macro
runs before any parent cfg, so a parent cfg writing the same setting wins
new attributes, or label attributes overridden to add aspects
The Smallest Useful Extension Adds A Transition
The rule-extension-cfg snippet pins Bazel 9.1.0 and plays both sides. third_party/upstream_rules stands in for a ruleset you can load but not edit. Its mode_report rule writes one line per target with the compilation_mode that target was analyzed in, and it collects its deps' lines through a ModeInfo provider (report.bzl). The consuming module wants a report that always builds in opt, whatever the command line says. Here is the whole extension:
load("@upstream_rules//:report.bzl", "mode_report")
def _opt_transition_impl(_settings, _attr):
return {"//command_line_option:compilation_mode": "opt"}
opt_transition = transition(
implementation = _opt_transition_impl,
inputs = [],
outputs = ["//command_line_option:compilation_mode"],
)
opt_mode_report = rule(
implementation = lambda ctx: ctx.super(),
parent = mode_report,
cfg = opt_transition,
)
The implementation is one call. ctx.super() takes no arguments, runs mode_report's implementation for this target, and returns that implementation's providers as a list.10 Returning the list unchanged keeps every upstream provider, which is exactly the forwarding a wrapper rule had to write by hand.8 The cfg is an ordinary incoming transition from 4.7.2 Starlark Transitions. It sets the configuration of the target being declared.
The BUILD file gives a plain report and an extended one the same dep:
mode_report(name = "lib")
mode_report(
name = "plain",
deps = [":lib"],
)
opt_mode_report(
name = "optimized",
deps = [":lib"],
)
After bazel build //app:plain //app:optimized, the two report files read:
plain: fastbuild
lib: fastbuild
optimized: opt
lib: opt
//app:optimized is one target of kind opt_mode_report, with no helper targets beside it. Its dep reports opt as well, because an incoming transition becomes the configuration of the target's whole dependency subtree. //app:plain still uses the same library in fastbuild, so bazel cquery "deps(//app:plain) + deps(//app:optimized)" lists //app:lib twice, once per configuration. This can create additional configured copies throughout the dependency subtree, increasing analysis and build work. Other transitions can change the configuration again, and cache hits can avoid executing registered actions. 4.7.4 Transition Boundaries & Gotchas explains how to contain that fan-out.
Production extensions follow the same shape. A py_wheel extension adds a public python_version = attr.string() attribute and a transition that reads it, so one build can produce wheels for several Python versions. The transition keeps the incoming Python version when the attribute is empty, so the added attribute's default leaves the parent's behavior alone. A child attribute whose name the parent does not use is simply added.11,12 A swift_library extension adds platform_type and minimum_os_version attributes and an Apple platform transition, so building a library on its own targets iOS without an extra ios_build_test target.7
When The Parent Already Has A cfg
Upstream also ships dbg_report, the same rule with its own incoming cfg that sets compilation_mode to dbg. The snippet extends it with the same opt_transition as opt_dbg_report and declares a target named pinned.
Predict: //app:pinned uses the child's opt_transition and inherits the parent's dbg_transition. Which compilation mode does its report show?
Reveal
It shows pinned: dbg and lib: dbg. The child's incoming transition runs first, then the parent's runs on its result.1 Both write the same setting, so the parent's value is the one that sticks. The extension cannot remove or reorder the parent's cfg. Read the parent's definition before you add a transition. If you need to override a parent transition, look for a lever the parent exposes, such as an attribute its transition reads.
Changing What The Parent Returns
Adding an output works by editing the provider list. The snippet's company.bzl adds a sorted output group to mode_report:
load("@upstream_rules//:report.bzl", _upstream_mode_report = "mode_report")
def _mode_report_impl(ctx):
providers = ctx.super()
# Built-in providers report their own type(). Custom ones such as ModeInfo report "struct".
default_info = [p for p in providers if type(p) == "DefaultInfo"][0]
report = default_info.files.to_list()[0]
sorted_report = ctx.actions.declare_file(ctx.label.name + ".sorted.txt")
ctx.actions.run_shell(
inputs = [report],
outputs = [sorted_report],
command = 'LC_ALL=C sort "$1" > "$2"',
arguments = [report.path, sorted_report.path],
)
return providers + [OutputGroupInfo(sorted = depset([sorted_report]))]
mode_report = rule(
implementation = _mode_report_impl,
parent = _upstream_mode_report,
)
Three details matter here.
First, the return value of ctx.super() is a list, not a Target. providers[DefaultInfo] fails with got Provider for sequence index, want int, so you search the list instead.13 Built-in providers report their name from type(), such as "DefaultInfo" or "OutputGroupInfo". A custom provider such as ModeInfo reports only "struct". To pick out a custom provider, check hasattr for one of its distinguishing fields.14 A direct way to get a provider from the ctx.super() result is an open feature request, bazel#26960.
Second, a target may return only one instance of each provider. Appending OutputGroupInfo works here because mode_report returns none. If the parent already returns one, a second one fails analysis with Multiple conflicting returned providers with key OutputGroupInfo.13 In that case you rebuild it: copy the parent's groups and add yours, as a cc_binary extension that adds a debug_info group does.14 4.2.9 OutputGroupInfo & Output Groups covers how consumers request output groups.
Third, keep what the parent promised. Adding providers, actions, and outputs is in scope for an extension.15 Replacing DefaultInfo with different files or dropping a provider that downstream rules require breaks the IS-A claim. If the child needs that, it is a different rule, not an extension.
The snippet also reuses the upstream name, mode_report, for the extended rule. The rule kind comes from the exported name, so bazel query 'kind("^mode_report rule$", //app:all + //dropin:all)' matches upstream targets and extended ones alike, and BUILD files switch over by changing only their load line. The pattern is anchored because kind() matches a regular expression, and a bare mode_report would also match opt_mode_report. Reusing the name keeps existing queries such as kind(cc_binary, ...) working.16 The trade-off is that kind() alone no longer tells you which implementation a target uses. The load line does.
Overriding Attributes And Adding Aspects
The child's attrs dictionary does two jobs. A name the parent does not have adds an attribute, as python_version did. A name that matches a parent's public label-typed attribute overrides it. That override is how you attach an aspect (4.8.1 Aspects — Cross-Cutting Graph Traversal) to the parent's dependency edges:17
bar = rule(
implementation = _bar_impl,
parent = foo,
attrs = {
"deps": attr.label_list(aspects = [custom_aspect]),
},
)
The design doc limits overrides to label-typed public attributes.18 Bazel checks these limits in the Loading phase, when it evaluates rule(). The snippet's errors/override_* packages trigger each one:13
- Overriding a non-label attribute such as a string fails with
Only label types maybe be overridden. - Replacing the label-list
depswith another type, such asattr.string_list(), fails withTypes of parent and child's attributes mismatch. - Overriding a parent's private attribute fails with
private attributes cannot be overridden. - Changing the required
providersof an inherited label attribute fails withcan't override required providers.
Not every label type can be overridden yet. attr.label_keyed_string_dict is one known gap. The workaround is a new attribute plus a macro that copies the original value into it.17
Which Rules Can Be Parents
parent must be a Starlark rule symbol. The snippet's errors/extend_macro package passes a macro and fails at load time:
Error in rule: Parent needs to be a Starlark rule, was function
Native rules are rejected too. In the snippet's errors/native_parent package, parent = native.genrule fails with Parent needs to be a Starlark rule, was rule.13 This bites more often than you might expect, because many rulesets export a macro under the rule's name to preprocess attributes. A cc_binary extension, for example, loads the underlying rule from @cc_compatibility_proxy//:proxy.bzl instead of the public macro. Skipping a macro this way is only safe once you understand what it was doing.16
The parent's author also decides whether extension is allowed at all, through extendable. It can be True, False, or an allowlist label, and the default allows extension.19 The snippet's sealed_report sets extendable = False, and extending it fails with a message that also lists rules that can never be parents:
Error in rule: The rule 'sealed_report' is not extendable. Only Starlark rules not using deprecated features (like implicit outputs, output to genfiles) may be extended. Special rules like analysis tests or rules using build_settings cannot be extended.
When a parent's macro does necessary preprocessing, the initializer parameter of rule() is the in-rule replacement. It is a function called in the Loading phase for each target, with name and the public attribute values. It returns a dictionary of the values to change. For an extended rule, Bazel calls the initializers from child to ancestors, and each one receives only the attributes it knows about.1 The design doc introduced this hook as macro_wrapper so that a ruleset's wrapper logic could live in the rule itself and stay extendable.20
The Rules Of The Call
The child must call ctx.super() exactly once. Skipping it fails with 'super' was not called., and a second call fails with 'super' called the second time.13 Passing arguments fails, because ctx.super() accepts none.10 The child inherits the parent's executable and test settings. It merges fragments, toolchains, exec_compatible_with, and exec_groups with the parent's, and it may not set legacy rule() parameters.1
All of these behaviors come from an experimental API. Pin the Bazel versions your ruleset supports and run a test like the snippet's assertion script against each of them before publishing an extension.
A rule extension is a new rule that is an upstream rule plus one narrow change. It is declared with rule(parent = ...), and its implementation calls ctx.super() once and gets the parent's providers back as a list. Use it for what a macro cannot do and a wrapper rule does clumsily: add an incoming transition, attach an aspect through a label-attribute override, or add an output, all without adding a target.
Plan around its edges. A parent's own cfg runs after yours and wins on settings both write. An incoming transition can create additional configured targets throughout the dependency subtree. Later transitions can change the configuration again. Custom providers come back as "struct", and only label attributes can be overridden. The parent must be an extendable Starlark rule, not the macro a ruleset exports. Use macros for BUILD-file convenience, and use 4.12.3 Subrules for HAS-A implementation reuse.
Check your understanding · 4 questions
1.You consume an upstream proto_bundle rule and need every target of it to build with --compilation_mode=opt, without adding a second target per use or forwarding providers by hand. Which approach fits?
Select one answer
2.An extension's implementation needs the parent's custom LibInfo provider. Which approach works in Bazel 9.1.0?
Select one answer
3.Which parent values fail when the child rule is defined?
Select all that apply
4.True or false: //app:optimized is an opt_mode_report target (an extension of mode_report with cfg = opt_transition), and //app:plain is a plain mode_report. Both depend on //app:lib.
Choose True or False for each sentence
//app:lib in two configurations.bazel query //app:optimized --output=label_kind prints mode_report rule //app:optimized.deps attribute with attr.label_list(aspects = [my_aspect]) is allowed."deps": attr.string_list() to the child's attrs replaces the inherited attribute.Footnotes
-
.bzl files —
rule()parametersparent,initializer, andcfg: merged attributes and providers, matchedexecutable/test, merged fragments, toolchains, and exec groups, parentcfgapplied after the child's, and initializers chained from child to ancestors. ↩1 ↩2 ↩3 ↩4 ↩5 -
ctx —
ctx.super()calls the parent's implementation function and returns its providers. ↩ -
Bazel rule extensions — introduction: rule extensions as a way to edit existing rules without re-implementing or forking them, available by default since Bazel 8.0. ↩
-
Bazel source for the flag's default:
falsein 7.0.0BuildLanguageOptions.javaandtruein 8.0.0FlagConstants.java. ↩ -
Command-Line Reference —
--[no]experimental_rule_extension_api, default"true": "Enable experimental rule extension API and subrule APIs". ↩ -
Extending Bazel rules — background: forks, elaborate wrapper macros, and why macros are fragile and limited, for example when adding an aspect. ↩
-
Bazel rule extensions —
swift_libraryplatform transition example and theios_build_testmacro workaround it replaces. ↩1 ↩2 -
Applying Bazel Transitions to Third-Party Rules the Right Way — forking, patching, or wrapping with manual provider forwarding, and the
lambda ctx: ctx.super()pass-through extension withcfg. ↩1 ↩2 -
Bazel Rules — rule extension and subrules presented as separate APIs for extending and structuring rules. ↩
-
ctx —
super()takes no parameters and returns the parent's providers. ↩1 ↩2 -
Bazel rule extensions —
py_wheelextension with an addedpython_versionattribute and a Python-version transition. ↩ -
rules_mojo repository map — the transition the post links to,
mojo/private/transitions.bzl, echoes the incomingpython_versionunless the attribute is set, and rejects underscore forms such as3_12. ↩ -
rule-extension-cfg snippet — the
errors/packages andassert_rule_extension.shreproduce each quoted error on Bazel 9.1.0. ↩1 ↩2 ↩3 ↩4 ↩5 -
Bazel rule extensions —
cc_binarydebug_infoexample: filteringctx.super()results bytype(),hasattron a"struct", rebuildingOutputGroupInfo, and the link to issue #26960. ↩1 ↩2 -
Bazel Rules — Q&A: rule extensions can add actions and providers, and adding outputs means modifying
DefaultInfo. ↩ -
Bazel rule extensions — closing notes: reuse the parent's rule name for
kind()queries, andparentmust be a rule, not a ruleset's preprocessing macro. ↩1 ↩2 -
Bazel rule extensions — "Adding an attribute with aspects" and the
attr.label_keyed_string_dictlimitation with its macro workaround. ↩1 ↩2 -
Extending Bazel rules —
attrstable: label-typed public attributes are overridden, other same-named public attributes are an error, and private attributes are not allowed. ↩ -
.bzl files —
extendable: allowlist label or boolean, with Bazel defaulting to allowing extensions. ↩ -
Extending Bazel rules — "Macro wrapper" section: load-time attribute preprocessing evaluated child first, then parent, proposed so wrapped rules become extendable. ↩