Skip to content

Dimensions (guardrail_calculus.dimensions)

The generic dimension-algebra dispatch engine and the symbolic conditional, built on the kernel's dimensional protocols. Concrete temporal values (duration_hours, clock_hm, ...) live in guardrail_calculus.dimension_value_builtins.

For what a dimension declares and what that declaration buys — the derived algebra, the invariants the solver assumes, and how to author one of your own — see Dimensions.

dimensions

The generic dimension-algebra dispatch engine and the symbolic conditional.

Despite the name, this is no longer where concrete dimensioned values live — roadmap V8 migrated Duration (Stage 2) and ClockTime/TimeExpr (Stage 3), the last two dimensions with a bespoke Python class, onto the values API (:mod:guardrail_calculus.dimension_values; their concrete instantiations in :mod:guardrail_calculus.dimension_value_builtins). What remains is almost entirely dimension-agnostic: _apply/_realise_rule read a dimensioned operand's own Dimension.algebra_rules() and dispatch generically, every dimension's compound expressions share the one generic DimensionExpr — now as a base, since _realise_rule builds the role subclass the result dimension's structure calls for (DisplacementExpr/PointExpr, in dimension_values.py) — and bind_value/DimensionFacade rebind and dispatch without naming a dimension either.

The exception is a small, genuinely Time/Duration-specific residue — TimeAlgebraFamily, IfTime, IfDuration, and their _DIMENSION_FACADES entries — kept here rather than moved to dimension_values.py because that module already imports _apply/ _DimensionArithmeticMixin from this one at module level; the reverse import would cycle. This module builds on the import-safe guardrail_kernel package; it does not import the public guardrail_calculus package itself.

NodeT module-attribute

NodeT = TypeVar('NodeT')

CondT module-attribute

CondT = TypeVar('CondT', bound=BoolLike)

ThenT module-attribute

ThenT = TypeVar('ThenT')

ElseT module-attribute

ElseT = TypeVar('ElseT')

TimeAlgebraFamily module-attribute

TimeAlgebraFamily = Literal['guardrail.family.time']

TimeLike module-attribute

TimeLike = DimensionLike[Literal['Instant']]

DurationLike module-attribute

DurationLike = DimensionLike[Literal['Duration']]

ExpressionValue

ExpressionValue = (
    BoolExpr[Any]
    | _ExprNode[Any]
    | _IfNode[Any, Any, Any]
    | DimensionExpr
    | DimensionValue
    | PointReference
    | BoundPointReference
    | Val[Any, Any]
    | PointVal[Any, Any]
    | _Add
    | _Sub
    | _Eq
    | _Lt
    | _Le
    | _Gt
    | _Ge
    | _And
    | _Or
    | _Not
    | _If
    | Predicate[Any]
    | bool
    | int
    | float
    | str
)

SubjectRef dataclass

A reference to another subject in the puzzle.

Attributes:

Name Type Description
path Path

The path to the referenced subject.

schema_type type[T] | None

The schema class of the referenced subject.

Source code in src/guardrail_calculus/dimensions.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
@dataclass(frozen=True)
class SubjectRef[T]:
    """A reference to another subject in the puzzle.

    Attributes:
        path: The path to the referenced subject.
        schema_type: The schema class of the referenced subject.
    """

    path: Path
    schema_type: type[T] | None = None

    def __getattr__(self, name: str) -> Any:
        if self.schema_type is not None:
            dim = resolve_field_dimension(self.schema_type, name)
            if dim is not None:
                # Deferred: see bind_value's own note in this module --
                # dimension_values.py imports from this module at top level,
                # so a top-level import back would cycle.
                from guardrail_calculus.dimension_values import (
                    PointReference,
                    symbolic_point_refs_for,
                )

                if symbolic_point_refs_for(dim):
                    return PointReference(self.path.child(name), _dimension=dim)

        return SlotRef(self.path.child(name))

path instance-attribute

path

schema_type class-attribute instance-attribute

