4.12.2 Rule Extension API: parent + ctx.super()

extra
Experimental API, version-sensitive

Sometimes 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

MacroWrapper ruleExtension
Targets per useUpstream target plus any helpersWrapper plus upstream targetOne
Puts the upstream target in a new configurationNoYes, through a transition on the edge to itYes, through the target's own cfg
Aspect on an existing attributeNoNoYes, through a label override
Change returned providersNoYes, by forwarding them manuallyYes, 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

How can a specialized rule reuse a baseline rule without forking it?
The child remains an IS-A rule: it reuses the parent contract before adding its own analysis behavior.
Experimental · version-sensitive The parent may restrict extension with extendable. The current default permits it. Use this only when the child remains substitutable for the parent.
Parent Rule
Defines the baseline
public rule contract
attrs + advertised providers

the child inherits the supported target surface

settings + toolchains

Bazel merges attrs, fragments, constraints, and exec groups into the child rule definition

implementation()

metadata merging does not run it. The child must call ctx.super()

extendable policy

None permits extension. False blocks it. An allowlist restricts callers.

Child Rule
Declares inheritance
rule(parent = ...)
parent = mode_report

must be a Starlark rule symbol, not a macro

cfg = opt_transition

runs before any parent cfg, so a parent cfg writing the same setting wins

attrs

new attributes, or label attributes overridden to add aspects

call ctx.super() runs the parent implementation, exactly once receive [DefaultInfo, ModeInfo] a plain list of parent providers return providers + [OutputGroupInfo] preserves the parent contract
Parent logic stays authoritative, ctx.super() hands its providers to the child, and the returned set should remain the parent contract plus a narrow extension.

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.

think

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 deps with another type, such as attr.string_list(), fails with Types of parent and child's attributes mismatch.
  • Overriding a parent's private attribute fails with private attributes cannot be overridden.
  • Changing the required providers of an inherited label attribute fails with can'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.

key takeaway

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

Building both targets analyzes //app:lib in two configurations.
bazel query //app:optimized --output=label_kind prints mode_report rule //app:optimized.
Overriding the inherited deps attribute with attr.label_list(aspects = [my_aspect]) is allowed.
Adding "deps": attr.string_list() to the child's attrs replaces the inherited attribute.
0 of 4 answered

Footnotes

  1. .bzl files — rule() parameters parent, initializer, and cfg: merged attributes and providers, matched executable/test, merged fragments, toolchains, and exec groups, parent cfg applied after the child's, and initializers chained from child to ancestors. ↩1 ↩2 ↩3 ↩4 ↩5

  2. ctx — ctx.super() calls the parent's implementation function and returns its providers. ↩

  3. 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. ↩

  4. Bazel source for the flag's default: false in 7.0.0 BuildLanguageOptions.java and true in 8.0.0 FlagConstants.java. ↩

  5. Command-Line Reference — --[no]experimental_rule_extension_api, default "true": "Enable experimental rule extension API and subrule APIs". ↩

  6. Extending Bazel rules — background: forks, elaborate wrapper macros, and why macros are fragile and limited, for example when adding an aspect. ↩

  7. Bazel rule extensions — swift_library platform transition example and the ios_build_test macro workaround it replaces. ↩1 ↩2

  8. 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 with cfg. ↩1 ↩2

  9. Bazel Rules — rule extension and subrules presented as separate APIs for extending and structuring rules. ↩

  10. ctx — super() takes no parameters and returns the parent's providers. ↩1 ↩2

  11. Bazel rule extensions — py_wheel extension with an added python_version attribute and a Python-version transition. ↩

  12. rules_mojo repository map — the transition the post links to, mojo/private/transitions.bzl, echoes the incoming python_version unless the attribute is set, and rejects underscore forms such as 3_12. ↩

  13. rule-extension-cfg snippet — the errors/ packages and assert_rule_extension.sh reproduce each quoted error on Bazel 9.1.0. ↩1 ↩2 ↩3 ↩4 ↩5

  14. Bazel rule extensions — cc_binary debug_info example: filtering ctx.super() results by type(), hasattr on a "struct", rebuilding OutputGroupInfo, and the link to issue #26960. ↩1 ↩2

  15. Bazel Rules — Q&A: rule extensions can add actions and providers, and adding outputs means modifying DefaultInfo. ↩

  16. Bazel rule extensions — closing notes: reuse the parent's rule name for kind() queries, and parent must be a rule, not a ruleset's preprocessing macro. ↩1 ↩2

  17. Bazel rule extensions — "Adding an attribute with aspects" and the attr.label_keyed_string_dict limitation with its macro workaround. ↩1 ↩2

  18. Extending Bazel rules — attrs table: label-typed public attributes are overridden, other same-named public attributes are an error, and private attributes are not allowed. ↩

  19. .bzl files — extendable: allowlist label or boolean, with Bazel defaulting to allowing extensions. ↩

  20. Extending Bazel rules — "Macro wrapper" section: load-time attribute preprocessing evaluated child first, then parent, proposed so wrapped rules become extendable. ↩