4.6.6 Custom Constraints & Custom Platforms

recommended

Most builds never need custom constraints. The @platforms repository already ships standard constraint_settings for OS and CPU, plus @platforms//host to auto-detect the local machine.1 Reach for custom constraints only when those standard dimensions cannot describe a real distinction your build matrix has to make: a GPU capability the toolchain depends on, a runtime library availability requirement, a staging-versus-production hardware generation, or anything else that meaningfully changes which toolchain or sources Bazel should select.

A constraint is a distinguishing property of a build or production machine. CPU architecture, presence or absence of a GPU, or the version of a locally installed compiler are common examples, but a constraint can be anything that meaningfully distinguishes machines when orchestrating build work.2 The vocabulary already exists from 3.3.3 Constraint Values. What changes at this level is that you decide when to add to it.

When @platforms Already Covers You

Before defining anything new, check whether the dimension you care about is already a constraint in @platforms. The Bazel team maintains github.com/bazelbuild/platforms precisely so OS and CPU vocabulary stays consistent across the ecosystem.3 If your build only needs to distinguish "Linux x86_64 vs macOS arm64," everything you need is already available — @platforms//os:linux, @platforms//cpu:x86_64, and so on. A custom constraint_setting for cpu would duplicate that vocabulary and break interoperability with other rule sets that read @platforms//cpu.

The same logic applies to extending an existing setting with a new value. Custom-purpose OSes or CPUs should be declared in your rule's repo rather than in @platforms, because rule-specific extensions belong to the owner of the rule, not to the shared ecosystem.4 You can do this directly: if visibility allows, you may add a new constraint_value for an existing constraint_setting such as @platforms//cpu:cpu.5

OS and CPU are not the only dimensions where a private vocabulary hurts. Constraints are useful only when the modules that read them agree on the labels. If your toolchain declares its glibc requirement with a setting of your own, libraries from the Bazel Central Registry (BCR) will not select() on it, and platforms defined by other modules will not declare it.6 platforms_contrib is a community module that standardizes some of those extra dimensions: Linux libc availability and x86-64 CPU capabilities. It extends the shared vocabulary without replacing the @platforms OS and CPU labels.7

Check @platforms first, then an applicable shared extension, and define local constraints only for the distinctions neither covers. platforms_contrib is still alpha and warns of backwards-incompatible changes, so pin its version. The @platforms_contrib//... labels and helper names below show the idea concretely, but they can change before a stable release. The three-question model that follows does not depend on them.7

Machine Availability, Compile Libc, and Link Policy

Some toolchain mismatches surface far too late. Suppose a toolchain's own compiler binaries need glibc 2.40, but your execution machines run Ubuntu 20.04, which ships glibc 2.31. OS and CPU constraints cannot express that requirement, so toolchain resolution can select the toolchain anyway. The build then fails during Execution with a linker or loader error. libc availability constraints let the toolchain state what it needs on each side:6

toolchain(
    name = "legacy_toolchain",
    exec_compatible_with = [
        "@platforms_contrib//os/linux/libc/glibc:at_least_2.40_available",
    ],
    target_compatible_with = [
        "@platforms_contrib//os/linux/libc/glibc:at_least_2.17_available",
    ],
    # toolchain and toolchain_type attributes omitted
)

Its compiler needs glibc 2.40 or newer on the execution platform, and the binaries it produces need glibc 2.17 or newer on the target platform. A platform declares which libcs it provides with the module's version helpers:7,6

load("@platforms_contrib//os/linux/libc/glibc:glibc.bzl", "glibc_version_constraints")
load("@platforms_contrib//os/linux/libc/musl:musl.bzl", "musl_version_constraints")

platform(
    name = "ubuntu_20_04_with_musl",
    constraint_values = [
        "@platforms//os:linux",
        "@platforms//cpu:x86_64",
    ] + glibc_version_constraints("2.31") + musl_version_constraints("1.2"),
)

This platform satisfies the toolchain's target requirement but not its execution requirement. Toolchain resolution then prefers a toolchain that fits, or reports the mismatch, instead of letting an action fail later.6

That success invites turning every libc question into a constraint. The useful test is narrower: does the distinction affect what can run on a machine?6 Three libc questions that sound similar need different answers:

QuestionSource of truth
Is glibc 2.35 or newer available on this machine?A platform requirement such as @platforms_contrib//os/linux/libc/glibc:at_least_2.35_available7
Is this library compiled against musl?The selected C++ toolchain. rules_cc exposes @rules_cc//cc/libc:musl as a config_setting for this question8
Should this build produce glibc or musl output, with static or dynamic linkage?Toolchain configuration or user policy, potentially a local build setting rather than a shared machine constraint6