schema_type = None

DimensionExpr dataclass

Bases: _ExprNode[NodeT], DimensionIdentity[Any], _ComparisonMechanics, _DimensionArithmeticMixin, DimensionTagged

A generic composite dimension expression (e.g. for user-defined dimensions).

The compound half of the role split's literal/compound axis: the two concrete compounds every arithmetic result actually is — DisplacementExpr and PointExpr, in dimension_values.py — derive from this, which is why it is no longer @final. Scaling is not declared here: it belongs to the displacement role, and inheriting it on the shared base is what let point * 2 through.

Attributes:

Name Type Description
node NodeT

The underlying provenance node.

label str

The expression label.

unit str | None

Optional unit string.

Source code in src/guardrail_calculus/dimensions.py
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
@dataclass(frozen=True, eq=False)
class DimensionExpr(
    _ExprNode[NodeT],
    DimensionIdentity[Any],
    _ComparisonMechanics,
    _DimensionArithmeticMixin,
    DimensionTagged,
):
    """A generic composite dimension expression (e.g. for user-defined dimensions).

    The compound half of the role split's literal/compound axis: the two
    concrete compounds every arithmetic result actually is —
    ``DisplacementExpr`` and ``PointExpr``, in ``dimension_values.py`` — derive
    from this, which is why it is no longer ``@final``. Scaling is not declared
    here: it belongs to the displacement role, and inheriting it on the shared
    base is what let ``point * 2`` through.

    Attributes:
        node: The underlying provenance node.
        label: The expression label.
        unit: Optional unit string.
    """

    _node: NodeT

    def node(self) -> NodeT:
        """The provenance tree this value was built from.

        A method rather than a field so the declared node type can be *derived*
        from a value's own type argument by a self-specialised overload -- the
        mapping that lets the declaration-only `Val`/`PointVal` facades become
        real classes. mypy refuses `@property` stacked on `@overload`, so a call
        is the only form that can carry it.
        """
        return self._node

    label: str
    _dimension: Dimension[Any] = field(kw_only=True)
    unit: str | None = None

label instance-attribute

label

unit class-attribute instance-attribute

unit = None

node

node()

The provenance tree this value was built from.

A method rather than a field so the declared node type can be derived from a value's own type argument by a self-specialised overload -- the mapping that lets the declaration-only Val/PointVal facades become real classes. mypy refuses @property stacked on @overload, so a call is the only form that can carry it.

Source code in src/guardrail_calculus/dimensions.py
504
505
506
507
508
509
510
511
512
513
def node(self) -> NodeT:
    """The provenance tree this value was built from.

    A method rather than a field so the declared node type can be *derived*
    from a value's own type argument by a self-specialised overload -- the
    mapping that lets the declaration-only `Val`/`PointVal` facades become
    real classes. mypy refuses `@property` stacked on `@overload`, so a call
    is the only form that can carry it.
    """
    return self._node

IfTime dataclass

Bases: _IfNode[CondT, ThenT, ElseT], DimensionIdentity[Literal['Instant']], DimensionTagged

Symbolic if/then/else conditional returning an instant.

Source code in src/guardrail_calculus/dimensions.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
@typing.final
@dataclass(frozen=True, eq=True)
class IfTime[
    CondT: BoolLike,
    ThenT: _TimeOperand,
    ElseT: _TimeOperand,
](
    _IfNode[CondT, ThenT, ElseT],
    DimensionIdentity[Literal["Instant"]],
    DimensionTagged,
):
    """Symbolic if/then/else conditional returning an instant."""

    _dimension: typing.ClassVar[Dimension[CarrierInt]] = INSTANT

IfDuration dataclass

Bases: _IfNode[CondT, ThenT, ElseT], DimensionIdentity[Literal['Duration']], DimensionTagged

Symbolic if/then/else conditional returning a duration.

