The capability spine¶
The capability spine records what each backend family and dialect can do, and acts on a selected part of that record during plan preparation and compilation. Declarations live as data in small segment modules beside the backends. The package loads them into one CapabilityRegistry, and the planner and both visitors ask that registry whether a bound call is allowed. Maintainers reach for three things: the segment modules under expressions/backends/capabilities/ and relations/backends/capabilities/, the registry lookups capability_for and violations_for, and the catalogue views that the generated support page is built from.
Assumes: Backend capabilities, families and dialects, The unified expression visitor and The unified relation visitor.
Information and policy¶
The spine runs in one direction. Segment leaves declare records; bootstrap discovers the leaves, binds each to its scope and validates it; the registry publishes the result as one immutable generation; consumers read that generation. Preflight checks every reachable occurrence of a relation plan before reading any source, the visitors check each call as it compiles, error enrichment and result protection act during materialization, and catalogue captures feed the coverage report.
flowchart LR
S["Segment leaves (SEGMENT)"] --> B["Bootstrap: discover, bind scope, validate"]
B --> R["CapabilityRegistry generation"]
R --> P["Preflight (plan preparation)"]
R --> G["Visitor gates"]
R --> E["Error enrichment, result protection"]
R --> C["Catalogue capture, coverage report"]
Operations live in the backends: backend expression and relation systems own native call construction, argument conversion and ordinary validation (Three-layer separation). A call with no record has unknown support; the catalogue is silent about it. A backend's own conversion and validation stay active when ma.capability_policy switches a protection off. Capability errors and capability_policy describes the user-facing side (the error type, the policy presets and the protection mechanisms).
A segment holds two kinds of record with different contracts. CapabilityInformation is descriptive: a level (unsupported, literal_only, polymorphic, expr_capable) at the native layer (what the engine does) or the public layer (what mountainash offers), a message, an optional workaround, an optional upstream issue identity and a set of issue kinds. Nothing executes it, so editing a description leaves execution exactly as it was. CapabilityPolicyRule is executable: it names its consumer (gate, immediate_error, materialization_error or result_protection) and its action (block, permit, enrich or detect_non_null_to_null), and construction rejects mismatched pairs. A policy may point at the information that explains it; the registry then copies that record's workaround and issue identity onto the published fact, which is where the Upstream ref: line of an error comes from.
CapabilityRegistry.reader(scope) reads one scope's records. The Narwhals Polars dialect describes two decimal-cast limits but acts on only one of them:
import mountainash as ma
from mountainash.core.capabilities import CapabilityRegistry
from mountainash.core.capabilities.catalogue import InformationQuery, PolicyQuery
from mountainash.core.capabilities.identity import Dialect, Scope
from mountainash.core.constants import CONST_BACKEND
from mountainash.expressions.core.expression_system.function_keys.enums import (
FKEY_MOUNTAINASH_SCALAR_VALUE,
)
DECIMAL_CAST = FKEY_MOUNTAINASH_SCALAR_VALUE.DECIMAL_CAST
reader = CapabilityRegistry.reader(Scope(CONST_BACKEND.NARWHALS, Dialect("narwhals-polars")))
for record in reader.search(InformationQuery(operation=DECIMAL_CAST)):
info = record.assertion
print("information:", info.key.subject, info.layer.value, info.level.value, info.issue)
for record in reader.search(PolicyQuery(operation=DECIMAL_CAST)):
policy = record.assertion
print("policy:", policy.key.subject, policy.consumer.value, policy.action.value)
information: * native unsupported NW-MATH-11
information: failure_behavior native unsupported NW-CAST-01
policy: * gate block
The subject * (WILDCARD_PARAM) covers the whole operation. Issue identities such as NW-MATH-11 join to registry/upstream-issues.yaml, and tests/core/test_upstream_registry_join.py fails on a reference with no registry entry. A gate refusal proves that the gate acted. A separate test on the native path checks whether the native limitation still exists, as Known divergences and per-backend xfail describes.
Segments and scopes¶
A segment is one Python module that exports a SEGMENT constant of type CapabilitySegment: a domain, a tuple of information records, a tuple of policy rules and a tuple of change records. Its location is its identity. The path below either capability root encodes the backend family, the scope, the operation's source namespace and its domain:
src/mountainash/expressions/backends/capabilities/
narwhals/
family/
_scope.py SCOPE = Scope(NARWHALS, FamilyWide())
substrait/string.py SEGMENT (information only)
extensions_mountainash/window.py
dialects/
narwhals_pandas/
_scope.py SCOPE = Scope(NARWHALS, Dialect("narwhals-pandas"))
substrait/string.py
extensions_mountainash/string.py
src/mountainash/relations/backends/capabilities/
ibis/dialects/ibis_duckdb/extensions_mountainash/relation.py
The scope always comes from the _scope.py beside the leaf. A family-wide scope covers every dialect of the family (Backend capabilities, families and dialects explains the identity pair). A dialect scope names one member of KNOWN_DIALECTS. The two scopes differ in what they may hold as well as in reach: family leaves hold information only, and every policy must sit under a concrete dialect. Shared information composes into a dialect's view with its family provenance kept (CatalogueCapture.composed_information) and stays descriptive there; a dialect never inherits it as an executable rule. Listing the string segments of the Narwhals family shows the split:
for bound in CapabilityRegistry.segments():
if bound.scope.backend is CONST_BACKEND.NARWHALS and "string" in bound.module:
segment = bound.segment
kinds = "information + policies" if segment.policies else "information"
print(bound.module.removeprefix("mountainash.expressions.backends.capabilities."),
bound.scope.dialect, kinds)
narwhals.dialects.narwhals_lazy.substrait.string narwhals-lazy information
narwhals.dialects.narwhals_pandas.extensions_mountainash.string narwhals-pandas information + policies
narwhals.dialects.narwhals_pandas.substrait.string narwhals-pandas information + policies
narwhals.dialects.narwhals_polars.substrait.string narwhals-polars information
narwhals.dialects.narwhals_pyarrow.extensions_mountainash.string narwhals-pyarrow information + policies
narwhals.family.extensions_mountainash.string None information
narwhals.family.substrait.string None information
BoundSegment, which pairs a module address with its scope and segment, checks that the path agrees with the declaration: the backend directory matches the scope's family, family or dialects/<dialect> matches its applicability, the source directory (substrait or extensions_mountainash) matches each operation key's enum family (FKEY_SUBSTRAIT_* against FKEY_MOUNTAINASH_*), the root (expressions or relations) matches FKEY against RKEY, and the file name matches the segment's Domain. CapabilitySegment itself rejects a record whose operation classifies into another domain and duplicate keys within the segment. Relation leaves use the relation domain; native_input holds native construction contracts.
The changes tuple keeps history. An AssertionChange records a retired or narrowed record with its disposition (upstream_fix, local_implementation_fix, narrowed_applicability, incorrect_declaration, supersession), a reason, evidence and any successors, so removing a declaration leaves a trace in the catalogue.
Bootstrap and the registry¶
Bootstrap turns leaves into a registry generation. Discovery walks both capability roots with pkgutil and takes every non-package module whose name lacks a leading underscore, so _scope.py and helper modules stay out of the leaf set. Bootstrap reads each leaf's source bytes and executes them in a private module namespace in place of an import, keeping the bytes as the record's source capture; that capture lets the catalogue report the exact origin of every record. A leaf therefore has to be import-safe data free of registration side effects, and the load stops with TypeError unless the leaf exports an exact CapabilitySegment named SEGMENT.
Publication is staged and all-or-nothing. All information from every segment is staged first, then every policy, so a dialect policy can reference information held in a family leaf. Staging rejects duplicate information or policy keys, a policy that references unpublished or mismatched information, unknown operations, parameters or dialects, and competing executable policies whose call domains and environment domains are not provably disjoint. Two independent blocks on different parameters may coexist; a block and a permit over overlapping calls may not. If any step fails, the registry keeps its previous data and enters a failed state, and every later query rethrows the original error (src/mountainash/core/capabilities/bootstrap.py, registry.py).
Loading is lazy: the first query loads everything. load_all_capability_declarations() forces a complete load and refuses to enumerate an isolated registry, which keeps a test's isolated state from being mistaken for production data.
CapabilityRegistry is a class-level registry holding one published generation at a time. Each query captures the current generation, so every lookup sees one whole publication. Policies are qualified into CapabilityFact objects, the prepared runtime form that carries the scope, enforcement role (gate or materialize_residue), boundary (build or materialize) and the policy's issue classes.
capability_for(operation_key, param, backend, dialect, option_value=None) answers "what is this cell's policy?" with at most one fact, and raises ValueError if two selected facts would answer the same cell:
from mountainash.core.capabilities import WILDCARD_PARAM
fact = CapabilityRegistry.capability_for(
DECIMAL_CAST, WILDCARD_PARAM, CONST_BACKEND.NARWHALS, "narwhals-polars"
)
print(fact.level, fact.enforcement, fact.boundary)
print(fact.consumer, fact.action, fact.issue_classes)
print(fact.message)
print(CapabilityRegistry.capability_for(DECIMAL_CAST, WILDCARD_PARAM, CONST_BACKEND.POLARS, "polars"))
print(CapabilityRegistry.capability_for(DECIMAL_CAST, WILDCARD_PARAM, CONST_BACKEND.NARWHALS, None))
CapabilityLevel.UNSUPPORTED Enforcement.GATE Boundary.BUILD
PolicyConsumer.GATE PolicyAction.BLOCK frozenset({<CapabilityIssueClass.UNCLASSIFIED: 'unclassified'>})
Narwhals cannot express decimal casts natively: no round mode (narwhals#3698) and no non-strict cast (narwhals#3702).
None
None
Polars declares no policy for the operation, so the answer is None. An unknown dialect also gets None: executable lookups read concrete-scope indexes only, so the family scope never answers them.
Applicability regions¶
A record can be limited to environments. Applicability is a union of Regions, each a conjunction of CoordinateConstraints over packages, engines, adapters, platforms or the interpreter; unbounded applies everywhere. Matching is three-valued. Version constraints are open-ended lower bounds: a limitation is declared from the version where it was observed (>=) and stays in force until a release that fixes it is observed, at which point an upper bound closes the region. The narwhals-pandas gate on dynamic regex patterns was observed at narwhals 2.27.1 with pandas 3.0.6:
from mountainash.core.capabilities.applicability import prepare_environment
from mountainash.core.capabilities.capture import Environment, EnvironmentCoordinate
from mountainash.expressions.core.expression_system.function_keys.enums import (
FKEY_MOUNTAINASH_SCALAR_STRING,
)
regex = CapabilityRegistry.reader(Scope(CONST_BACKEND.NARWHALS, Dialect("narwhals-pandas"))).search(
PolicyQuery(operation=FKEY_MOUNTAINASH_SCALAR_STRING.REGEX_CONTAINS)
)[0].assertion
print(regex.key.subject, regex.level.value, regex.issue_classes)
for region in regex.applicability.regions:
print([(c.kind, c.name, c.specifier) for c in region.constraints])
def environment(**packages):
return Environment(tuple(EnvironmentCoordinate("package", name, version) for name, version in packages.items()))
for packages in ({"narwhals": "2.27.1", "pandas": "3.0.6"},
{"narwhals": "2.27.1", "pandas": "3.0.3"},
{"narwhals": "2.27.1"}):
prepared = prepare_environment(environment(**packages), regex.applicability.requirements)
print(packages, regex.applicability.match(prepared).value)
pattern literal_only frozenset({<CapabilityIssueClass.ARGUMENT_CONTRACT: 'argument_contract'>})
[('package', 'narwhals', '>=2.27.1'), ('package', 'pandas', '>=3.0.6')]
{'narwhals': '2.27.1', 'pandas': '3.0.6'} applicable
{'narwhals': '2.27.1', 'pandas': '3.0.3'} not_applicable
{'narwhals': '2.27.1'} indeterminate
A fact is selected only when matching returns applicable; in an indeterminate environment, version-conditioned protection, error enrichment and expected failures all stay off. At run time the execution context observes just the coordinates that selected policies require for the target, and a lookup with no execution context selects only unbounded facts. Outside the declared region the call reaches the backend unchanged. This page was built with pandas 3.0.3, where the declaration is not applicable, so the native error surfaces:
import pandas as pd
print(CapabilityRegistry.capability_for(
FKEY_MOUNTAINASH_SCALAR_STRING.REGEX_CONTAINS, "pattern", CONST_BACKEND.NARWHALS, "narwhals-pandas"
))
words = pd.DataFrame({"word": ["apple", "kiwi"], "pattern": ["^a", "^b"]})
try:
print(ma.relation(words).select(ma.col("word").str.regex_contains(ma.col("pattern"))).to_polars())
except TypeError as exc:
print(type(exc).__name__, exc)
The coverage report¶
CapabilityRegistry.capture() returns an immutable CatalogueCapture of every scope, segment, information record and policy, each with its origins. python -m mountainash.core.capabilities.render_markdown --output OUTDIR builds the report behind Backend support and known limits from that capture. It gathers the captured records, takes the operation universe from the expression and relation operation registries, and discovers implementation independently by walking the method resolution order of the Polars, Narwhals and Ibis systems. build_coverage_report is then a pure function of those inputs: it keeps information and policies as separate records, leaves family records at family scope, and bases every support claim on a record, never on its absence. Optional --environment and --policy files add a diagnostics view of which records an environment and policy would select. docs-site/scripts/support-matrix/generate.sh runs this command and turns expression-coverage.json into chapter 16's tables.
Bound calls and value classes¶
A bound call is an operation applied to particular arguments at a particular location: BoundCall(operation_key, backend, dialect, bindings, supplied). bindings maps every protocol parameter name to its bound value or AST node, including defaults; supplied names the parameters the caller actually passed. The visitors build it from the canonical AST node and the protocol method signature, so the same call binds identically whichever builder produced it. Two reserved roots, filled by the compiler alone, carry derived metadata: __window__ (the number of order keys, whether there are several, whether any is descending) and __operand_types__.
The spine asks two separate questions of a call. capability_for is the single-answer lookup per parameter or option value. violations_for(bound_call) is the collecting question "what forbids this call?": it evaluates every predicate gate for the exact backend and dialect and returns all that hold, so independent limits on different parameters each contribute their own reason. It collects blocking facts only. The Ibis seeded exact-count sample from chapter 09, asked directly:
from mountainash.core.capabilities import BoundCall
from mountainash.relations.core.relation_system.relation_keys.enums import RKEY_MOUNTAINASH_REL
def sample_call(n=None, fraction=None, seed=None):
bindings = {"n": n, "fraction": fraction, "seed": seed}
return BoundCall(
operation_key=RKEY_MOUNTAINASH_REL.SAMPLE,
backend=CONST_BACKEND.IBIS,
dialect="ibis-duckdb",
bindings=bindings,
supplied=frozenset(name for name, value in bindings.items() if value is not None),
)
for call in (sample_call(n=5, seed=7), sample_call(n=5), sample_call(fraction=0.1, seed=7)):
violations = CapabilityRegistry.violations_for(call)
print(sorted(call.supplied), [fact.param for fact in violations])
Selectors narrow a record within its parameter. Selector("exact", value) matches one option value, such as one Substrait rounding mode. Selector("predicate", Predicate(...)) matches a conjunction of Clauses over binding paths, using a closed operator set: eq, in, is_set, is_null, is_literal, is_dynamic and matches_class. Selector("value_class", ValueClass.X) matches an unbounded family of strings through a predicate in core/capabilities/value_classes.py. These classify option strings for a capability decision. ma.value_kind is a separate feature that classifies Python scalars. A value-class predicate tests real membership, so a well-shaped value can still fail:
from mountainash.core.capabilities import ValueClass
from mountainash.core.capabilities.value_classes import matches
for value in ("Australia/Sydney", "Mars/Olympus_Mons", "UTC"):
print(value, matches(ValueClass.IANA_TIMEZONE, value))
for value in ("2d", "1d", "12mo"):
print(value, matches(ValueClass.DURATION_MULTIPLIER, value))
from mountainash.expressions.core.expression_system.function_keys.enums import (
FKEY_SUBSTRAIT_SCALAR_DATETIME,
)
pandas_reader = CapabilityRegistry.reader(Scope(CONST_BACKEND.NARWHALS, Dialect("narwhals-pandas")))
query = InformationQuery(operation=FKEY_SUBSTRAIT_SCALAR_DATETIME.ASSUME_TIMEZONE, subject="timezone")
for record in pandas_reader.search(query):
print(record.key.local.selector.kind, record.key.local.selector.value, record.assertion.level.value)
Australia/Sydney True
Mars/Olympus_Mons False
UTC True
2d True
1d False
12mo True
value_class ValueClass.IANA_TIMEZONE unsupported
A class can gate a parameter only where the API builder validates that parameter to exactly the class's domain, which is why strftime patterns have no value class. The published value-class records are information; the registry resolves a value-class policy within capability_for when a dialect declares one (tests/core/test_capability_value_class_gate.py).
Gates and preflight¶
A gate is a policy whose consumer is gate. The expression visitor applies gates to the canonical node before the backend prepares or lowers any argument (gate then lower). It first asks whether the active policy demands gates and whether the call's dialect has any gate candidate at all. It then evaluates the bound call's predicate gates that need no metadata (violations_for in the raw phase), the whole-operation gate (*) and each argument (unsupported, or literal_only against a non-literal argument). After argument preparation it evaluates the remaining predicate gates with operand types attached (the complete phase) and finally each option value. Each lookup passes the execution context, so ma.capability_policy selection and applicability both apply. A refused call raises BackendCapabilityError naming the operation and the first violated fact, with every violated fact's key in candidate_fact_keys. The visitor refuses ranking by several sort keys on pandas through Narwhals, through a predicate that reads compiler metadata:
from mountainash.exceptions import BackendCapabilityError
sales = pd.DataFrame({"region": ["n", "n", "s", "s"], "month": [1, 2, 2, 1], "units": [5, 3, 4, 4]})
for order in ("month", ["month", "units"]):
ranked = ma.relation(sales).select(
ma.col("units").rank().over("region", order_by=order).alias("r")
)
try:
print(order, ranked.to_polars()["r"].to_list())
except BackendCapabilityError as exc:
print(order, exc)
print(exc.function_key, exc.limitation.dialect, exc.limitation.predicate)
month [1.0, 2.0, 2.0, 1.0]
['month', 'units'] [narwhals] Narwhals pandas cannot rank by several sort keys: .over(partition) accepts only elementary expressions.
FKEY_MOUNTAINASH_WINDOW.RANK_AVERAGE narwhals-pandas Predicate(clauses=(Clause(path='__window__.multi_key', op=<ClauseOp.EQ: 'eq'>, operand=True),))
The relation visitor applies the same checks to relation operations, with the node's options and gate parameters as bindings (src/mountainash/relations/core/execution/capabilities.py).
Preflight runs those gates over the whole plan before anything executes. Plan preparation resolves an execution location for every reachable occurrence, then checks each relation node and each expression it compiles against that location's dialect, before phase rejection, operand transfer or any source read. It evaluates predicates in the raw phase, which skips gates that need compiler metadata such as __window__ or operand types; the visitor evaluates those, which is why the ranking refusal above comes from compilation. Preflight catches a whole-operation gate, so even explain() refuses a decimal cast on pandas:
prices = ma.relation(pd.DataFrame({"price": [1.25, 3.5]})).select(
ma.col("price").cast(ma.DecimalDtype(10, 2), rounding="half_to_even")
)
try:
prices.explain()
except BackendCapabilityError as exc:
print(exc)
[narwhals] Narwhals cannot express decimal casts natively: no round mode (narwhals#3698) and no non-strict cast (narwhals#3702).
Upstream ref: NW-MATH-11
Declaring a new segment¶
A contributor records a backend fact or adds a protection by declaring a segment, with visitor and backend code left as they are. The steps, in order:
- Choose the scope. Information that holds for every dialect of a family goes under
<family>/family/; anything executable goes under<family>/dialects/<dialect>/. A new dialect needs an entry inKNOWN_DIALECTS(src/mountainash/core/capabilities/identity.py) and a_scope.pyexportingSCOPE. - Place the file at
<source>/<domain>.py, where the source namespace matches the operation key's enum family and the file name is theDomainvalue. A new operation-key category needs aDomainmember and a suffix in_DOMAIN_SUFFIXES(declarations.py);classify_domainraises until it has one. - Export
SEGMENT = CapabilitySegment(...)as side-effect-free data. Key each record withCapabilityKey(operation, subject, selector), give it anapplicability(unbounded, or a region when there is version evidence), and link a policy to its explanation withinformation=QualifiedInformationKey(...). - Run the declaration guards. Bootstrap picks the file up on the next load by itself.
The same segment can be published into an isolated registry to see it act. This one declares a literal-only prefix for starts_with on Polars, publishes it with register_segment, and restores the production registry afterwards:
from mountainash.core.capabilities import (
BoundSegment,
CapabilityIssueClass,
CapabilityKey,
CapabilityLevel,
CapabilityPolicyRule,
CapabilitySegment,
Domain,
PolicyAction,
PolicyConsumer,
unbounded,
)
from mountainash.expressions.core.expression_system.function_keys.enums import (
FKEY_SUBSTRAIT_SCALAR_STRING,
)
literal_prefix = CapabilityPolicyRule(
key=CapabilityKey(FKEY_SUBSTRAIT_SCALAR_STRING.STARTS_WITH, "substring"),
level=CapabilityLevel.LITERAL_ONLY,
message="Example: starts_with needs a literal prefix on this dialect.",
consumer=PolicyConsumer.GATE,
action=PolicyAction.BLOCK,
applicability=unbounded,
issue_classes=frozenset({CapabilityIssueClass.ARGUMENT_CONTRACT}),
)
segment = CapabilitySegment(domain=Domain.STRING, policies=(literal_prefix,))
bound = BoundSegment(
"mountainash.expressions.backends.capabilities.polars.dialects.polars.substrait.string.example",
Scope(CONST_BACKEND.POLARS, Dialect("polars")),
segment,
)
import polars as pl
names = pl.DataFrame({"name": ["anna", "bob"], "prefix": ["a", "c"]})
snapshot = CapabilityRegistry.snapshot()
CapabilityRegistry.reset()
try:
CapabilityRegistry.register_segment(bound)
print(ma.relation(names).select(ma.col("name").str.starts_with("a")).to_polars()["name"].to_list())
try:
ma.relation(names).select(ma.col("name").str.starts_with(ma.col("prefix"))).to_polars()
except BackendCapabilityError as exc:
print(exc)
finally:
CapabilityRegistry.restore(snapshot)
Validation runs when the records are constructed and when they are bound, ahead of any call. BoundSegment rejects the same policy under a family scope:
from mountainash.core.capabilities.identity import FamilyWide
try:
BoundSegment(
"mountainash.expressions.backends.capabilities.polars.family.substrait.string.example",
Scope(CONST_BACKEND.POLARS, FamilyWide()),
segment,
)
except ValueError as exc:
print(exc)
Declarations are covered by closed guards: tests/core/test_capability_protocol_guard.py fails when a discovered leaf has no segment, when importing declarations has registration side effects or when loaded keys collide, and tests/core/test_capability_integrity.py checks the loaded publication, for example that every policy has a concrete dialect scope. Run the targeted guards after adding a segment:
hatch run test:test-target-quick tests/core/test_capability_protocol_guard.py
hatch run test:test-target-quick tests/core/test_capability_integrity.py
A segment states what is true or what to protect. The tests that prove it are written separately, never generated from the records they check. A refusal test proves that the gate acted, so a new gate also needs a test of the native behaviour it guards against (Cross-backend testing).