A machine can provide both glibc and musl. Their availability therefore must not be encoded as mutually exclusive values of one “which libc?” setting. The shared module models them independently, which is why the platform above uses both helpers. Use the helpers rather than listing individual version values: they also add the lower-version availability constraints that make "at least" requirements match.7 The glibc_version refinement example later in this article uses exact versions only to show the underlying Bazel mechanism.

A library's libc-specific code needs the opposite source of truth. A machine that provides both glibc and musl says nothing about which one the selected toolchain compiles against, so a library should select on the toolchain's libc:

cc_library(
    name = "allocator",
    srcs = ["allocator.c"],
    local_defines = select({
        "@rules_cc//cc/libc:musl": ["ALLOCATOR_MUSL"],
        "//conditions:default": [],
    }),
)

@rules_cc//cc/libc:musl does not choose musl. It matches when the selected C++ toolchain reports musl as its libc. Version suffixes are ignored, so a toolchain reporting glibc-2.31 matches :glibc. Toolchains are encouraged, not required, to use these libc names, so a toolchain that reports an unrecognized name falls through to the default branch.8 If you need a user-selectable policy knob, define that separately using 4.7.1 Build Settings for Rule Authors.

think

Classify: Your Linux machine provides glibc 2.35 and musl 1.2. A library needs musl-specific source behavior. You want a statically linked musl executable for deployment. Which facts describe the machine, which describe the selected toolchain, and which express your build policy? Would that executable itself require musl to be installed on the deployment machine?

Reveal

The two available libc versions are independent machine facts. The library's source choice should inspect the selected toolchain's libc, not infer it from installed libraries. Requesting static musl output is build policy that the toolchain must implement. A fully statically linked musl executable does not require a separately installed musl runtime merely because musl was used to build it. It still has other platform requirements, such as OS and CPU compatibility.6

extra

Machine-Specific Optimization Without Hidden Inputs

A compiler flag such as -march=native optimizes for whichever machine runs the compiler. Bazel cannot see that dependency, so a cached or remotely built result can be reused on a machine that lacks those CPU features. The safer pattern is to describe the machine's capabilities as platform constraints and let toolchains and select() read them. platforms_contrib offers auto-detected host platforms for this: a generic one that rounds libc versions into buckets for better cache sharing, and a native one that also exposes detected x86-64 CPU features.6,7

Defining a Custom Constraint

A constraint_setting declares a dimension. A constraint_value is a named value within that dimension. Both are plain BUILD-level targets.9

package(default_visibility = ["//visibility:public"])

constraint_setting(name = "gpu")

constraint_value(
    name = "cuda",
    constraint_setting = ":gpu",
)

constraint_value(
    name = "rocm",
    constraint_setting = ":gpu",
)

constraint_value(
    name = "no_gpu",
    constraint_setting = ":gpu",
)

If these live in //constraints/BUILD.bazel, downstream BUILD files refer to them as //constraints:cuda, //constraints:no_gpu, and so on — ordinary labels. They participate in everything that already accepts a constraint_value: platform(), config_setting, target_compatible_with, and toolchain target_compatible_with / exec_compatible_with clauses.9

A constraint_setting may also nominate one of its constraint_values as the setting's default. A target_compatible_with or exec_compatible_with clause matches a platform when, for each constraint_value in its list, the platform also has that constraint_value — either explicitly or as a default.10 In practice this means a "neutral" value can stand in for platforms that don't say anything about that setting — for example, marking :no_gpu as the default for the :gpu setting so platforms that omit a GPU value still match toolchains that require :no_gpu.

Refining an Existing Constraint Value

Some custom dimensions only make sense underneath a broader constraint. A glibc_version setting, for example, is not an arbitrary machine property in the same way OS or CPU is. It is a Linux-specific refinement. The Build Encyclopedia now exposes that relationship directly with constraint_setting(refines_constraint_value = ...).11

constraint_setting(
    name = "glibc_version",
    default_constraint_value = ":glibc_unspecified",
    refines_constraint_value = "@platforms//os:linux",
)

constraint_value(
    name = "glibc_unspecified",
    constraint_setting = ":glibc_version",
)

constraint_value(
    name = "glibc_2_31",
    constraint_setting = ":glibc_version",
)