Source code in src/guardrail_calculus/dimensions.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
@typing.final
@dataclass(frozen=True, eq=True)
class IfDuration[
    CondT: BoolLike,
    ThenT: DurationLike,
    ElseT: DurationLike,
](
    _IfNode[CondT, ThenT, ElseT],
    DimensionIdentity[Literal["Duration"]],
    DimensionTagged,
):
    """Symbolic if/then/else conditional returning a duration."""

    _dimension: typing.ClassVar[Dimension[CarrierInt]] = DURATION

IfBool dataclass

Bases: _IfNode[CondT, ThenT, ElseT]

Symbolic if/then/else conditional returning a boolean.

Source code in src/guardrail_calculus/dimensions.py
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
@typing.final
@dataclass(frozen=True, eq=True)
class IfBool[
    CondT: BoolLike,
    ThenT: BoolLike,
    ElseT: BoolLike,
](_IfNode[CondT, ThenT, ElseT]):
    """Symbolic if/then/else conditional returning a boolean."""

    _z3_dim: Literal["bool"] = field(
        default="bool",
        init=False,
        repr=False,
        compare=False,
    )

IfDimensionExpr dataclass

Bases: _IfNode[CondT, ThenT, ElseT], DimensionIdentity[Any], DimensionTagged

Symbolic if/then/else conditional returning a generic dimension expression.

Source code in src/guardrail_calculus/dimensions.py
595
596
597
598
599
600
601
602
603
604
605
606
607
608
@typing.final
@dataclass(frozen=True, eq=True)
class IfDimensionExpr[
    CondT: BoolLike,
    ThenT: DimensionLike[Any],
    ElseT: DimensionLike[Any],
](
    _IfNode[CondT, ThenT, ElseT],
    DimensionIdentity[Any],
    DimensionTagged,
):
    """Symbolic if/then/else conditional returning a generic dimension expression."""

    _dimension: Dimension[Any] = field(kw_only=True)

DimensionFacade dataclass

The calculus-layer Python types that realise one kernel dimension.

A dimension's kernel descriptor (:class:~guardrail_kernel.dimension_registry.Dimension) is dialect-agnostic data; it cannot reference these Python classes without pulling guardrail_calculus into the kernel. This is the single place that fact is authored instead: one record per dimension, gathering every bespoke wrapper type that dispatch previously scattered across parallel name-keyed tables and hardcoded isinstance chains (z3_if's conditional wrapper, the two subject-ref placeholder forms). A dimension absent here, or a None field, falls back to the generic IfDimensionExpr/plain SlotRef — only dimensions needing a dedicated field's behaviour fill it in.

No field for a bespoke compound-expression wrapper class exists any more: it was dropped once roadmap V8 migrated the last two dimensions that ever used one (Duration, Stage 2; Instant, Stage 3) — every dimension's compounds are the generic DimensionExpr now, unwrapped unconditionally by _realise_rule and bind_value. The current-subject/resolved-subject placeholder fields this record once carried (bound/resolved, filled only by TimePoint/ BoundTimePoint) were dropped the same way once roadmap V12 retired those classes: every point-structured dimension's placeholders are now BoundPointReference/PointReference (dimension_values.py), admitted by symbolic_point_refs_for(dimension) reading the dimension's own structure — a registry-data-driven policy with nothing left to register here.

Source code in src/guardrail_calculus/dimensions.py
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
@dataclass(frozen=True)
class DimensionFacade:
    """The calculus-layer Python types that realise one kernel dimension.

    A dimension's kernel descriptor (:class:`~guardrail_kernel.dimension_registry.Dimension`)
    is dialect-agnostic data; it cannot reference these Python classes without
    pulling ``guardrail_calculus`` into the kernel. This is the single place that
    fact is authored instead: one record per dimension, gathering every bespoke
    wrapper type that dispatch previously scattered across parallel
    name-keyed tables and hardcoded ``isinstance`` chains (``z3_if``'s
    conditional wrapper, the two subject-ref placeholder forms). A dimension
    absent here, or a ``None`` field, falls back to the generic
    ``IfDimensionExpr``/plain ``SlotRef`` — only dimensions needing a
    dedicated field's behaviour fill it in.

    No field for a bespoke compound-expression wrapper class exists any
    more: it was dropped once roadmap V8 migrated the last two dimensions
    that ever used one (Duration, Stage 2; Instant, Stage 3) — every
    dimension's compounds are the generic ``DimensionExpr`` now, unwrapped
    unconditionally by ``_realise_rule`` and ``bind_value``. The
    current-subject/resolved-subject placeholder fields this record once
    carried (``bound``/``resolved``, filled only by ``TimePoint``/
    ``BoundTimePoint``) were dropped the same way once roadmap V12 retired
    those classes: every point-structured dimension's placeholders are now
    ``BoundPointReference``/``PointReference`` (``dimension_values.py``),
    admitted by ``symbolic_point_refs_for(dimension)`` reading the
    dimension's own ``structure`` — a registry-data-driven policy with
    nothing left to register here.
    """

    if_: type[Any] | None = None

if_ class-attribute instance-attribute

if_ = None

dimension_facade

dimension_facade(name)

The :class:DimensionFacade registered for dimension name.

Returns the shared empty facade (every field None) for a dimension with no bespoke Python types, so callers need only check the field they want rather than the presence of the dimension itself.

Source code in src/guardrail_calculus/dimensions.py
657
658
659
660
661
662
663
664
def dimension_facade(name: str) -> DimensionFacade:
    """The :class:`DimensionFacade` registered for dimension ``name``.

    Returns the shared empty facade (every field ``None``) for a dimension with
    no bespoke Python types, so callers need only check the field they want
    rather than the presence of the dimension itself.
    """
    return _DIMENSION_FACADES.get(name, _EMPTY_FACADE)

is_dimension_expr

is_dimension_expr(value)

True if value is a compound dimension-expression wrapper.