platform(
    name = "linux_glibc_2_31",
    constraint_values = [
        "@platforms//os:linux",
        ":glibc_2_31",
    ],
)

The refinement is a validity rule, not inheritance. If a platform lists a non-default value from the refining setting, it must also list the refined value — :glibc_2_31 requires @platforms//os:linux in the example above. Platforms that get the default value, either implicitly by omitting the setting or explicitly by listing it, are exempt.11

Refinement also helps select() specificity. If one branch matches the broad value (@platforms//os:linux) and another matches the refining value (:glibc_2_31), Bazel treats the refining condition as more specific when both match, instead of reporting an ambiguous match.11 That is useful for nested vocabularies: choose a broad Linux default, then override only for particular libc versions, SDK families, or hardware generations that refine an existing platform value.

Practical guidance on picking custom constraints:

  • One setting per orthogonal dimension. GPU capability, libc availability, and hardware generation are independent and belong to separate constraint_settings. A platform may only carry one constraint_value per setting, so you cannot encode multiple values of the same kind on a single platform.12
  • PascalCase or lowercase names tied to vocabulary, not products. Prefer gpu over nvidia_a100_or_amd_mi300, since the value, not the setting, names the concrete option.
  • Public visibility for cross-package consumption. In a constraints-only package, use package(default_visibility = ["//visibility:public"]). Otherwise set visibility = ["//visibility:public"] on each exported constraint_setting / constraint_value.

Composing a Custom Platform

A platform() target is a named set of constraint_values.13 To define a platform that uses both standard @platforms constraints and your custom ones, list them together:

platform(
    name = "linux_arm64_cuda",
    constraint_values = [
        "@platforms//os:linux",
        "@platforms//cpu:arm64",
        "//constraints:cuda",
    ],
)

This is the shape that puts custom constraints to use: standard OS and CPU vocabulary for portability and interop with toolchains that already read @platforms, plus your project-specific dimension for the distinction @platforms cannot express. The platform() rule does not require a special syntax for "custom" values — every entry in constraint_values is a label to a constraint_value target, whatever repository it lives in.

A platform may only carry one constraint_value per constraint_setting. So a platform cannot describe a machine with "two CPUs" without a second constraint_setting modeling the second slot.12 In practice this means custom constraints should describe orthogonal capabilities, not alternative values of the same capability.

You can inspect the mechanics in the target-compatibility snippet: its platform definitions use a deliberately synthetic demo_os setting with demo_linux and demo_macos values. Its filegroups demonstrate the wildcard-skip behavior introduced in 3.3.4 Target Compatibility. In a real project, keep using @platforms//os labels for OS, as the pitfalls below explain.

Where Custom Constraints Show Up

Once defined, a custom constraint is a normal constraint_value label. Every place that already accepts @platforms//cpu:arm64 accepts //constraints:cuda:

  • select() keys. A config_setting with constraint_values = ["//constraints:cuda"] matches platforms that include the :cuda value, just like the is_arm example in the migration guide does for @platforms//cpu:arm.14
  • target_compatible_with on targets and toolchains. A target restricted to ["//constraints:cuda"] will be silently skipped under bazel build //... when the target platform does not include :cuda, following the rules from 3.3.4 Target Compatibility.
  • Toolchain resolution. When you write a toolchain() target as in 4.6.2 Defining, Registering & Accessing Toolchains, its target_compatible_with and exec_compatible_with clauses can list custom constraints. The resolution algorithm from 4.6.3 Toolchain Resolution treats them like any other constraint_value: each clause must be satisfied by the candidate platform.10

The mental model is symmetric. Define a constraint once. Consume it in any of the existing platform APIs without adding new machinery. That is what makes custom constraints a localized extension rather than a parallel system.

Common Pitfalls

  • Modelling the wrong axis. If two values are alternatives within a single dimension — like "CUDA" and "no GPU" — they should be constraint_values of the same constraint_setting, not separate settings. If they are independent capabilities — like "has GPU" and "provides glibc 2.31" — they need separate settings.12
  • Putting common vocabulary in your repo. OS and CPU constraints belong in @platforms so multiple rule sets read the same labels. Putting os:linux in your project's own constraint package fragments the ecosystem and breaks interop with rule sets that already consume @platforms//os:linux.4
  • Forgetting visibility. Constraint targets are referenced from BUILD files all over the workspace. If a downstream package cannot see your constraint_value, every platform() and target_compatible_with that references it fails to load.
  • Treating platforms as arbitrary sets. A platform() is a constraint vector with at most one value per setting. Custom constraints widen the vector. They do not let you encode multiple values of the same dimension on one platform.12
  • Forgetting the refined parent. refines_constraint_value does not add the parent value automatically. A platform that lists a non-default refining value must also list the value it refines. Use defaults for the neutral or "unspecified" case.11
key takeaway

Check @platforms first, then shared extensions such as platforms_contrib, before defining local constraints, because constraints help only when the modules reading them share the labels. Model a distinction as a constraint when it affects what can run on a machine. libc availability qualifies: it lets toolchain resolution reject a toolchain the machine cannot run instead of failing during Execution. Which libc the selected toolchain compiles against, and which linkage the user wants, are toolchain and policy questions, not machine constraints. Define a constraint_setting per orthogonal dimension, add constraint_values for the concrete options, and compose them with standard @platforms constraints inside platform() targets. When a custom dimension is only meaningful under an existing value, model that relationship with refines_constraint_value instead of relying on comments or naming conventions.

Everything else — select(), target_compatible_with, toolchain resolution — keeps working unchanged, because a custom constraint_value is just another label in the same shape Bazel already accepts.

Check your understanding · 4 questions

1.Which scenario most clearly justifies defining a new constraint_setting instead of reusing @platforms?

Select one answer

2.True or false: custom constraint_values and platform APIs.

Choose True or False for each sentence

A custom constraint_value can appear as a key in select() via a config_setting with constraint_values = [...].
A platform() may carry two constraint_values belonging to the same constraint_setting to express alternative options.
A toolchain() target's target_compatible_with and exec_compatible_with can list custom constraint_value labels alongside @platforms ones.
Custom constraint_values only work with target_compatible_with. select() and toolchain resolution require values from @platforms.

3.A constraint_setting nominates one of its values as the setting's default. How does Bazel treat a platform that does NOT list any value for that setting when matching a clause like target_compatible_with = [":default_value"]?

Select one answer

4.True or false: refines_constraint_value on a custom constraint_setting.

Choose True or False for each sentence

A platform that lists a non-default value from a refining setting must also list the value being refined.
Bazel automatically adds the refined parent value to platform.constraint_values when a refining value is present.
Platforms that resolve to the setting's default value are exempt from the refined-parent requirement.
When a broad select() condition and a refining condition both match, the refining condition is treated as more specific.
0 of 4 answered

Footnotes

  1. Platforms — @platforms//host auto-detects local OS and CPU, and standard constraints live in github.com/bazelbuild/platforms. ↩

  2. Platforms — definition of a constraint and a platform. Constraints can be any meaningful distinguishing property. ↩

  3. Platforms — Bazel team maintains common constraint definitions for popular OSes and CPUs to keep the ecosystem consistent. ↩

  4. Migrating to Platforms — common cross-language properties belong in @platforms. Rule-specific properties belong in the rule's repo. ↩1 ↩2

  5. Platforms — extending an existing constraint_setting by defining your own constraint_value is supported when visibility allows. ↩

  6. More expressive platforms with platforms_contrib - Fabian Meumertzheim, BuildBuddy — why constraints must be shared, toolchain libc requirements with mismatch errors during resolution, host platforms compared with -march=native, and machine availability versus compile libc and linkage policy ↩1 ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8

  7. platforms_contrib — alpha shared platform vocabulary — v1.0.0-alpha.0: alpha status, libc helpers and their load paths, host descriptions and feature-label roles ↩1 ↩2 ↩3 ↩4 ↩5 ↩6

  8. rules_cc 0.2.25 — libc selection conditions — cc/libc/BUILD public conditions and toolchain-derived implementation in libc_flag.bzl ↩1 ↩2

  9. Platforms — constraint_setting declares a property type, constraint_value declares a possible value, both referenced as labels. ↩1 ↩2

  10. Toolchains — target_compatible_with / exec_compatible_with match if every required constraint_value is on the platform, either explicitly or as a default. ↩1 ↩2

  11. Platforms and Toolchains Rules — constraint_setting.refines_constraint_value requires non-default refining values to appear with the refined value, exempts default values, and makes refining select() conditions more specific. ↩1 ↩2 ↩3 ↩4

  12. Platforms — a platform may have at most one constraint_value per constraint_setting. ↩1 ↩2 ↩3 ↩4

  13. Platforms — the platform rule defines a platform as a collection of constraint_values. ↩

  14. Migrating to Platforms — config_setting with constraint_values lets select() branch on platform properties. ↩