Covers every current and future compound wrapper (the once-bespoke DurationExpr/TimeExpr, both since removed by roadmap V8, and the generic DimensionExpr every migrated and user-authored dimension's compounds share now) with one dimension-agnostic check, since they all share :class:_ExprNode for z3 lowering and symbolic equality — for dispatch that needs "is this some dimension's compound expression" without naming which dimension.

Source code in src/guardrail_calculus/dimensions.py
667
668
669
670
671
672
673
674
675
676
677
678
def is_dimension_expr(value: object) -> typing_extensions.TypeIs[_ExprNode[Any]]:
    """True if ``value`` is a compound dimension-expression wrapper.

    Covers every current and future compound wrapper (the once-bespoke
    ``DurationExpr``/``TimeExpr``, both since removed by roadmap V8, and the
    generic ``DimensionExpr`` every migrated and user-authored dimension's
    compounds share now) with one dimension-agnostic check, since they all
    share :class:`_ExprNode` for z3 lowering and symbolic equality — for
    dispatch that needs "is this some dimension's compound expression"
    without naming which dimension.
    """
    return isinstance(value, _ExprNode)

provenance_children

provenance_children(value)

The children of an authored expression value; () at a leaf.

Structural traversal dispatches on the node's type. It must not probe attribute names: a :class:~guardrail_kernel.expressions.SlotRef answers any non-underscore attribute by extending its path, so an hasattr-driven walk over a dimensionless slot manufactures budget.node().node()... until the stack ends rather than stopping at the leaf.

The vocabulary is closed and small. Provenance nodes expose their own operands (the shared accessor every binary, unary, conditional and route-membership node defines); the three wrapper kinds — a :class:~guardrail_kernel.expressions.Predicate, a dimension expression (:class:_ExprNode), a symbolic conditional (:class:_IfNode) — each carry exactly one provenance node, their label/z3 being derived. Everything else is a leaf: a slot or point reference, a folded literal, an int, a unit string.

Source code in src/guardrail_calculus/dimensions.py
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
def provenance_children(value: object) -> tuple[object, ...]:
    """The children of an authored expression value; ``()`` at a leaf.

    Structural traversal dispatches on the node's *type*. It must not probe
    attribute names: a :class:`~guardrail_kernel.expressions.SlotRef` answers
    any non-underscore attribute by extending its path, so an
    ``hasattr``-driven walk over a dimensionless slot manufactures
    ``budget.node().node()...`` until the stack ends rather than stopping at the
    leaf.

    The vocabulary is closed and small. Provenance nodes expose their own
    ``operands`` (the shared accessor every binary, unary, conditional and
    route-membership node defines); the three wrapper kinds — a
    :class:`~guardrail_kernel.expressions.Predicate`, a dimension expression
    (:class:`_ExprNode`), a symbolic conditional (:class:`_IfNode`) — each
    carry exactly one provenance ``node``, their ``label``/``z3`` being
    derived. Everything else is a leaf: a slot or point reference, a folded
    literal, an int, a unit string.
    """
    if isinstance(value, (BinaryNode, UnaryNode, _If, _Includes)):
        return value.operands
    if isinstance(value, (Predicate, _ExprNode, _IfNode)):
        return (value.node(),)
    return ()

z3_if

z3_if(
    condition: CondT, then_: ThenT, else_: ElseT
) -> IfTime[CondT, ThenT, ElseT]
z3_if(
    condition: CondT, then_: ThenT, else_: ElseT
) -> IfDuration[CondT, ThenT, ElseT]
z3_if(
    condition: CondT, then_: ThenT, else_: ElseT
) -> IfBool[CondT, ThenT, ElseT]
z3_if(
    condition: CondT, then_: ThenT, else_: ElseT
) -> IfDimensionExpr[CondT, ThenT, ElseT]
z3_if(condition, then_, else_)

Symbolic if/then/else.

Returns then_ when condition is true, else_ otherwise. Chooses among IfTime, IfDuration, IfBool, and IfDimensionExpr by inspecting the types of then_ and else_.

Parameters:

Name Type Description Default
condition BoolLike

The symbolic boolean condition.

required
then_ object

The branch returned if the condition evaluates to true.

required
else_ object

The branch returned if the condition evaluates to false.

required

Returns:

Type Description
Any

A symbolic branch wrapper.

Source code in src/guardrail_calculus/dimensions.py
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
def z3_if(
    condition: BoolLike,
    then_: object,
    else_: object,
) -> Any:
    """Symbolic if/then/else.

    Returns `then_` when condition is true, `else_` otherwise. Chooses among
    [IfTime][guardrail_calculus.dimensions.IfTime], [IfDuration][guardrail_calculus.dimensions.IfDuration],
    [IfBool][guardrail_calculus.dimensions.IfBool], and [IfDimensionExpr][guardrail_calculus.dimensions.IfDimensionExpr]
    by inspecting the types of `then_` and `else_`.

    Args:
        condition: The symbolic boolean condition.
        then_: The branch returned if the condition evaluates to true.
        else_: The branch returned if the condition evaluates to false.

    Returns:
        A symbolic branch wrapper.
    """
    if not is_bool_like(condition):
        raise TypeError(f"z3_if condition must be BoolLike, got {condition!r}")

    then_node = cast(Any, then_)
    else_node = cast(Any, else_)
    then_dim = dimension_of(then_)
    else_dim = dimension_of(else_)

    if then_dim is not None and else_dim is not None:
        if then_dim.name != else_dim.name:
            raise TypeError("z3_if branches must have the same expression dimension.")

        wrapper = dimension_facade(then_dim.name).if_
        if wrapper is None:
            return IfDimensionExpr(
                condition=condition,
                then_=then_node,
                else_=else_node,
                label=(
                    f"if {condition.label} then {then_node.label} "
                    f"else {else_node.label}"
                ),
                _dimension=then_dim,
            )
    elif is_bool_like(then_) and is_bool_like(else_):
        wrapper = IfBool
    else:
        raise TypeError("z3_if branches must have the same expression dimension.")

    return wrapper(
        condition=condition,
        then_=then_node,
        else_=else_node,
        label=f"if {condition.label} then {then_node.label} else {else_node.label}",
    )

bind_value

bind_value(value, *, subject_name)

Recursively bind subject-bound placeholders (_.name) in a value.

BoundPointReference (dimension_values.py, roadmap V12) is the one subject-bound placeholder shape left — family-generic, not named per dimension, so a direct isinstance check is the whole dispatch; no per-dimension facade registration is needed for it to work with a future point-structured dimension either.

Parameters:

Name Type Description Default
value ExpressionValue

The value to bind.

required
subject_name str

The name of the subject to bind to.

required

Returns:

Type Description
ExpressionValue

The bound object/expression.

Source code in src/guardrail_calculus/dimensions.py
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
def bind_value(value: ExpressionValue, *, subject_name: str) -> ExpressionValue:
    """Recursively bind subject-bound placeholders (`_.name`) in a value.

    ``BoundPointReference`` (``dimension_values.py``, roadmap V12) is the one
    subject-bound placeholder shape left — family-generic, not named per
    dimension, so a direct ``isinstance`` check is the whole dispatch; no
    per-dimension facade registration is needed for it to work with a future
    point-structured dimension either.

    Args:
        value: The value to bind.
        subject_name: The name of the subject to bind to.

    Returns:
        The bound object/expression.
    """
    match value:
        case BoolExpr():
            return bind_bool_expr(value, subject_name=subject_name)
        case _Add() | _Sub() | _Eq() | _Lt() | _Le() | _Gt() | _Ge() | _And() | _Or():
            return type(value)(
                bind_value(value.left, subject_name=subject_name),
                bind_value(value.right, subject_name=subject_name),
            )
        case _Not():
            return _Not(bind_value(value.value, subject_name=subject_name))
        case _:
            # Deferred: dimension_values.py imports from this module at top
            # level (TimeAlgebraFamily, _apply, _DimensionArithmeticMixin),
            # so a top-level import back would cycle — the same reason
            # dsl.py's CurrentSubjectRef defers its own dimension_facade
            # import.
            from guardrail_calculus.dimension_values import BoundPointReference

            if isinstance(value, BoundPointReference):
                return value.bind(subject_name)
            # A compound still needs its node rebinding, or a nested `_.`
            # placeholder ships to the solver unresolved (V8's Finding B). A
            # compound carries `_dimension`/`unit` as per-instance fields,
            # unlike the facade-backed wrappers' class-level constants, so it
            # can't reuse _rebind_expr's fixed (node=, label=) call shape.
            #
            # Rebuilt through `type(value)` rather than by naming the base:
            # binding a placeholder does not change a value's role, and
            # naming `DimensionExpr` here would silently demote a
            # `PointExpr` to the base on the way through.
            if isinstance(value, DimensionExpr):
                return type(value)(
                    _node=bind_value(value.node(), subject_name=subject_name),
                    label=value.label.replace("_.", f"{subject_name.capitalize()}."),
                    _dimension=value.dimension(),
                    unit=value.unit,
                )
            return value

bind_bool_expr

bind_bool_expr(expr, *, subject_name)

Bind subject-bound placeholders in a boolean expression.

Parameters:

Name Type Description Default
expr BoolExpr[NodeT]

The boolean expression.

required
subject_name str

The subject name to bind to.

required

Returns:

Type Description
BoolExpr[Any]

The bound expression.

Source code in src/guardrail_calculus/dimensions.py
895
896
897
898
899
900
901
902
903
904
905
def bind_bool_expr(expr: BoolExpr[NodeT], *, subject_name: str) -> BoolExpr[Any]:
    """Bind subject-bound placeholders in a boolean expression.

    Args:
        expr: The boolean expression.
        subject_name: The subject name to bind to.

    Returns:
        The bound expression.
    """
    return _rebind_expr(expr, BoolExpr, subject_name=subject_name)