Skip to content

Effects

An effect interface declares the operations a computation can request and the types of their arguments and results (Plotkin and Pretnar, 2009; Bauer and Pretnar, 2015). An effect instance is one named occurrence of an interface, so two state instances share an interface without sharing their state (instances). An effect row lists the instances a computation may request (Leijen, 2014). The module gives typed effect interfaces, rows, and handler signatures.

Discharge allocates the addresses of inlined calls and local instances at their original entry points. A residual request observes the live addresses in their original order. Resumptions restore the same allocations for each shot, which has its own resumption path. Effects in an intervening clause use the scope outside the captured continuation. The clause keeps the shot path of its triggering request while it runs. When its answer leaves the handler, the continuation recovers the path outside the capture. Surviving outer shots still contribute to later addresses.

A retained call also inherits its enclosing discharged shots and clause activations. Discharge keeps the reference handler when the call's residual row is open or could invoke an outer multi-shot clause inside that path.

A resumption can revisit a runtime constructor case. Discharge can copy a case whose motive has no indices and whose patterns bind no static arguments. Each new copy has fresh pattern scopes and retains the original request sites. Execution still selects one branch per shot. An enclosing join keeps each case together when several result components are needed. The existing statement limit counts the copies. A repeated case with static pattern arguments or an indexed motive keeps reference execution with a case obstacle, as does a case whose branches cannot meet an outer continuation.

An effectful return clause uses the address of its handler installation. Different installations of the same declaration have different return addresses. Multiple shots through one installation share its return address, with their own shot paths. If an outer handler captures the return, its operation-clause address includes the captured activation alongside any captured local instance addresses.

Exact scalar derivatives

exact_jvp runs a checked scalar computation and returns its value and Jacobian-vector product as rational numbers. It follows the reference machine through authored clauses, parameter updates, resumptions, and recursive calls. Its arithmetic includes division by nonzero values and powers with fixed integral exponents. A constructor from a closed monomorphic family carries exact scalar fields into the selected case arm when its application has no static arguments. Each field is evaluated in declaration order.

Every comparison reached by the run must either have unequal operands or be independent of the input. This gives a neighborhood where the same branch is taken. At an input-dependent equality, the checker raises JvpBoundaryError, even when the supplied tangent is zero. Unsupported primitives, undefined arithmetic, and exhausted limits raise errors.

The handler below doubles the value supplied to its continuation, which then squares it. The resulting function is \(f(x)=4x^2\). At \(x=3\), a direction of \(1/2\) gives \(Df(3)[1/2]=12\).

from fractions import Fraction

from quivers.dsl import Compiler, parse
from quivers.qiec import exact_jvp

source = """
effect Staging
    shift : Real -> Real

instance stage : Staging

handler double for Staging : Real -> Real [coverage=total, forwards=none, implementation=authored]
    return x =>
        return x
    shift(v : Real) resumes 1 =>
        resume(2.0 * v)

define squared(x : Real) : Real !{} =
    handle stage with double in
        let y <- perform stage.shift(x)
        return y * y
"""
module = Compiler(parse(source), module_name="exact-jvp-example").qiec_module
assert module is not None
result = exact_jvp(module, "squared", (3,), (Fraction(1, 2),))
assert (result.value, result.tangent) == (36, 12)

exact_mixed_derivative seeds two perturbations independently. Their product gives the mixed directional derivative. For the same \(f\), \(D^2 f(3)[1/2,2]=8\).

from quivers.qiec import exact_mixed_derivative

result = exact_mixed_derivative(module, "squared", (3,), (Fraction(1, 2),), (2,))
assert (result.value, result.first, result.second, result.mixed) == (36, 12, 48, 8)

exact_gradient records the scalar operations executed by the reference machine and then accumulates their cotangents in reverse order. Every use of a value contributes, including uses of a captured value in different resumptions. The result lists partial derivatives in parameter order.

from quivers.qiec import exact_gradient

result = exact_gradient(module, "squared", (3,))
assert (result.value, result.gradient) == (36, (24,))

Implicit roots

exact_implicit_gradient takes a scalar residual \(F(z,\theta)\) and an exact root \(z\) at the supplied parameter values. It requires \(F(z,\theta)=0\), a regular scalar execution, and a nonzero state derivative \(F_z(z,\theta)\). These conditions give a local solution branch through \(z\), with gradient \(-F_\theta/F_z\). The result records the implicit derivative conditions and the exact state derivative.

from fractions import Fraction

from quivers.dsl import Compiler, parse
from quivers.qiec import exact_implicit_gradient

source = """
define residual(z : Real, x : Real) : Real !{} =
    return z * z - x
"""
module = Compiler(parse(source), module_name="exact-root-example").qiec_module
assert module is not None
result = exact_implicit_gradient(module, "residual", 3, (9,))
assert (result.value, result.gradient) == (3, (Fraction(1, 6),))
assert result.semantics.kind == "implicit"

Authored implicit derivatives

An authored implicit derivative binds a primal computation \(G(\theta)\) to a residual computation \(F(z,\theta)\). The checked declaration requires closed scalar real signatures, with the residual taking the root before the primal parameters in their declared order.

from fractions import Fraction

from quivers.dsl import Compiler, parse

source = """
define equilibrium(rate : Real, cost : Real) : Real !{} =
    return cost / (1.0 - rate)

define residual(z : Real, rate : Real, cost : Real) : Real !{} =
    return (1.0 - rate) * z - cost

effect_law equilibrium_gradient [primal=equilibrium, residual=residual]
"""
compiler = Compiler(parse(source))
proof = compiler.authored_implicit_gradient("equilibrium_gradient", (Fraction(1, 2), 1))
assert (proof.solution.value, proof.solution.gradient) == (2, (4, 2))
assert proof.solution.state_derivative == Fraction(1, 2)

The request first checks \(F(G(\theta),\theta)=0\) symbolically. The domain record includes every reached divisor of the composition, including unused divisions. Thus the identity holds on an open domain of the primal parameters. At the requested point, the evaluator computes the root from \(G\) and verifies that \(F\) is regular in the root and parameter coordinates and has nonzero \(F_z\). Local uniqueness then identifies the derivative of \(G\) with \(-F_\theta/F_z\). Agreement at one root, even with the same gradient at that point, is insufficient to establish the composition identity.

The proof uses the guarded scalar rational fragment and its arithmetic work budget. Each symbolic computation, exact primal evaluation, and residual gradient evaluation has its own reference step limit. A false identity, a reached pole, an unstable comparison in the residual, or a singular root refuses the request. The certificate concerns the exact returned scalar and its local derivative. Root selection stays in the authored primal, and ordinary evaluation and target emission retain their existing behavior.

differentiation

Exact derivatives on regular scalar executions of checked QIEC.

JvpUnsupported

Bases: ValueError

A checked computation lies outside the exact scalar derivative fragment.

JvpBoundaryError

Bases: JvpUnsupported

Comparison stability could not be certified at an equality boundary.

JvpLimit

Bases: ValueError

Exact derivative evaluation exhausted a resource bound.

ImplicitRootError

Bases: ValueError

The supplied point cannot establish a regular implicit root.

ExactGradient dataclass

ExactGradient(value: Fraction, gradient: tuple[Fraction, ...])

A scalar and the exact gradient returned by its reverse pass.

PARAMETER DESCRIPTION
value

The result at the supplied point.

TYPE: Fraction

gradient

Its partial derivatives, in parameter order.

TYPE: tuple[Fraction, ...]

ExactImplicitGradient dataclass

ExactImplicitGradient(value: Fraction, gradient: tuple[Fraction, ...], state_derivative: Fraction)

The exact gradient of a local scalar solution branch.

PARAMETER DESCRIPTION
value

The supplied root verified by the residual computation.

TYPE: Fraction

gradient

The local solution's partial derivatives in parameter order.

TYPE: tuple[Fraction, ...]

state_derivative

The residual derivative with respect to the root coordinate.

TYPE: Fraction

semantics property

The derivative report and its checked implicit hypotheses.

RETURNS DESCRIPTION
DerivativeSemantics

An implicit derivative over the regular zero of the residual.

ExactImplicitCertificate dataclass

ExactImplicitCertificate(primal: ComputationId, residual: ComputationId, arguments: tuple[Fraction, ...], identity: RationalLawDecision, solution: ExactImplicitGradient)

An exact derivative of a named scalar root computation.

PARAMETER DESCRIPTION
primal

The checked root and residual identities.

TYPE: ComputationId

residual

The checked root and residual identities.

TYPE: ComputationId

arguments

The checked primal parameter point.

TYPE: tuple[Fraction, ...]

identity

The exact zero identity and strict domain of the composition.

TYPE: RationalLawDecision

solution

The verified root and local derivative at the requested point.

TYPE: ExactImplicitGradient

ExactJvp dataclass

ExactJvp(value: Fraction, tangent: Fraction)

A computed value and its exact directional derivative.

PARAMETER DESCRIPTION
value

The result of the admitted scalar computation.

TYPE: Fraction

tangent

Its Jacobian applied to the supplied input direction.

TYPE: Fraction

ExactMixedDerivative dataclass

ExactMixedDerivative(value: Fraction, first: Fraction, second: Fraction, mixed: Fraction)

A scalar and its derivatives along two independent input directions.

PARAMETER DESCRIPTION
value

The result at the supplied point.

TYPE: Fraction

first

The derivative along the first direction.

TYPE: Fraction

second

The derivative along the second direction.

TYPE: Fraction

mixed

The Hessian evaluated on the two directions.

TYPE: Fraction

exact_gradient

exact_gradient(module: QiecModule, computation: str, arguments: tuple[int | Fraction, ...], *, fuel: int = 65536, rule: RationalDerivativeDeclaration | None = None, max_rule_work: int = 65536, choose_first_at_ties: bool = False) -> ExactGradient

Evaluate a checked scalar computation and its exact reverse gradient.

The reference execution records scalar primitive occurrences. The reverse pass sums every use of a recorded value, including uses in several resumptions of one captured continuation. The admitted operations and comparisons are those of :func:exact_jvp, subject to the bounds on local slopes and accumulated cotangents.

PARAMETER DESCRIPTION
module

The checked QIEC module.

TYPE: QiecModule

computation

A named, closed scalar real computation.

TYPE: str

arguments

The evaluation point in parameter order.

TYPE: tuple[int or Fraction, ...]

fuel

The maximum number of reference machine steps.

TYPE: int DEFAULT: 65536

rule

If given, certify and execute the corresponding authored action.

TYPE: RationalDerivativeDeclaration or None DEFAULT: None

max_rule_work

The symbolic work limit for certifying a supplied rule.

TYPE: int DEFAULT: 65536

choose_first_at_ties

Return the first operand's action at a scalar minimum or maximum tie. This is a selected branch action. By default an equal pair refuses.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
ExactGradient

The scalar and its partial derivatives in parameter order.

RAISES DESCRIPTION
JvpUnsupported

If the computation or a reached operation has no rule.

JvpBoundaryError

If a comparison equality cannot be certified stable, or a scalar selection ties without an explicit branch rule.

JvpLimit

If the evaluation exhausts a bound.

ValueError

If the point or limit is malformed.

Source code in src/quivers/qiec/differentiation.py
def exact_gradient(
    module: QiecModule,
    computation: str,
    arguments: tuple[int | Fraction, ...],
    *,
    fuel: int = 65_536,
    rule: RationalDerivativeDeclaration | None = None,
    max_rule_work: int = 65_536,
    choose_first_at_ties: bool = False,
) -> ExactGradient:
    """Evaluate a checked scalar computation and its exact reverse gradient.

    The reference execution records scalar primitive occurrences. The
    reverse pass sums every use of a recorded value, including uses in
    several resumptions of one captured continuation. The admitted
    operations and comparisons are those of :func:`exact_jvp`, subject
    to the bounds on local slopes and accumulated cotangents.

    Parameters
    ----------
    module : QiecModule
        The checked QIEC module.
    computation : str
        A named, closed scalar real computation.
    arguments : tuple[int or Fraction, ...]
        The evaluation point in parameter order.
    fuel : int
        The maximum number of reference machine steps.
    rule : RationalDerivativeDeclaration or None
        If given, certify and execute the corresponding authored action.
    max_rule_work : int
        The symbolic work limit for certifying a supplied rule.
    choose_first_at_ties : bool
        Return the first operand's action at a scalar minimum or maximum tie.
        This is a selected branch action. By default an equal pair refuses.

    Returns
    -------
    ExactGradient
        The scalar and its partial derivatives in parameter order.

    Raises
    ------
    JvpUnsupported
        If the computation or a reached operation has no rule.
    JvpBoundaryError
        If a comparison equality cannot be certified stable,
        or a scalar selection ties without an explicit branch rule.
    JvpLimit
        If the evaluation exhausts a bound.
    ValueError
        If the point or limit is malformed.
    """
    _check_selection_policy(choose_first_at_ties, rule)
    registry, declaration = _prepare_scalar(module, computation, fuel)
    parameters = declaration.parameters
    if len(arguments) != len(parameters):
        raise ValueError("arguments must match the computation's arity")
    if rule is not None:
        if rule.vjp is None:
            raise JvpUnsupported("the declaration has no reverse action")
        decision = _check_action(module, declaration, rule, max_rule_work, fuel)
        assert decision.vjp is not None
        value = _scalar_value(module, computation, arguments, fuel)
        gradient = tuple(
            _scalar_value(module, action.computation, (*arguments, 1), fuel)
            for action in decision.vjp
        )
        return ExactGradient(value, gradient)
    evaluator = _ReverseEvaluator(
        module, fuel, choose_first_at_ties=choose_first_at_ties
    )
    result = evaluator.run(declaration, registry, arguments, record=True)
    return ExactGradient(result.value, evaluator.gradient(result, len(parameters)))

exact_implicit_gradient

exact_implicit_gradient(module: QiecModule, residual: str, root: int | Fraction, arguments: tuple[int | Fraction, ...], *, fuel: int = 65536) -> ExactImplicitGradient

Differentiate the local solution of a scalar residual equation.

The residual runs in the regular scalar fragment of :func:exact_gradient. Its first parameter is the unknown. At the supplied point, the residual must vanish exactly and its derivative in that first coordinate must be nonzero. The result differentiates the local branch through this root with respect to the remaining parameters.

PARAMETER DESCRIPTION
module

The checked module declaring the residual.

TYPE: QiecModule

residual

The named real computation defining the scalar equation.

TYPE: str

root

The exact value to verify in its first parameter.

TYPE: int or Fraction

arguments

Values of its other parameters in order.

TYPE: tuple[int or Fraction, ...]

fuel

The maximum number of reference machine steps.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
ExactImplicitGradient

The verified root, local derivatives and residual state derivative.

RAISES DESCRIPTION
ImplicitRootError

If the residual is nonzero or its first partial derivative vanishes.

JvpUnsupported

If the residual or a reached operation is unsupported.

JvpBoundaryError

If a comparison equality cannot be certified stable, or a scalar selection ties without an explicit branch rule.

JvpLimit

If the evaluation or exact gradient exhausts a bound.

ValueError

If the point or limit is malformed.

Source code in src/quivers/qiec/differentiation.py
def exact_implicit_gradient(
    module: QiecModule,
    residual: str,
    root: int | Fraction,
    arguments: tuple[int | Fraction, ...],
    *,
    fuel: int = 65_536,
) -> ExactImplicitGradient:
    """Differentiate the local solution of a scalar residual equation.

    The residual runs in the regular scalar fragment of
    :func:`exact_gradient`. Its first parameter is the unknown. At the
    supplied point, the residual must vanish exactly and its derivative
    in that first coordinate must be nonzero. The result differentiates
    the local branch through this root with respect to the remaining
    parameters.

    Parameters
    ----------
    module : QiecModule
        The checked module declaring the residual.
    residual : str
        The named real computation defining the scalar equation.
    root : int or Fraction
        The exact value to verify in its first parameter.
    arguments : tuple[int or Fraction, ...]
        Values of its other parameters in order.
    fuel : int
        The maximum number of reference machine steps.

    Returns
    -------
    ExactImplicitGradient
        The verified root, local derivatives and residual state derivative.

    Raises
    ------
    ImplicitRootError
        If the residual is nonzero or its first partial derivative vanishes.
    JvpUnsupported
        If the residual or a reached operation is unsupported.
    JvpBoundaryError
        If a comparison equality cannot be certified stable,
        or a scalar selection ties without an explicit branch rule.
    JvpLimit
        If the evaluation or exact gradient exhausts a bound.
    ValueError
        If the point or limit is malformed.
    """
    value = _fraction(root)
    evaluated = exact_gradient(module, residual, (value, *arguments), fuel=fuel)
    if evaluated.value != 0:
        raise ImplicitRootError("the supplied root does not make the residual zero")
    state_derivative, *other_partials = evaluated.gradient
    if state_derivative == 0:
        raise ImplicitRootError("the residual's state derivative is zero at the root")
    gradient = tuple(-partial / state_derivative for partial in other_partials)
    _bound(*gradient)
    return ExactImplicitGradient(value, gradient, state_derivative)

exact_jvp

exact_jvp(module: QiecModule, computation: str, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], *, fuel: int = 65536, rule: RationalDerivativeDeclaration | None = None, max_rule_work: int = 65536, choose_first_at_ties: bool = False) -> ExactJvp

Evaluate a named real computation and its exact forward derivative.

The run follows the checked reference machine, including authored clauses and resumptions. The result uses rational arithmetic for the admitted primitives. Constructors from closed monomorphic families carry exact scalar fields through their selected case arms when the constructor application has no static arguments. An input-dependent comparison is admitted when its primals differ or the same checked value arithmetic expression occurs on both sides. A generated nominal strict comparison requires unequal rational primals even when both operands are constants.

PARAMETER DESCRIPTION
module

The module declaring the checked computation.

TYPE: QiecModule

computation

The computation's name. Its arguments and result are scalar reals and its residual effect row is empty.

TYPE: str

arguments

The point at which to evaluate.

TYPE: tuple[int or Fraction, ...]

direction

The input tangent, in the same parameter order.

TYPE: tuple[int or Fraction, ...]

fuel

The maximum number of reference machine steps.

TYPE: int DEFAULT: 65536

rule

If given, certify and execute the corresponding authored action.

TYPE: RationalDerivativeDeclaration or None DEFAULT: None

max_rule_work

The symbolic work limit for certifying a supplied rule.

TYPE: int DEFAULT: 65536

choose_first_at_ties

Return the first operand's action at a scalar minimum or maximum tie. This is a selected branch action. By default an equal pair refuses.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
ExactJvp

The exact value and Jacobian-vector product.

RAISES DESCRIPTION
JvpUnsupported

If the checked computation or a reached operation has no rule.

JvpBoundaryError

If a comparison equality cannot be certified stable, or a scalar selection ties without an explicit branch rule.

JvpLimit

If the evaluation exhausts a bound.

ValueError

If the supplied arguments, direction, or limit is malformed.

Source code in src/quivers/qiec/differentiation.py
def exact_jvp(
    module: QiecModule,
    computation: str,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    *,
    fuel: int = 65_536,
    rule: RationalDerivativeDeclaration | None = None,
    max_rule_work: int = 65_536,
    choose_first_at_ties: bool = False,
) -> ExactJvp:
    """Evaluate a named real computation and its exact forward derivative.

    The run follows the checked reference machine, including authored
    clauses and resumptions. The result uses rational arithmetic for the
    admitted primitives. Constructors from closed monomorphic families
    carry exact scalar fields through their selected case arms when the
    constructor application has no static arguments. An input-dependent
    comparison is admitted when its primals differ or the same checked value
    arithmetic expression occurs on both sides. A generated nominal strict
    comparison requires unequal rational primals even when
    both operands are constants.

    Parameters
    ----------
    module : QiecModule
        The module declaring the checked computation.
    computation : str
        The computation's name. Its arguments and result are scalar
        reals and its residual effect row is empty.
    arguments : tuple[int or Fraction, ...]
        The point at which to evaluate.
    direction : tuple[int or Fraction, ...]
        The input tangent, in the same parameter order.
    fuel : int
        The maximum number of reference machine steps.
    rule : RationalDerivativeDeclaration or None
        If given, certify and execute the corresponding authored action.
    max_rule_work : int
        The symbolic work limit for certifying a supplied rule.
    choose_first_at_ties : bool
        Return the first operand's action at a scalar minimum or maximum tie.
        This is a selected branch action. By default an equal pair refuses.

    Returns
    -------
    ExactJvp
        The exact value and Jacobian-vector product.

    Raises
    ------
    JvpUnsupported
        If the checked computation or a reached operation has no rule.
    JvpBoundaryError
        If a comparison equality cannot be certified stable,
        or a scalar selection ties without an explicit branch rule.
    JvpLimit
        If the evaluation exhausts a bound.
    ValueError
        If the supplied arguments, direction, or limit is malformed.
    """
    _check_selection_policy(choose_first_at_ties, rule)
    if rule is not None:
        _, declaration = _prepare_scalar(module, computation, fuel)
        if len(arguments) != len(declaration.parameters) or len(direction) != len(
            arguments
        ):
            raise ValueError(
                "arguments and direction must each match the computation's arity"
            )
        if rule.jvp is None:
            raise JvpUnsupported("the declaration has no forward action")
        decision = _check_action(module, declaration, rule, max_rule_work, fuel)
        assert decision.jvp is not None
        value = _scalar_value(module, computation, arguments, fuel)
        tangent = _scalar_value(
            module, decision.jvp.computation, (*arguments, *direction), fuel
        )
        return ExactJvp(value, tangent)
    result = _evaluate_dual(
        module,
        computation,
        arguments,
        direction,
        None,
        fuel,
        choose_first_at_ties=choose_first_at_ties,
    )
    return ExactJvp(result.value, result.tangent)

exact_mixed_derivative

exact_mixed_derivative(module: QiecModule, computation: str, arguments: tuple[int | Fraction, ...], first: tuple[int | Fraction, ...], second: tuple[int | Fraction, ...], *, fuel: int = 65536) -> ExactMixedDerivative

Evaluate a scalar's first derivatives and mixed second derivative.

The first and second input directions seed separate perturbation variables. Each variable squares to zero and their product gives the mixed derivative. The run requires the same regularity and exact arithmetic as :func:exact_jvp.

PARAMETER DESCRIPTION
module

The checked QIEC module.

TYPE: QiecModule

computation

A named, closed scalar real computation.

TYPE: str

arguments

The point where both derivatives are evaluated.

TYPE: tuple[int or Fraction, ...]

first

The first input direction.

TYPE: tuple[int or Fraction, ...]

second

The second input direction.

TYPE: tuple[int or Fraction, ...]

fuel

The maximum number of reference machine steps.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
ExactMixedDerivative

The scalar value, both first directional derivatives, and the Hessian's bilinear action on the given directions.

RAISES DESCRIPTION
JvpUnsupported

If the checked computation or a reached operation has no rule.

JvpBoundaryError

If a comparison equality cannot be certified stable, or a scalar selection ties without an explicit branch rule.

JvpLimit

If the evaluation exhausts a bound.

ValueError

If a point, direction, or limit is malformed.

Source code in src/quivers/qiec/differentiation.py
def exact_mixed_derivative(
    module: QiecModule,
    computation: str,
    arguments: tuple[int | Fraction, ...],
    first: tuple[int | Fraction, ...],
    second: tuple[int | Fraction, ...],
    *,
    fuel: int = 65_536,
) -> ExactMixedDerivative:
    """Evaluate a scalar's first derivatives and mixed second derivative.

    The first and second input directions seed separate perturbation
    variables. Each variable squares to zero and their product gives
    the mixed derivative. The run requires the same regularity and
    exact arithmetic as :func:`exact_jvp`.

    Parameters
    ----------
    module : QiecModule
        The checked QIEC module.
    computation : str
        A named, closed scalar real computation.
    arguments : tuple[int or Fraction, ...]
        The point where both derivatives are evaluated.
    first : tuple[int or Fraction, ...]
        The first input direction.
    second : tuple[int or Fraction, ...]
        The second input direction.
    fuel : int
        The maximum number of reference machine steps.

    Returns
    -------
    ExactMixedDerivative
        The scalar value, both first directional derivatives, and the
        Hessian's bilinear action on the given directions.

    Raises
    ------
    JvpUnsupported
        If the checked computation or a reached operation has no rule.
    JvpBoundaryError
        If a comparison equality cannot be certified stable,
        or a scalar selection ties without an explicit branch rule.
    JvpLimit
        If the evaluation exhausts a bound.
    ValueError
        If a point, direction, or limit is malformed.
    """
    result = _evaluate_dual(module, computation, arguments, first, second, fuel)
    return ExactMixedDerivative(
        result.value, result.tangent, result.second_tangent, result.mixed
    )

Least fixed points of polynomial maps

exact_least_fixed_point_gradient checks an exact positive state against a tuple of ordinary scalar QVR components. The component polynomials must remain nonnegative on the nonnegative orthant for parameters near the requested point. A positive vector with \(DF(x)v < v\) certifies contraction on the order interval below the checked fixed point. The resulting Jacobian is the derivative of the least solution and solves \((I - DF(x))D_\theta x = D_\theta F(x)\). At criticality this route refuses. The candidate state and the vector are inputs to the check.

least_fixed_points

Exact derivatives of certified positive least fixed points of source maps.

ExactLeastFixedPointGradient dataclass

ExactLeastFixedPointGradient(components: tuple[ComputationId, ...], state: tuple[Fraction, ...], arguments: tuple[Fraction, ...], gradient: tuple[tuple[Fraction, ...], ...], state_jacobian: tuple[tuple[Fraction, ...], ...], spectral_bound: Fraction, work: int)

The verified least fixed point of a checked map and its local sensitivities.

PARAMETER DESCRIPTION
components

The actual named map components in state-coordinate order.

TYPE: tuple of ComputationId

state

The verified least state and the parameter point.

TYPE: tuple of Fraction

arguments

The verified least state and the parameter point.

TYPE: tuple of Fraction

gradient

The state Jacobian, with one row per state and one column per parameter.

TYPE: tuple of tuple of Fraction

state_jacobian

The map's exact state derivative at the least state.

TYPE: tuple of tuple of Fraction

spectral_bound

An upper bound below one on the state Jacobian's spectral radius.

TYPE: Fraction

work

Charged symbolic normalization, coefficient checking and linear solve work for this representation of the checked source. Native evaluation has its own step bound, and its reverse pass follows the local graph.

TYPE: int

semantics property

Report the checked hypotheses of the implicit derivative.

RETURNS DESCRIPTION
DerivativeSemantics

The least-fixed-point and spectral hypotheses at the checked point.

exact_least_fixed_point_gradient

exact_least_fixed_point_gradient(module: QiecModule, components: tuple[ComputationId, ...], state: tuple[int | Fraction, ...], arguments: tuple[int | Fraction, ...], witness: tuple[int | Fraction, ...], *, max_work: int = 65536, fuel: int = 65536) -> ExactLeastFixedPointGradient

Verify a source map's least fixed point and differentiate it exactly.

The component computations are pure Real polynomials in the state coordinates followed by the shared parameters. Coefficients of state powers, considered as polynomials in the parameters, must be strictly positive at the point or structurally zero. The state is positive and must be an exact fixed point of the actual source. The positive witness establishes a strict componentwise inequality between the state Jacobian applied to the witness and the witness.

This gives a monotone map on the nonnegative orthant and a contraction on the order interval from zero to the fixed point. The least fixed point is the given state. The strict conditions persist along its local regular branch, and the implicit Jacobian is the derivative of that branch.

PARAMETER DESCRIPTION
module

The checked ordinary source.

TYPE: QiecModule

components

The nominal source computations, in state coordinate order.

TYPE: tuple of ComputationId

state

A candidate positive fixed point and exact parameter coordinates.

TYPE: tuple of int or Fraction

arguments

A candidate positive fixed point and exact parameter coordinates.

TYPE: tuple of int or Fraction

witness

Positive weights for the exact spectral upper bound.

TYPE: tuple of int or Fraction

max_work

Bound on polynomial normalization, coefficient and linear algebra work in exact arithmetic operations. Validation and fraction bit costs are outside this count.

TYPE: int DEFAULT: 65536

fuel

The reference machine step bound per native component evaluation.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
ExactLeastFixedPointGradient

The verified least point, exact implicit Jacobian and measured work.

RAISES DESCRIPTION
ValueError

If an input, identity, signature arity or bound is malformed.

ImplicitRootError

If the positive state or strict contraction certificate fails.

JvpUnsupported

If a checked computation leaves the locally monotone polynomial fragment.

JvpLimit

If normalization, exact evaluation or linear algebra exceeds a bound.

Source code in src/quivers/qiec/least_fixed_points.py
def exact_least_fixed_point_gradient(
    module: QiecModule,
    components: tuple[ComputationId, ...],
    state: tuple[int | Fraction, ...],
    arguments: tuple[int | Fraction, ...],
    witness: tuple[int | Fraction, ...],
    *,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> ExactLeastFixedPointGradient:
    """Verify a source map's least fixed point and differentiate it exactly.

    The component computations are pure Real polynomials in the state
    coordinates followed by the shared parameters. Coefficients of
    state powers, considered as polynomials in the parameters, must be
    strictly positive at the point or structurally zero. The state is
    positive and must be an exact fixed point of the actual source. The
    positive witness establishes a strict componentwise inequality
    between the state Jacobian applied to the witness and the witness.

    This gives a monotone map on the nonnegative orthant and a contraction
    on the order interval from zero to the fixed point. The least fixed
    point is the given state. The strict conditions persist along its
    local regular branch, and the implicit Jacobian is the derivative
    of that branch.

    Parameters
    ----------
    module : QiecModule
        The checked ordinary source.
    components : tuple of ComputationId
        The nominal source computations, in state coordinate order.
    state, arguments : tuple of int or Fraction
        A candidate positive fixed point and exact parameter coordinates.
    witness : tuple of int or Fraction
        Positive weights for the exact spectral upper bound.
    max_work : int
        Bound on polynomial normalization, coefficient and linear algebra
        work in exact arithmetic operations. Validation and fraction bit
        costs are outside this count.
    fuel : int
        The reference machine step bound per native component evaluation.

    Returns
    -------
    ExactLeastFixedPointGradient
        The verified least point, exact implicit Jacobian and measured work.

    Raises
    ------
    ValueError
        If an input, identity, signature arity or bound is malformed.
    ImplicitRootError
        If the positive state or strict contraction certificate fails.
    JvpUnsupported
        If a checked computation leaves the locally monotone polynomial fragment.
    JvpLimit
        If normalization, exact evaluation or linear algebra exceeds a bound.
    """
    _validate_limit("max_work", max_work)
    _validate_limit("fuel", fuel)
    dimension = len(components)
    if not dimension or len(state) != dimension or len(witness) != dimension:
        raise ValueError(
            "component, state and witness dimensions must agree and be positive"
        )
    root = tuple(map(_fraction, state))
    point = tuple(map(_fraction, arguments))
    direction = tuple(map(_fraction, witness))
    _bound(*root, *point, *direction)
    if any(value <= 0 for value in root + direction):
        raise ImplicitRootError(
            "the fixed point and its spectral witness must be positive"
        )
    width = dimension + len(point)
    if width * width > max_work:
        raise JvpLimit("least fixed point polynomial work limit exhausted")
    registry = validate_module(module)
    named = {item.id: item for item in module.computations}
    normalizer = _Normalizer(module, width, max_work)
    normalizer.spend(width * width)
    formal = tuple(
        {tuple(int(i == j) for i in range(width)): Fraction(1)} for j in range(width)
    )
    rows = []
    try:
        for component, expected in zip(components, root, strict=True):
            item = named.get(component)
            if item is None or len(item.parameters) != width:
                raise ValueError(
                    "each component identity and positional signature must match the map"
                )
            normalizer.check_source(module, item.name, item.name)
            polynomial = normalizer.call(item, formal, frozenset())
            _check_coefficients(normalizer, polynomial, item.name, dimension, point)
            evaluator = _ReverseEvaluator(module, fuel)
            output = evaluator.run(item, registry, root + point, record=True)
            if output.value != expected:
                raise ImplicitRootError(
                    f"`{item.name}` does not fix the candidate state"
                )
            rows.append(evaluator.gradient(output, width))
        jacobian = tuple(row[:dimension] for row in rows)
        normalized = []
        normalizer.spend(dimension * (2 * dimension + 1))
        for row, weight in zip(jacobian, direction, strict=True):
            if any(value < 0 for value in row):
                raise ImplicitRootError(
                    "the state Jacobian violates certified monotonicity"
                )
            ratio = (
                sum((a * v for a, v in zip(row, direction, strict=True)), Fraction())
                / weight
            )
            _bound(ratio)
            normalized.append(ratio)
        spectral_bound = max(normalized)
        if spectral_bound >= 1:
            raise ImplicitRootError(
                "the state Jacobian does not strictly contract the positive witness"
            )
        gradient = _solve(normalizer, jacobian, tuple(row[dimension:] for row in rows))
    except PolynomialLawUnsupported as error:
        raise JvpUnsupported(str(error)) from error
    except PolynomialLawLimit as error:
        raise JvpLimit(str(error)) from error
    except RecursionError as error:
        raise JvpLimit(
            "least fixed point polynomial nesting limit exhausted"
        ) from error

    return ExactLeastFixedPointGradient(
        components,
        root,
        point,
        gradient,
        jacobian,
        spectral_bound,
        max_work - normalizer.remaining,
    )

Checkpointed scalar iterations

exact_checkpointed_gradient differentiates a finite sequence of deterministic scalar transitions. Each transition reads the current state and the same parameters. Replay recovers a segment's midpoint state, reverses the later segment, and uses the saved initial state to reverse the earlier segment.

For \(n\) transitions, bisection saves at most \(1+\lceil\log_2 n\rceil\) states when \(n>0\). It builds and uses one local reverse graph at a time. Each transition is reversed once and replayed at most once per level. The result counts both kinds of evaluations and the peak number of saved states. The reported derivative is for the specified finite iteration.

from quivers.dsl import Compiler, parse
from quivers.qiec import exact_checkpointed_gradient

source = """
define advance(state : Real, rate : Real, offset : Real) : Real !{} =
    return state * rate + offset
"""
module = Compiler(parse(source), module_name="scalar-checkpoint-example").qiec_module
assert module is not None
result = exact_checkpointed_gradient(module, "advance", 3, (1, 2), 8)
assert (result.value, result.gradient) == (19, (1, 80, 8))
assert (result.replay_steps, result.reverse_steps, result.peak_saved_states) == (12, 8, 4)

Authored checkpoint requests

An authored checkpoint request names a scalar iteration and its transition. The checker counts the calls in the compiled iteration. Every call must use the named transition, pass the preceding result as its first argument, and pass the original shared parameters in order. The result must be the final state. An iteration that returns its initial state has zero steps.

from quivers.dsl import Compiler, parse

source = """
define advance(state : Real, rate : Real, offset : Real) : Real !{} =
    return state * rate + offset

define iterate(state : Real, rate : Real, offset : Real) : Real !{} =
    let first <- advance(state, rate, offset)
    let second <- advance(first, rate, offset)
    advance(second, rate, offset)

effect_law iteration_gradient [primal=iterate, checkpoint=advance]
"""
compiler = Compiler(parse(source))
proof = compiler.authored_checkpointed_gradient("iteration_gradient", (3, 1, 2))
assert proof.steps == 3
assert (proof.sweep.value, proof.sweep.gradient) == (9, (1, 15, 3))
assert (proof.sweep.replay_steps, proof.sweep.reverse_steps) == (2, 3)
assert proof.sweep.peak_saved_states == 3

Each checked call has the form \(s_{i+1}=T(s_i,\theta)\), so induction identifies the iteration's returned scalar with \(T\) applied \(n\) times. The request differentiates this finite composition using the same regularity checks as exact_checkpointed_gradient. It counts evaluations and saved scalar states in the sweep. Those counts exclude checking the source, the size of exact numbers, and the local reverse graph within one transition. The certificate concerns the exact returned scalar and its gradient.

checkpointing

Checkpointed reverse differentiation of scalar iterations.

ExactCheckpointedGradient dataclass

ExactCheckpointedGradient(value: Fraction, gradient: tuple[Fraction, ...], replay_steps: int, reverse_steps: int, peak_saved_states: int)

A finite iteration's output, exact gradient, and replay counts.

PARAMETER DESCRIPTION
value

The state after all transitions.

TYPE: Fraction

gradient

Derivatives with respect to the initial state and shared parameters.

TYPE: tuple[Fraction, ...]

replay_steps

Transitions executed for a primal checkpoint without a reverse graph.

TYPE: int

reverse_steps

Transitions executed with their reverse graph, once per iterate.

TYPE: int

peak_saved_states

The maximum number of simultaneously saved state checkpoints, including the initial state for a nonempty iteration.

TYPE: int

semantics property

Report the exact finite composition that was differentiated.

RETURNS DESCRIPTION
DerivativeSemantics

The iteration count, or exact identity for the empty iteration.

ExactCheckpointCertificate dataclass

ExactCheckpointCertificate(primal: ComputationId, transition: ComputationId, arguments: tuple[Fraction, ...], steps: int, sweep: ExactCheckpointedGradient)

The checkpointed derivative of a verified source iteration.

PARAMETER DESCRIPTION
primal

The checked iteration and the computation it calls at each step.

TYPE: ComputationId

transition

The checked iteration and the computation it calls at each step.

TYPE: ComputationId

arguments

The initial state followed by the shared parameters.

TYPE: tuple[Fraction, ...]

steps

The count derived from the checked iteration body.

TYPE: int

sweep

The exact final value, ordered gradient and measured replay counts.

TYPE: ExactCheckpointedGradient

exact_checkpointed_gradient

exact_checkpointed_gradient(module: QiecModule, computation: str, initial: int | Fraction, arguments: tuple[int | Fraction, ...], steps: int, *, max_work: int = 65536, fuel: int = 65536) -> ExactCheckpointedGradient

Differentiate a finite scalar iteration using deterministic replay.

The transition takes its current state followed by the parameters shared across all steps. It runs in the closed regular scalar fragment of :func:~quivers.qiec.differentiation.exact_gradient. The schedule saves a midpoint state, reverses the second segment, and restores the earlier state to reverse the first segment. Every visited transition must satisfy the derivative fragment's strict arithmetic and branch conditions, including transitions with zero output cotangent.

For positive steps, the schedule saves at most one state per bisection level plus the initial state. Each step is differentiated once and may also replay once at each containing bisection level. These counts are in units of transitions and saved scalar states.

PARAMETER DESCRIPTION
module

The checked module declaring the transition.

TYPE: QiecModule

computation

The name of the scalar transition.

TYPE: str

initial

The initial state of the iteration.

TYPE: int or Fraction

arguments

The shared parameters in positional order.

TYPE: tuple[int or Fraction, ...]

steps

The nonnegative number of iterations.

TYPE: int

max_work

The maximum number of transition evaluations, including replays.

TYPE: int DEFAULT: 65536

fuel

The maximum reference machine steps per transition.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
ExactCheckpointedGradient

The output, ordered gradient and measured replay counts.

RAISES DESCRIPTION
JvpUnsupported

If the transition is outside the closed scalar fragment.

JvpBoundaryError

If an input-dependent comparison is at equality.

JvpLimit

If bounded work, fuel or arithmetic is exhausted.

ValueError

If an argument or resource limit is malformed.

Source code in src/quivers/qiec/checkpointing.py
def exact_checkpointed_gradient(
    module: QiecModule,
    computation: str,
    initial: int | Fraction,
    arguments: tuple[int | Fraction, ...],
    steps: int,
    *,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> ExactCheckpointedGradient:
    """Differentiate a finite scalar iteration using deterministic replay.

    The transition takes its current state followed by the parameters
    shared across all steps. It runs in the closed regular scalar fragment
    of :func:`~quivers.qiec.differentiation.exact_gradient`. The schedule
    saves a midpoint state, reverses the second segment, and restores the
    earlier state to reverse the first segment. Every visited transition
    must satisfy the derivative fragment's strict arithmetic and branch
    conditions, including transitions with zero output cotangent.

    For positive ``steps``, the schedule saves at most one state per
    bisection level plus the initial state. Each step is differentiated
    once and may also replay once at each containing bisection level.
    These counts are in units of transitions and saved scalar states.

    Parameters
    ----------
    module : QiecModule
        The checked module declaring the transition.
    computation : str
        The name of the scalar transition.
    initial : int or Fraction
        The initial state of the iteration.
    arguments : tuple[int or Fraction, ...]
        The shared parameters in positional order.
    steps : int
        The nonnegative number of iterations.
    max_work : int
        The maximum number of transition evaluations, including replays.
    fuel : int
        The maximum reference machine steps per transition.

    Returns
    -------
    ExactCheckpointedGradient
        The output, ordered gradient and measured replay counts.

    Raises
    ------
    JvpUnsupported
        If the transition is outside the closed scalar fragment.
    JvpBoundaryError
        If an input-dependent comparison is at equality.
    JvpLimit
        If bounded work, fuel or arithmetic is exhausted.
    ValueError
        If an argument or resource limit is malformed.
    """
    if type(steps) is not int or steps < 0:
        raise ValueError("steps must be a nonnegative integer")
    if type(max_work) is not int or max_work < 1:
        raise ValueError("max_work must be a positive integer")
    registry, transition = _prepare_scalar(module, computation, fuel)
    if len(transition.parameters) != len(arguments) + 1:
        raise ValueError("state and arguments must match the transition's arity")
    state = _fraction(initial)
    parameters = tuple(map(_fraction, arguments))
    _bound(state, *parameters)
    if steps == 0:
        return ExactCheckpointedGradient(
            state, (Fraction(1), *((Fraction(),) * len(parameters))), 0, 0, 0
        )
    if steps > max_work:
        raise JvpLimit("checkpointed gradient transition limit exhausted")
    sweep = _CheckpointSweep(
        module, transition, registry, state, parameters, fuel, max_work
    )
    return sweep.finish(steps)

exact_normal_checkpointed_gradient

exact_normal_checkpointed_gradient(module: QiecModule, computation: ComputationId, transition: ComputationId, arguments: tuple[int | Fraction, ...], tape: tuple[tuple[_Address, int | Fraction], ...], *, max_work: int = 65536, fuel: int = 65536) -> ExactCheckpointCertificate

Differentiate an authored Normal transition chain at fixed base noise.

Every source call uses the preceding state and the original shared arguments. Its transition starts with one direct scalar Normal draw and continues with local regular scalar code. Each coordinate in the immutable replay tape is held constant. Location and positive scale are recomputed from the current arguments, including the checkpointed state. The result differentiates that pointwise finite composition.

The tape uses the full canonical draw addresses of the named entry run directly. The sweep checks the reached address on every replay. It keeps at most one saved state per bisection level and reverses one local graph at a time. The read-only input tape and the checked source already have one entry per step and are outside the saved-state count.

PARAMETER DESCRIPTION
module

The checked source owning both computations.

TYPE: QiecModule

computation

The iteration and its sole nominal transition.

TYPE: ComputationId

transition

The iteration and its sole nominal transition.

TYPE: ComputationId

arguments

The initial state followed by the shared real parameters.

TYPE: tuple[int or Fraction, ...]

tape

One exact pair of canonical address and fixed noise per call, in original forward order.

TYPE: tuple

max_work

The maximum number of local transition evaluations.

TYPE: int DEFAULT: 65536

fuel

The reference machine step limit for each local evaluation.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
ExactCheckpointCertificate

The actual source identities, exact point and sweep.

RAISES DESCRIPTION
ValueError

If an identity, exact input, tape length or bound is malformed.

JvpUnsupported

If the source, a tape address or a reached operation is unsupported.

JvpBoundaryError

If a reached decision is not locally stable at the fixed noise.

JvpLimit

If the work, step or arithmetic bound is exhausted.

Source code in src/quivers/qiec/checkpointing.py
def exact_normal_checkpointed_gradient(
    module: QiecModule,
    computation: ComputationId,
    transition: ComputationId,
    arguments: tuple[int | Fraction, ...],
    tape: tuple[tuple[_Address, int | Fraction], ...],
    *,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> ExactCheckpointCertificate:
    """Differentiate an authored Normal transition chain at fixed base noise.

    Every source call uses the preceding state and the original shared
    arguments. Its transition starts with one direct scalar Normal draw
    and continues with local regular scalar code. Each coordinate in the
    immutable replay tape is held constant. Location and positive scale
    are recomputed from the current arguments, including the checkpointed
    state. The result differentiates that pointwise finite composition.

    The tape uses the full canonical draw addresses of the named entry
    run directly. The sweep checks the reached address on every replay.
    It keeps at most one saved state per bisection level and reverses one
    local graph at a time. The read-only input tape and the checked source
    already have one entry per step and are outside the saved-state count.

    Parameters
    ----------
    module : QiecModule
        The checked source owning both computations.
    computation, transition : ComputationId
        The iteration and its sole nominal transition.
    arguments : tuple[int or Fraction, ...]
        The initial state followed by the shared real parameters.
    tape : tuple
        One exact pair of canonical address and fixed noise per call,
        in original forward order.
    max_work : int
        The maximum number of local transition evaluations.
    fuel : int
        The reference machine step limit for each local evaluation.

    Returns
    -------
    ExactCheckpointCertificate
        The actual source identities, exact point and sweep.

    Raises
    ------
    ValueError
        If an identity, exact input, tape length or bound is malformed.
    JvpUnsupported
        If the source, a tape address or a reached operation is unsupported.
    JvpBoundaryError
        If a reached decision is not locally stable at the fixed noise.
    JvpLimit
        If the work, step or arithmetic bound is exhausted.
    """
    if type(max_work) is not int or max_work < 1:
        raise ValueError("max_work must be a positive integer")
    if type(fuel) is not int or fuel < 1:
        raise ValueError("fuel must be a positive integer")
    if type(tape) is not tuple:
        raise ValueError("Normal checkpoint replay requires an immutable tuple tape")
    registry, owner = _random_computation(module, computation, "Normal checkpoint")
    target = next((item for item in module.computations if item.id == transition), None)
    if target is None:
        raise ValueError(f"unknown Normal checkpoint transition {transition}")
    _check_normal_transition(owner, target)
    steps = _checkpoint_calls(owner, target)
    if not steps:
        raise JvpUnsupported("Normal checkpoint replay needs at least one transition")
    if len(arguments) != len(owner.parameters):
        raise ValueError("arguments must match the Normal checkpoint iteration's arity")
    if len(tape) != steps:
        raise ValueError("Normal checkpoint tape must match the checked chain length")
    if steps > max_work:
        raise JvpLimit("checkpointed gradient transition limit exhausted")
    point = tuple(map(_fraction, arguments))
    _bound(*point)
    # Every Call has the same checked callee and positional locals. The first
    # Call gives the ordinary reference machine those bindings. Its dynamic
    # address contribution is the callee and original one-based serial.
    first = owner.body.first if isinstance(owner.body, Bind) else owner.body
    assert isinstance(first, Call)
    sweep = _NormalCheckpointSweep(
        module,
        owner.with_(body=first),
        registry,
        point[0],
        point[1:],
        tape,
        fuel,
        max_work,
    )
    return ExactCheckpointCertificate(
        owner.id, target.id, point, steps, sweep.finish(steps)
    )

Superposition, repeated draws, and completion

In superposed, the measure at x is \(p\,\mathcal N(\mu_a,1)+(1-p)\,\mathcal N(\mu_b,1)\). Replay at \(x\) scores the logarithm of that sum and records one Random address. In two_shots, the handler evaluates two resumption branches. Each reaches the same source origin with a distinct resumption ordinal. Their replay joint is the product of the two Normal densities. The handler returns the weighted arithmetic mean of the two drawn values.

The last two programs give a product-space completion with different sites. In disjoint, the selector \(z\) determines the sole reached Bernoulli site. Write its conditional mass as \(f_z(x)\) and the selector mass as \(q_z\). completed also draws the inactive site from the normalized law \(f_{1-z}(y)\). For each selector and active result, summing its extended mass \(q_z f_z(x) f_{1-z}(y)\) over \(y\) gives \(q_z f_z(x)\). The returned value and its marginal score under the selector are preserved. The completed program has three realized addresses where the disjoint program has two. An auxiliary factor with total mass other than one changes the marginal by that factor.

object UnitInput : FinSet 1
object Output : Real 1

instance random : Random

effect Choice
    split : Real -> Bool

instance choice : Choice

handler both for Choice : Real -> Real [coverage=total, forwards=none, implementation=authored]
    split(probability : Real) resumes omega =>
        let first <- resume(true)
        let second <- resume(false)
        return probability * first + (1.0 - probability) * second

define choose_mean(first : Bool, left : Real, right : Real) : Real !{} =
    if first then
        return left
    else
        return right

define draw_twice(p : Real, left : Real, right : Real) : Real !{random} =
    handle choice with both in
        let first <- perform choice.split(p)
        let mean <- choose_mean(first, left, right)
        perform random.sample[Real](site("x"), Normal(loc=mean, scale=1.0))

define lift_truth(flag : Bool) : Real !{} =
    if flag then
        return 1.0
    else
        return 0.0

define selected_draw(first : Bool, p_left : Real, p_right : Real) : Real !{random} =
    if first then
        let value <- perform random.sample[Bool](site("left"), Bernoulli(probs=p_left))
        lift_truth(value)
    else
        let value <- perform random.sample[Bool](site("right"), Bernoulli(probs=p_right))
        lift_truth(value)

define selected_value(first : Bool, left : Bool, right : Bool) : Real !{} =
    if first then
        lift_truth(left)
    else
        lift_truth(right)

define draw_mixture(p : Real, mu_a : Real, mu_b : Real) : Real !{random} =
    let weights = [p, 1.0 - p]
    let locations = [mu_a, mu_b]
    perform random.sample[Real](site("x"), MixtureNormal(weights=weights, loc=locations, scale=[1.0, 1.0]))

program superposed(p : Real, mu_a : Real, mu_b : Real) : UnitInput -> Output
    let x <- draw_mixture(p, mu_a, mu_b)
    return x

program two_shots(p : Real, mu_a : Real, mu_b : Real) : UnitInput -> Output
    let x <- draw_twice(p, mu_a, mu_b)
    return x

program disjoint(p : Real, p_left : Real, p_right : Real) : UnitInput -> Output
    let first <- sample Bernoulli(probs=p)
    let x <- selected_draw(first, p_left, p_right)
    return x

program completed(p : Real, p_left : Real, p_right : Real) : UnitInput -> Output
    let first <- sample Bernoulli(probs=p)
    let left <- sample Bernoulli(probs=p_left)
    let right <- sample Bernoulli(probs=p_right)
    let x <- selected_value(first, left, right)
    return x

export superposed
export two_shots
export disjoint
export completed

effects

Typed effect interfaces, lexical rows, and handler signatures for QIEC.

EMPTY_ROW module-attribute

EMPTY_ROW = EffectRow()

The row of a computation that performs no effects.

RowVariable didactic-model

RowVariable(*, name: str, identity: RowVariableId = field(opaque=True, extras=OPAQUE_BY_VALUE), lacks: tuple[EffectInstanceId, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The open tail of an effect row, with the instances it excludes.

PARAMETER DESCRIPTION
name

Display name, used in diagnostics only. Two variables with the same identity and different names are the same variable.

TYPE: str

identity

Stable identity. Equality and hashing are taken from this rather than from name, so renaming for readability cannot silently split one variable into two.

TYPE: RowVariableId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

lacks

Instances the tail is proven not to contain. Sorted at construction, so equality is insensitive to the order given.

TYPE: tuple[EffectInstanceId, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

proves_lacks

proves_lacks(instance: EffectInstanceId) -> bool

Whether this tail is known not to contain instance.

PARAMETER DESCRIPTION
instance

The lexical instance to test.

TYPE: EffectInstanceId

RETURNS DESCRIPTION
bool

True when the constraint is carried, which is what permits an explicit entry for instance to sit beside this tail.

Source code in src/quivers/qiec/effects.py
def proves_lacks(self, instance: EffectInstanceId) -> bool:
    """Whether this tail is known not to contain `instance`.

    Parameters
    ----------
    instance : EffectInstanceId
        The lexical instance to test.

    Returns
    -------
    bool
        True when the constraint is carried, which is what permits an
        explicit entry for `instance` to sit beside this tail.
    """
    return instance in self.lacks

merge

merge(other: RowVariable) -> RowVariable

Unify two occurrences, accumulating their lacks constraints.

PARAMETER DESCRIPTION
other

Another occurrence of the same variable.

TYPE: RowVariable

RETURNS DESCRIPTION
RowVariable

One variable carrying the union of both constraint sets, which is sound because each occurrence's constraints hold of the single variable they both name.

RAISES DESCRIPTION
ValueError

If the two variables have different identities, and so are not occurrences of one variable at all.

Source code in src/quivers/qiec/effects.py
def merge(self, other: RowVariable) -> RowVariable:
    """Unify two occurrences, accumulating their lacks constraints.

    Parameters
    ----------
    other : RowVariable
        Another occurrence of the same variable.

    Returns
    -------
    RowVariable
        One variable carrying the union of both constraint sets, which
        is sound because each occurrence's constraints hold of the
        single variable they both name.

    Raises
    ------
    ValueError
        If the two variables have different identities, and so are not
        occurrences of one variable at all.
    """
    if self.identity != other.identity:
        raise ValueError("cannot unify distinct row variables")
    merged = tuple(sorted(set((*self.lacks, *other.lacks)), key=str))
    return RowVariable(name=self.name, identity=self.identity, lacks=merged)

with_lacks

with_lacks(instances: tuple[EffectInstanceId, ...]) -> RowVariable

Return this variable with further instances excluded.

PARAMETER DESCRIPTION
instances

Instances to add to the constraint set. Instances already excluded are absorbed rather than repeated.

TYPE: tuple[EffectInstanceId, ...]

RETURNS DESCRIPTION
RowVariable

A variable of the same identity carrying the wider constraint.

Source code in src/quivers/qiec/effects.py
def with_lacks(self, instances: tuple[EffectInstanceId, ...]) -> RowVariable:
    """Return this variable with further instances excluded.

    Parameters
    ----------
    instances : tuple[EffectInstanceId, ...]
        Instances to add to the constraint set. Instances already
        excluded are absorbed rather than repeated.

    Returns
    -------
    RowVariable
        A variable of the same identity carrying the wider constraint.
    """
    merged = tuple(sorted(set((*self.lacks, *instances)), key=str))
    return RowVariable(name=self.name, identity=self.identity, lacks=merged)

RowEntry didactic-model

RowEntry(*, instance: EffectInstanceId = field(opaque=True, extras=OPAQUE_BY_VALUE), effect: EffectRef = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One lexical effect instance and the interface it implements.

PARAMETER DESCRIPTION
instance

The lexical instance. Two instances of one interface stay distinct, so this rather than effect is the row's key.

TYPE: EffectInstanceId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

effect

The saturated interface application the instance implements.

TYPE: EffectRef DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

EffectRow didactic-model

EffectRow(*, entries: tuple[RowEntry, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), tail: RowVariable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A finite map from lexical instance IDs to interfaces plus a tail.

Entries are sorted by stable identifier at construction time, so row equality is insensitive to source order. Two instances of the same interface remain distinct entries.

PARAMETER DESCRIPTION
entries

The instances the row names, each with its interface; any order is accepted and normalized.

TYPE: tuple[RowEntry, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

tail

A row variable standing for further entries, or None for a closed row. An open row's tail must prove it lacks every explicit entry.

TYPE: RowVariable | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

lookup

lookup(instance: EffectInstanceId) -> EffectRef | None

The interface an instance implements in this row.

PARAMETER DESCRIPTION
instance

The lexical instance to resolve.

TYPE: EffectInstanceId

RETURNS DESCRIPTION
EffectRef or None

The interface when the row carries the instance explicitly, and None otherwise. An open tail is not consulted, so None means absent from the explicit entries rather than absent from every instantiation of the row.

Source code in src/quivers/qiec/effects.py
def lookup(self, instance: EffectInstanceId) -> EffectRef | None:
    """The interface an instance implements in this row.

    Parameters
    ----------
    instance : EffectInstanceId
        The lexical instance to resolve.

    Returns
    -------
    EffectRef or None
        The interface when the row carries the instance explicitly,
        and None otherwise. An open tail is not consulted, so None
        means absent from the explicit entries rather than absent
        from every instantiation of the row.
    """
    return next(
        (entry.effect for entry in self.entries if entry.instance == instance),
        None,
    )

contains

contains(instance: EffectInstanceId) -> bool

Whether the row carries an explicit entry for an instance.

PARAMETER DESCRIPTION
instance

The lexical instance to test.

TYPE: EffectInstanceId

RETURNS DESCRIPTION
bool

True when an explicit entry names the instance.

Source code in src/quivers/qiec/effects.py
def contains(self, instance: EffectInstanceId) -> bool:
    """Whether the row carries an explicit entry for an instance.

    Parameters
    ----------
    instance : EffectInstanceId
        The lexical instance to test.

    Returns
    -------
    bool
        True when an explicit entry names the instance.
    """
    return self.lookup(instance) is not None

add

add(entry: RowEntry) -> EffectRow

Return this row extended with one entry.

PARAMETER DESCRIPTION
entry

The instance and interface to add. Re-adding an entry the row already carries returns the row unchanged, so the operation is idempotent.

TYPE: RowEntry

RETURNS DESCRIPTION
EffectRow

The extended row. When the row is open, its tail gains a lacks constraint for the new instance, which keeps the invariant model validation enforces.

RAISES DESCRIPTION
ValueError

If the row already binds this instance to a different interface, since one lexical instance implements one interface.

Source code in src/quivers/qiec/effects.py
def add(self, entry: RowEntry) -> EffectRow:
    """Return this row extended with one entry.

    Parameters
    ----------
    entry : RowEntry
        The instance and interface to add. Re-adding an entry the row
        already carries returns the row unchanged, so the operation is
        idempotent.

    Returns
    -------
    EffectRow
        The extended row. When the row is open, its tail gains a lacks
        constraint for the new instance, which keeps the invariant
        model validation enforces.

    Raises
    ------
    ValueError
        If the row already binds this instance to a different
        interface, since one lexical instance implements one
        interface.
    """
    existing = self.lookup(entry.instance)
    if existing is not None and existing != entry.effect:
        raise ValueError("one lexical instance cannot implement two interfaces")
    if existing is not None:
        return self
    tail = self.tail
    if tail is not None and not tail.proves_lacks(entry.instance):
        tail = tail.with_lacks((entry.instance,))
    return EffectRow(entries=(*self.entries, entry), tail=tail)

without

without(instance: EffectInstanceId) -> EffectRow

Return this row with one instance discharged.

PARAMETER DESCRIPTION
instance

The lexical instance to remove, as a handler does when it handles every operation of that instance.

TYPE: EffectInstanceId

RETURNS DESCRIPTION
EffectRow

The row without that entry, keeping the tail as it was.

RAISES DESCRIPTION
KeyError

If the row carries no explicit entry for the instance. This is an error rather than a no-op because discharging an effect the row never had indicates the caller has the wrong row.

Source code in src/quivers/qiec/effects.py
def without(self, instance: EffectInstanceId) -> EffectRow:
    """Return this row with one instance discharged.

    Parameters
    ----------
    instance : EffectInstanceId
        The lexical instance to remove, as a handler does when it
        handles every operation of that instance.

    Returns
    -------
    EffectRow
        The row without that entry, keeping the tail as it was.

    Raises
    ------
    KeyError
        If the row carries no explicit entry for the instance. This
        is an error rather than a no-op because discharging an effect
        the row never had indicates the caller has the wrong row.
    """
    if not self.contains(instance):
        raise KeyError(str(instance))
    return EffectRow(
        entries=tuple(
            entry for entry in self.entries if entry.instance != instance
        ),
        tail=self.tail,
    )

union

union(other: EffectRow) -> EffectRow

Union two rows, preserving a compatible open tail.

PARAMETER DESCRIPTION
other

The row to merge in.

TYPE: EffectRow

RETURNS DESCRIPTION
EffectRow

A row carrying every entry of both. When both are open their tails are merged, and the surviving tail is constrained to lack every explicit instance on either side.

RAISES DESCRIPTION
ValueError

If the two rows bind one instance to different interfaces, or if their tails are distinct variables and so cannot merge.

Source code in src/quivers/qiec/effects.py
def union(self, other: EffectRow) -> EffectRow:
    """Union two rows, preserving a compatible open tail.

    Parameters
    ----------
    other : EffectRow
        The row to merge in.

    Returns
    -------
    EffectRow
        A row carrying every entry of both. When both are open their
        tails are merged, and the surviving tail is constrained to
        lack every explicit instance on either side.

    Raises
    ------
    ValueError
        If the two rows bind one instance to different interfaces, or
        if their tails are distinct variables and so cannot merge.
    """
    if self.tail is not None and other.tail is not None:
        tail = self.tail.merge(other.tail)
    else:
        tail = self.tail or other.tail
    if tail is not None:
        tail = tail.with_lacks(
            tuple(entry.instance for entry in (*self.entries, *other.entries))
        )
    result = EffectRow(entries=self.entries, tail=tail)
    for entry in other.entries:
        result = result.add(entry)
    return result

RowSubstitution didactic-model

RowSubstitution(*, bindings: tuple[tuple[RowVariableId, EffectRow], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A finite, occurs-checked substitution for stable row variables.

PARAMETER DESCRIPTION
bindings

What each row variable stands for. At most one binding per variable, and no binding whose row is tailed by the variable it replaces.

TYPE: tuple[tuple[RowVariableId, EffectRow], ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

lookup

lookup(variable: RowVariable) -> EffectRow | None

The row a variable stands for under this substitution.

PARAMETER DESCRIPTION
variable

The variable to resolve, matched on its identity rather than its display name.

TYPE: RowVariable

RETURNS DESCRIPTION
EffectRow or None

The bound row, or None when the variable is unbound and so remains an open tail.

Source code in src/quivers/qiec/effects.py
def lookup(self, variable: RowVariable) -> EffectRow | None:
    """The row a variable stands for under this substitution.

    Parameters
    ----------
    variable : RowVariable
        The variable to resolve, matched on its identity rather than
        its display name.

    Returns
    -------
    EffectRow or None
        The bound row, or None when the variable is unbound and so
        remains an open tail.
    """
    return next(
        (row for identity, row in self.bindings if identity == variable.identity),
        None,
    )

apply

apply(row: EffectRow) -> EffectRow

Replace this row's tail, and any tail it resolves to.

PARAMETER DESCRIPTION
row

The row to substitute into. A closed row is returned as is.

TYPE: EffectRow

RETURNS DESCRIPTION
EffectRow

The row with its tail resolved as far as the bindings reach.

RAISES DESCRIPTION
ValueError

If the bindings are cyclic, or if resolving a tail would introduce an instance that tail was proven to lack.

Source code in src/quivers/qiec/effects.py
def apply(self, row: EffectRow) -> EffectRow:
    """Replace this row's tail, and any tail it resolves to.

    Parameters
    ----------
    row : EffectRow
        The row to substitute into. A closed row is returned as is.

    Returns
    -------
    EffectRow
        The row with its tail resolved as far as the bindings reach.

    Raises
    ------
    ValueError
        If the bindings are cyclic, or if resolving a tail would
        introduce an instance that tail was proven to lack.
    """
    return self._apply(row, frozenset())

RowUnification didactic-model

RowUnification(*, row: EffectRow = field(opaque=True, extras=OPAQUE_BY_VALUE), substitution: RowSubstitution = field(default=RowSubstitution(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The common row two rows unify to, and how their tails were bound.

PARAMETER DESCRIPTION
row

The unified row.

TYPE: EffectRow DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

substitution

The bindings that carry each input row to row. Empty when the rows already agreed.

TYPE: RowSubstitution DEFAULT: field(default=RowSubstitution(), opaque=True, extras=OPAQUE_BY_VALUE)

ComputationType didactic-model

ComputationType(*, effects: EffectRow = field(opaque=True, extras=OPAQUE_BY_VALUE), result: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The type of a computation: its effect row and result type.

PARAMETER DESCRIPTION
effects

The row of effect instances the computation may perform.

TYPE: EffectRow DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

result

The type of the value it returns.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

ArgumentDef didactic-model

ArgumentDef(*, name: str, type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One named, typed value argument of an operation.

PARAMETER DESCRIPTION
name

The argument's display name.

TYPE: str

type

The argument's type, which may mention the operation's telescope.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

OperationDef didactic-model

OperationDef(*, id: OperationId = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str, telescope: Telescope = field(opaque=True, extras=OPAQUE_BY_VALUE), arguments: tuple[ArgumentDef, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), result_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One result-indexed request constructor in an effect interface.

PARAMETER DESCRIPTION
id

Stable identity, derived from the owning effect and this operation's name.

TYPE: OperationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

name

Source name, as written in the effect declaration.

TYPE: str

telescope

Static binders this operation introduces on top of the interface's own. They may not shadow the interface binders.

TYPE: Telescope DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

arguments

Value arguments the request carries, named uniquely.

TYPE: tuple[ArgumentDef, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

result_type

What resuming the request supplies, possibly mentioning the binders above.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

EffectDef didactic-model

EffectDef(*, ref: EffectRef = field(opaque=True, extras=OPAQUE_BY_VALUE), telescope: Telescope = field(opaque=True, extras=OPAQUE_BY_VALUE), operations: tuple[OperationDef, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

An operation interface.

Identity is nominal: the declaration is fixed by its module and its own name, carried in ref. Static arguments distinguish applications of the interface without changing which declaration they apply.

PARAMETER DESCRIPTION
ref

The declaration's own reference, which must be unsaturated: a declaration names the interface, and applying it is what supplies arguments.

TYPE: EffectRef DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

telescope

Static binders the interface takes.

TYPE: Telescope DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

operations

The declared operations, unique by both identity and name.

TYPE: tuple[OperationDef, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

apply

apply(arguments: tuple[StaticArgument, ...]) -> EffectRef

Instantiate the interface telescope as a concrete effect.

PARAMETER DESCRIPTION
arguments

Static arguments to saturate the telescope with.

TYPE: tuple[StaticArgument, ...]

RETURNS DESCRIPTION
EffectRef

The saturated application, carrying this declaration's identity together with the arguments given.

RAISES DESCRIPTION
TypeError

If an argument is of the wrong static class for its binder.

ValueError

If the argument count does not match the telescope, or an argument is ill-kinded.

Source code in src/quivers/qiec/effects.py
def apply(self, arguments: tuple[StaticArgument, ...]) -> EffectRef:
    """Instantiate the interface telescope as a concrete effect.

    Parameters
    ----------
    arguments : tuple[StaticArgument, ...]
        Static arguments to saturate the telescope with.

    Returns
    -------
    EffectRef
        The saturated application, carrying this declaration's
        identity together with the arguments given.

    Raises
    ------
    TypeError
        If an argument is of the wrong static class for its binder.
    ValueError
        If the argument count does not match the telescope, or an
        argument is ill-kinded.
    """
    check_static_arguments(self.telescope, arguments)
    return EffectRef(
        id=self.ref.id,
        name=self.ref.name,
        arguments=arguments,
    )

matches

matches(effect: EffectRef) -> bool

Whether a concrete effect is a well-kinded application here.

PARAMETER DESCRIPTION
effect

The saturated application to test.

TYPE: EffectRef

RETURNS DESCRIPTION
bool

True when effect names this declaration and its arguments saturate the telescope. False rather than raising, so callers can test candidates; use apply when the reason matters.

Source code in src/quivers/qiec/effects.py
def matches(self, effect: EffectRef) -> bool:
    """Whether a concrete effect is a well-kinded application here.

    Parameters
    ----------
    effect : EffectRef
        The saturated application to test.

    Returns
    -------
    bool
        True when `effect` names this declaration and its arguments
        saturate the telescope. False rather than raising, so callers
        can test candidates; use `apply` when the reason matters.
    """
    if effect.id != self.ref.id:
        return False
    try:
        self.apply(effect.arguments)
    except TypeError, ValueError:
        return False
    return True

operation

operation(operation: OperationId) -> OperationDef

The declared operation with a given identity.

PARAMETER DESCRIPTION
operation

The identity to resolve.

TYPE: OperationId

RETURNS DESCRIPTION
OperationDef

The matching declaration.

RAISES DESCRIPTION
KeyError

If this interface declares no such operation, which is how a request naming an operation another effect owns is caught.

Source code in src/quivers/qiec/effects.py
def operation(self, operation: OperationId) -> OperationDef:
    """The declared operation with a given identity.

    Parameters
    ----------
    operation : OperationId
        The identity to resolve.

    Returns
    -------
    OperationDef
        The matching declaration.

    Raises
    ------
    KeyError
        If this interface declares no such operation, which is how a
        request naming an operation another effect owns is caught.
    """
    for candidate in self.operations:
        if candidate.id == operation:
            return candidate
    raise KeyError(str(operation))

ResumptionGrade

Bases: str, Enum

Quantitative use allowed for a handler-clause resumption.

ResumptionInterval didactic-model

ResumptionInterval(*, minimum: int = field(opaque=True, extras=OPAQUE_BY_VALUE), maximum: int = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A finite multi-shot bound on one normally completing native token.

PARAMETER DESCRIPTION
minimum

Inclusive counts. The maximum is at least two. The existing zero and one-shot grades retain their canonical representations.

TYPE: int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

maximum

Inclusive counts. The maximum is at least two. The existing zero and one-shot grades retain their canonical representations.

TYPE: int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

value property

value: str

The canonical display of the two inclusive bounds.

RETURNS DESCRIPTION
str

The textual grade label used in native traces.

HandlerClauseDef didactic-model

HandlerClauseDef(*, operation: OperationId = field(opaque=True, extras=OPAQUE_BY_VALUE), grade: ResumptionGrade | ResumptionInterval = field(opaque=True, extras=OPAQUE_BY_VALUE), parameters: tuple[Local, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), body: Computation | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One operation a handler covers, and how it may resume.

PARAMETER DESCRIPTION
operation

The operation this clause handles.

TYPE: OperationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

grade

How often the clause may invoke its continuation. The grade is part of the clause contract and is checked against the body.

TYPE: ResumptionGrade or ResumptionInterval DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

parameters

Binders for the operation's value arguments, in declaration order. The body refers to the request's arguments through these.

TYPE: tuple[Local, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

body

What the clause does. None is a signature rather than an implementation, and is legal only for a handler whose implementation is supplied at runtime. An absent body never means "look up a callback": the declaration has to say so.

TYPE: Computation or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

HandlerReturnClauseDef didactic-model

HandlerReturnClauseDef(*, binder: Local = field(opaque=True, extras=OPAQUE_BY_VALUE), body: Computation = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

What a handler does with a value its computation returns.

Separate from an operation clause because it answers a different thing: an operation clause responds to a request and may resume, while this responds to the computation finishing and has no continuation to invoke.

PARAMETER DESCRIPTION
binder

Names the returned value inside the body.

TYPE: Local DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

body

What the handler produces from it. There is no signature-only form: a handler that answers returns at all has to say how.

TYPE: Computation DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

HandlerDef didactic-model

HandlerDef(*, id: HandlerId = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str, effect: EffectRef = field(opaque=True, extras=OPAQUE_BY_VALUE), clauses: tuple[HandlerClauseDef, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), input_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), output_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), introduced: EffectRow = field(default=EMPTY_ROW, opaque=True, extras=OPAQUE_BY_VALUE), total: bool = True, forwards_unknown: bool = False, telescope: Telescope = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), return_clause: HandlerReturnClauseDef | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), implementation: Literal['authored', 'foreign'] = 'foreign', parameters: tuple[Local, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), foreign: ForeignSemantics | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Serializable type-and-coverage signature for a handler.

An authored handler carries its clause bodies in the stable core; a foreign handler's bodies are runtime attachments keyed by id.

PARAMETER DESCRIPTION
id

The handler's stable identity.

TYPE: HandlerId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

name

The handler's display name.

TYPE: str

effect

The interface application the handler handles.

TYPE: EffectRef DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

clauses

One clause per operation the handler covers.

TYPE: tuple[HandlerClauseDef, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

input_type

The result type of the computation the handler accepts.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

output_type

The type of the handler's answer.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

introduced

The effects the handler's own clauses perform, which the residual row of a handled computation gains.

TYPE: EffectRow DEFAULT: field(default=EMPTY_ROW, opaque=True, extras=OPAQUE_BY_VALUE)

total

Whether the clauses cover every operation of effect.

TYPE: bool DEFAULT: True

forwards_unknown

Whether an operation no clause covers is forwarded outward rather than rejected; incompatible with total.

TYPE: bool DEFAULT: False

telescope

The static parameters the handler abstracts over, in order.

TYPE: Telescope DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

return_clause

How the handler answers the computation's return, or None to return the value unchanged.

TYPE: HandlerReturnClauseDef | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

implementation

"authored" when every clause carries a body, "foreign" when none does and a runtime provider supplies the behavior.

TYPE: Literal['authored', 'foreign'] DEFAULT: 'foreign'

parameters

The handler's parameters, in declaration order: binders whose values are given where the handler is installed, are read by every clause body, and are given anew by each resumption.

TYPE: tuple[Local, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

foreign

What a foreign handler computes, which its runtime provider builds it from, or None for one whose provider is configured by other means. An authored handler's bodies say what it computes.

TYPE: ForeignSemantics | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

clause

clause(operation: OperationId) -> HandlerClauseDef | None

The clause covering an operation, if this handler has one.

PARAMETER DESCRIPTION
operation

The operation to look for.

TYPE: OperationId

RETURNS DESCRIPTION
HandlerClauseDef or None

The clause, or None when the operation is uncovered. For a forwarding handler None means the request passes through rather than that it is an error.

Source code in src/quivers/qiec/effects.py
def clause(self, operation: OperationId) -> HandlerClauseDef | None:
    """The clause covering an operation, if this handler has one.

    Parameters
    ----------
    operation : OperationId
        The operation to look for.

    Returns
    -------
    HandlerClauseDef or None
        The clause, or None when the operation is uncovered. For a
        forwarding handler None means the request passes through
        rather than that it is an error.
    """
    return next(
        (clause for clause in self.clauses if clause.operation == operation),
        None,
    )

EffectRequest didactic-model

EffectRequest(*, instance: EffectInstanceId = field(opaque=True, extras=OPAQUE_BY_VALUE), effect: EffectRef = field(opaque=True, extras=OPAQUE_BY_VALUE), operation: OperationId = field(opaque=True, extras=OPAQUE_BY_VALUE), static_arguments: tuple[StaticArgument, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), arguments: tuple[Value, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), result_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), origin: SiteProvenance = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['effect_request'] = 'effect_request')

Bases: QiecModel

A typed request allocated before filtering or handler dispatch.

PARAMETER DESCRIPTION
instance

The effect instance the request is addressed to.

TYPE: EffectInstanceId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

effect

The instance's interface application.

TYPE: EffectRef DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

operation

The operation requested.

TYPE: OperationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

static_arguments

The operation's telescope instantiation, in binder order.

TYPE: tuple[StaticArgument, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

arguments

The value arguments, one per operation argument.

TYPE: tuple[Value, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

result_type

The type of the value the operation returns under the instantiation.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

origin

Where the request was written and how it was reached.

TYPE: SiteProvenance DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "effect_request".

TYPE: Literal['effect_request'] DEFAULT: 'effect_request'

unify_effect_rows

unify_effect_rows(left: EffectRow, right: EffectRow) -> RowUnification

Unify two rows, returning their common row and tail substitution.

Unification is symmetric and driven by the tails. Two closed rows unify only when already equal. One open row unifies with a closed one by binding its tail to the entries it lacks. Two open rows with distinct tails unify by binding both to a fresh tail carrying every instance either side names.

PARAMETER DESCRIPTION
left

One row to unify.

TYPE: EffectRow

right

The other row. The result does not depend on the order of the two arguments.

TYPE: EffectRow

RETURNS DESCRIPTION
RowUnification

The common row and the substitution taking both inputs to it.

RAISES DESCRIPTION
ValueError

If the rows bind one instance to different interfaces, if two closed rows differ, if an open row carries an entry the closed row lacks, if one side needs an instance the other's tail is proven to lack, or if the computed substitution fails to carry both inputs to the unified row.

Source code in src/quivers/qiec/effects.py
def unify_effect_rows(left: EffectRow, right: EffectRow) -> RowUnification:
    """Unify two rows, returning their common row and tail substitution.

    Unification is symmetric and driven by the tails. Two closed rows
    unify only when already equal. One open row unifies with a closed one
    by binding its tail to the entries it lacks. Two open rows with
    distinct tails unify by binding both to a fresh tail carrying every
    instance either side names.

    Parameters
    ----------
    left : EffectRow
        One row to unify.
    right : EffectRow
        The other row. The result does not depend on the order of the two
        arguments.

    Returns
    -------
    RowUnification
        The common row and the substitution taking both inputs to it.

    Raises
    ------
    ValueError
        If the rows bind one instance to different interfaces, if two
        closed rows differ, if an open row carries an entry the closed
        row lacks, if one side needs an instance the other's tail is
        proven to lack, or if the computed substitution fails to carry
        both inputs to the unified row.
    """
    left_entries = {entry.instance: entry.effect for entry in left.entries}
    right_entries = {entry.instance: entry.effect for entry in right.entries}
    for instance in left_entries.keys() & right_entries.keys():
        if left_entries[instance] != right_entries[instance]:
            raise ValueError("row entries disagree on an effect interface")
    left_only = tuple(
        RowEntry(instance=instance, effect=effect)
        for instance, effect in left_entries.items()
        if instance not in right_entries
    )
    right_only = tuple(
        RowEntry(instance=instance, effect=effect)
        for instance, effect in right_entries.items()
        if instance not in left_entries
    )

    if left.tail is None and right.tail is None:
        if left_only or right_only:
            raise ValueError("closed effect rows do not unify")
        return RowUnification(row=left)

    if left.tail is not None and right.tail is None:
        if left_only:
            raise ValueError("an open row has entries absent from the closed row")
        replacement = EffectRow(entries=right_only)
        substitution = RowSubstitution(bindings=((left.tail.identity, replacement),))
        if substitution.apply(left) != right:
            raise ValueError("row substitution violates a lacks constraint")
        return RowUnification(row=right, substitution=substitution)

    if left.tail is None and right.tail is not None:
        result = unify_effect_rows(right, left)
        return RowUnification(row=result.row, substitution=result.substitution)

    assert left.tail is not None and right.tail is not None
    if left.tail.identity == right.tail.identity:
        if left_only or right_only:
            raise ValueError(
                "two occurrences of one row variable have incompatible entries"
            )
        tail = left.tail.merge(right.tail)
        return RowUnification(row=EffectRow(entries=left.entries, tail=tail))

    if any(entry.instance in left.tail.lacks for entry in right_only):
        raise ValueError("left row lacks an entry required by the right row")
    if any(entry.instance in right.tail.lacks for entry in left_only):
        raise ValueError("right row lacks an entry required by the left row")
    all_instances = tuple((*left_entries.keys(), *right_entries.keys()))
    fresh_identity = RowVariableId.derive(
        "unify",
        *sorted((left.tail.identity, right.tail.identity), key=str),
        *sorted(all_instances, key=str),
    )
    fresh = RowVariable(
        name="unified_tail",
        identity=fresh_identity,
        lacks=tuple(
            sorted(
                set((*left.tail.lacks, *right.tail.lacks, *all_instances)),
                key=str,
            )
        ),
    )
    left_replacement = EffectRow(entries=right_only, tail=fresh)
    right_replacement = EffectRow(entries=left_only, tail=fresh)
    substitution = RowSubstitution(
        bindings=(
            (left.tail.identity, left_replacement),
            (right.tail.identity, right_replacement),
        )
    )
    unified_entries = tuple(
        RowEntry(instance=instance, effect=effect)
        for instance, effect in {**left_entries, **right_entries}.items()
    )
    unified = EffectRow(entries=unified_entries, tail=fresh)
    if substitution.apply(left) != unified or substitution.apply(right) != unified:
        raise ValueError("row unification produced an inconsistent substitution")
    return RowUnification(row=unified, substitution=substitution)

instantiate_effect

instantiate_effect(effect: EffectRef, *, module: str, lexical_path: tuple[str | int, ...]) -> RowEntry

Allocate a deterministic lexical instance of an effect interface.

The instance identity is derived rather than generated, so the same interface allocated at the same place in the same module is the same instance on every run. That is what lets a serialized row refer to an instance across processes.

PARAMETER DESCRIPTION
effect

The saturated interface application to allocate.

TYPE: EffectRef

module

Module the allocation occurs in. Part of the identity, so two modules allocating at the same lexical path stay distinct.

TYPE: str

lexical_path

Position of the allocation within the module. Two allocations of one interface at different paths are different instances, which is what makes two instances of the same effect distinguishable.

TYPE: tuple[str | int, ...]

RETURNS DESCRIPTION
RowEntry

The fresh instance paired with the interface it implements, ready to add to a row.

Source code in src/quivers/qiec/effects.py
def instantiate_effect(
    effect: EffectRef,
    *,
    module: str,
    lexical_path: tuple[str | int, ...],
) -> RowEntry:
    """Allocate a deterministic lexical instance of an effect interface.

    The instance identity is derived rather than generated, so the same
    interface allocated at the same place in the same module is the same
    instance on every run. That is what lets a serialized row refer to an
    instance across processes.

    Parameters
    ----------
    effect : EffectRef
        The saturated interface application to allocate.
    module : str
        Module the allocation occurs in. Part of the identity, so two
        modules allocating at the same lexical path stay distinct.
    lexical_path : tuple[str | int, ...]
        Position of the allocation within the module. Two allocations of
        one interface at different paths are different instances, which
        is what makes two instances of the same effect distinguishable.

    Returns
    -------
    RowEntry
        The fresh instance paired with the interface it implements, ready
        to add to a row.
    """
    instance = EffectInstanceId.derive(
        str(effect.id),
        effect.arguments,
        module,
        lexical_path,
    )
    return RowEntry(instance=instance, effect=effect)

tunneled_instance

tunneled_instance(instance: EffectInstanceId) -> EffectInstanceId

The row entry of requests to an instance that tunnel past one handler.

A Mask of instance routes its body's requests past the innermost handler of the instance. Its row records them under this derived identity, so the handler they skip does not discharge them; that handler's installation then restores the identity, and the next handler out sees them as requests to instance.

PARAMETER DESCRIPTION
instance

The masked instance.

TYPE: EffectInstanceId

RETURNS DESCRIPTION
EffectInstanceId

The identity its tunneled requests carry in a row.

Source code in src/quivers/qiec/effects.py
def tunneled_instance(instance: EffectInstanceId) -> EffectInstanceId:
    """The row entry of requests to an instance that tunnel past one handler.

    A `Mask` of ``instance`` routes its body's requests past the innermost
    handler of the instance. Its row records them under this derived
    identity, so the handler they skip does not discharge them; that
    handler's installation then restores the identity, and the next
    handler out sees them as requests to ``instance``.

    Parameters
    ----------
    instance : EffectInstanceId
        The masked instance.

    Returns
    -------
    EffectInstanceId
        The identity its tunneled requests carry in a row.
    """
    return EffectInstanceId.derive("tunnel", str(instance))

restore_tunneled

restore_tunneled(row: EffectRow, instance: EffectInstanceId) -> EffectRow

Give requests that tunneled past a handler their instance back.

PARAMETER DESCRIPTION
row

The residual row of a handler installation for instance.

TYPE: EffectRow

instance

The handled instance.

TYPE: EffectInstanceId

RETURNS DESCRIPTION
EffectRow

The row with every entry of tunneled_instance(instance) renamed to instance.

Source code in src/quivers/qiec/effects.py
def restore_tunneled(row: EffectRow, instance: EffectInstanceId) -> EffectRow:
    """Give requests that tunneled past a handler their instance back.

    Parameters
    ----------
    row : EffectRow
        The residual row of a handler installation for ``instance``.
    instance : EffectInstanceId
        The handled instance.

    Returns
    -------
    EffectRow
        The row with every entry of ``tunneled_instance(instance)`` renamed
        to ``instance``.
    """
    tunneled = tunneled_instance(instance)
    if not row.contains(tunneled):
        return row
    restored = row.without(tunneled)
    entry = next(item for item in row.entries if item.instance == tunneled)
    return restored.add(RowEntry(instance=instance, effect=entry.effect))

elaborated_row

elaborated_row(row: EffectRow, introduced: Mapping[EffectInstanceId, EffectRow]) -> EffectRow

Replace every elaborated instance of a row by what its elaborator introduces.

PARAMETER DESCRIPTION
row

The row.

TYPE: EffectRow

introduced

Each elaborated instance and its elaborator's introduced row.

TYPE: Mapping[EffectInstanceId, EffectRow]

RETURNS DESCRIPTION
EffectRow

The row with each elaborated instance removed and the introduced rows added, repeatedly, since an elaboration may introduce another elaborated instance.

RAISES DESCRIPTION
ValueError

If elaborations introduce each other without end.

Source code in src/quivers/qiec/effects.py
def elaborated_row(
    row: EffectRow, introduced: Mapping[EffectInstanceId, EffectRow]
) -> EffectRow:
    """Replace every elaborated instance of a row by what its elaborator introduces.

    Parameters
    ----------
    row : EffectRow
        The row.
    introduced : Mapping[EffectInstanceId, EffectRow]
        Each elaborated instance and its elaborator's introduced row.

    Returns
    -------
    EffectRow
        The row with each elaborated instance removed and the introduced
        rows added, repeatedly, since an elaboration may introduce another
        elaborated instance.

    Raises
    ------
    ValueError
        If elaborations introduce each other without end.
    """
    result = row
    for _ in range(len(introduced) + 1):
        pending = [instance for instance in introduced if result.contains(instance)]
        if not pending:
            return result
        for instance in pending:
            result = result.without(instance).union(introduced[instance])
    raise ValueError("elaborations introduce each other without end")

render_instance

render_instance(identity: EffectInstanceId, names: Mapping[EffectInstanceId, str] | None = None) -> str

Render one effect instance in the surface spelling.

PARAMETER DESCRIPTION
identity

The instance.

TYPE: EffectInstanceId

names

The source name of each lexical instance.

TYPE: Mapping[EffectInstanceId, str] | None DEFAULT: None

RETURNS DESCRIPTION
str

Its source name, or instance: and the first eight characters of its digest when it has none.

Source code in src/quivers/qiec/effects.py
def render_instance(
    identity: EffectInstanceId, names: Mapping[EffectInstanceId, str] | None = None
) -> str:
    """Render one effect instance in the surface spelling.

    Parameters
    ----------
    identity : EffectInstanceId
        The instance.
    names : Mapping[EffectInstanceId, str] | None
        The source name of each lexical instance.

    Returns
    -------
    str
        Its source name, or ``instance:`` and the first eight characters
        of its digest when it has none.
    """
    table = names or {}
    return table.get(identity, f"instance:{identity.digest[:8]}")

render_row

render_row(row: EffectRow, names: Mapping[EffectInstanceId, str] | None = None) -> str

Render an effect row in the surface spelling.

PARAMETER DESCRIPTION
row

The row.

TYPE: EffectRow

names

The source name of each lexical instance; an instance with no name renders as the first eight characters of its digest.

TYPE: Mapping[EffectInstanceId, str] | None DEFAULT: None

RETURNS DESCRIPTION
str

!{a : Effect, b : Other[Int] | rho}: each entry as its instance's name and interface, in name order, and an open row's tail after a bar, with the instances it lacks after a backslash.

Source code in src/quivers/qiec/effects.py
def render_row(
    row: EffectRow, names: Mapping[EffectInstanceId, str] | None = None
) -> str:
    """Render an effect row in the surface spelling.

    Parameters
    ----------
    row : EffectRow
        The row.
    names : Mapping[EffectInstanceId, str] | None
        The source name of each lexical instance; an instance with no
        name renders as the first eight characters of its digest.

    Returns
    -------
    str
        ``!{a : Effect, b : Other[Int] | rho}``: each entry as its
        instance's name and interface, in name order, and an open row's
        tail after a bar, with the instances it lacks after a backslash.
    """
    entries = ", ".join(
        sorted(
            f"{render_instance(entry.instance, names)} : {render_static(entry.effect)}"
            for entry in row.entries
        )
    )
    if row.tail is None:
        return "!{" + entries + "}"
    tail = row.tail.name
    if row.tail.lacks:
        tail += " \\ " + ", ".join(
            render_instance(item, names) for item in row.tail.lacks
        )
    return "!{" + (entries + " | " if entries else "") + tail + "}"

Checked completion of one Bernoulli branch

plan_bernoulli_completion verifies one authored scalar entry that draws a Boolean selector and then draws at a distinct Bernoulli site in each arm. The inactive distribution for each arm coordinate is declared by its original static site and a fixed interior probability. The checked fragment requires probabilities that Real literals represent exactly.

The ordinary completed QIEC graph evaluates the active arm before drawing the inactive coordinate. It keeps the original selector and active request addresses and returns the active arm's saved result. Each extended history has three coordinates in selector, active and inactive order. For a source atom of mass \(m\) and directional derivative \(\dot m\), the two extended atoms have masses \(mg(y)\) and directional derivatives \(\dot m g(y)\). The fixed Bernoulli kernel has \(g(0)+g(1)=1\). Summing over the inactive coordinate recovers the original mass and derivative. The extended trace itself has a different law.

The planner checks four original histories and their eight extensions with the existing finite evaluator. It verifies each raw mass and directional derivative and each returned scalar before checking the projected law. Both per-replay fuel and exact-number limits apply. A separately checked completed graph can be verified against the original source and the declared auxiliaries.

from fractions import Fraction

from quivers.dsl import Compiler, parse
from quivers.qiec import plan_bernoulli_completion

source = """
instance random : Random

define trial(p : Real, a : Real, b : Real) : Real !{random} =
    let z <- perform random.sample[Bool](site("selector"), Bernoulli(probs=p))
    if z then
        let x <- perform random.sample[Bool](site("left"), Bernoulli(probs=a))
        return real(x) + a
    else
        let y <- perform random.sample[Bool](site("right"), Bernoulli(probs=b))
        return real(y) - b
"""
module = Compiler(parse(source)).qiec_module
assert module is not None
entry, = module.computations
branch = entry.body.then
left = branch.then.first.request.origin.static_site
right = branch.otherwise.first.request.origin.static_site
completion = plan_bernoulli_completion(
    module,
    entry.id,
    (Fraction(3, 8), Fraction(5, 8), Fraction(3, 4)),
    (1, 0, 0),
    ((left, Fraction(1, 4)), (right, Fraction(3, 8))),
)
assert len(completion.source) == 4 and len(completion.extended) == 8
assert completion.projected == completion.source

bernoulli_completion

Check a normalized completion of a finite addressed Bernoulli branch.

BernoulliCompletionAtom dataclass

BernoulliCompletionAtom(history: _History, mass: ExactJvp, result: ExactJvp)

One chronological history of a checked source or completed law.

PARAMETER DESCRIPTION
history

The full request addresses and their Boolean outcomes.

TYPE: tuple

mass

The exact joint atom mass, returned scalar and their directional derivatives at the report's parameter point.

TYPE: ExactJvp

result

The exact joint atom mass, returned scalar and their directional derivatives at the report's parameter point.

TYPE: ExactJvp

BernoulliCompletion dataclass

BernoulliCompletion(computation: ComputationId, point: tuple[Fraction, ...], direction: tuple[Fraction, ...], completed_module: QiecModule, selector: _Address, auxiliaries: tuple[tuple[_Address, Fraction], ...], source: tuple[BernoulliCompletionAtom, ...], extended: tuple[BernoulliCompletionAtom, ...], projected: tuple[BernoulliCompletionAtom, ...], source_steps: int, completed_steps: int)

A source-bound finite completion and its addressed projection.

PARAMETER DESCRIPTION
computation

The named source entry retained by the ordinary QIEC completion.

TYPE: ComputationId

point

The exact parameter point and direction recorded by the check.

TYPE: tuple of Fraction

direction

The exact parameter point and direction recorded by the check.

TYPE: tuple of Fraction

completed_module

The checked graph that executes one additional inactive draw.

TYPE: QiecModule

selector

The full address common to the two original branches.

TYPE: tuple

auxiliaries

The true-arm and false-arm canonical addresses with their fixed probabilities when inactive, in that order.

TYPE: tuple

source

The four original atoms, eight completed atoms, and four atoms obtained by summing over the removed coordinate. Chronological histories in the completed law record all three actual draws.

TYPE: tuple of BernoulliCompletionAtom

extended

The four original atoms, eight completed atoms, and four atoms obtained by summing over the removed coordinate. Chronological histories in the completed law record all three actual draws.

TYPE: tuple of BernoulliCompletionAtom

projected

The four original atoms, eight completed atoms, and four atoms obtained by summing over the removed coordinate. Chronological histories in the completed law record all three actual draws.

TYPE: tuple of BernoulliCompletionAtom

source_steps

Machine steps measured across the respective bounded replay trees.

TYPE: int

completed_steps

Machine steps measured across the respective bounded replay trees.

TYPE: int

plan_bernoulli_completion

plan_bernoulli_completion(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], auxiliaries: tuple[tuple[SiteId, Fraction], ...], *, completed_module: QiecModule | None = None, fuel: int = 65536) -> BernoulliCompletion

Check a fixed normalized completion on an authored Bernoulli branch.

The source has a direct Boolean selector draw and one differently named Bernoulli draw and scalar return in each arm. The completed graph saves that exact arm's result before drawing the other arm's coordinate. Each auxiliary is a fixed scalar probability exactly representable by a Real literal. The original and extended laws have different histories. Dropping the inactive coordinate preserves the joint mass and its directional derivative without rescaling.

PARAMETER DESCRIPTION
module

The independently checked original module.

TYPE: QiecModule

computation

The actual source entry to complete.

TYPE: ComputationId

arguments

The exact parameter point and direction for both addressed laws.

TYPE: tuple of int or Fraction

direction

The exact parameter point and direction for both addressed laws.

TYPE: tuple of int or Fraction

auxiliaries

One pair of original static site identity and fixed exact interior probability for each arm. Input order is immaterial.

TYPE: tuple

completed_module

An independently provided completed graph to verify. When absent, construct the canonical ordinary QIEC graph from the source.

TYPE: QiecModule or None DEFAULT: None

fuel

Evaluator step bound for each replay of either graph.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
BernoulliCompletion

The addressed source, extension and projection verified at the requested point and direction.

RAISES DESCRIPTION
JvpUnsupported

If the source shape, nominal addresses, candidate completion or regularity lies outside the checked fragment.

JvpLimit

If an exact computation exceeds its replay or number bound.

ValueError

If an auxiliary declaration or replay input is invalid.

Source code in src/quivers/qiec/bernoulli_completion.py
def plan_bernoulli_completion(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    auxiliaries: tuple[tuple[SiteId, Fraction], ...],
    *,
    completed_module: QiecModule | None = None,
    fuel: int = 65_536,
) -> BernoulliCompletion:
    """Check a fixed normalized completion on an authored Bernoulli branch.

    The source has a direct Boolean selector draw and one differently
    named Bernoulli draw and scalar return in each arm. The completed
    graph saves that exact arm's result before drawing the other arm's
    coordinate. Each auxiliary is a fixed scalar probability exactly
    representable by a Real literal. The original and extended laws have
    different histories. Dropping the inactive coordinate preserves the
    joint mass and its directional derivative without rescaling.

    Parameters
    ----------
    module : QiecModule
        The independently checked original module.
    computation : ComputationId
        The actual source entry to complete.
    arguments, direction : tuple of int or Fraction
        The exact parameter point and direction for both addressed laws.
    auxiliaries : tuple
        One pair of original static site identity and fixed exact
        interior probability for each arm. Input order is immaterial.
    completed_module : QiecModule or None
        An independently provided completed graph to verify. When absent,
        construct the canonical ordinary QIEC graph from the source.
    fuel : int
        Evaluator step bound for each replay of either graph.

    Returns
    -------
    BernoulliCompletion
        The addressed source, extension and projection verified at the
        requested point and direction.

    Raises
    ------
    JvpUnsupported
        If the source shape, nominal addresses, candidate completion or
        regularity lies outside the checked fragment.
    JvpLimit
        If an exact computation exceeds its replay or number bound.
    ValueError
        If an auxiliary declaration or replay input is invalid.
    """
    shape = _completion_shape(module, computation)
    owner, root, branch = shape.owner, shape.root, shape.branch
    yes, left = shape.left
    no, right = shape.right
    sites = shape.sites
    left_probability, right_probability = _completion_probabilities(
        sites[1:], auxiliaries
    )
    used = {parameter.name for parameter in owner.parameters} | {root.binder.name}
    completed = owner.with_(
        body=root.with_(
            then=branch.with_(
                then=_extend_arm(yes, right, right_probability, used),
                otherwise=_extend_arm(no, left, left_probability, used),
            )
        ),
    )
    expected_module = module.with_(
        computations=tuple(
            completed if item.id == computation else item
            for item in module.computations
        ),
    )
    if completed_module is not None and completed_module != expected_module:
        raise JvpUnsupported(
            "Bernoulli completion differs from the selected source or declared auxiliary laws"
        )
    selected = expected_module if completed_module is None else completed_module
    policies = tuple(SiteEstimator(site=site, estimator="enumerate") for site in sites)
    point = tuple(map(_fraction, arguments))
    tangent = tuple(map(_fraction, direction))
    original = _checked_finite_unit(
        module,
        computation,
        point,
        tangent,
        policies,
        4,
        fuel,
    )
    extension = _checked_finite_unit(
        selected,
        computation,
        point,
        tangent,
        policies,
        8,
        fuel,
    )
    source = tuple(
        BernoulliCompletionAtom(*atom) for atom in _prior_histories(original.tree)
    )
    extended = tuple(
        BernoulliCompletionAtom(*atom) for atom in _prior_histories(extension.tree)
    )
    selector, left_address, right_address = (
        request.request.origin.dynamic_key()
        for request in (shape.selector, left, right)
    )
    auxiliary_sites = (
        (left_address, left_probability),
        (right_address, right_probability),
    )
    projected = _project_completion(source, extended, selector, *auxiliary_sites)
    return BernoulliCompletion(
        computation,
        point,
        tangent,
        selected,
        selector,
        auxiliary_sites,
        source,
        extended,
        projected,
        original.source_steps,
        extension.source_steps,
    )

Handler carrier shapes

classify_handler_carrier inspects the actual checked clauses of a handler. A tail-state clause resumes exactly once in tail position. A tail-or-abort clause can also return an answer directly. The classifier reports continuation when a clause uses general control, including a resumption followed by other work.

The classifier checks both arms of a conditional unless its condition is a Boolean literal. Closed calls in a prefix are checked through their reachable bodies.

The report retains the nominal operation, the declared resumption grade, and the handler's return action. A compiler uses separate conditions for each transformation, including exchanging handlers.

from quivers.dsl import Compiler, parse
from quivers.qiec import classify_handler_carrier

source = """
effect Offset
    advance : Real -> Real

instance offset : Offset

handler carry for Offset : Real -> Real with (current : Real) [coverage=total, forwards=none, implementation=authored]
    return answer =>
        return answer
    advance(v : Real) resumes 1 =>
        resume(v + current) with (v)
"""
module = Compiler(parse(source), module_name="carrier-example").qiec_module
assert module is not None
shape = classify_handler_carrier(module, module.handlers[0].id)
assert shape.kind == "tail-state"
assert shape.return_action == "identity"
assert shape.clauses[0].completions == ("resume",)

handler_carriers

Classify checked handlers by the position of their resumptions.

ClauseCarrierShape dataclass

ClauseCarrierShape(operation: OperationId, grade: ResumptionGrade | ResumptionInterval, completions: tuple[_Completion, ...], obstacle: str | None)

The possible terminal actions of one checked operation clause.

PARAMETER DESCRIPTION
operation

The nominal operation this clause answers.

TYPE: OperationId

grade

The declared grade or interval, retained even when the body uses fewer shots.

TYPE: ResumptionGrade or ResumptionInterval

completions

Terminal actions on the recognized paths through the clause.

TYPE: tuple of {"abort", "resume"}

obstacle

The first reason the clause needs a general continuation.

TYPE: str or None

kind property

kind: _CarrierKind

The carrier shape of the clause's recognized terminal actions.

RETURNS DESCRIPTION
_CarrierKind

Tail state, tail with an abort arm, or a general continuation.

HandlerCarrierShape dataclass

HandlerCarrierShape(handler: HandlerId, fingerprint: str, kind: _CarrierKind, return_action: _ReturnAction, clauses: tuple[ClauseCarrierShape, ...], obstacle: str | None)

The carrier and return-action shapes of an actual checked handler.

PARAMETER DESCRIPTION
handler

The nominal handler whose clauses were examined.

TYPE: HandlerId

fingerprint

A binding to the checked module, handler and classification version.

TYPE: str

kind

The shape required by the whole handler.

TYPE: ('tail-state', 'tail-or-abort', 'continuation') DEFAULT: "tail-state"

return_action

Whether completing the handled computation uses the identity, an authored return clause, or provider behavior.

TYPE: ('identity', 'authored', 'opaque') DEFAULT: "identity"

clauses

The checked clause shapes in declaration order.

TYPE: tuple[ClauseCarrierShape, ...]

obstacle

The first source construct requiring a general continuation.

TYPE: str or None

classify_handler_carrier

classify_handler_carrier(module: QiecModule, handler: HandlerId) -> HandlerCarrierShape

Recognize tail-state and tail-or-abort shapes of a checked handler.

A recognized operation clause returns an answer directly or resumes in tail position after ordinary prefixes. Every reachable named prefix call must have an ordinary acyclic body. Handler metadata and the exact return action stay visible in the result. Transformations that use a carrier shape also need their own semantic hypotheses.

PARAMETER DESCRIPTION
module

The checked module containing the actual handler and its callees.

TYPE: QiecModule

handler

The nominal handler to classify.

TYPE: HandlerId

RETURNS DESCRIPTION
HandlerCarrierShape

A source-bound classification with clause shapes and obstacles.

RAISES DESCRIPTION
ValueError

If the nominal handler is absent from the module.

Source code in src/quivers/qiec/handler_carriers.py
def classify_handler_carrier(
    module: QiecModule, handler: HandlerId
) -> HandlerCarrierShape:
    """Recognize tail-state and tail-or-abort shapes of a checked handler.

    A recognized operation clause returns an answer directly or resumes
    in tail position after ordinary prefixes. Every reachable named
    prefix call must have an ordinary acyclic body. Handler metadata and
    the exact return action stay visible in the result. Transformations
    that use a carrier shape also need their own semantic hypotheses.

    Parameters
    ----------
    module : QiecModule
        The checked module containing the actual handler and its callees.
    handler : HandlerId
        The nominal handler to classify.

    Returns
    -------
    HandlerCarrierShape
        A source-bound classification with clause shapes and obstacles.

    Raises
    ------
    ValueError
        If the nominal handler is absent from the module.
    """
    registry = validate_module(module)
    target = registry.handlers.get(handler)
    if target is None:
        raise ValueError(f"unknown handler for carrier classification `{handler}`")
    fingerprint = sha256(
        dumps(("handler-carrier-v1", module, handler)).encode("utf-8")
    ).hexdigest()
    analysis = _CarrierAnalysis(module)
    obstacle = _handler_obstacle(target)
    try:
        clauses = tuple(analysis.clause(clause, obstacle) for clause in target.clauses)
        if obstacle is None and target.return_clause is not None:
            why = analysis.ordinary(target.return_clause.body)
            if why is not None:
                obstacle = f"return action: {why}"
    except RecursionError:
        obstacle = "carrier analysis nesting limit reached"
        clauses = tuple(analysis.clause(clause, obstacle) for clause in target.clauses)
    if obstacle is None:
        obstacle = next(
            (clause.obstacle for clause in clauses if clause.obstacle is not None), None
        )
    kind: _CarrierKind = "tail-state"
    if obstacle is not None:
        kind = "continuation"
    elif any(clause.kind == "tail-or-abort" for clause in clauses):
        kind = "tail-or-abort"
    return HandlerCarrierShape(
        handler, fingerprint, kind, _return_action(target), clauses, obstacle
    )

Recursive state specialization

specialize_recursive_state rewrites a named installation of a single nominal state handler into pure QIEC computations. The handler must be total and authored. An operation clause can resume once in tail position after ordinary closed prefixes, or it can declare grade zero and return a final handler answer. The specialization requires monomorphic declarations with no residual effects.

The specialized body passes the current state to each effectful callee. A callee that completes returns its result and new state. A grade-zero clause returns the final answer through each pending specialized callee. This path discards the captured continuation, including any pending stateful work or ordinary value computation. The original installation applies the handler's return action once on normal completion. A resuming clause evaluates its reply and all updated state coordinates in the old state, in declaration order. Recursive calls reuse the same companion definitions, so the size of the rewritten module is independent of run depth.

A case in a stateful body can match a closed monomorphic family without indices or static pattern arguments. The companion keeps the scrutinee and field bindings. Its selected arm receives the incoming state and returns the original result paired with the outgoing state.

Module-level discharge uses the specialization when it reaches a recursive handled call within this fragment. The original and specialized computations produce the same values under the checked contracts, and surviving effects in the caller keep their QIEC addresses. The specialization removes the handled requests and can take a different number of runtime steps. The Pyro target uses checked discharge for the recursive grade-zero fragment and renders other retained source handlers through the usual runtime. Other targets check the capabilities required by their selected graph. A direct call to the specialization reports unsupported control or an exceeded construction limit.

from quivers.dsl import Compiler, parse
from quivers.qiec import run_named, specialize_recursive_state

source = """
effect Counter
    read_value : Unit -> Real
    write_value : Real -> Unit

instance counter : Counter

handler threaded for Counter : Real -> (Real * Real) with (state : Real) [coverage=total, forwards=none, implementation=authored]
    return answer =>
        return (answer, state)
    read_value resumes 1 =>
        resume(state)
    write_value(value : Real) resumes 1 =>
        resume() with (value)

define walk(n : Real) : Real !{counter} =
    if n > 0.0 then
        let prior <- perform counter.read_value()
        perform counter.write_value(prior + 1.0)
        let answer <- walk(n - 1.0)
        return answer + prior
    else
        perform counter.read_value()

define execute(n : Real, initial : Real) : (Real * Real) !{} =
    handle counter with threaded(initial) in
        walk(n)
"""
module = Compiler(parse(source), module_name="recursive-counter").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "execute")
specialized = specialize_recursive_state(module, entry.id)
result = run_named(specialized, "execute", (2, 3))
assert tuple(map(float, result.value)) == (12.0, 5.0)

state_specialization

Specialize closed recursive state handlers with tail resume or abort.

StateSpecializationUnsupported

Bases: ValueError

The selected installation is outside the proved state fragment.

StateSpecializationLimit

Bases: StateSpecializationUnsupported

State specialization exceeds the requested construction bound.

specialize_recursive_state

specialize_recursive_state(module: QiecModule, computation: ComputationId, *, max_terms: int = 2048) -> QiecModule

Eliminate one closed state installation from a named recursive body.

The selected computation must install a total authored handler on one module-scoped nominal instance. Grade-one clauses need one tail resume after ordinary prefixes. Grade-zero clauses evaluate an ordinary abort answer. The handler introduces no effects. Recursive companions return their result and updated state on completion, and propagate an abort answer through the captured call chain. The selected boundary applies the authored return action on normal completion. A case in a stateful body can select an arm of a closed monomorphic family without indices or static pattern arguments. Inlining the pure clauses preserves the number and order of calls that allocate runtime addresses. Evaluation agrees on returned values under the checked contracts. Handler and request diagnostic events and evaluator fuel counts can differ.

PARAMETER DESCRIPTION
module

The checked source module.

TYPE: QiecModule

computation

The named installation to replace. Its signature and identity stay the same, and other declarations are available for their original callers.

TYPE: ComputationId

max_terms

Positive bound on constructed sequencings, cases, calls, returns and generated outcome declarations. Source validation and runtime recursion have their own costs.

TYPE: int DEFAULT: 2048

RETURNS DESCRIPTION
QiecModule

The checked module with this installation replaced and its companions added.

RAISES DESCRIPTION
StateSpecializationUnsupported

If the installation is outside the closed state fragment.

StateSpecializationLimit

If construction exceeds the bound or the source is too deeply nested.

ValueError

If the computation is absent or the requested bound is invalid.

Source code in src/quivers/qiec/state_specialization.py
def specialize_recursive_state(
    module: QiecModule, computation: ComputationId, *, max_terms: int = 2048
) -> QiecModule:
    """Eliminate one closed state installation from a named recursive body.

    The selected computation must install a total authored handler on one
    module-scoped nominal instance. Grade-one clauses need one tail resume
    after ordinary prefixes. Grade-zero clauses evaluate an ordinary abort
    answer. The handler introduces no effects. Recursive companions return
    their result and updated state on completion, and propagate an abort
    answer through the captured call chain. The selected boundary applies
    the authored return action on normal completion. A case in a stateful
    body can select an arm of a closed
    monomorphic family without indices or static pattern arguments.
    Inlining the pure clauses preserves the number and order
    of calls that allocate runtime addresses. Evaluation agrees on returned
    values under the checked contracts. Handler and request diagnostic
    events and evaluator fuel counts can differ.

    Parameters
    ----------
    module : QiecModule
        The checked source module.
    computation : ComputationId
        The named installation to replace. Its signature and identity stay
        the same, and other declarations are available for their original callers.
    max_terms : int
        Positive bound on constructed sequencings, cases, calls, returns
        and generated outcome declarations. Source validation and runtime
        recursion have their own costs.

    Returns
    -------
    QiecModule
        The checked module with this installation replaced and its companions added.

    Raises
    ------
    StateSpecializationUnsupported
        If the installation is outside the closed state fragment.
    StateSpecializationLimit
        If construction exceeds the bound or the source is too deeply nested.
    ValueError
        If the computation is absent or the requested bound is invalid.
    """
    return _specialize_state(module, computation, max_terms, frozenset())

Shared suffixes for a closed two-shot handler

specialize_shared_fork checks one closed scalar computation whose total authored handler invokes two ordered unrestricted resumptions at each request. The source is a straight sequence of requests on one nominal instance. Scalar arguments can read the preceding response and the original input values. The return and the handler clause use checked scalar arithmetic. Branches, foreign attachments, and surviving requests are outside this fragment.

The projected graph has one computation per lexical suffix. Both shots call the next suffix independently, carrying its new response and the immutable entry inputs. Later clauses combine the two returned values with the original answer expression, which can be nonlinear. At depth \(n\) the graph retains \(7n+1\) computation-node occurrences and executes \(2^{n+1}-2\) calls with \(2^n\) terminal returns on a successful run. The first count excludes the embedded scalar expressions. With \(k\) carried inputs and a clause of \(a\) scalar syntax nodes, construction and serialized size in syntax nodes include \(O(n(k+a))\) occurrences in addition to the original request and terminal expressions. The two budget checks concern retained computation nodes and unfolded shots separately.

The plan records the original site at each depth. The source reference execution can observe its original requests and shot paths. The pure residual has fresh ordinary calls at each projected occurrence and preserves the closed value and its regular derivative. It emits no handled request events. The projection is opt-in and leaves the ordinary discharge classifier unchanged.

shared_continuation

Share checked suffix code for a bounded scalar two-shot handler.

SharedForkUnsupported

Bases: ValueError

The checked source leaves the closed shared fork fragment.

SharedForkLimit

Bases: SharedForkUnsupported

The companion construction or dynamic shot count exceeds its limit.

SharedForkPlan dataclass

SharedForkPlan(module: QiecModule, source_digest: str, computation: ComputationId, handler: HandlerId, instance: EffectInstanceId, operation: OperationId, sites: tuple[SiteId, ...], companions: tuple[ComputationId, ...], retained_terms: int, request_count: int, shot_count: int, leaf_count: int)

The typed shared code and its original closed fork schedule.

PARAMETER DESCRIPTION
module

The validated residual module replacing only the selected body.

TYPE: QiecModule

source_digest

The SHA-256 digest of the checked source module.

TYPE: str

computation

The original entry preserved by the projection.

TYPE: ComputationId

handler

The authored handler used by this projection.

TYPE: HandlerId

instance

The matching effect instance at its original installation.

TYPE: EffectInstanceId

operation

The nominal operation invoked at every level.

TYPE: OperationId

sites

Original request identities in source nesting order.

TYPE: tuple of SiteId

companions

Generated suffix bodies ordered from the first child to the leaf.

TYPE: tuple of ComputationId

retained_terms

Occurrences of computation nodes in the entry and its companions.

TYPE: int

request_count

Counts for a complete successful native source execution. Each projected shot is a fresh call, including equal arguments.

TYPE: int

shot_count

Counts for a complete successful native source execution. Each projected shot is a fresh call, including equal arguments.

TYPE: int

leaf_count

Counts for a complete successful native source execution. Each projected shot is a fresh call, including equal arguments.

TYPE: int

specialize_shared_fork

specialize_shared_fork(module: QiecModule, computation: ComputationId, *, max_terms: int = 2048, max_shots: int = 65534) -> SharedForkPlan

Replace one closed scalar two-shot chain with shared typed suffixes.

Each source request computes its payload once. The corresponding suffix calls the next suffix once per written resume, in lexical order, then runs the original clause's pure answer expression. A suffix parameter carries the preceding response alongside the entry's immutable Real parameters. A successful run executes every shot. The projection preserves the result and its regular scalar derivative. Original handled request events are internal to the source execution.

PARAMETER DESCRIPTION
module

The module with the actual named, monomorphic Real entry.

TYPE: QiecModule

computation

The exact identity of the selected closed installation.

TYPE: ComputationId

max_terms

A limit on computation node occurrences in the entry and companions.

TYPE: int DEFAULT: 2048

max_shots

The separate limit on dynamic invocations in a successful run.

TYPE: int DEFAULT: 65534

RETURNS DESCRIPTION
SharedForkPlan

The validated residual and its nominal source and schedule evidence.

RAISES DESCRIPTION
ValueError

If the source identity or a positive integer budget is malformed.

SharedForkUnsupported

If the reachable source is outside the exact closed scalar fragment.

SharedForkLimit

If the retained terms or fully unfolded shot count exceeds its cap.

Source code in src/quivers/qiec/shared_continuation.py
def specialize_shared_fork(
    module: QiecModule,
    computation: ComputationId,
    *,
    max_terms: int = 2_048,
    max_shots: int = 65_534,
) -> SharedForkPlan:
    """Replace one closed scalar two-shot chain with shared typed suffixes.

    Each source request computes its payload once. The corresponding
    suffix calls the next suffix once per written resume, in lexical order,
    then runs the original clause's pure answer expression. A suffix
    parameter carries the preceding response alongside the entry's
    immutable Real parameters. A successful run executes every shot.
    The projection preserves the result and its regular scalar derivative.
    Original handled request events are internal to the source execution.

    Parameters
    ----------
    module : QiecModule
        The module with the actual named, monomorphic Real entry.
    computation : ComputationId
        The exact identity of the selected closed installation.
    max_terms : int
        A limit on computation node occurrences in the entry and companions.
    max_shots : int
        The separate limit on dynamic invocations in a successful run.

    Returns
    -------
    SharedForkPlan
        The validated residual and its nominal source and schedule evidence.

    Raises
    ------
    ValueError
        If the source identity or a positive integer budget is malformed.
    SharedForkUnsupported
        If the reachable source is outside the exact closed scalar fragment.
    SharedForkLimit
        If the retained terms or fully unfolded shot count exceeds its cap.
    """
    _validate_limit("max_terms", max_terms)
    _validate_limit("max_shots", max_shots)
    validate_module(module)
    owner = next((item for item in module.computations if item.id == computation), None)
    if owner is None:
        raise ValueError(f"unknown computation for shared fork {computation}")
    install = owner.body
    if (
        owner.telescope
        or owner.type.effects != EMPTY_ROW
        or owner.type.result != REAL
        or any(parameter.type != REAL for parameter in owner.parameters)
        or not isinstance(install, Handle)
        or install.arguments
        or install.static_arguments
    ):
        raise SharedForkUnsupported("shared fork needs one closed scalar installation")
    handler = next(item for item in module.handlers if item.id == install.handler)
    operation, payload, body = _fork_clause(handler)

    captured = frozenset(owner.parameters)
    names = {parameter.name for parameter in captured}
    available = captured
    source = install.computation
    steps: list[tuple[Local, Value, SiteId]] = []
    while isinstance(source, Bind) and isinstance(source.first, Perform):
        request = source.first.request
        origin = request.origin
        if (
            request.instance != install.instance
            or request.effect != handler.effect
            or request.operation != operation
            or request.result_type != REAL
            or request.static_arguments
            or len(request.arguments) != 1
            or source.binder.type != REAL
            or source.binder.name in names
            or origin.dynamic_path
            or origin.resumption_path
            or origin.relation != "preserve"
            or origin.parents
        ):
            raise SharedForkUnsupported(
                "shared fork needs distinct direct requests of its own operation"
            )
        _check_value(request.arguments[0], available)
        steps.append((source.binder, request.arguments[0], origin.static_site))
        names.add(source.binder.name)
        available = captured | {source.binder}
        source = source.then
    if not steps or not isinstance(source, Return):
        raise SharedForkUnsupported(
            "shared fork needs a straight request sequence and pure return"
        )
    _check_value(source.value, available)
    sites = tuple(site for _, _, site in steps)
    if len(set(sites)) != len(sites):
        raise SharedForkUnsupported(
            "shared fork requires distinct original request sites"
        )

    depth = len(steps)
    retained = 7 * depth + 1
    if retained > max_terms:
        raise SharedForkLimit(
            f"shared fork needs {retained} retained terms, exceeding {max_terms}"
        )
    if depth + 1 >= (max_shots + 2).bit_length():
        raise SharedForkLimit(f"shared fork exceeds {max_shots} dynamic shots")
    leaves = 1 << depth

    fresh = _LocalNames(owner)
    renamed: dict[str, str] = {}
    prefix = cast(Local, _relocate(payload, fresh, renamed))
    first = cast(Bind, _relocate(body, fresh, renamed))
    second = cast(Bind, first.then)
    left, right = cast(Resume, first.first), cast(Resume, second.first)
    original_ids = {item.id for item in module.computations}
    original_names = {item.name for item in module.computations}
    suffixes: list[_Companion] = []
    for level in range(1, depth + 1):
        identity = ComputationId.derive("shared-fork-v1", owner.id, handler.id, level)
        name = f"__fork_{identity.digest}"
        if identity in original_ids or name in original_names:
            raise SharedForkUnsupported(
                "shared fork companion conflicts with an existing declaration"
            )
        suffixes.append(_Companion(identity, name, REAL))
    carried = tuple(Var(local=parameter) for parameter in owner.parameters)
    projected = [
        Bind(
            binder=prefix,
            first=Return(value=operand),
            then=first.with_(
                first=suffix.call(
                    (left.value, *carried),
                    left.origin.with_(
                        structural_path=(
                            *owner.origin.structural_path,
                            "shared-fork",
                            level,
                            "left",
                        ),
                    ),
                ),
                then=second.with_(
                    first=suffix.call(
                        (right.value, *carried),
                        right.origin.with_(
                            structural_path=(
                                *owner.origin.structural_path,
                                "shared-fork",
                                level,
                                "right",
                            ),
                        ),
                    ),
                ),
            ),
        )
        for level, ((_, operand, _), suffix) in enumerate(
            zip(steps, suffixes, strict=True)
        )
    ]
    companions: tuple[NamedComputation, ...] = tuple(
        suffix.declaration(
            (step[0], *owner.parameters),
            rest,
            owner.origin.with_(
                structural_path=(*owner.origin.structural_path, "shared-fork", level),
            ),
        )
        for level, (suffix, step, rest) in enumerate(
            zip(suffixes, steps, (*projected[1:], source), strict=True), 1
        )
    )
    output = module.with_(
        computations=(
            *(
                owner.with_(body=projected[0]) if item.id == owner.id else item
                for item in module.computations
            ),
            *companions,
        )
    )
    validate_module(output)
    return SharedForkPlan(
        module=output,
        source_digest=sha256(dumps(module).encode("utf-8")).hexdigest(),
        computation=owner.id,
        handler=handler.id,
        instance=install.instance,
        operation=operation,
        sites=sites,
        companions=tuple(item.id for item in companions),
        retained_terms=retained,
        request_count=leaves - 1,
        shot_count=2 * leaves - 2,
        leaf_count=leaves,
    )

Finite laws

The finite law checker compares two named QIEC computations with the same positional input types and result type. It runs both sides for every assignment of Booleans, unit values, and their finite products. Each side has an empty residual effect row, and reachable handler clauses use the same exact finite fragment.

finite_continuation_type gives a total continuation one result cell for every tuple of arguments. Include handler state among those arguments when the continuation can observe it. Both sides receive the same table. For a continuation from a pair of Booleans to a Boolean, the four cells are indexed by (false, false), (false, true), (true, false), and (true, true), in that order.

The checker returns the first counterexample with its full assignment and both results. A positive decision follows only after every assignment completes. An unsupported term or an exhausted limit raises an error.

laws

Exhaustive laws of finite checked QIEC computations.

A finite continuation is a product with one result cell for each argument tuple. The same immutable table is passed to both sides of a law, so repeated continuation applications can read the same cell. Enumeration covers all total tables, including those that distinguish two values a handler might return.

FiniteValue

FiniteValue = bool | None | tuple[FiniteValue, ...]

The host encoding of a Boolean, unit, or recursively finite product.

FiniteLawUnsupported

Bases: ValueError

The law falls outside the deterministic finite fragment.

FiniteLawLimit

Bases: ValueError

The law checker exhausted a limit before deciding the law.

FiniteLawCounterexample dataclass

FiniteLawCounterexample(arguments: tuple[FiniteValue, ...], left: FiniteValue, right: FiniteValue)

A complete assignment on which both sides return different values.

PARAMETER DESCRIPTION
arguments

Inputs to both sides, including the full continuation tables.

TYPE: tuple[FiniteValue, ...]

left

The left result.

TYPE: FiniteValue

right

The right result.

TYPE: FiniteValue

FiniteLawDecision dataclass

FiniteLawDecision(checked: int, counterexample: FiniteLawCounterexample | None = None)

The result of checking a typed finite law on the reference machine.

PARAMETER DESCRIPTION
checked

The number of assignments checked.

TYPE: int

counterexample

The first failing assignment, if any. A positive decision has checked every assignment.

TYPE: FiniteLawCounterexample or None DEFAULT: None

finite_continuation_type

finite_continuation_type(arguments: tuple[TypeExpr, ...], result: TypeExpr, *, max_cells: int = _DEFAULT_LIMIT) -> TypeApplication

Construct the QIEC product type of a total finite continuation.

PARAMETER DESCRIPTION
arguments

The continuation's argument types, including any handler state.

TYPE: tuple[TypeExpr, ...]

result

The answer type.

TYPE: TypeExpr

max_cells

The largest product the checker will construct.

TYPE: int DEFAULT: _DEFAULT_LIMIT

RETURNS DESCRIPTION
TypeApplication

A product of result cells in lexicographic argument order. Booleans order false before true, unit has one value, and products order lexicographically over their component carriers. An argument list of length zero has one cell.

RAISES DESCRIPTION
FiniteLawUnsupported

If an argument or answer is outside the supported finite types.

FiniteLawLimit

If the continuation has more than max_cells cells.

ValueError

If max_cells is not a positive integer.

Source code in src/quivers/qiec/laws.py
def finite_continuation_type(
    arguments: tuple[TypeExpr, ...],
    result: TypeExpr,
    *,
    max_cells: int = _DEFAULT_LIMIT,
) -> TypeApplication:
    """Construct the QIEC product type of a total finite continuation.

    Parameters
    ----------
    arguments : tuple[TypeExpr, ...]
        The continuation's argument types, including any handler state.
    result : TypeExpr
        The answer type.
    max_cells : int
        The largest product the checker will construct.

    Returns
    -------
    TypeApplication
        A product of result cells in lexicographic argument order. Booleans
        order false before true, unit has one value, and products order
        lexicographically over their component carriers. An argument list
        of length zero has one cell.

    Raises
    ------
    FiniteLawUnsupported
        If an argument or answer is outside the supported finite types.
    FiniteLawLimit
        If the continuation has more than ``max_cells`` cells.
    ValueError
        If ``max_cells`` is not a positive integer.
    """
    _validate_limit("max_cells", max_cells)
    _shape(result)
    size = prod(_size(_shape(argument)) for argument in arguments)
    if size > max_cells:
        raise FiniteLawLimit(f"continuation has {size} cells, exceeding {max_cells}")
    return product_type(*((result,) * size))

check_finite_law

check_finite_law(module: QiecModule, left: str, right: str, *, max_assignments: int = _DEFAULT_LIMIT, fuel: int = _DEFAULT_LIMIT) -> FiniteLawDecision

Decide equality on every assignment to two named finite computations.

PARAMETER DESCRIPTION
module

The checked kernel module.

TYPE: QiecModule

left

The left computation's name.

TYPE: str

right

The right computation's name. The computations must have the same positional finite argument types, the same finite result type, and closed empty residual rows. Continuations can be supplied as products from :func:finite_continuation_type.

TYPE: str

max_assignments

The largest number of assignments the checker will enumerate.

TYPE: int DEFAULT: _DEFAULT_LIMIT

fuel

The reference evaluator's step limit for each side of each assignment.

TYPE: int DEFAULT: _DEFAULT_LIMIT

RETURNS DESCRIPTION
FiniteLawDecision

A decision after all assignments agree or a concrete assignment whose results differ.

RAISES DESCRIPTION
FiniteLawUnsupported

If the signatures differ or reachable code leaves the exact finite fragment of unit, Booleans, finite products, and authored handlers.

FiniteLawLimit

If the assignment or evaluator step limit prevents a decision.

ExecutionFailure

If a checked assignment cannot be evaluated.

ValueError

If an assignment or evaluator limit is not a positive integer.

Source code in src/quivers/qiec/laws.py
def check_finite_law(
    module: QiecModule,
    left: str,
    right: str,
    *,
    max_assignments: int = _DEFAULT_LIMIT,
    fuel: int = _DEFAULT_LIMIT,
) -> FiniteLawDecision:
    """Decide equality on every assignment to two named finite computations.

    Parameters
    ----------
    module : QiecModule
        The checked kernel module.
    left : str
        The left computation's name.
    right : str
        The right computation's name. The computations must have the same
        positional finite argument types, the same finite result type,
        and closed empty residual rows. Continuations can be supplied as
        products from :func:`finite_continuation_type`.
    max_assignments : int
        The largest number of assignments the checker will enumerate.
    fuel : int
        The reference evaluator's step limit for each side of each assignment.

    Returns
    -------
    FiniteLawDecision
        A decision after all assignments agree or a concrete assignment
        whose results differ.

    Raises
    ------
    FiniteLawUnsupported
        If the signatures differ or reachable code leaves the exact finite
        fragment of unit, Booleans, finite products, and authored handlers.
    FiniteLawLimit
        If the assignment or evaluator step limit prevents a decision.
    ExecutionFailure
        If a checked assignment cannot be evaluated.
    ValueError
        If an assignment or evaluator limit is not a positive integer.
    """
    _validate_limit("max_assignments", max_assignments)
    _validate_limit("fuel", fuel)
    validate_module(module)
    named = {item.name: item for item in module.computations}
    if left not in named or right not in named:
        missing = left if left not in named else right
        raise FiniteLawUnsupported(f"unknown finite law computation `{missing}`")
    lhs, rhs = named[left], named[right]
    parameters = tuple(parameter.type for parameter in lhs.parameters)
    if (
        parameters != tuple(parameter.type for parameter in rhs.parameters)
        or lhs.type.result != rhs.type.result
    ):
        raise FiniteLawUnsupported(
            "a finite law requires matching positional signatures"
        )
    if lhs.type.effects != EMPTY_ROW or rhs.type.effects != EMPTY_ROW:
        raise FiniteLawUnsupported("a finite law requires an empty residual effect row")
    shapes = tuple(_shape(parameter) for parameter in parameters)
    answer = _shape(lhs.type.result)
    count = prod(_size(shape) for shape in shapes)
    if count > max_assignments:
        raise FiniteLawLimit(
            f"law has {count} assignments, exceeding {max_assignments}"
        )
    _check_reachable(module, lhs, rhs)
    for index, arguments in enumerate(
        product(*(_values(shape) for shape in shapes)), 1
    ):
        try:
            first = _observed(
                answer,
                host_value(
                    run_named(
                        module, left, arguments, fuel=fuel, record_trace=False
                    ).value
                ),
            )
            second = _observed(
                answer,
                host_value(
                    run_named(
                        module, right, arguments, fuel=fuel, record_trace=False
                    ).value
                ),
            )
        except ExecutionFailure as error:
            if error.diagnostic.code == "qiec-run-fuel":
                raise FiniteLawLimit(
                    f"fuel exhausted at assignment {arguments!r}"
                ) from error
            raise
        if first != second:
            return FiniteLawDecision(
                index, FiniteLawCounterexample(arguments, first, second)
            )
    return FiniteLawDecision(count)

Nominal finite effect equations

EffectEquation names one effect interface, a concrete instance, the operations in the equation, and two checked computations over that instance. check_finite_effect_law installs the selected authored handler around each computation. Each assignment includes the initial values of the handler's parameters. An equation can use a finite product as a continuation table, so the checker sees every possible response in the declared carrier.

The decision binds the checked module, equation and handler identities, and the finite checking domain. Passing an earlier decision checks that binding and runs the finite check again.

from quivers.dsl import Compiler, parse
from quivers.qiec import EffectEquation, check_finite_effect_law

source = """
effect ReadOnly
    read_value : Unit -> Bool

instance reader : ReadOnly

handler fixed for ReadOnly : Bool -> Bool with (current : Bool) [coverage=total, forwards=none, implementation=authored]
    return x =>
        return x
    read_value resumes 1 =>
        resume(current)

define repeated() : Bool !{reader} =
    let first <- perform reader.read_value()
    let second <- perform reader.read_value()
    if first then
        return second
    else
        if second then
            return false
        else
            return true

define agreed() : Bool !{} =
    return true
"""
module = Compiler(parse(source), module_name="read-effect-law").qiec_module
assert module is not None
instance = next(item.entry for item in module.instances if item.name == "reader")
effect = next(item for item in module.effects if item.ref.id == instance.effect.id)
roots = {item.name: item.id for item in module.computations}
equation = EffectEquation(
    effect.ref.id, "same-read", instance.instance, (effect.operations[0].id,),
    roots["repeated"], roots["agreed"],
)
decision = check_finite_effect_law(module, equation, module.handlers[0].id)
assert decision.certified
assert decision.result.checked == 2

Nominal scalar effect equations

An effect_law can request method=polynomial or method=rational when the two computations' inputs, handler state and returned values are scalar reals. Both methods check formal returned values under the named handler. The rational method also checks the two strict domains, including divisions whose results are unused. If it cannot establish a common domain, or the check exceeds its work limit, the obligation remains unresolved. Finite checks are the default when method is omitted.

The example checks additivity for an operation whose handler divides its argument by the supplied scale. Both sides are defined when that scale is nonzero. The left side requests transform once and the right side requests it twice. Their formal equality allows different traces and different rounding in finite-precision execution. Discharge and target selection still use their own checked rules.

from quivers.dsl import Compiler, parse

source = """
effect Scale
    transform : Real -> Real

instance scaling : Scale

handler divide for Scale : Real -> Real with (s : Real) [coverage=total, forwards=none, implementation=authored]
    return x =>
        return x
    transform(v : Real) resumes 1 =>
        resume(v / s)

define combined(a : Real, b : Real) : Real !{scaling} =
    perform scaling.transform(a + b)

define separate(a : Real, b : Real) : Real !{scaling} =
    let first <- perform scaling.transform(a)
    let second <- perform scaling.transform(b)
    return first + second

define scaled_sum(a : Real, b : Real, s : Real) : Real !{} =
    handle scaling with divide(s) in
        combined(a, b)

effect_law additivity [instance=scaling, operations=[transform], left=combined, right=separate, handlers=[divide], method=rational]
"""
compiler = Compiler(parse(source), module_name="scale-effect-law")
plan = compiler.effect_plan("scaled_sum")
(report,) = plan.laws
decision = report.decision
assert report.status == "checked"
assert decision is not None and decision.certified
assert decision.result.domain_polynomial == (((0, 0, 1), 1),)

effect_laws

Check nominal effect equations against authored QIEC handlers.

EffectEquation

EffectEquation(effect: EffectId, name: str, instance: EffectInstanceId, operations: tuple[OperationId, ...], left: ComputationId, right: ComputationId)

Bases: QiecModel

Declare a pair of checked computations over one nominal effect.

The law's name is scoped to its effect. Its statement is the two computation bodies, checked under the listed nominal operation set.

PARAMETER DESCRIPTION
effect

The declared interface owning the law.

TYPE: EffectId

name

The law's name within that interface.

TYPE: str

instance

The concrete instance whose requests form the two sides.

TYPE: EffectInstanceId

operations

The operations occurring across both bodies.

TYPE: tuple[OperationId, ...]

left

The left computation.

TYPE: ComputationId

right

The right computation, with the same positional domain and result.

TYPE: ComputationId

Source code in src/quivers/qiec/effect_law_schema.py
def __init__(
    self,
    effect: EffectId,
    name: str,
    instance: EffectInstanceId,
    operations: tuple[OperationId, ...],
    left: ComputationId,
    right: ComputationId,
) -> None:
    # Didactic reads constructor fields from the concrete model.
    initialize = cast(Callable[..., None], super().__init__)
    initialize(
        effect=effect,
        name=name,
        instance=instance,
        operations=operations,
        left=left,
        right=right,
    )

FiniteEffectLawDecision dataclass

FiniteEffectLawDecision(equation: EffectEquation, handler: HandlerId, fingerprint: str, parameter_types: tuple[TypeExpr, ...], answer_type: TypeExpr, result: FiniteLawDecision)

An exhaustive handler-law decision on a finite carrier.

PARAMETER DESCRIPTION
equation

The checked equation.

TYPE: EffectEquation

handler

The exact handler installed around each side.

TYPE: HandlerId

fingerprint

The canonical checked module and equation binding, including the handler identity and the checking fragment.

TYPE: str

parameter_types

The common domain in order, followed by the handler's initial parameter types. The checker exhausts every assignment.

TYPE: tuple[TypeExpr, ...]

answer_type

The type of the observable handled answers.

TYPE: TypeExpr

result

The exhaustive result or a separating assignment and both answers.

TYPE: FiniteLawDecision

certified property

certified: bool

Whether the installed handler satisfies the finite equation.

RETURNS DESCRIPTION
bool

Whether every enumerated assignment agrees.

ScalarEffectLawDecision dataclass

ScalarEffectLawDecision(equation: EffectEquation, handler: HandlerId, fingerprint: str, parameter_types: tuple[TypeExpr, ...], answer_type: TypeExpr, method: Literal['polynomial', 'rational'], result: PolynomialLawDecision | RationalLawDecision)

An exact polynomial or rational handler-law decision.

PARAMETER DESCRIPTION
equation

The checked nominal equation.

TYPE: EffectEquation

handler

The actual handler installed around each side.

TYPE: HandlerId

fingerprint

The checked source, equation, handler and method binding.

TYPE: str

parameter_types

The scalar equation inputs followed by the initial handler state.

TYPE: tuple[TypeExpr, ...]

answer_type

The common scalar real answer type.

TYPE: TypeExpr

method

The exact interpretation used for this decision.

TYPE: ('polynomial', 'rational') DEFAULT: "polynomial"

result

The normalized identity or exact witness, with the common strict domain for a rational decision.

TYPE: PolynomialLawDecision or RationalLawDecision

certified property

certified: bool

Whether both handled answers agree throughout the checked domain.

RETURNS DESCRIPTION
bool

Whether the exact checker certified the identity.

check_finite_effect_law

check_finite_effect_law(module: QiecModule, equation: EffectEquation, handler: HandlerId, *, prior: FiniteEffectLawDecision | None = None, max_assignments: int = 65536, fuel: int = 65536) -> FiniteEffectLawDecision

Check the actual handler on both sides of a declared finite equation.

Each side is open over the equation's concrete instance and built from returns, sequences, branches and direct requests. The checker installs the same authored handler around each side and checks every assignment to their common parameters and initial handler state. Continuations can be represented by finite products in the equation's parameter types.

An earlier result can supply the expected subject and fingerprint. The current implementation is then checked again on that subject.

PARAMETER DESCRIPTION
module

The checked source containing the interface, instance, equation sides and handler.

TYPE: QiecModule

equation

The law's exact nominal scope and two named open bodies.

TYPE: EffectEquation

handler

The authored handler to install on that instance for both probes.

TYPE: HandlerId

prior

An earlier result whose equation, handler and binding must agree.

TYPE: FiniteEffectLawDecision or None DEFAULT: None

max_assignments

The maximum number of finite input assignments.

TYPE: int DEFAULT: 65536

fuel

The reference step limit per side and assignment.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
FiniteEffectLawDecision

The current checker decision and its exact subject binding.

RAISES DESCRIPTION
FiniteLawUnsupported

If the subject has a mismatched identity, scope, checked carrier, unsupported term, or implementation.

FiniteLawLimit

If an assignment or evaluator limit prevents an exhaustive decision.

Source code in src/quivers/qiec/effect_laws.py
def check_finite_effect_law(
    module: QiecModule,
    equation: EffectEquation,
    handler: HandlerId,
    *,
    prior: FiniteEffectLawDecision | None = None,
    max_assignments: int = 65_536,
    fuel: int = 65_536,
) -> FiniteEffectLawDecision:
    """Check the actual handler on both sides of a declared finite equation.

    Each side is open over the equation's concrete instance and built from
    returns, sequences, branches and direct requests. The checker installs
    the same authored handler around each side and checks every assignment
    to their common parameters and initial handler state. Continuations can
    be represented by finite products in the equation's parameter types.

    An earlier result can supply the expected subject and fingerprint.
    The current implementation is then checked again on that subject.

    Parameters
    ----------
    module : QiecModule
        The checked source containing the interface, instance, equation
        sides and handler.
    equation : EffectEquation
        The law's exact nominal scope and two named open bodies.
    handler : HandlerId
        The authored handler to install on that instance for both probes.
    prior : FiniteEffectLawDecision or None
        An earlier result whose equation, handler and binding must agree.
    max_assignments : int
        The maximum number of finite input assignments.
    fuel : int
        The reference step limit per side and assignment.

    Returns
    -------
    FiniteEffectLawDecision
        The current checker decision and its exact subject binding.

    Raises
    ------
    FiniteLawUnsupported
        If the subject has a mismatched identity, scope, checked carrier,
        unsupported term, or implementation.
    FiniteLawLimit
        If an assignment or evaluator limit prevents an exhaustive decision.
    """
    checked, left, right, binding = _checked_probes(
        module, equation, handler, "finite", prior
    )
    result = check_finite_law(
        checked, left.name, right.name, max_assignments=max_assignments, fuel=fuel
    )
    return FiniteEffectLawDecision(
        equation,
        handler,
        binding,
        tuple(parameter.type for parameter in left.parameters),
        left.type.result,
        result,
    )

check_scalar_effect_law

check_scalar_effect_law(module: QiecModule, equation: EffectEquation, handler: HandlerId, *, method: Literal['polynomial', 'rational'], prior: ScalarEffectLawDecision | None = None, max_work: int = 65536, fuel: int = 65536) -> ScalarEffectLawDecision

Check the actual handler on both sides of a scalar nominal equation.

The probes install the same authored handler around the checked open sides. All equation inputs and initial handler parameters are exact symbolic reals. The polynomial checker requires a total polynomial fragment. The rational checker also compares strict domains before checking equality there.

PARAMETER DESCRIPTION
module

The checked module containing the equation sides and handler.

TYPE: QiecModule

equation

The exact nominal law statement and operation scope.

TYPE: EffectEquation

handler

The actual authored implementation to check.

TYPE: HandlerId

method

The exact algebra and domain check to apply.

TYPE: ('polynomial', 'rational') DEFAULT: "polynomial"

prior

A prior result whose source, equation, handler and method must match. Both checked sides are evaluated again.

TYPE: ScalarEffectLawDecision or None DEFAULT: None

max_work

The exact algebra and witness construction budget.

TYPE: int DEFAULT: 65536

fuel

The reference step limit per side in rational checking.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
ScalarEffectLawDecision

The bound decision and exact form or separating witness.

RAISES DESCRIPTION
PolynomialLawUnsupported or RationalLawUnsupported

If the nominal proof subject or reached code is outside the chosen fragment, or the rational strict domains could not be matched.

PolynomialLawLimit or RationalLawLimit

If the exact comparison exhausts a resource bound.

ValueError

If a method or resource limit is invalid.

Source code in src/quivers/qiec/effect_laws.py
def check_scalar_effect_law(
    module: QiecModule,
    equation: EffectEquation,
    handler: HandlerId,
    *,
    method: Literal["polynomial", "rational"],
    prior: ScalarEffectLawDecision | None = None,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> ScalarEffectLawDecision:
    """Check the actual handler on both sides of a scalar nominal equation.

    The probes install the same authored handler around the checked open
    sides. All equation inputs and initial handler parameters are exact
    symbolic reals. The polynomial checker requires a total polynomial
    fragment. The rational checker also compares strict domains before
    checking equality there.

    Parameters
    ----------
    module : QiecModule
        The checked module containing the equation sides and handler.
    equation : EffectEquation
        The exact nominal law statement and operation scope.
    handler : HandlerId
        The actual authored implementation to check.
    method : {"polynomial", "rational"}
        The exact algebra and domain check to apply.
    prior : ScalarEffectLawDecision or None
        A prior result whose source, equation, handler and method must match.
        Both checked sides are evaluated again.
    max_work : int
        The exact algebra and witness construction budget.
    fuel : int
        The reference step limit per side in rational checking.

    Returns
    -------
    ScalarEffectLawDecision
        The bound decision and exact form or separating witness.

    Raises
    ------
    PolynomialLawUnsupported or RationalLawUnsupported
        If the nominal proof subject or reached code is outside the chosen
        fragment, or the rational strict domains could not be matched.
    PolynomialLawLimit or RationalLawLimit
        If the exact comparison exhausts a resource bound.
    ValueError
        If a method or resource limit is invalid.
    """
    if method not in ("polynomial", "rational"):
        raise ValueError("unknown scalar effect law check method")
    checked, left, right, binding = _checked_probes(
        module, equation, handler, method, prior
    )
    result = (
        check_polynomial_law(checked, left.name, right.name, max_work=max_work)
        if method == "polynomial"
        else check_rational_law(
            checked, left.name, right.name, max_work=max_work, fuel=fuel
        )
    )
    return ScalarEffectLawDecision(
        equation,
        handler,
        binding,
        tuple(parameter.type for parameter in left.parameters),
        left.type.result,
        method,
        result,
    )

Effect law obligations

An EffectLawBundle pairs a checked module with a set of EffectLawObligation records. Each obligation names the equation, handler and checking method and can carry named hypotheses. The bundle checks these identifiers against the module and assigns one statement to each effect's law name. Use the indicated exact checker on the module and equation to obtain a decision.

The bundle round-trips with dumps and loads. A prior decision is bound to the checked implementation, equation, handler and method. The rational check of the scale law can be run again after decoding its obligation.

from quivers.qiec import EffectLawBundle, check_scalar_effect_law, dumps, loads

decoded = loads(dumps(plan.bundle))
assert isinstance(decoded, EffectLawBundle)
obligation = decoded.obligations[0]
assert obligation.method == "rational"
rechecked = check_scalar_effect_law(
    decoded.module, obligation.equation, obligation.handler, method=obligation.method
)
assert rechecked == decision

effect_law_schema

Stable declarations of QIEC effect equations and obligations.

EffectEquation

EffectEquation(effect: EffectId, name: str, instance: EffectInstanceId, operations: tuple[OperationId, ...], left: ComputationId, right: ComputationId)

Bases: QiecModel

Declare a pair of checked computations over one nominal effect.

The law's name is scoped to its effect. Its statement is the two computation bodies, checked under the listed nominal operation set.

PARAMETER DESCRIPTION
effect

The declared interface owning the law.

TYPE: EffectId

name

The law's name within that interface.

TYPE: str

instance

The concrete instance whose requests form the two sides.

TYPE: EffectInstanceId

operations

The operations occurring across both bodies.

TYPE: tuple[OperationId, ...]

left

The left computation.

TYPE: ComputationId

right

The right computation, with the same positional domain and result.

TYPE: ComputationId

Source code in src/quivers/qiec/effect_law_schema.py
def __init__(
    self,
    effect: EffectId,
    name: str,
    instance: EffectInstanceId,
    operations: tuple[OperationId, ...],
    left: ComputationId,
    right: ComputationId,
) -> None:
    # Didactic reads constructor fields from the concrete model.
    initialize = cast(Callable[..., None], super().__init__)
    initialize(
        effect=effect,
        name=name,
        instance=instance,
        operations=operations,
        left=left,
        right=right,
    )

EffectLawObligation didactic-model

EffectLawObligation(*, equation: EffectEquation = field(opaque=True, extras=OPAQUE_BY_VALUE), handler: HandlerId = field(opaque=True, extras=OPAQUE_BY_VALUE), method: _CheckMethod, guards: tuple[Condition, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A request to check one handler against a nominal effect equation.

PARAMETER DESCRIPTION
equation

The exact nominal statement to check.

TYPE: EffectEquation DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

handler

The implementation the obligation addresses.

TYPE: HandlerId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

method

The exact checking method requested.

TYPE: ('finite', 'polynomial', 'rational') DEFAULT: "finite"

guards

The named hypotheses declared with this obligation. The ordinary exact checks compare each side throughout the method's natural domain.

TYPE: tuple[Condition, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

EffectLawBundle didactic-model

EffectLawBundle(*, module: QiecModule = field(opaque=True, extras=OPAQUE_BY_VALUE), obligations: tuple[EffectLawObligation, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A QIEC module with declarative law checks for that module.

PARAMETER DESCRIPTION
module

The unchanged QIEC compilation unit.

TYPE: QiecModule DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

obligations

The requested checks, with one statement per scoped effect-law name and one obligation per equation, handler and method.

TYPE: tuple[EffectLawObligation, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

EffectLawEvidence didactic-model

EffectLawEvidence(*, obligation: EffectLawObligation = field(opaque=True, extras=OPAQUE_BY_VALUE), module_digest: str, evidence: Tested | Assumed = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Record tested or assumed evidence for one exact authored law subject.

PARAMETER DESCRIPTION
obligation

The nominal equation, handler, method, and hypotheses at issue.

TYPE: EffectLawObligation DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

module_digest

The SHA-256 digest of the exact canonical module supplying it.

TYPE: str

evidence

The empirical test or assumption declared with this obligation.

TYPE: Tested or Assumed DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

for_module classmethod

for_module(module: QiecModule, obligation: EffectLawObligation, evidence: Tested | Assumed) -> EffectLawEvidence

Bind declared evidence to the exact module and law obligation.

PARAMETER DESCRIPTION
module

The executable QIEC module to which the evidence refers.

TYPE: QiecModule

obligation

The law and handler to which the evidence refers.

TYPE: EffectLawObligation

evidence

The empirical result or assumption to record.

TYPE: Tested or Assumed

RETURNS DESCRIPTION
EffectLawEvidence

Evidence with a checked nominal subject and source digest.

Source code in src/quivers/qiec/effect_law_schema.py
@classmethod
def for_module(
    cls,
    module: QiecModule,
    obligation: EffectLawObligation,
    evidence: Tested | Assumed,
) -> EffectLawEvidence:
    """Bind declared evidence to the exact module and law obligation.

    Parameters
    ----------
    module : QiecModule
        The executable QIEC module to which the evidence refers.
    obligation : EffectLawObligation
        The law and handler to which the evidence refers.
    evidence : Tested or Assumed
        The empirical result or assumption to record.

    Returns
    -------
    EffectLawEvidence
        Evidence with a checked nominal subject and source digest.
    """
    EffectLawBundle(module=module, obligations=(obligation,))
    return cls(
        obligation=obligation,
        module_digest=_module_digest(module),
        evidence=evidence,
    )

Checked effect plans

Compiler.effect_plan reports the carrier shapes of handlers in a selected entry's checked call graph, including calls made from authored clauses. Its stages describe the source computations reached in the resulting execution graph. Ordinary discharge and recursive state specialization report the rewrites actually applied. A remaining handler carries the reason it requires the reference machine. A direct caller can appear beside a retained callee in the same report. An EffectLawBundle can be inspected directly with checked_effect_plan. EffectLawEvidence.for_module attaches a Tested or Assumed claim to that exact module and obligation. Pass these records as law_evidence to Compiler.effect_plan. Each comparison reports its exact check status and the held declaration. A refuted equation retains its counterexample even if the attached record declares an assumption. The digest changes when the source or its checked operations change.

The report gives every requested law its own result. A checked law carries the evidence for its actual named handler. A refuted law carries the checker’s separating assignment. An unsupported comparison, exhausted limit, or unproved named condition leaves that obligation unresolved. Ordinary discharge applies its own checked rules independently of these reports.

For a scalar real entry, plan.check_jvp(arguments, direction) runs the exact reference derivative on both the source graph and its staged graph. It records their values and tangents at the supplied point. A comparison boundary or an exhausted evaluation reports its actual obstacle. A checked equality certifies those two observations at that point and direction.

Use plan.check_output_jvp to permit shared suffixes in a pointwise scalar output comparison. If ordinary discharge retained the selected entry because of growth, this check independently confirms the obstacle and tries the closed two-shot specialization. The comparison records the actual selected graph and its observed value and tangent. Scope or budget refusal leaves the alternate comparison unresolved. The ordinary plan and its source trace and target evidence remain available through the existing interfaces.

from quivers.dsl import Compiler, parse
from quivers.qiec import EffectEquation, EffectLawObligation

source = """
effect Reader
    read_value : Unit -> Bool

instance reader : Reader

handler fixed for Reader : Bool -> Bool with (value : Bool) [coverage=total, forwards=none, implementation=authored]
    read_value resumes 1 =>
        resume(value)

define read_once() : Bool !{reader} =
    perform reader.read_value()

define read_twice() : Bool !{reader} =
    let ignored <- perform reader.read_value()
    perform reader.read_value()

define example(value : Bool) : Bool !{} =
    handle reader with fixed(value) in
        read_once()
"""
compiler = Compiler(parse(source), module_name="planned-reader")
module = compiler.qiec_module
assert module is not None
effect = next(item for item in module.effects if item.ref.name == "Reader")
instance = next(item.entry for item in module.instances if item.name == "reader")
handler = next(item for item in module.handlers if item.name == "fixed")
roots = {item.name: item.id for item in module.computations}
equation = EffectEquation(
    effect.ref.id, "repeated-read", instance.instance,
    tuple(item.id for item in effect.operations), roots["read_once"], roots["read_twice"],
)
obligation = EffectLawObligation(equation=equation, handler=handler.id, method="finite")
plan = compiler.effect_plan("example", obligations=(obligation,))
assert plan.carriers[0].kind == "tail-state"
assert plan.laws[0].status == "checked"
stage = next(item for item in plan.stages if item.computation == roots["example"])
assert stage.stage == "evidence-passing"
assert stage.rewrite is not None and len(stage.rewrite.companions) == 1

Authored finite laws

An effect_law declaration names the instance, the operations used by the equation, and its two named computations. The handlers entry requests a separate check for each implementation. The default finite check enumerates the common input values and each handler's initial state. A Boolean product can represent a continuation table with one answer for each Boolean input.

The equation compares the returned values under each named handler. For instance, reading once and reading twice can return the same value while producing different request traces. The effect plan reports the law independently of ordinary discharge and target selection.

authored_source = source + """
effect_law repeated_read [instance=reader, operations=[read_value], left=read_once, right=read_twice, handlers=[fixed]]
"""
authored = Compiler(parse(authored_source), module_name="planned-reader")
plan = authored.effect_plan("example")
report = plan.laws[0]
assert report.obligation.equation.name == "repeated_read"
assert report.obligation.method == "finite"
assert report.status == "checked"
assert report.decision is not None and report.decision.result.checked == 2

plan.check_target(target) reports the outcome of a QIEC export. It uses the ordinary target projector, renderer and grammar emitter. A host target can select the original handlers, which appear as source-handler. A static target reads the discharged computation and its stages. An unsupported export carries the target's refusal names and diagnostic. For a probabilistic program, Compiler.effect_plan retains the parsed source with its checked module. The report follows the public export selection and uses the program planner for data, constraints and sites. It labels the result program-plan and gives its QIEC helper projection in helper_projection. A plan made from QIEC alone needs parsed source to report that target stage.

With arguments and direction, the report compares exact native JVPs for the source and the graph selected by the target. A supplied derivative_rule is checked independently against its nominal source. These checks concern QIEC. The external_derivative field records that the backend derivative is unverified even when the source and projected JVPs agree and the target emits code. A request to compare native JVPs on a probabilistic program reports an obstacle because the emitted statement plan has no corresponding scalar QIEC entry for that check.

plan.target_evidence(target) records the selected stages and the SHA-256 digest of the emitted artifact, or the target's named refusals. It binds these observations to the exact checked QIEC module and entry. The wire loader checks the record's structure. verify_target_evidence repeats ordinary discharge and target emission against an independently supplied plan before comparing the receipt. For a program, that plan needs the compiler's parsed source. Native JVP and law checks retain their own scopes. External derivatives remain unverified after successful emission.

When an emitted Python, WebPPL, Julia, or Scheme runtime executes an authored grade-one clause, its usage check runs when the clause returns. Deferred calls and forwarded requests preserve that check in the clause's continuation. An enclosing abort can discard the check along with the pending clause. An enclosing multi-shot resumption preserves the existing token, whose upper bound still allows one use. A suspension before the token is used is refused when its captured continuation owns an active mutable handler or a lifecycle with observer hooks. The usage check of an explicitly supplied foreign callback remains at the callback's return.

A QVR clause written with resumes [1, 2] lowers to ResumptionInterval(minimum=1, maximum=2) for native execution. The isolated named installation handles one request to the declared nominal operation with the identity return. Its clause and resumed suffix use Booleans, unit and their products with local bindings and conditionals. They also admit scalar Real values with the nominal addition, subtraction, multiplication and greater-than primitives. Exact forward and reverse derivatives use the branch selected at the point of evaluation. An input-dependent comparison at equality raises a boundary error even when the given tangent is zero. The checker adds usage bounds across sequential terms and takes the minimum and maximum across branches. The interval bounds every completed clause path when that lexical range lies inside it. No admitted path can hand the token to a caller, intercept it in another handler, or invoke a foreign clause.

The native runtime checks the upper bound before it records or copies a shot. It checks the lower bound when the sole clause token returns. Shots are numbered in execution order from zero. An interval requires an upper bound of at least two. The existing grades cover upper bounds of zero and one and keep their wire encoding. Target projection reports resumption-interval at an entry that reaches such an installation.

Emitted Python, Julia, Scheme, and WebPPL release an authored grade-zero clause's capture after the clause returns. A forwarded request carries the pending cleanup in the original lifecycle order. If an enclosing authored grade-zero clause abandons it, the runtime releases the hidden capture once. A live pending cleanup requires exclusive ownership. An enclosing affine or unrestricted resumption, a foreign abort, or a foreign resume that would return a still-suspended cleanup raises a named refusal. WebPPL preserves cleanup order when hooks return normally. A hook that raises a WebPPL error terminates execution at that hook.

In emitted WebPPL, Julia, and Scheme, request addresses retain the original static site. Taking an unrestricted resumption adds its shot ordinal to the path. Affine and linear resumptions preserve the path they inherit.

An emitted Pyro trace records site["infer"]["qiec_address"] for each draw and explicit score reached inside a QIEC helper. The address contains the original static site, the ordered frames inside that helper's entry, and the helper runtime's resumption path. An affine or linear resumption adds no ordinal. Pyro uses its usual site names to condition or replay draws. The reference program may have extra frames for the enclosing program and its call of the helper. Pyro puts the density contribution on the draw's trace node and records each explicit score as a separate factor.

For instance, suppose a clause resumes a Bernoulli continuation twice, with probabilities \(p\) and \(1-p\), and returns the sum of the answers. A second handler resumes once with each supplied probability. At fixed outcomes \((b_0,b_1)\), let each continuation return its probability times \(1+b_i\) and add its squared probability as a log factor. Let the caller add a final log factor of \(3p\) after the handler exits. The two draws and the factors inside their continuations have paths \((0)\) and \((1)\), and the final factor has an empty resumption path. For \(0 < p < 1\), the returned value has derivative \(b_0-b_1\). The derivative of the fixed trace's log joint adds the two Bernoulli log-mass derivatives and \(2p-2(1-p)+3\). It holds the outcomes fixed throughout.

from quivers.dsl import Compiler, parse
from quivers.qiec import EffectTargetEvidence, dumps, loads

source = """
effect Echo
    echo : Real -> Real

instance echo : Echo

handler identity for Echo : Real -> Real [coverage=total, forwards=none, implementation=authored]
    echo(value : Real) resumes 1 =>
        resume(value)

define square(x : Real) : Real !{} =
    handle echo with identity in
        let value <- perform echo.echo(x)
        return value * value
"""
plan = Compiler(parse(source), module_name="echo-square").effect_plan("square")
pyro = plan.check_target("pyro", arguments=(2,), direction=(1,))
stan = plan.check_target("stan", arguments=(2,), direction=(1,))
assert pyro.stages[0].stage == "source-handler"
assert stan.stages[0].stage == "evidence-passing"
assert stan.native_jvp.status == "checked" and stan.native_jvp.staged.tangent == 4
assert stan.external_derivative.missing == ("external derivative unverified",)
receipt = loads(dumps(plan.target_evidence("stan")))
assert isinstance(receipt, EffectTargetEvidence)
owner = Compiler(parse(source), module_name="echo-square").effect_plan("square")
assert owner.verify_target_evidence(receipt) == receipt
assert receipt.artifact_digest is not None
assert receipt.external_derivative.missing == ("external derivative unverified",)
from quivers.dsl import Compiler, parse

source = """
object Row : FinSet 4

program draws : Row -> Row
    let x <- sample Normal(loc=0.0, scale=1.0)
    return x

export draws
"""
plan = Compiler(parse(source), module_name="simple-draw").effect_plan("draws")
report = plan.check_target("stan")
assert report.projection == "program-plan"
assert report.helper_projection == "discharged"
assert report.external_derivative.missing == ("external derivative unverified",)

EffectPlan.classify_targets runs the registered renderers for one checked entry. Each row records the stage selected by the emitter, the independently checked law and interchange claims, and the native derivative comparison when requested. A refused row retains the backend's diagnostic. The law, helper, and derivative receipts in the row use their existing verification methods. External derivative status remains unverified after emission alone.

For entries with named returns, each row also reports their checked order, optional labels, and any return coordinates identified by the emitter. Pyro and WebPPL report coordinates for the eligible return layouts. A missing coordinate carries a reason tied to the selected target.

The standalone computation below squares its input. At \(x=2\) in direction \(dx=3\), the value and directional derivative are \(4\) and \(12\).

from quivers.dsl import Compiler, parse
from quivers.qiec import EffectDerivativeRequest, Rational

source = """
define square(x : Real) : Real !{} =
    return x * x
"""
plan = Compiler(parse(source)).effect_plan("square")
request = EffectDerivativeRequest(
    target="pyro", arguments=(Rational.of(2),), direction=(Rational.of(3),),
)
targets = {
    row.emission.target: row for row in plan.classify_targets(derivatives=(request,))
}
pyro = targets["pyro"]
assert pyro.derivative is not None
assert pyro.derivative.native_source == (Rational.of(4), Rational.of(12))
assert pyro.derivative.native_staged == pyro.derivative.native_source
assert pyro.external_derivative.missing == ("external derivative unverified",)

effect_plan

Report the actual checked handler shapes and nominal law checks for a plan.

EffectLawReport dataclass

EffectLawReport(obligation: EffectLawObligation, decision: _Decision | None, reason: str | None, declared_evidence: EffectLawEvidence | None = None)

The result of checking one declared obligation against its source.

PARAMETER DESCRIPTION
obligation

The exact requested equation, handler, method, and guard conditions.

TYPE: EffectLawObligation

decision

The freshly checked result, including a witness when the law fails.

TYPE: FiniteEffectLawDecision or ScalarEffectLawDecision or None

reason

Why the checker could not decide the obligation, if it could not.

TYPE: str or None

declared_evidence

The test or assumption attached to this exact source.

TYPE: EffectLawEvidence or None DEFAULT: None

status property

status: _ClaimStatus

The result of the check.

RETURNS DESCRIPTION
_ClaimStatus

Whether the law was checked, refuted, or left unresolved.

EffectInterchangeReport dataclass

EffectInterchangeReport(statement: FiniteHandlerInterchange, decision: FiniteLawDecision | None, reason: str | None, name: str | None = None)

The returned-value observation of one requested finite interchange.

PARAMETER DESCRIPTION
statement

The two named computations whose installation orders are compared.

TYPE: FiniteHandlerInterchange

decision

The result of the finite comparison when it can be decided.

TYPE: FiniteLawDecision or None

reason

The obstacle to deciding the interchange, if there is one.

TYPE: str or None

name

The name of an interchange declared in source, if any.

TYPE: str or None DEFAULT: None

status property

status: _ClaimStatus

The status of the returned-value comparison.

RETURNS DESCRIPTION
_ClaimStatus

Whether the interchange was checked, refuted, or left unresolved.

EffectExecutionStage dataclass

EffectExecutionStage(computation: ComputationId, stage: _Stage, rewrite: DischargeRewrite | None = None, obstacle: DischargeObstacle | None = None)

One source computation reached in the selected execution graph.

PARAMETER DESCRIPTION
computation

The original checked identity, preserved by lowering.

TYPE: ComputationId

stage

direct has no local rewrite. Ordinary discharge uses reference for a retained handler and names its obstacle. A target retaining a source handler uses source-handler at its original installation. A direct caller can reach a computation at another stage. program-plan is the target's probabilistic statement plan.

TYPE: ('direct', 'handler-discharge', 'recursive-state', 'evidence-passing', 'reference', 'source-handler', 'program-plan') DEFAULT: "direct"

rewrite

The checked transformation and its companions, if one ran.

TYPE: DischargeRewrite or None DEFAULT: None

obstacle

The reason a handler remains for reference execution.

TYPE: DischargeObstacle or None DEFAULT: None

EffectJvpCheck dataclass

EffectJvpCheck(computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], source: ExactJvp | None, staged: ExactJvp | None, source_obstacle: str | None, staged_obstacle: str | None)

A pointwise comparison of exact source and staged derivatives.

PARAMETER DESCRIPTION
computation

The checked source identity selected for both evaluations.

TYPE: ComputationId

arguments

The source coordinates in parameter order.

TYPE: tuple[int or Fraction, ...]

direction

The supplied tangent in that order.

TYPE: tuple[int or Fraction, ...]

source

The source machine's result when it admits the calculation.

TYPE: ExactJvp or None

staged

The selected staged graph's result under the same calculation.

TYPE: ExactJvp or None

source_obstacle

The actual derivative refusal in the source graph, if any.

TYPE: str or None

staged_obstacle

The actual derivative refusal in the staged graph, if any.

TYPE: str or None

status property

status: _ClaimStatus

Report whether the two actual observations agree.

RETURNS DESCRIPTION
_ClaimStatus

Whether both results agree, differ, or a result is unavailable.

EffectOutputJvpCheck dataclass

EffectOutputJvpCheck(comparison: EffectJvpCheck, stage: Literal['ordinary', 'shared-fork'] | None, ordinary_growth: DischargeObstacle | None, shared_fork: SharedForkPlan | None)

An output-only scalar comparison and the graph selected for it.

PARAMETER DESCRIPTION
comparison

The actual exact source and selected graph observations, or their named refusals, at the requested point and direction.

TYPE: EffectJvpCheck

stage

The graph used for the staged observation. Ordinary selects the graph of the existing plan, including a retained reference graph when the older output-only comparison allows it. None means the requested staged representation was unavailable before evaluation.

TYPE: ('ordinary', 'shared-fork') DEFAULT: "ordinary"

ordinary_growth

The independently checked growth obstacle of the selected source entry, when it triggered an alternate check.

TYPE: DischargeObstacle or None

shared_fork

The freshly checked residual and its nominal fork evidence, when that graph was selected.

TYPE: SharedForkPlan or None

EffectTargetReport dataclass

EffectTargetReport(target: str, computation: ComputationId, projection: _TargetProjection | None, stages: tuple[EffectExecutionStage, ...], refusals: tuple[str, ...], detail: str | None, laws: tuple[EffectLawReport, ...], native_jvp: EffectJvpCheck | None, derivative_rule: RationalDerivativeDeclaration | None, rule_decision: RationalDerivativeDecision | None, rule_obstacle: str | None, external_derivative: DerivativeSemantics, helper_projection: _HelperProjection | None = None, native_obstacle: str | None = None, _artifact_digest: str | None = None, _helper_stages: tuple[EffectHelperStageRecord, ...] = (), _output_layout: tuple[tuple[str, ...], Literal['single', 'tuple', 'array']] | None = None)

An actual export outcome with scoped derivative evidence.

PARAMETER DESCRIPTION
target

The requested public target key.

TYPE: str

computation

The source entry whose execution stages are reported.

TYPE: ComputationId

projection

The selected standalone QIEC graph or probabilistic program plan.

TYPE: ('source', 'discharged', 'program-plan') DEFAULT: "source"

stages

Source entries reached by a standalone graph, or the selected program entry carrying the probabilistic statement stage.

TYPE: tuple[EffectExecutionStage, ...]

refusals

The target's named refusal kinds, if the export failed.

TYPE: tuple[str, ...]

detail

The backend diagnostic including any failed hypothesis.

TYPE: str or None

laws

The plan's source law reports and their existing evidence.

TYPE: tuple[EffectLawReport, ...]

native_jvp

Requested exact comparison of source and selected QIEC graph.

TYPE: EffectJvpCheck or None

derivative_rule

The nominal source derivative formula, if requested.

TYPE: RationalDerivativeDeclaration or None

rule_decision

The exact recheck of that formula against the actual source.

TYPE: RationalDerivativeDecision or None

rule_obstacle

The reason the source formula could not be checked, if any.

TYPE: str or None

external_derivative

The report for the emitted backend's derivative. Emission and QIEC checks provide no evidence about that derivative.

TYPE: DerivativeSemantics

helper_projection

Whether the QIEC helper graph has any checked discharge rewrites.

TYPE: ('source', 'discharged') DEFAULT: "source"

native_obstacle

The named hypothesis blocking a requested comparison when its target stage does not emit a comparable scalar QIEC graph.

TYPE: str or None DEFAULT: None

_artifact_digest

SHA-256 of successfully emitted bytes for a target receipt.

TYPE: str or None DEFAULT: None

_helper_stages

Emitted helper stages when requested by the portable helper receipt.

TYPE: tuple of EffectHelperStageRecord DEFAULT: ()

_output_layout

The emitted locals and result layout when output evidence is requested.

TYPE: tuple or None DEFAULT: None

EffectTargetClassification dataclass

EffectTargetClassification(claims: EffectTargetClaimEvidence, helpers: EffectTargetHelperEvidence | None, helper_obstacle: str | None, derivative: EffectTargetDerivativeEvidence | None, diagnostic: str | None, outputs: EffectTargetOutputEvidence | None = None)

The existing checked observations from one target emission.

The receipts retain their ordinary independent verification methods. They name the same artifact or refusal under the same entry and target.

PARAMETER DESCRIPTION
claims

The source-bound emission and all independently checked law and interchange claims, in the plan's request order.

TYPE: EffectTargetClaimEvidence

helpers

The definitions the actual target selected, when its selector is covered by the helper receipt.

TYPE: EffectTargetHelperEvidence | None

helper_obstacle

The reason a registered target has no supported helper manifest.

TYPE: str | None

derivative

The existing native comparison and source rule receipt when explicitly requested for this target.

TYPE: EffectTargetDerivativeEvidence | None

diagnostic

The renderer or emitter's diagnostic when the export was refused.

TYPE: str | None

outputs

Coordinates and derivative scope for the checked program's named returns, when the source entry declares any.

TYPE: EffectTargetOutputEvidence | None DEFAULT: None

emission property

Read the common source, stages, and artifact identity.

RETURNS DESCRIPTION
EffectTargetEvidence

The actual target observation for this entry.

external_derivative property

external_derivative: DerivativeSemantics

Read the external status established by this emission path.

RETURNS DESCRIPTION
DerivativeSemantics

The record of unverified external derivatives or an export refusal.

__post_init__

__post_init__() -> None

Check that all present receipts identify the same observation.

RAISES DESCRIPTION
ValueError

If components name different emissions or omit a helper outcome.

Source code in src/quivers/qiec/effect_plan.py
def __post_init__(self) -> None:
    """Check that all present receipts identify the same observation.

    Raises
    ------
    ValueError
        If components name different emissions or omit a helper outcome.
    """
    emission = self.claims.emission
    expected_obstacle = (
        None
        if emission.target in _HELPER_MANIFEST_TARGETS
        else f"qiec:target-helper:manifest-unavailable:{emission.target}"
    )
    if (
        self.helper_obstacle != expected_obstacle
        or (self.helpers is None) != (expected_obstacle is not None)
        or (self.helpers is not None and self.helpers.emission != emission)
        or (self.derivative is not None and self.derivative.emission != emission)
        or (
            self.outputs is not None
            and (
                self.outputs.emission != emission
                or self.outputs.derivative != self.derivative
            )
        )
    ):
        raise ValueError("target classification components disagree on emission")

EffectBernoulliBatchCheck dataclass

EffectBernoulliBatchCheck(source_digest: str, discharged_digest: str, batch: BernoulliBatchPlan, shared_direction: tuple[int | Fraction, ...], row_directions: tuple[tuple[int | Fraction, ...], ...], exact: tuple[ExactJvp, ...])

An executed native finite Bernoulli batch on a checked discharged owner.

The finite-bernoulli-batch stage uses exact scalar basis replays.

PARAMETER DESCRIPTION
source_digest

The canonical source and actual discharged module digests.

TYPE: str

discharged_digest

The canonical source and actual discharged module digests.

TYPE: str

batch

The selected computation's exact batch with its addressed row laws and measured source work.

TYPE: BernoulliBatchPlan

shared_direction

The exact shared tangent and the local tangents in row order.

TYPE: tuple

row_directions

The exact shared tangent and the local tangents in row order.

TYPE: tuple

exact

The expectation and its directional derivative for each row.

TYPE: tuple[ExactJvp, ...]

EffectScalarObservationRequest dataclass

EffectScalarObservationRequest(arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], allow_shared_fork: bool = False, fuel: int = 65536, max_terms: int = 2048, max_shots: int = 65534)

Select an exact scalar returned-value and JVP comparison.

PARAMETER DESCRIPTION
arguments

The exact point and tangent in source parameter order.

TYPE: tuple of int or Fraction

direction

The exact point and tangent in source parameter order.

TYPE: tuple of int or Fraction

allow_shared_fork

Allow shared suffixes when the selected entry exceeds ordinary discharge growth. The observation concerns the scalar output.

TYPE: bool DEFAULT: False

fuel

Evaluator steps per source or staged run.

TYPE: int DEFAULT: 65536

max_terms

Retained terms and unfolded calls allowed in the shared stage.

TYPE: int DEFAULT: 2048

max_shots

Retained terms and unfolded calls allowed in the shared stage.

TYPE: int DEFAULT: 2048

EffectBernoulliAxisRequest dataclass

EffectBernoulliAxisRequest(axis: str, shared: tuple[int | Fraction, ...], rows: tuple[tuple[int | Fraction, ...], ...], policies: tuple[SiteEstimator, ...], shared_direction: tuple[int | Fraction, ...], row_directions: tuple[tuple[int | Fraction, ...], ...], max_rows: int = 256, max_paths: int = 256, max_work: int = 1000000, max_comparison_work: int = 1000000, fuel: int = 50000)

Select the addressed law and exact first action of a Bernoulli row axis.

PARAMETER DESCRIPTION
axis

The namespace of the independent row histories.

TYPE: str

shared

Exact shared and row-local coordinates in source and row order.

TYPE: tuple

rows

Exact shared and row-local coordinates in source and row order.

TYPE: tuple

policies

The original nominal enumeration policies.

TYPE: tuple of SiteEstimator

shared_direction

Exact tangents in the same order as their coordinates.

TYPE: tuple

row_directions

Exact tangents in the same order as their coordinates.

TYPE: tuple

max_rows

Row cap and complete history cap per scalar traversal.

TYPE: int DEFAULT: 256

max_paths

Row cap and complete history cap per scalar traversal.

TYPE: int DEFAULT: 256

max_work

Hard evaluator-step caps for the staged basis schedule and the extra source and staged directional replay schedules.

TYPE: int DEFAULT: 1000000

max_comparison_work

Hard evaluator-step caps for the staged basis schedule and the extra source and staged directional replay schedules.

TYPE: int DEFAULT: 1000000

fuel

Evaluator steps per replay prefix, including partial histories.

TYPE: int DEFAULT: 50000

EffectBernoulliAxisAtom dataclass

EffectBernoulliAxisAtom(tape: BernoulliRowReplay, mass: ExactJvp, payoff: ExactJvp)

One complete outward Random history and its exact directional data.

PARAMETER DESCRIPTION
tape

The axis, original ordinal, full Random addresses and outcomes.

TYPE: BernoulliRowReplay

mass

The probability and its derivative at the requested input.

TYPE: ExactJvp

payoff

The returned value and its derivative with those choices fixed.

TYPE: ExactJvp

EffectBernoulliAxisObservation dataclass

EffectBernoulliAxisObservation(axis: EffectBernoulliBatchCheck, source: tuple[tuple[EffectBernoulliAxisAtom, ...], ...], staged: tuple[tuple[EffectBernoulliAxisAtom, ...], ...], source_exact: tuple[ExactJvp, ...], staged_exact: tuple[ExactJvp, ...], source_steps: int, staged_steps: int, difference: str | None)

Compare the original Random law to the actual exact discharged axis.

The source and staged histories concern the selected Random instance. The scalar and axis comparisons make no claim about external targets.

PARAMETER DESCRIPTION
axis

The selected exact staged basis computation and its row JVPs.

TYPE: EffectBernoulliBatchCheck

source

Complete ordered atom observations from the two separate executions.

TYPE: tuple of tuple of EffectBernoulliAxisAtom

staged

Complete ordered atom observations from the two separate executions.

TYPE: tuple of tuple of EffectBernoulliAxisAtom

source_exact

The two scalar schedules' row expectations and directional actions.

TYPE: tuple of ExactJvp

staged_exact

The two scalar schedules' row expectations and directional actions.

TYPE: tuple of ExactJvp

source_steps

Reference ticks counted in the extra directional traversals. The staged basis schedule has a separate count in axis.batch.

TYPE: int

staged_steps

Reference ticks counted in the extra directional traversals. The staged basis schedule has a separate count in axis.batch.

TYPE: int

difference

The first named difference, including the row ordinal.

TYPE: str or None

status property

status: Literal['checked', 'refuted']

Give the result of comparing the observed addressed laws.

RETURNS DESCRIPTION
{'checked', 'refuted'}

Whether the actual observations agree.

EffectBernoulliTensorReplayCheck dataclass

EffectBernoulliTensorReplayCheck(source_digest: str, discharged_digest: str, computation: ComputationId, shared: Tensor, rows: Tensor, shared_direction: Tensor, row_directions: Tensor, replay: BernoulliTensorResult, value_jvp: Tensor, log_score_jvp: Tensor, max_rows: int, fuel: int, allow_disjoint_replay: bool = False)

One physical tensor replay and its working-precision fixed-tape JVP.

The native observation has stage bernoulli-tensor-replay.

PARAMETER DESCRIPTION
source_digest

The canonical source and the recomputed discharged module digests.

TYPE: str

discharged_digest

The canonical source and the recomputed discharged module digests.

TYPE: str

computation

The nominal source entry preserved by discharge.

TYPE: ComputationId

shared

Detached copies of the shared and local working-precision inputs.

TYPE: Tensor

rows

Detached copies of the shared and local working-precision inputs.

TYPE: Tensor

shared_direction

Detached copies of the matching directional inputs.

TYPE: Tensor

row_directions

Detached copies of the matching directional inputs.

TYPE: Tensor

replay

The observed row values, per-occurrence log scores, complete addressed tapes and native evaluator counters.

TYPE: BernoulliTensorResult

value_jvp

The observed directional derivatives with the tapes held fixed.

TYPE: Tensor

log_score_jvp

The observed directional derivatives with the tapes held fixed.

TYPE: Tensor

max_rows

The configured row and physical evaluator step caps.

TYPE: int

fuel

The configured row and physical evaluator step caps.

TYPE: int

allow_disjoint_replay

Whether the requested replay permits different original addresses in the two checked constructor cohorts.

TYPE: bool DEFAULT: False

EffectPlan dataclass

EffectPlan(bundle: EffectLawBundle, computation: ComputationId, carriers: tuple[HandlerCarrierShape, ...], laws: tuple[EffectLawReport, ...], discharge: DischargedModule, interchanges: tuple[EffectInterchangeReport, ...] = (), stages: tuple[EffectExecutionStage, ...] = (), _program_source: object | None = None, _claim_request: object | None = None)

A view of the source, carrier analysis, law results, and discharge.

PARAMETER DESCRIPTION
bundle

The checked source and all the law obligations requested for it.

TYPE: EffectLawBundle

computation

The selected source computation.

TYPE: ComputationId

carriers

Carrier shapes for handlers in the computation's checked call graph.

TYPE: tuple[HandlerCarrierShape, ...]

laws

One result per requested obligation, regardless of reachability from the selected computation.

TYPE: tuple[EffectLawReport, ...]

discharge

The result of ordinary checked discharge, including its obstacles. Ordinary discharge applies its own checked rules.

TYPE: DischargedModule

interchanges

Returned-value observations from independently checked finite interchanges.

TYPE: tuple[EffectInterchangeReport, ...] DEFAULT: ()

stages

The stages of reachable source computations in the discharged graph. Generated computations appear on their originating rewrite.

TYPE: tuple[EffectExecutionStage, ...] DEFAULT: ()

_program_source

The compiler's parsed program source and the digest of the checked QIEC module compiled from it. Direct QIEC plans have neither.

TYPE: object or None DEFAULT: None

_claim_request

The independent request and bounds for rechecking all recorded claims.

TYPE: object or None DEFAULT: None

check_jvp

check_jvp(arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], *, fuel: int = 65536) -> EffectJvpCheck

Compare exact scalar JVPs in the source and staged QIEC graphs.

Both evaluations use the selected source identity. The reported equality concerns the exact supplied point and direction in the regular scalar fragment.

PARAMETER DESCRIPTION
arguments

Exact input coordinates in source order.

TYPE: tuple[int or Fraction, ...]

direction

Exact tangent coordinates in the same order.

TYPE: tuple[int or Fraction, ...]

fuel

Reference steps allowed independently in each graph.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
EffectJvpCheck

Both results or the specified refusals at the point.

RAISES DESCRIPTION
ValueError

If the computation identity, inputs, or fuel are invalid.

Source code in src/quivers/qiec/effect_plan.py
def check_jvp(
    self,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    *,
    fuel: int = 65_536,
) -> EffectJvpCheck:
    """Compare exact scalar JVPs in the source and staged QIEC graphs.

    Both evaluations use the selected source identity. The reported
    equality concerns the exact supplied point and direction in the
    regular scalar fragment.

    Parameters
    ----------
    arguments : tuple[int or Fraction, ...]
        Exact input coordinates in source order.
    direction : tuple[int or Fraction, ...]
        Exact tangent coordinates in the same order.
    fuel : int
        Reference steps allowed independently in each graph.

    Returns
    -------
    EffectJvpCheck
        Both results or the specified refusals at the point.

    Raises
    ------
    ValueError
        If the computation identity, inputs, or fuel are invalid.
    """
    return _compare_jvp(
        self.bundle.module,
        self.discharge.module,
        self.computation,
        arguments,
        direction,
        fuel,
    )

check_output_jvp

check_output_jvp(arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], *, fuel: int = 65536, max_terms: int = 2048, max_shots: int = 65534) -> EffectOutputJvpCheck

Compare scalar outputs, trying a shared fork after local growth.

Only the selected source entry's ordinary growth obstacle can select a shared fork. The report compares exact values and tangents at the requested point. This check leaves the ordinary execution stages, trace and target evidence untouched.

PARAMETER DESCRIPTION
arguments

Exact input coordinates in source order.

TYPE: tuple[int or Fraction, ...]

direction

Exact tangent coordinates in that order.

TYPE: tuple[int or Fraction, ...]

fuel

Reference steps independently allowed in each graph.

TYPE: int DEFAULT: 65536

max_terms

Bound on the alternative's retained computation nodes.

TYPE: int DEFAULT: 2048

max_shots

Bound on the alternative's unfolded calls.

TYPE: int DEFAULT: 65534

RETURNS DESCRIPTION
EffectOutputJvpCheck

The selected observation and exact results or named refusals.

RAISES DESCRIPTION
ValueError

If inputs or bounds are invalid, or the plan's recorded growth status disagrees with the checked source.

Source code in src/quivers/qiec/effect_plan.py
def check_output_jvp(
    self,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    *,
    fuel: int = 65_536,
    max_terms: int = 2_048,
    max_shots: int = 65_534,
) -> EffectOutputJvpCheck:
    """Compare scalar outputs, trying a shared fork after local growth.

    Only the selected source entry's ordinary growth obstacle can
    select a shared fork. The report compares exact values and
    tangents at the requested point. This check leaves the ordinary
    execution stages, trace and target evidence untouched.

    Parameters
    ----------
    arguments : tuple[int or Fraction, ...]
        Exact input coordinates in source order.
    direction : tuple[int or Fraction, ...]
        Exact tangent coordinates in that order.
    fuel : int
        Reference steps independently allowed in each graph.
    max_terms : int
        Bound on the alternative's retained computation nodes.
    max_shots : int
        Bound on the alternative's unfolded calls.

    Returns
    -------
    EffectOutputJvpCheck
        The selected observation and exact results or named refusals.

    Raises
    ------
    ValueError
        If inputs or bounds are invalid, or the plan's recorded
        growth status disagrees with the checked source.
    """
    _validate_limit("fuel", fuel)
    _validate_limit("max_terms", max_terms)
    _validate_limit("max_shots", max_shots)
    source = self.bundle.module
    owner = next(
        (item for item in source.computations if item.id == self.computation), None
    )
    if owner is None:
        raise ValueError("the effect plan does not name a source computation")

    attested = (
        discharge_computation(owner, source) if installs_handler(owner) else None
    )
    growth = (
        attested
        if isinstance(attested, DischargeObstacle) and attested.kind == "growth"
        else None
    )
    recorded = self.discharge.obstacle(owner.name)
    recorded_growth = (
        recorded if recorded is not None and recorded.kind == "growth" else None
    )
    if growth != recorded_growth:
        raise ValueError(
            "the effect plan's growth obstacle differs from checked source"
        )

    if growth is None:
        comparison = self.check_jvp(arguments, direction, fuel=fuel)
        return EffectOutputJvpCheck(comparison, "ordinary", None, None)
    if owner not in self.discharge.module.computations:
        raise ValueError(
            "the effect plan's growth entry differs from checked source"
        )

    try:
        shared = specialize_shared_fork(
            source, self.computation, max_terms=max_terms, max_shots=max_shots
        )
    except SharedForkUnsupported as error:
        reason = "limit" if isinstance(error, SharedForkLimit) else "scope"
        comparison = _compare_jvp(
            source,
            None,
            self.computation,
            arguments,
            direction,
            fuel,
            unavailable=f"qiec:shared-fork:{reason}: {error}",
        )
        return EffectOutputJvpCheck(comparison, None, growth, None)

    comparison = _compare_jvp(
        source, shared.module, self.computation, arguments, direction, fuel
    )
    return EffectOutputJvpCheck(comparison, "shared-fork", growth, shared)

check_native_observation

Execute the native comparison selected by an explicit request.

A scalar request compares returned values and directional actions. A reachable retained reference obstacle leaves the staged scalar observation unresolved unless a checked shared fork is selected. An addressed axis request compares original and selected Random histories through exact scalar and staged basis execution. Each request has its own stages, observations and resource bounds.

PARAMETER DESCRIPTION
request

The selected observation and its independently chosen inputs.

TYPE: EffectScalarObservationRequest or EffectBernoulliAxisRequest

RETURNS DESCRIPTION
EffectOutputJvpCheck or EffectBernoulliAxisObservation

The executed scope and its exact comparison results.

RAISES DESCRIPTION
ValueError

If arguments, bounds or the plan's checked discharge are invalid.

TypeError

If the observation request has an unsupported type.

JvpUnsupported

If an addressed graph, operation or regularity condition is outside the finite axis fragment.

JvpLimit

If the addressed axis or directional comparison reaches a limit.

Source code in src/quivers/qiec/effect_plan.py
def check_native_observation(
    self,
    request: EffectScalarObservationRequest | EffectBernoulliAxisRequest,
) -> EffectOutputJvpCheck | EffectBernoulliAxisObservation:
    """Execute the native comparison selected by an explicit request.

    A scalar request compares returned values and directional actions.
    A reachable retained reference obstacle leaves the staged scalar
    observation unresolved unless a checked shared fork is selected.
    An addressed axis request compares original and selected
    Random histories through exact scalar and staged basis execution.
    Each request has its own stages, observations and resource bounds.

    Parameters
    ----------
    request : EffectScalarObservationRequest or EffectBernoulliAxisRequest
        The selected observation and its independently chosen inputs.

    Returns
    -------
    EffectOutputJvpCheck or EffectBernoulliAxisObservation
        The executed scope and its exact comparison results.

    Raises
    ------
    ValueError
        If arguments, bounds or the plan's checked discharge are invalid.
    TypeError
        If the observation request has an unsupported type.
    JvpUnsupported
        If an addressed graph, operation or regularity condition is outside
        the finite axis fragment.
    JvpLimit
        If the addressed axis or directional comparison reaches a limit.
    """
    if isinstance(request, EffectBernoulliAxisRequest):
        return self._check_bernoulli_axis_observation(request)
    if not isinstance(request, EffectScalarObservationRequest):
        raise TypeError(
            "a native observation needs a scalar or Bernoulli axis request"
        )
    if type(request.allow_shared_fork) is not bool:
        raise ValueError("shared-fork selection must be Boolean")
    _validate_limit("fuel", request.fuel)
    source = self.bundle.module
    fresh = discharge_module(source)
    if fresh != self.discharge or _module_digest(fresh.module) != _module_digest(
        self.discharge.module
    ):
        raise ValueError("native observation needs the plan's checked discharge")

    retained = tuple(
        (stage.computation, stage.obstacle)
        for stage in _ordinary_stages(source, fresh, self.computation)
        if stage.stage == "reference" and stage.obstacle is not None
    )
    if request.allow_shared_fork:
        _validate_limit("max_terms", request.max_terms)
        _validate_limit("max_shots", request.max_shots)
        if any(
            entry == self.computation and obstacle.kind == "growth"
            for entry, obstacle in retained
        ):
            return self.check_output_jvp(
                request.arguments,
                request.direction,
                fuel=request.fuel,
                max_terms=request.max_terms,
                max_shots=request.max_shots,
            )
    if retained:
        _, obstacle = retained[0]
        comparison = _compare_jvp(
            source,
            None,
            self.computation,
            request.arguments,
            request.direction,
            request.fuel,
            unavailable=(
                "qiec:native-observation:retained-reference:"
                f"{obstacle.kind}:{obstacle.computation}"
            ),
        )
        return EffectOutputJvpCheck(comparison, None, None, None)
    return EffectOutputJvpCheck(
        self.check_jvp(request.arguments, request.direction, fuel=request.fuel),
        "ordinary",
        None,
        None,
    )

native_observation_evidence

Record a fresh checked native observation under an exact request.

PARAMETER DESCRIPTION
request

The independently selected coordinates, policies and limits.

TYPE: EffectScalarObservationRequest or EffectBernoulliAxisRequest

RETURNS DESCRIPTION
EffectNativeObservationEvidence

The checked owner, actual stage and exact observation binding.

RAISES DESCRIPTION
ValueError

If the request is noncanonical, the plan is invalid, or the observation was refuted or could not be checked.

TypeError

If the request has no supported native observation form.

JvpUnsupported

If the selected addressed observation is outside its fragment.

JvpLimit

If the addressed observation reaches its work limit.

Source code in src/quivers/qiec/effect_plan.py
def native_observation_evidence(
    self, request: EffectScalarObservationRequest | EffectBernoulliAxisRequest
) -> EffectNativeObservationEvidence:
    """Record a fresh checked native observation under an exact request.

    Parameters
    ----------
    request : EffectScalarObservationRequest or EffectBernoulliAxisRequest
        The independently selected coordinates, policies and limits.

    Returns
    -------
    EffectNativeObservationEvidence
        The checked owner, actual stage and exact observation binding.

    Raises
    ------
    ValueError
        If the request is noncanonical, the plan is invalid, or the
        observation was refuted or could not be checked.
    TypeError
        If the request has no supported native observation form.
    JvpUnsupported
        If the selected addressed observation is outside its fragment.
    JvpLimit
        If the addressed observation reaches its work limit.
    """
    request_digest = _native_observation_request_digest(request)
    observed = self.check_native_observation(request)
    source_digest = _module_digest(self.bundle.module)
    stage: _NativeObservationStage
    if isinstance(observed, EffectBernoulliAxisObservation):
        if observed.difference is not None:
            raise ValueError(
                f"native axis observation is refuted: {observed.difference}"
            )
        stage = "finite-bernoulli-batch"
        staged_digest = observed.axis.discharged_digest
        outcome = _native_axis_observation(observed)
    else:
        comparison = observed.comparison
        if comparison.status != "checked" or observed.stage is None:
            reason = (
                comparison.staged_obstacle
                or comparison.source_obstacle
                or "exact results differ"
            )
            raise ValueError(
                f"native scalar observation is {comparison.status}: {reason}"
            )
        stage = observed.stage
        shared = observed.shared_fork
        staged_digest = _module_digest(
            self.discharge.module if shared is None else shared.module
        )
        outcome = _native_scalar_observation(observed)
    return EffectNativeObservationEvidence(
        source_digest=source_digest,
        computation=self.computation,
        request_digest=request_digest,
        stage=stage,
        staged_digest=staged_digest,
        observation_digest=_native_digest(
            ("native-observation-v1", stage, outcome)
        ),
    )

verify_native_observation_evidence

Repeat the actual native comparison under an independent request.

PARAMETER DESCRIPTION
evidence

The detached receipt to verify.

TYPE: EffectNativeObservationEvidence

request

The verifier's own exact observation selection and bounds.

TYPE: EffectScalarObservationRequest or EffectBernoulliAxisRequest

RETURNS DESCRIPTION
EffectNativeObservationEvidence

The freshly checked matching receipt.

RAISES DESCRIPTION
ValueError

If the receipt differs, the request is invalid, or the comparison cannot be checked.

TypeError

If the request has no supported native observation form.

JvpUnsupported

If the selected addressed observation is outside its fragment.

JvpLimit

If the addressed observation reaches its work limit.

Source code in src/quivers/qiec/effect_plan.py
def verify_native_observation_evidence(
    self,
    evidence: EffectNativeObservationEvidence,
    *,
    request: EffectScalarObservationRequest | EffectBernoulliAxisRequest,
) -> EffectNativeObservationEvidence:
    """Repeat the actual native comparison under an independent request.

    Parameters
    ----------
    evidence : EffectNativeObservationEvidence
        The detached receipt to verify.
    request : EffectScalarObservationRequest or EffectBernoulliAxisRequest
        The verifier's own exact observation selection and bounds.

    Returns
    -------
    EffectNativeObservationEvidence
        The freshly checked matching receipt.

    Raises
    ------
    ValueError
        If the receipt differs, the request is invalid, or the
        comparison cannot be checked.
    TypeError
        If the request has no supported native observation form.
    JvpUnsupported
        If the selected addressed observation is outside its fragment.
    JvpLimit
        If the addressed observation reaches its work limit.
    """
    if evidence.request_digest != _native_observation_request_digest(request):
        raise ValueError("native observation evidence names a different request")
    if (
        evidence.source_digest != _module_digest(self.bundle.module)
        or evidence.computation != self.computation
    ):
        raise ValueError(
            "native observation evidence names a different checked source or entry"
        )
    observed = self.native_observation_evidence(request)
    if observed != evidence:
        raise ValueError(
            "native observation evidence disagrees with checked execution"
        )
    return observed

check_normal_piecewise_pathwise

check_normal_piecewise_pathwise(arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_work: int = 65536) -> NormalPiecewisePathwisePlan

Check the continuous Normal pathwise derivative of the selected source.

The check uses the original QIEC computation selected by the effect plan. It reports the expected return and directional derivative for one checked Normal site and affine payoff at the given point. The result concerns the source's Normal denotation and has the planner's exact fixed-noise action.

PARAMETER DESCRIPTION
arguments

The exact location and scale and their directional tangents, in source parameter order.

TYPE: tuple of int or Fraction

direction

The exact location and scale and their directional tangents, in source parameter order.

TYPE: tuple of int or Fraction

policies

One explicit reparam policy for the actual source site.

TYPE: tuple of SiteEstimator

max_work

The exact polynomial work budget for checking both arms.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
NormalPiecewisePathwisePlan

The freshly checked source boundary, symbolic mean and directional derivative, and fixed-noise action.

RAISES DESCRIPTION
ValueError

If the source owner, exact inputs or bound are invalid.

JvpUnsupported

If the source or policy fails the continuous Normal check.

JvpLimit

If the exact coefficient or proof budget is exceeded.

Source code in src/quivers/qiec/effect_plan.py
def check_normal_piecewise_pathwise(
    self,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    max_work: int = 65_536,
) -> NormalPiecewisePathwisePlan:
    """Check the continuous Normal pathwise derivative of the selected source.

    The check uses the original QIEC computation selected by the
    effect plan. It reports the expected return and directional
    derivative for one checked Normal site and affine payoff at the
    given point. The result concerns the source's Normal
    denotation and has the planner's exact fixed-noise action.

    Parameters
    ----------
    arguments, direction : tuple of int or Fraction
        The exact location and scale and their directional tangents,
        in source parameter order.
    policies : tuple of SiteEstimator
        One explicit reparam policy for the actual source site.
    max_work : int
        The exact polynomial work budget for checking both arms.

    Returns
    -------
    NormalPiecewisePathwisePlan
        The freshly checked source boundary, symbolic mean and
        directional derivative, and fixed-noise action.

    Raises
    ------
    ValueError
        If the source owner, exact inputs or bound are invalid.
    JvpUnsupported
        If the source or policy fails the continuous Normal check.
    JvpLimit
        If the exact coefficient or proof budget is exceeded.
    """
    return plan_normal_piecewise_pathwise(
        self.bundle.module,
        self.computation,
        arguments,
        direction,
        policies,
        max_work=max_work,
    )

check_bernoulli_batch

check_bernoulli_batch(axis: str, shared: tuple[int | Fraction, ...], rows: tuple[tuple[int | Fraction, ...], ...], policies: tuple[SiteEstimator, ...], *, shared_direction: tuple[int | Fraction, ...], row_directions: tuple[tuple[int | Fraction, ...], ...], max_rows: int = 256, max_paths: int = 256, max_work: int = 1000000, fuel: int = 50000) -> EffectBernoulliBatchCheck

Execute an explicitly requested exact row axis after checked discharge.

PARAMETER DESCRIPTION
axis

The axis label for the original row and draw identities.

TYPE: str

shared

Exact shared inputs and local inputs in row order.

TYPE: tuple

rows

Exact shared inputs and local inputs in row order.

TYPE: tuple

policies

Explicit enumeration policies for the selected source draws.

TYPE: tuple[SiteEstimator, ...]

shared_direction

Exact tangents matching the shared and local input shapes.

TYPE: tuple

row_directions

Exact tangents matching the shared and local input shapes.

TYPE: tuple

max_rows

Bounds on rows, complete paths per scalar run, total accepted reference steps, and steps per source replay.

TYPE: int DEFAULT: 256

max_paths

Bounds on rows, complete paths per scalar run, total accepted reference steps, and steps per source replay.

TYPE: int DEFAULT: 256

max_work

Bounds on rows, complete paths per scalar run, total accepted reference steps, and steps per source replay.

TYPE: int DEFAULT: 256

fuel

Bounds on rows, complete paths per scalar run, total accepted reference steps, and steps per source replay.

TYPE: int DEFAULT: 256

RETURNS DESCRIPTION
EffectBernoulliBatchCheck

A native stage check with the actual row laws and exact expectation JVPs at the requested point and direction.

RAISES DESCRIPTION
ValueError

If the discharged module disagrees with ordinary discharge or an input, tangent, policy or bound is invalid.

JvpUnsupported

If the selected graph is outside the checked batch fragment.

JvpBoundaryError

If the scalar execution reaches an input equality boundary.

JvpLimit

If a bound on row evaluation or exact arithmetic is exceeded.

Source code in src/quivers/qiec/effect_plan.py
def check_bernoulli_batch(
    self,
    axis: str,
    shared: tuple[int | Fraction, ...],
    rows: tuple[tuple[int | Fraction, ...], ...],
    policies: tuple[SiteEstimator, ...],
    *,
    shared_direction: tuple[int | Fraction, ...],
    row_directions: tuple[tuple[int | Fraction, ...], ...],
    max_rows: int = 256,
    max_paths: int = 256,
    max_work: int = 1_000_000,
    fuel: int = 50_000,
) -> EffectBernoulliBatchCheck:
    """Execute an explicitly requested exact row axis after checked discharge.

    Parameters
    ----------
    axis : str
        The axis label for the original row and draw identities.
    shared, rows : tuple
        Exact shared inputs and local inputs in row order.
    policies : tuple[SiteEstimator, ...]
        Explicit enumeration policies for the selected source draws.
    shared_direction, row_directions : tuple
        Exact tangents matching the shared and local input shapes.
    max_rows, max_paths, max_work, fuel : int
        Bounds on rows, complete paths per scalar run, total accepted
        reference steps, and steps per source replay.

    Returns
    -------
    EffectBernoulliBatchCheck
        A native stage check with the actual row laws and exact
        expectation JVPs at the requested point and direction.

    Raises
    ------
    ValueError
        If the discharged module disagrees with ordinary discharge
        or an input, tangent, policy or bound is invalid.
    JvpUnsupported
        If the selected graph is outside the checked batch fragment.
    JvpBoundaryError
        If the scalar execution reaches an input equality boundary.
    JvpLimit
        If a bound on row evaluation or exact arithmetic is exceeded.
    """
    source = self.bundle.module
    discharged = discharge_module(source).module
    discharged_digest = _module_digest(discharged)
    if discharged_digest != _module_digest(self.discharge.module):
        raise ValueError("Bernoulli batch requires the plan's checked discharge")
    batch = plan_bernoulli_batch(
        discharged,
        self.computation,
        axis,
        shared,
        rows,
        policies,
        max_rows=max_rows,
        max_paths=max_paths,
        max_work=max_work,
        fuel=fuel,
    )
    tangents = batch.expected.jvp(shared_direction, row_directions)
    return EffectBernoulliBatchCheck(
        _module_digest(source),
        discharged_digest,
        batch,
        tuple(shared_direction),
        tuple(map(tuple, row_directions)),
        tuple(
            ExactJvp(value, tangent)
            for value, tangent in zip(batch.expected.values, tangents, strict=True)
        ),
    )

check_bernoulli_tensor_replay

check_bernoulli_tensor_replay(axis: str, shared: Tensor, rows: Tensor, tapes: tuple[BernoulliRowReplay, ...], *, shared_direction: Tensor, row_directions: Tensor, max_rows: int = 256, fuel: int = 50000, allow_disjoint_replay: bool = False) -> EffectBernoulliTensorReplayCheck

Observe a fixed-tape JVP produced by native physical replay.

The transform runs the regular tensor axis on the independently checked discharge. It observes finite values and per-request log scores and their directional derivatives in the tensor domain. Both tapes and dtype stay fixed in this observation. The scalar expectation comparison and portable target reports are separate.

PARAMETER DESCRIPTION
axis

The nominal row-axis label held by each tape.

TYPE: str

shared

The shared prefix and rows by local input coordinate.

TYPE: Tensor

rows

The shared prefix and rows by local input coordinate.

TYPE: Tensor

tapes

A complete addressed tape for each input row.

TYPE: tuple of BernoulliRowReplay

shared_direction

Dense, finite directions in the matching dtype, shape and device.

TYPE: Tensor

row_directions

Dense, finite directions in the matching dtype, shape and device.

TYPE: Tensor

max_rows

The physical maximum row count and aggregate replay step cap.

TYPE: int DEFAULT: 256

fuel

The physical maximum row count and aggregate replay step cap.

TYPE: int DEFAULT: 256

allow_disjoint_replay

Allow the checked two-constructor case to replay different original requests in its reached row cohorts.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
EffectBernoulliTensorReplayCheck

The actual working-precision observation and physical work.

RAISES DESCRIPTION
ValueError

If the discharge, inputs, working domain or tapes are invalid.

JvpUnsupported

If the source is outside the tensor fragment or a directional result is nonfinite at working precision.

JvpLimit

If physical replay exceeds its row or step limit.

Source code in src/quivers/qiec/effect_plan.py
def check_bernoulli_tensor_replay(
    self,
    axis: str,
    shared: torch.Tensor,
    rows: torch.Tensor,
    tapes: tuple[BernoulliRowReplay, ...],
    *,
    shared_direction: torch.Tensor,
    row_directions: torch.Tensor,
    max_rows: int = 256,
    fuel: int = 50_000,
    allow_disjoint_replay: bool = False,
) -> EffectBernoulliTensorReplayCheck:
    """Observe a fixed-tape JVP produced by native physical replay.

    The transform runs the regular tensor axis on the independently
    checked discharge. It observes finite values and per-request log
    scores and their directional derivatives in the tensor domain.
    Both tapes and dtype stay fixed in this observation. The scalar
    expectation comparison and portable target reports are separate.

    Parameters
    ----------
    axis : str
        The nominal row-axis label held by each tape.
    shared, rows : torch.Tensor
        The shared prefix and rows by local input coordinate.
    tapes : tuple of BernoulliRowReplay
        A complete addressed tape for each input row.
    shared_direction, row_directions : torch.Tensor
        Dense, finite directions in the matching dtype, shape and device.
    max_rows, fuel : int
        The physical maximum row count and aggregate replay step cap.
    allow_disjoint_replay : bool
        Allow the checked two-constructor case to replay different
        original requests in its reached row cohorts.

    Returns
    -------
    EffectBernoulliTensorReplayCheck
        The actual working-precision observation and physical work.

    Raises
    ------
    ValueError
        If the discharge, inputs, working domain or tapes are invalid.
    JvpUnsupported
        If the source is outside the tensor fragment or a directional
        result is nonfinite at working precision.
    JvpLimit
        If physical replay exceeds its row or step limit.
    """
    source = self.bundle.module
    discharged = discharge_module(source).module
    digest = _module_digest(discharged)
    if digest != _module_digest(self.discharge.module):
        raise ValueError(
            "Bernoulli tensor replay requires the plan's checked discharge"
        )

    physical = BernoulliTensorAxis(
        discharged,
        self.computation,
        axis,
        shared.numel(),
        max_rows=max_rows,
        fuel=fuel,
        allow_disjoint_replay=allow_disjoint_replay,
    )
    physical._inputs(shared, rows)
    for value, direction in ((shared, shared_direction), (rows, row_directions)):
        if (
            direction.shape != value.shape
            or direction.dtype != value.dtype
            or direction.device != value.device
            or direction.layout != torch.strided
            or not bool(torch.isfinite(direction.detach()).all())
        ):
            raise ValueError(
                "Bernoulli tensor replay directions must be finite and match the input domain"
            )

    observed: tuple[tuple[BernoulliRowReplay, ...], int, int, int] | None = None

    def execute(
        shared_input: torch.Tensor, row_input: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor]:
        """Return the actual physical primal outputs for forward AD.

        Parameters
        ----------
        shared_input, row_input : torch.Tensor
            The working shared prefix and local inputs of this run.

        Returns
        -------
        tuple of torch.Tensor
            The working value and per-occurrence log score arrays.
        """
        nonlocal observed
        result = physical.replay(shared_input, row_input, tapes)
        observed = (
            result.tapes,
            result.source_passes,
            result.source_steps,
            result.lane_steps,
        )
        return result.values, result.log_scores

    primal, tangent = cast(
        tuple[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor, torch.Tensor]],
        torch.func.jvp(execute, (shared, rows), (shared_direction, row_directions)),
    )
    if any(not bool(torch.isfinite(item.detach()).all()) for item in primal):
        raise JvpUnsupported(
            "Bernoulli tensor replay output is outside working precision"
        )
    if any(not bool(torch.isfinite(item.detach()).all()) for item in tangent):
        raise JvpUnsupported(
            "Bernoulli tensor replay JVP is outside working precision"
        )
    assert observed is not None
    values, log_scores = (item.detach().clone() for item in primal)
    value_jvp, log_score_jvp = (item.detach().clone() for item in tangent)
    return EffectBernoulliTensorReplayCheck(
        source_digest=_module_digest(source),
        discharged_digest=digest,
        computation=self.computation,
        shared=shared.detach().clone(),
        rows=rows.detach().clone(),
        shared_direction=shared_direction.detach().clone(),
        row_directions=row_directions.detach().clone(),
        replay=BernoulliTensorResult(values, log_scores, *observed),
        value_jvp=value_jvp,
        log_score_jvp=log_score_jvp,
        max_rows=max_rows,
        fuel=fuel,
        allow_disjoint_replay=allow_disjoint_replay,
    )

select_pullback

select_pullback(request: PullbackRequest) -> PullbackExecution

Select the returned primal and cotangent graph of this source entry.

PARAMETER DESCRIPTION
request

The original named reverse instance, handler and carrier, with an explicit returned-value observation and reverse mode.

TYPE: PullbackRequest

RETURNS DESCRIPTION
PullbackExecution

The independently checked graph for native or target execution.

RAISES DESCRIPTION
ValueError

If the request names a different entry or has an unknown mode.

KernelError

If the requested observation or source leaves the reverse fragment.

Source code in src/quivers/qiec/effect_plan.py
def select_pullback(self, request: PullbackRequest) -> PullbackExecution:
    """Select the returned primal and cotangent graph of this source entry.

    Parameters
    ----------
    request : PullbackRequest
        The original named reverse instance, handler and carrier, with an
        explicit returned-value observation and reverse mode.

    Returns
    -------
    PullbackExecution
        The independently checked graph for native or target execution.

    Raises
    ------
    ValueError
        If the request names a different entry or has an unknown mode.
    KernelError
        If the requested observation or source leaves the reverse fragment.
    """
    if (
        not isinstance(request, PullbackRequest)
        or request.computation != self.computation
    ):
        raise ValueError("pullback request must name this checked source entry")
    return _select_pullback(self.bundle.module, request)

verify_pullback_target

verify_pullback_target(request: PullbackRequest, target: str, observed: PullbackTargetArtifact) -> PullbackTargetArtifact

Repeat source selection and emission under the caller's request.

The artifact must bind the same source and selected graph, and carry exactly the emitted bytes.

PARAMETER DESCRIPTION
request

The caller's original source request.

TYPE: PullbackRequest

target

The independently selected target.

TYPE: str

observed

The artifact to check against that request and target.

TYPE: PullbackTargetArtifact

RETURNS DESCRIPTION
PullbackTargetArtifact

The independently selected and emitted artifact.

RAISES DESCRIPTION
ValueError

If the artifact does not match the source, request or output.

KernelError

If the request is outside the checked pullback domain.

UnsupportedConstruct

If the target cannot emit the checked graph.

Source code in src/quivers/qiec/effect_plan.py
def verify_pullback_target(
    self, request: PullbackRequest, target: str, observed: PullbackTargetArtifact
) -> PullbackTargetArtifact:
    """Repeat source selection and emission under the caller's request.

    The artifact must bind the same source and selected graph, and carry
    exactly the emitted bytes.

    Parameters
    ----------
    request : PullbackRequest
        The caller's original source request.
    target : str
        The independently selected target.
    observed : PullbackTargetArtifact
        The artifact to check against that request and target.

    Returns
    -------
    PullbackTargetArtifact
        The independently selected and emitted artifact.

    Raises
    ------
    ValueError
        If the artifact does not match the source, request or output.
    KernelError
        If the request is outside the checked pullback domain.
    UnsupportedConstruct
        If the target cannot emit the checked graph.
    """
    if (
        type(observed) is not PullbackTargetArtifact
        or type(observed.code) is not bytes
    ):
        raise ValueError("an observed pullback artifact must carry emitted bytes")
    expected = self.select_pullback(request).emit_target(target)
    if observed != expected:
        raise ValueError(
            "pullback artifact differs from the checked source, request or bytes"
        )
    return expected

select_weighted_value

select_weighted_value(request: WeightedValueRequest) -> WeightedValueProjection

Select the isolated ordinary graph of a checked weighted value.

PARAMETER DESCRIPTION
request

The original entry, exact clause operators, observation, and limits.

TYPE: WeightedValueRequest

RETURNS DESCRIPTION
WeightedValueProjection

The executable returned-value graph and its preflight counts.

RAISES DESCRIPTION
ValueError

If the request names another source computation or has invalid limits.

FiniteLawUnsupported

If the source or requested observation is outside the fragment.

FiniteLawLimit

If either independent construction bound is exceeded.

Source code in src/quivers/qiec/effect_plan.py
def select_weighted_value(
    self, request: WeightedValueRequest
) -> WeightedValueProjection:
    """Select the isolated ordinary graph of a checked weighted value.

    Parameters
    ----------
    request : WeightedValueRequest
        The original entry, exact clause operators, observation, and limits.

    Returns
    -------
    WeightedValueProjection
        The executable returned-value graph and its preflight counts.

    Raises
    ------
    ValueError
        If the request names another source computation or has invalid limits.
    FiniteLawUnsupported
        If the source or requested observation is outside the fragment.
    FiniteLawLimit
        If either independent construction bound is exceeded.
    """
    if (
        not isinstance(request, WeightedValueRequest)
        or request.computation != self.computation
    ):
        raise ValueError(
            "weighted value request must name this checked source entry"
        )
    return _select_weighted_value(self.bundle.module, request)

verify_weighted_value_projection

verify_weighted_value_projection(request: WeightedValueRequest, observed: WeightedValueProjection) -> WeightedValueProjection

Rebuild a weighted projection against its independently expected request.

PARAMETER DESCRIPTION
request

The independently chosen original source and projection options.

TYPE: WeightedValueRequest

observed

The selected graph and receipt to compare.

TYPE: WeightedValueProjection

RETURNS DESCRIPTION
WeightedValueProjection

The freshly checked projection.

RAISES DESCRIPTION
ValueError

If the receipt, graph, or independently requested selection differs.

FiniteLawUnsupported

If the source or observation is outside the fragment.

FiniteLawLimit

If the expected request exceeds a checked limit.

Source code in src/quivers/qiec/effect_plan.py
def verify_weighted_value_projection(
    self, request: WeightedValueRequest, observed: WeightedValueProjection
) -> WeightedValueProjection:
    """Rebuild a weighted projection against its independently expected request.

    Parameters
    ----------
    request : WeightedValueRequest
        The independently chosen original source and projection options.
    observed : WeightedValueProjection
        The selected graph and receipt to compare.

    Returns
    -------
    WeightedValueProjection
        The freshly checked projection.

    Raises
    ------
    ValueError
        If the receipt, graph, or independently requested selection differs.
    FiniteLawUnsupported
        If the source or observation is outside the fragment.
    FiniteLawLimit
        If the expected request exceeds a checked limit.
    """
    expected = self.select_weighted_value(request)
    if observed != expected or _module_digest(
        observed.executable
    ) != _module_digest(expected.executable):
        raise ValueError(
            "weighted value projection differs from the checked source or request"
        )
    return expected

weighted_value_evidence

weighted_value_evidence(request: WeightedValueRequest) -> EffectWeightedValueEvidence

Record the source-bound selection of an isolated weighted stage.

PARAMETER DESCRIPTION
request

The nominal source entry, operators, observation and work limits.

TYPE: WeightedValueRequest

RETURNS DESCRIPTION
EffectWeightedValueEvidence

The detached graph identity, source sites and structural counts.

RAISES DESCRIPTION
ValueError

If the request names another source computation or has invalid limits.

FiniteLawUnsupported

If the source or observation is outside the weighted fragment.

FiniteLawLimit

If selection exceeds a checked construction or occurrence limit.

Source code in src/quivers/qiec/effect_plan.py
def weighted_value_evidence(
    self, request: WeightedValueRequest
) -> EffectWeightedValueEvidence:
    """Record the source-bound selection of an isolated weighted stage.

    Parameters
    ----------
    request : WeightedValueRequest
        The nominal source entry, operators, observation and work limits.

    Returns
    -------
    EffectWeightedValueEvidence
        The detached graph identity, source sites and structural counts.

    Raises
    ------
    ValueError
        If the request names another source computation or has invalid limits.
    FiniteLawUnsupported
        If the source or observation is outside the weighted fragment.
    FiniteLawLimit
        If selection exceeds a checked construction or occurrence limit.
    """
    projection = self.select_weighted_value(request)
    cost = projection.cost
    return EffectWeightedValueEvidence(
        source_digest=projection.source_digest,
        staged_digest=_module_digest(projection.executable),
        computation=self.computation,
        request_digest=_weighted_value_request_digest(request),
        stage=projection.stage,
        observation="returned-value",
        request_sites=projection.request_sites,
        resume_sites=projection.resume_sites,
        syntax_nodes=cost.syntax_nodes,
        operand_slots=cost.operand_slots,
        outer_operands=cost.outer_operands,
        requests=cost.requests,
        occurrences=cost.occurrences,
        leaves=cost.leaves,
    )

verify_weighted_value_evidence

verify_weighted_value_evidence(evidence: EffectWeightedValueEvidence, *, request: WeightedValueRequest, executable: QiecModule | None = None) -> EffectWeightedValueEvidence

Rebuild a detached weighted receipt under the verifier's request.

PARAMETER DESCRIPTION
evidence

The inert stage receipt.

TYPE: EffectWeightedValueEvidence

request

The independently expected entry, operators, scope and limits.

TYPE: WeightedValueRequest

executable

A separately received graph to compare by canonical encoding.

TYPE: QiecModule or None DEFAULT: None

RETURNS DESCRIPTION
EffectWeightedValueEvidence

The freshly rebuilt matching receipt.

RAISES DESCRIPTION
ValueError

If the source, request, graph or structural observations differ.

TypeError

If the receipt, request or executable has an unsupported type.

FiniteLawUnsupported

If the expected source or observation is outside the fragment.

FiniteLawLimit

If selection exceeds an independently expected limit.

Source code in src/quivers/qiec/effect_plan.py
def verify_weighted_value_evidence(
    self,
    evidence: EffectWeightedValueEvidence,
    *,
    request: WeightedValueRequest,
    executable: QiecModule | None = None,
) -> EffectWeightedValueEvidence:
    """Rebuild a detached weighted receipt under the verifier's request.

    Parameters
    ----------
    evidence : EffectWeightedValueEvidence
        The inert stage receipt.
    request : WeightedValueRequest
        The independently expected entry, operators, scope and limits.
    executable : QiecModule or None
        A separately received graph to compare by canonical encoding.

    Returns
    -------
    EffectWeightedValueEvidence
        The freshly rebuilt matching receipt.

    Raises
    ------
    ValueError
        If the source, request, graph or structural observations differ.
    TypeError
        If the receipt, request or executable has an unsupported type.
    FiniteLawUnsupported
        If the expected source or observation is outside the fragment.
    FiniteLawLimit
        If selection exceeds an independently expected limit.
    """
    if not isinstance(evidence, EffectWeightedValueEvidence) or not isinstance(
        request, WeightedValueRequest
    ):
        raise TypeError("weighted value verification needs a receipt and request")
    if executable is not None and not isinstance(executable, QiecModule):
        raise TypeError("weighted value verification needs a QIEC executable")
    if (
        evidence.source_digest != _module_digest(self.bundle.module)
        or evidence.computation != self.computation
    ):
        raise ValueError(
            "weighted value evidence names a different source or entry"
        )
    if evidence.request_digest != _weighted_value_request_digest(request):
        raise ValueError("weighted value evidence names a different request")
    expected = self.weighted_value_evidence(request)
    if evidence != expected:
        raise ValueError("weighted value evidence disagrees with checked selection")
    if (
        executable is not None
        and _module_digest(executable) != expected.staged_digest
    ):
        raise ValueError("weighted value executable differs from checked selection")
    return expected

check_ranked_weighted_addresses

check_ranked_weighted_addresses(algebra: FiniteAlgebra) -> RankedWeightedAddressEvidence

Check the static-site and shot-path projection of the source.

This opt-in check uses the weighted factor recognizer on one closed entry without arguments. Its result describes the request and shot order of an ordinary native invocation. Dynamic frames and derivative evidence have separate contracts.

PARAMETER DESCRIPTION
algebra

The named addition and multiplication in the authored clause. The address check uses their identities and the pure helper graph. Algebra law verification belongs to finite elimination.

TYPE: FiniteAlgebra

RETURNS DESCRIPTION
RankedWeightedAddressEvidence

The verified source digest, nominal owners, sites, and rank.

RAISES DESCRIPTION
FiniteLawUnsupported

If the entry or its request lies outside the ranked source scope.

Source code in src/quivers/qiec/effect_plan.py
def check_ranked_weighted_addresses(
    self, algebra: FiniteAlgebra
) -> RankedWeightedAddressEvidence:
    """Check the static-site and shot-path projection of the source.

    This opt-in check uses the weighted factor recognizer on one
    closed entry without arguments. Its result describes the
    request and shot order of an ordinary native invocation.
    Dynamic frames and derivative evidence have separate contracts.

    Parameters
    ----------
    algebra : FiniteAlgebra
        The named addition and multiplication in the authored clause.
        The address check uses their identities and the pure helper
        graph. Algebra law verification belongs to finite elimination.

    Returns
    -------
    RankedWeightedAddressEvidence
        The verified source digest, nominal owners, sites, and rank.

    Raises
    ------
    FiniteLawUnsupported
        If the entry or its request lies outside the ranked source scope.
    """
    return _ranked_weighted_address_evidence(
        self.bundle.module, self.computation, algebra
    )

verify_ranked_weighted_address_evidence

verify_ranked_weighted_address_evidence(evidence: RankedWeightedAddressEvidence, algebra: FiniteAlgebra) -> RankedWeightedAddressEvidence

Recompute a host address observation from its checked source owner.

PARAMETER DESCRIPTION
evidence

The projected address description to verify.

TYPE: RankedWeightedAddressEvidence

algebra

The ordinary named operators in the source's weighted clause.

TYPE: FiniteAlgebra

RETURNS DESCRIPTION
RankedWeightedAddressEvidence

The freshly checked matching observation.

RAISES DESCRIPTION
ValueError

If the source, selected entry or recorded address facts differ.

FiniteLawUnsupported

If the entry is outside the checked ranked source scope.

Source code in src/quivers/qiec/effect_plan.py
def verify_ranked_weighted_address_evidence(
    self, evidence: RankedWeightedAddressEvidence, algebra: FiniteAlgebra
) -> RankedWeightedAddressEvidence:
    """Recompute a host address observation from its checked source owner.

    Parameters
    ----------
    evidence : RankedWeightedAddressEvidence
        The projected address description to verify.
    algebra : FiniteAlgebra
        The ordinary named operators in the source's weighted clause.

    Returns
    -------
    RankedWeightedAddressEvidence
        The freshly checked matching observation.

    Raises
    ------
    ValueError
        If the source, selected entry or recorded address facts differ.
    FiniteLawUnsupported
        If the entry is outside the checked ranked source scope.
    """
    observed = self.check_ranked_weighted_addresses(algebra)
    if (observed.source_digest, observed.computation) != (
        evidence.source_digest,
        evidence.computation,
    ):
        raise ValueError(
            "ranked weighted addresses name a different source or entry"
        )
    if observed != evidence:
        raise ValueError("ranked weighted addresses disagree with checked source")
    return observed

check_ranked_weighted_observation

check_ranked_weighted_observation(algebra: FiniteAlgebra, *, observation: Literal['finite-answer', 'addressed-trace'], formal_base: FiniteAlgebra | None = None, max_checks: int = 65536, max_weighted_state_cells: int = 65536, max_formal_checks: int = 65536, fuel: int = 65536) -> tuple[Literal['ranked-weighted-state-tabulation'], RankedWeightedEliminationCheck] | tuple[Literal['reference'], ExecutionResult]

Select and execute the ranked stage for the requested observation.

A finite answer uses the certified ordered arithmetic of the ranked state table. An addressed trace uses the original checked source to observe every dynamic event, including calls and resumption paths.

PARAMETER DESCRIPTION
algebra

The named operations of the ranked weighted handler. The finite-answer query also checks the declared algebra and units.

TYPE: FiniteAlgebra

observation

The exact finite answer or the original addressed execution.

TYPE: ('finite-answer', 'addressed-trace') DEFAULT: "finite-answer"

formal_base

An optional base for a finite-answer query's formal dual proof.

TYPE: FiniteAlgebra or None DEFAULT: None

max_checks

The operator proof, state-cell and formal dual budgets for a finite-answer query.

TYPE: int DEFAULT: 65536

max_weighted_state_cells

The operator proof, state-cell and formal dual budgets for a finite-answer query.

TYPE: int DEFAULT: 65536

max_formal_checks

The operator proof, state-cell and formal dual budgets for a finite-answer query.

TYPE: int DEFAULT: 65536

fuel

The step limit for the complete reference invocation or for each checked call in finite tabulation.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
tuple

The selected stage and its actual result.

RAISES DESCRIPTION
ValueError

If the observation, options or a relevant limit is invalid.

FiniteLawUnsupported

If the selected source is outside the checked ranked fragment.

FiniteAlgebraLawError

If a finite answer requires an algebra equation that fails.

FiniteLawLimit

If finite proof or tabulation exceeds its bound.

ExecutionFailure

If the addressed reference invocation fails or exhausts its fuel.

Source code in src/quivers/qiec/effect_plan.py
def check_ranked_weighted_observation(
    self,
    algebra: FiniteAlgebra,
    *,
    observation: Literal["finite-answer", "addressed-trace"],
    formal_base: FiniteAlgebra | None = None,
    max_checks: int = 65_536,
    max_weighted_state_cells: int = 65_536,
    max_formal_checks: int = 65_536,
    fuel: int = 65_536,
) -> (
    tuple[
        Literal["ranked-weighted-state-tabulation"], RankedWeightedEliminationCheck
    ]
    | tuple[Literal["reference"], ExecutionResult]
):
    """Select and execute the ranked stage for the requested observation.

    A finite answer uses the certified ordered arithmetic of the ranked
    state table. An addressed trace uses the original checked source to
    observe every dynamic event, including calls and resumption paths.

    Parameters
    ----------
    algebra : FiniteAlgebra
        The named operations of the ranked weighted handler. The
        finite-answer query also checks the declared algebra and units.
    observation : {"finite-answer", "addressed-trace"}
        The exact finite answer or the original addressed execution.
    formal_base : FiniteAlgebra or None
        An optional base for a finite-answer query's formal dual proof.
    max_checks, max_weighted_state_cells, max_formal_checks : int
        The operator proof, state-cell and formal dual budgets for a
        finite-answer query.
    fuel : int
        The step limit for the complete reference invocation or for
        each checked call in finite tabulation.

    Returns
    -------
    tuple
        The selected stage and its actual result.

    Raises
    ------
    ValueError
        If the observation, options or a relevant limit is invalid.
    FiniteLawUnsupported
        If the selected source is outside the checked ranked fragment.
    FiniteAlgebraLawError
        If a finite answer requires an algebra equation that fails.
    FiniteLawLimit
        If finite proof or tabulation exceeds its bound.
    ExecutionFailure
        If the addressed reference invocation fails or exhausts its fuel.
    """
    if observation == "finite-answer":
        result = self.check_ranked_weighted_elimination(
            algebra,
            formal_base=formal_base,
            max_checks=max_checks,
            max_weighted_state_cells=max_weighted_state_cells,
            max_formal_checks=max_formal_checks,
            fuel=fuel,
        )
        return result.stage, result
    if observation != "addressed-trace":
        raise ValueError(f"unknown ranked weighted observation {observation!r}")
    if formal_base is not None:
        raise ValueError(
            "formal dual reporting requires the finite-answer observation"
        )

    if not isinstance(algebra, FiniteAlgebra):
        raise FiniteLawUnsupported(
            "ranked observation needs a declared finite algebra"
        )
    _validate_limit("fuel", fuel)
    self.check_ranked_weighted_addresses(algebra)
    source = self.bundle.module
    owner = next(
        item for item in source.computations if item.id == self.computation
    )
    return "reference", run_named(source, owner.name, fuel=fuel, record_trace=True)

emit_ranked_weighted_observation

emit_ranked_weighted_observation(target: str, algebra: FiniteAlgebra, *, observation: Literal['finite-answer', 'addressed-trace'], formal_base: FiniteAlgebra | None = None, max_checks: int = 65536, max_weighted_state_cells: int = 65536, max_formal_checks: int = 65536, fuel: int = 65536) -> tuple[RankedWeightedEliminationCheck, bytes]

Emit the certified finite answer of a selected standalone entry.

The ranked stage evaluates the closed finite answer before emission. The target receives one checked constant definition with the original computation identity. This artifact represents the returned value. Complete addressed execution belongs to the original source machine.

PARAMETER DESCRIPTION
target

The public backend key for the selected answer definition.

TYPE: str

algebra

The exact semiring for the source's weighted clause.

TYPE: FiniteAlgebra

observation

The artifact can answer a finite-answer observation. An addressed-trace request receives a target-stage refusal.

TYPE: ('finite-answer', 'addressed-trace') DEFAULT: "finite-answer"

formal_base

An optional base for the finite answer's checked formal coefficients.

TYPE: FiniteAlgebra or None DEFAULT: None

max_checks

The operator proof, state-cell and formal dual bounds.

TYPE: int DEFAULT: 65536

max_weighted_state_cells

The operator proof, state-cell and formal dual bounds.

TYPE: int DEFAULT: 65536

max_formal_checks

The operator proof, state-cell and formal dual bounds.

TYPE: int DEFAULT: 65536

fuel

The machine step bound per checked call during tabulation.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
tuple[RankedWeightedEliminationCheck, bytes]

The selected finite stage and its emitted answer definition. Formal coefficients describe the finite algebra observation.

RAISES DESCRIPTION
ValueError

If the source identity, observation or a bound is invalid.

UnsupportedConstruct

If the requested stage or definition cannot be emitted.

FiniteLawUnsupported

If the selected factor is outside the supported ranked fragment.

FiniteAlgebraLawError

If the requested finite proof has an exact counterexample.

FiniteLawLimit

If tabulation or its proof exhausts a bound.

Source code in src/quivers/qiec/effect_plan.py
def emit_ranked_weighted_observation(
    self,
    target: str,
    algebra: FiniteAlgebra,
    *,
    observation: Literal["finite-answer", "addressed-trace"],
    formal_base: FiniteAlgebra | None = None,
    max_checks: int = 65_536,
    max_weighted_state_cells: int = 65_536,
    max_formal_checks: int = 65_536,
    fuel: int = 65_536,
) -> tuple[RankedWeightedEliminationCheck, bytes]:
    """Emit the certified finite answer of a selected standalone entry.

    The ranked stage evaluates the closed finite answer before emission.
    The target receives one checked constant definition with the
    original computation identity. This artifact represents the
    returned value. Complete addressed execution belongs to the
    original source machine.

    Parameters
    ----------
    target : str
        The public backend key for the selected answer definition.
    algebra : FiniteAlgebra
        The exact semiring for the source's weighted clause.
    observation : {"finite-answer", "addressed-trace"}
        The artifact can answer a finite-answer observation. An
        addressed-trace request receives a target-stage refusal.
    formal_base : FiniteAlgebra or None
        An optional base for the finite answer's checked formal coefficients.
    max_checks, max_weighted_state_cells, max_formal_checks : int
        The operator proof, state-cell and formal dual bounds.
    fuel : int
        The machine step bound per checked call during tabulation.

    Returns
    -------
    tuple[RankedWeightedEliminationCheck, bytes]
        The selected finite stage and its emitted answer definition.
        Formal coefficients describe the finite algebra observation.

    Raises
    ------
    ValueError
        If the source identity, observation or a bound is invalid.
    UnsupportedConstruct
        If the requested stage or definition cannot be emitted.
    FiniteLawUnsupported
        If the selected factor is outside the supported ranked fragment.
    FiniteAlgebraLawError
        If the requested finite proof has an exact counterexample.
    FiniteLawLimit
        If tabulation or its proof exhausts a bound.
    """
    from panproto import PanprotoError

    from quivers.transpile._api import UnsupportedConstruct
    from quivers.transpile._entry import _emit_target, available_targets
    from quivers.transpile.ir import IRProgram
    from quivers.transpile.qiec_ir import project_for_target

    source = self.bundle.module
    owner = next(
        (item for item in source.computations if item.id == self.computation), None
    )
    if owner is None:
        raise ValueError("the effect plan does not name a source computation")
    targets = available_targets()
    if target not in targets:
        raise UnsupportedConstruct(
            target, [f"target:unknown:{target}:{','.join(targets)}"]
        )
    if observation == "addressed-trace":
        raise UnsupportedConstruct(
            f"qvr-{target}",
            [f"qiec:target-stage:ranked-addressed-trace:{owner.name}"],
        )
    if observation != "finite-answer":
        raise ValueError(f"unknown ranked weighted observation {observation!r}")
    if source.entries or source.gap:
        raise UnsupportedConstruct(
            f"qvr-{target}",
            [f"qiec:target-stage:ranked-answer-standalone:{owner.name}"],
        )

    proof = self.check_ranked_weighted_elimination(
        algebra,
        formal_base=formal_base,
        max_checks=max_checks,
        max_weighted_state_cells=max_weighted_state_cells,
        max_formal_checks=max_formal_checks,
        fuel=fuel,
    )
    (answer,) = proof.tabulation.result.factor.cells
    returned = owner.with_(body=Return(value=_ranked_answer_value(answer)))
    projected = QiecModule(
        module=source.module,
        source_protocol=source.source_protocol,
        computations=(returned,),
    )
    discharge = discharge_module(projected)
    ir = project_for_target(projected, discharge, target)
    target_plan = IRProgram(name=ir.module, inputs=(), body=(), module=ir)
    if target not in _HELPER_MANIFEST_TARGETS or tuple(
        row.computation
        for row in _emitted_helper_stages(target_plan, target, projected, discharge)
    ) != (self.computation,):
        raise UnsupportedConstruct(
            f"qvr-{target}",
            [f"qiec:target-stage:ranked-answer-not-defined:{owner.name}"],
        )
    try:
        artifact = _emit_target(target_plan, target)
    except PanprotoError as error:
        raise UnsupportedConstruct(
            f"qvr-{target}", [f"qiec:target-emission:{type(error).__name__}"]
        ) from error
    return proof, artifact

target_ranked_weighted_evidence

target_ranked_weighted_evidence(request: EffectRankedObservationRequest, algebra: FiniteAlgebra, *, formal_base: FiniteAlgebra | None = None) -> EffectTargetRankedEvidence

Record actual ranked target emission under a finite observation.

PARAMETER DESCRIPTION
request

The target, observation and bounds.

TYPE: EffectRankedObservationRequest

algebra

The exact nominal finite operations and units.

TYPE: FiniteAlgebra

formal_base

The optional independent algebra of the formal coefficients.

TYPE: FiniteAlgebra or None DEFAULT: None

RETURNS DESCRIPTION
EffectTargetRankedEvidence

The checked emission or its named target refusal.

RAISES DESCRIPTION
ValueError

If the source owner or algebra is invalid.

FiniteLawUnsupported

If the selected source leaves the ranked fragment.

FiniteLawLimit

If tabulation or its proof exhausts a bound.

FiniteAlgebraLawError

If a required algebraic equation fails.

Source code in src/quivers/qiec/effect_plan.py
def target_ranked_weighted_evidence(
    self,
    request: EffectRankedObservationRequest,
    algebra: FiniteAlgebra,
    *,
    formal_base: FiniteAlgebra | None = None,
) -> EffectTargetRankedEvidence:
    """Record actual ranked target emission under a finite observation.

    Parameters
    ----------
    request : EffectRankedObservationRequest
        The target, observation and bounds.
    algebra : FiniteAlgebra
        The exact nominal finite operations and units.
    formal_base : FiniteAlgebra or None
        The optional independent algebra of the formal coefficients.

    Returns
    -------
    EffectTargetRankedEvidence
        The checked emission or its named target refusal.

    Raises
    ------
    ValueError
        If the source owner or algebra is invalid.
    FiniteLawUnsupported
        If the selected source leaves the ranked fragment.
    FiniteLawLimit
        If tabulation or its proof exhausts a bound.
    FiniteAlgebraLawError
        If a required algebraic equation fails.
    """
    from quivers.transpile._api import UnsupportedConstruct

    source = self.bundle.module
    validate_module(source)
    algebra_digest = _ranked_algebra_digest(algebra)
    formal_base_digest = (
        _ranked_algebra_digest(formal_base) if formal_base is not None else None
    )
    stage = tabulation_digest = artifact_digest = None
    refusals: tuple[str, ...] = ()
    try:
        proof, artifact = self.emit_ranked_weighted_observation(
            request.target,
            algebra,
            observation=request.observation,
            formal_base=formal_base,
            max_checks=request.max_checks,
            max_weighted_state_cells=request.max_weighted_state_cells,
            max_formal_checks=request.max_formal_checks,
            fuel=request.fuel,
        )
    except UnsupportedConstruct as error:
        refusals = tuple(error.kinds)
    else:
        stage = proof.stage
        tabulation_digest = _ranked_tabulation_digest(proof)
        artifact_digest = sha256(artifact).hexdigest()
    return EffectTargetRankedEvidence(
        source_digest=_module_digest(source),
        computation=self.computation,
        request=request,
        algebra_digest=algebra_digest,
        formal_base_digest=formal_base_digest,
        stage=stage,
        tabulation_digest=tabulation_digest,
        artifact_digest=artifact_digest,
        refusals=refusals,
    )

verify_target_ranked_weighted_evidence

verify_target_ranked_weighted_evidence(evidence: EffectTargetRankedEvidence, *, request: EffectRankedObservationRequest, algebra: FiniteAlgebra, formal_base: FiniteAlgebra | None = None, artifact: bytes | None = None) -> EffectTargetRankedEvidence

Repeat ranked observation under the independently expected request.

PARAMETER DESCRIPTION
evidence

The detached receipt to verify.

TYPE: EffectTargetRankedEvidence

request

The verifier's expected target, observation and bounds.

TYPE: EffectRankedObservationRequest

algebra

The verifier's expected finite operations and units.

TYPE: FiniteAlgebra

formal_base

The verifier's expected formal coefficient algebra, if requested.

TYPE: FiniteAlgebra or None DEFAULT: None

artifact

The immutable bytes presented for use, if any.

TYPE: bytes or None DEFAULT: None

RETURNS DESCRIPTION
EffectTargetRankedEvidence

The freshly checked matching receipt.

RAISES DESCRIPTION
ValueError

If the request, checked owner, observation, or emitted bytes differ.

TypeError

If the artifact is outside the immutable bytes type.

FiniteLawUnsupported

If the selected source leaves the ranked fragment.

FiniteLawLimit

If tabulation or its proof exhausts a bound.

FiniteAlgebraLawError

If a required algebraic equation fails.

Source code in src/quivers/qiec/effect_plan.py
def verify_target_ranked_weighted_evidence(
    self,
    evidence: EffectTargetRankedEvidence,
    *,
    request: EffectRankedObservationRequest,
    algebra: FiniteAlgebra,
    formal_base: FiniteAlgebra | None = None,
    artifact: bytes | None = None,
) -> EffectTargetRankedEvidence:
    """Repeat ranked observation under the independently expected request.

    Parameters
    ----------
    evidence : EffectTargetRankedEvidence
        The detached receipt to verify.
    request : EffectRankedObservationRequest
        The verifier's expected target, observation and bounds.
    algebra : FiniteAlgebra
        The verifier's expected finite operations and units.
    formal_base : FiniteAlgebra or None
        The verifier's expected formal coefficient algebra, if requested.
    artifact : bytes or None
        The immutable bytes presented for use, if any.

    Returns
    -------
    EffectTargetRankedEvidence
        The freshly checked matching receipt.

    Raises
    ------
    ValueError
        If the request, checked owner, observation, or emitted bytes differ.
    TypeError
        If the artifact is outside the immutable bytes type.
    FiniteLawUnsupported
        If the selected source leaves the ranked fragment.
    FiniteLawLimit
        If tabulation or its proof exhausts a bound.
    FiniteAlgebraLawError
        If a required algebraic equation fails.
    """
    if (
        evidence.request != request
        or evidence.algebra_digest != _ranked_algebra_digest(algebra)
        or evidence.formal_base_digest
        != (
            _ranked_algebra_digest(formal_base) if formal_base is not None else None
        )
    ):
        raise ValueError("ranked target evidence names a different request")
    if (
        evidence.source_digest != _module_digest(self.bundle.module)
        or evidence.computation != self.computation
    ):
        raise ValueError(
            "ranked target evidence names a different checked source or entry"
        )
    observed = self.target_ranked_weighted_evidence(
        request, algebra, formal_base=formal_base
    )
    if observed != evidence:
        raise ValueError("ranked target evidence disagrees with checked emission")
    if artifact is not None:
        _verify_target_artifact(observed, artifact)
    return observed

check_ranked_weighted_elimination

check_ranked_weighted_elimination(algebra: FiniteAlgebra, *, formal_base: FiniteAlgebra | None = None, max_checks: int = 65536, max_weighted_state_cells: int = 65536, max_formal_checks: int = 65536, fuel: int = 65536) -> RankedWeightedEliminationCheck

Observe the actual bounded finite tabulation for this ranked owner.

The source addresses and executed factor refer to the same checked computation in the original plan bundle.

PARAMETER DESCRIPTION
algebra

The exact named semiring and working units.

TYPE: FiniteAlgebra

formal_base

An explicit finite base for checking and projecting a dual value.

TYPE: FiniteAlgebra or None DEFAULT: None

max_checks

The finite operator proof and suffix-state caps.

TYPE: int DEFAULT: 65536

max_weighted_state_cells

The finite operator proof and suffix-state caps.

TYPE: int DEFAULT: 65536

max_formal_checks

The separate cap for the optional finite dual proof.

TYPE: int DEFAULT: 65536

fuel

The machine step limit per individual checked call.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
RankedWeightedEliminationCheck

The source address scope and actual counted finite result.

RAISES DESCRIPTION
ValueError

If a limit or declaration is invalid.

FiniteLawUnsupported

If the selected source or its operations leave the fragment.

FiniteLawLimit

If a proof, weighted table or call exceeds a checked limit.

FiniteAlgebraLawError

If an exact operator equation fails.

RuntimeError

If the underlying execution is inconsistent with its proof.

Source code in src/quivers/qiec/effect_plan.py
def check_ranked_weighted_elimination(
    self,
    algebra: FiniteAlgebra,
    *,
    formal_base: FiniteAlgebra | None = None,
    max_checks: int = 65_536,
    max_weighted_state_cells: int = 65_536,
    max_formal_checks: int = 65_536,
    fuel: int = 65_536,
) -> RankedWeightedEliminationCheck:
    """Observe the actual bounded finite tabulation for this ranked owner.

    The source addresses and executed factor refer to the same
    checked computation in the original plan bundle.

    Parameters
    ----------
    algebra : FiniteAlgebra
        The exact named semiring and working units.
    formal_base : FiniteAlgebra or None
        An explicit finite base for checking and projecting a dual value.
    max_checks, max_weighted_state_cells : int
        The finite operator proof and suffix-state caps.
    max_formal_checks : int
        The separate cap for the optional finite dual proof.
    fuel : int
        The machine step limit per individual checked call.

    Returns
    -------
    RankedWeightedEliminationCheck
        The source address scope and actual counted finite result.

    Raises
    ------
    ValueError
        If a limit or declaration is invalid.
    FiniteLawUnsupported
        If the selected source or its operations leave the fragment.
    FiniteLawLimit
        If a proof, weighted table or call exceeds a checked limit.
    FiniteAlgebraLawError
        If an exact operator equation fails.
    RuntimeError
        If the underlying execution is inconsistent with its proof.
    """
    return check_ranked_weighted_elimination(
        self.bundle.module,
        self.computation,
        algebra,
        formal_base=formal_base,
        max_checks=max_checks,
        max_weighted_state_cells=max_weighted_state_cells,
        max_formal_checks=max_formal_checks,
        fuel=fuel,
    )

check_target

check_target(target: str, *, arguments: tuple[int | Fraction, ...] | None = None, direction: tuple[int | Fraction, ...] | None = None, derivative_rule: RationalDerivativeDeclaration | None = None, fuel: int = 65536, max_rule_work: int = 65536, _include_helper_stages: bool = False, _include_output_layout: bool = False) -> EffectTargetReport

Report the actual target export stage of the selected entry.

Standalone computations use the registered QIEC projector. A compiler-created probabilistic plan uses its bound parsed source and the same program preparation as public transpilation. The regular renderer and emitter must accept the result. A reachable retained reference stage leaves the staged native derivative unresolved. An explicit derivative rule is checked on the original QIEC source. Emission does not execute the backend derivative.

PARAMETER DESCRIPTION
target

The public backend key accepted by the transpiler.

TYPE: str

arguments

Optional input coordinates and tangent in source order. Supply both for a native pointwise comparison of standalone QIEC graphs. Probabilistic statement plans lack such an entry.

TYPE: tuple[int or Fraction, ...] or None DEFAULT: None

direction

Optional input coordinates and tangent in source order. Supply both for a native pointwise comparison of standalone QIEC graphs. Probabilistic statement plans lack such an entry.

TYPE: tuple[int or Fraction, ...] or None DEFAULT: None

derivative_rule

A nominal source formula to certify or refute.

TYPE: RationalDerivativeDeclaration or None DEFAULT: None

fuel

The step limit of each native derivative check.

TYPE: int DEFAULT: 65536

max_rule_work

The symbolic work limit of the rule check.

TYPE: int DEFAULT: 65536

_include_helper_stages

Collect the opted-in definition manifest after emission.

TYPE: bool DEFAULT: False

_include_output_layout

Collect model return coordinates when the emitter records them.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
EffectTargetReport

The selected stage or refusal, with each observation scoped to the graph on which it was checked.

RAISES DESCRIPTION
ValueError

If the source identity, inputs or a requested bound is invalid.

Source code in src/quivers/qiec/effect_plan.py
def check_target(
    self,
    target: str,
    *,
    arguments: tuple[int | Fraction, ...] | None = None,
    direction: tuple[int | Fraction, ...] | None = None,
    derivative_rule: RationalDerivativeDeclaration | None = None,
    fuel: int = 65_536,
    max_rule_work: int = 65_536,
    _include_helper_stages: bool = False,
    _include_output_layout: bool = False,
) -> EffectTargetReport:
    """Report the actual target export stage of the selected entry.

    Standalone computations use the registered QIEC projector. A
    compiler-created probabilistic plan uses its bound parsed source
    and the same program preparation as public transpilation. The
    regular renderer and emitter must accept the result. A reachable
    retained reference stage leaves the staged native derivative
    unresolved. An explicit derivative rule is checked on the
    original QIEC source. Emission does not execute the backend derivative.

    Parameters
    ----------
    target : str
        The public backend key accepted by the transpiler.
    arguments, direction : tuple[int or Fraction, ...] or None
        Optional input coordinates and tangent in source order.
        Supply both for a native pointwise comparison of standalone
        QIEC graphs. Probabilistic statement plans lack such an entry.
    derivative_rule : RationalDerivativeDeclaration or None
        A nominal source formula to certify or refute.
    fuel : int
        The step limit of each native derivative check.
    max_rule_work : int
        The symbolic work limit of the rule check.
    _include_helper_stages : bool
        Collect the opted-in definition manifest after emission.
    _include_output_layout : bool
        Collect model return coordinates when the emitter records them.

    Returns
    -------
    EffectTargetReport
        The selected stage or refusal, with each observation scoped
        to the graph on which it was checked.

    Raises
    ------
    ValueError
        If the source identity, inputs or a requested bound is invalid.
    """
    from panproto import PanprotoError

    from quivers.dsl.qiec_diagnostics import QiecDiagnosticError
    from quivers.transpile._api import UnsupportedConstruct
    from quivers.transpile._entry import (
        _emit_target,
        _emit_target_with_return_layout,
        _prepare_target_with_qiec,
        available_targets,
    )
    from quivers.transpile.ir import IRProgram
    from quivers.transpile.lower import pick_program
    from quivers.transpile.qiec_ir import (
        _target_discharge,
        capabilities_for_target,
        project_for_target,
    )

    source = self.bundle.module
    owner = next(
        (item for item in source.computations if item.id == self.computation), None
    )
    if owner is None:
        raise ValueError("the effect plan does not name a source computation")
    program = next(
        (item for item in source.entries if item.computation == self.computation),
        None,
    )
    if (arguments is None) != (direction is None):
        raise ValueError(
            "supply both arguments and direction for a native comparison"
        )
    rule, rule_obstacle = _declared_rule(
        source, self.computation, derivative_rule, fuel, max_rule_work
    )
    stages: tuple[EffectExecutionStage, ...] = ()
    helper_stages: tuple[EffectHelperStageRecord, ...] = ()
    output_layout = None
    native_jvp = None
    selected: QiecModule | None = None
    program_preparation = None
    projection: _TargetProjection | None = None
    helper_projection: _HelperProjection | None = None
    native_obstacle = None
    detail = None
    artifact_digest = None
    refusals: tuple[str, ...] = ()
    try:
        targets = available_targets()
        if target not in targets:
            raise UnsupportedConstruct(
                target, [f"target:unknown:{target}:{','.join(targets)}"]
            )
        capabilities = capabilities_for_target(target)
        if program is not None:
            if self._program_source is None:
                raise UnsupportedConstruct(
                    f"qvr-{target}",
                    [f"qiec:target-stage:program-plan-required:{program.name}"],
                )
            binding = self._program_source
            if not isinstance(
                binding, _ProgramTargetSource
            ) or binding.checked_digest != _module_digest(source):
                raise UnsupportedConstruct(
                    f"qvr-{target}",
                    [f"qiec:target-stage:program-source-mismatch:{program.name}"],
                )
            exported = pick_program(binding.parsed).name
            if exported != program.name:
                raise UnsupportedConstruct(
                    f"qvr-{target}",
                    [
                        f"qiec:target-stage:program-not-exported:{program.name}:{exported}"
                    ],
                )
            target_plan, program_preparation = _prepare_target_with_qiec(
                binding.parsed, target
            )
            if target_plan.name != program.name:
                raise UnsupportedConstruct(
                    f"qvr-{target}",
                    [
                        f"qiec:target-stage:program-not-exported:{program.name}:{target_plan.name}"
                    ],
                )
        else:
            if source.gap:
                raise UnsupportedConstruct(
                    f"qvr-{target}", [source.gap.partition("; ")[0]]
                )
            if source.entries or self.computation in program_computations(source):
                raise UnsupportedConstruct(
                    f"qvr-{target}",
                    [f"qiec:target-stage:program-plan-required:{owner.name}"],
                )
            ir = project_for_target(
                source, self.discharge, target, capabilities=capabilities
            )
            if not any(
                item.id.text == str(self.computation) and item.name == owner.name
                for item in ir.computations
            ):
                raise UnsupportedConstruct(
                    f"qvr-{target}",
                    [f"qiec:target-stage:entry-not-projected:{owner.name}"],
                )
            target_plan = IRProgram(name=ir.module, inputs=(), body=(), module=ir)
        if _include_output_layout and target in ("pyro", "webppl"):
            artifact, returned = _emit_target_with_return_layout(
                target_plan, target
            )
            if returned is not None:
                output_layout = (returned.names, returned.kind)
        else:
            artifact = _emit_target(target_plan, target)
    except UnsupportedConstruct as error:
        refusals = tuple(error.kinds)
        detail = str(error)
    except QiecDiagnosticError as error:
        refusals = (f"qiec:target-lowering:{error.code}",)
        detail = str(error)
    except PanprotoError as error:
        refusals = (f"qiec:target-emission:{type(error).__name__}",)
        detail = str(error)
    else:
        artifact_digest = sha256(artifact).hexdigest()
        if program_preparation is None:
            target_source, ordinary_discharge = source, self.discharge
        else:
            target_source = program_preparation.module
            ordinary_discharge = program_preparation.discharged
        target_discharge = _target_discharge(
            target_source, ordinary_discharge, target, capabilities
        )
        if _include_helper_stages:
            helper_stages = _emitted_helper_stages(
                target_plan, target, target_source, target_discharge
            )
        if program is not None:
            projection = "program-plan"
            helper_projection = "source"
            if not capabilities.supports("handle"):
                helper_projection = "discharged"
            elif target_discharge is not None and target_plan.module is not None:
                emitted = {item.id.text for item in target_plan.module.computations}
                if any(
                    str(companion) in emitted
                    for rewrite in target_discharge.rewrites
                    for companion in rewrite.companions
                ):
                    helper_projection = "discharged"
            stages = (EffectExecutionStage(self.computation, "program-plan"),)
            if arguments is not None:
                native_obstacle = "qiec:target-stage:program-jvp-unverified"
        elif target_discharge is None:
            projection, selected = "source", source
            reached, _ = _execution_reachability(source, self.computation)
            stages = tuple(
                EffectExecutionStage(
                    item.id,
                    "source-handler" if installed_handlers(item.body) else "direct",
                )
                for item in source.computations
                if item.id in reached
            )
        else:
            projection, selected = "discharged", target_discharge.module
            stages = _ordinary_stages(
                source,
                target_discharge,
                self.computation,
                retain_source_handlers=capabilities.supports("handle"),
            )
        if selected is not None and arguments is not None and direction is not None:
            reached = {stage.computation for stage in stages}
            reached_names = {
                item.name for item in source.computations if item.id in reached
            }
            retained = next(
                (
                    obstacle
                    for obstacle in ordinary_discharge.obstacles
                    if obstacle.computation in reached_names
                ),
                None,
            )
            native_jvp = _compare_jvp(
                source,
                selected if retained is None else None,
                self.computation,
                arguments,
                direction,
                fuel,
                unavailable=(
                    None
                    if retained is None
                    else "qiec:target-stage:retained-reference:"
                    f"{retained.kind}:{retained.computation}"
                ),
            )

    external = DerivativeSemantics.none(
        "target export refused" if refusals else "external derivative unverified"
    )
    return EffectTargetReport(
        target,
        self.computation,
        projection,
        stages,
        refusals,
        detail,
        self.laws,
        native_jvp,
        derivative_rule,
        rule,
        rule_obstacle,
        external,
        helper_projection,
        native_obstacle,
        artifact_digest,
        helper_stages,
        output_layout,
    )

classify_targets

classify_targets(*, derivatives: tuple[EffectDerivativeRequest, ...] = ()) -> tuple[EffectTargetClassification, ...]

Classify this checked source entry on every registered export target.

The actual registered renderer and emitter decide each outcome. The source discharge and the complete independent claim request are rechecked once. A law result describes its source observation. The renderer's selected stages use their own admission checks. Named program returns use the layout observed by the same emitter. Secondary program exports follow the public emitter's existing primary selection. Emission alone establishes no external derivative.

PARAMETER DESCRIPTION
derivatives

At most one independently chosen native point or source rule request per registered target. Omitted targets run no such check.

TYPE: tuple[EffectDerivativeRequest, ...] DEFAULT: ()

RETURNS DESCRIPTION
tuple of EffectTargetClassification

One row in public registry order per target, including refusals.

RAISES DESCRIPTION
ValueError

If derivative requests repeat a target, name an unregistered target, the program's checked return labels are invalid, or the plan disagrees with independently checked source.

Source code in src/quivers/qiec/effect_plan.py
def classify_targets(
    self, *, derivatives: tuple[EffectDerivativeRequest, ...] = ()
) -> tuple[EffectTargetClassification, ...]:
    """Classify this checked source entry on every registered export target.

    The actual registered renderer and emitter decide each outcome. The
    source discharge and the complete independent claim request are
    rechecked once. A law result describes its source observation.
    The renderer's selected stages use their own admission checks.
    Named program returns use the layout observed by the same emitter.
    Secondary program exports follow the public emitter's existing
    primary selection. Emission alone establishes no external derivative.

    Parameters
    ----------
    derivatives
        At most one independently chosen native point or source rule
        request per registered target. Omitted targets run no such check.

    Returns
    -------
    tuple of EffectTargetClassification
        One row in public registry order per target, including refusals.

    Raises
    ------
    ValueError
        If derivative requests repeat a target, name an unregistered
        target, the program's checked return labels are invalid, or
        the plan disagrees with independently checked source.
    """
    from quivers.transpile._entry import available_targets

    targets = available_targets()
    requests = {item.target: item for item in derivatives}
    if len(requests) != len(derivatives) or not requests.keys() <= set(targets):
        raise ValueError(
            "target classification needs distinct registered derivative targets"
        )
    program = self._output_program()
    plan = self._checked_target_plan()
    request = self._checked_claim_request()
    claims = _target_claim_records(request)
    rows = []
    for target in targets:
        derivative_request = requests.get(target)
        include_helpers = target in _HELPER_MANIFEST_TARGETS
        emission, report = plan._observe_target(
            target,
            include_helpers=include_helpers,
            derivative=derivative_request,
            include_output_layout=program is not None,
        )
        derivative = (
            _derivative_evidence(derivative_request, emission, report)
            if derivative_request is not None
            else None
        )
        rows.append(
            EffectTargetClassification(
                claims=_target_claims(request, emission, claims=claims),
                helpers=(
                    EffectTargetHelperEvidence(
                        emission=emission, helpers=report._helper_stages
                    )
                    if include_helpers
                    else None
                ),
                helper_obstacle=(
                    None
                    if include_helpers
                    else f"qiec:target-helper:manifest-unavailable:{target}"
                ),
                derivative=derivative,
                diagnostic=report.detail,
                outputs=(
                    _output_evidence(program, emission, report, derivative)
                    if program is not None
                    else None
                ),
            )
        )
    return tuple(rows)

target_evidence

target_evidence(target: str) -> EffectTargetEvidence

Record the normal target emission from the checked source.

PARAMETER DESCRIPTION
target

The requested backend key.

TYPE: str

RETURNS DESCRIPTION
EffectTargetEvidence

The selected stages and emitted byte digest, or named refusals. A probabilistic plan needs the compiler's parsed source.

RAISES DESCRIPTION
ValueError

If the plan's discharge differs from the independently checked source.

Source code in src/quivers/qiec/effect_plan.py
def target_evidence(self, target: str) -> EffectTargetEvidence:
    """Record the normal target emission from the checked source.

    Parameters
    ----------
    target : str
        The requested backend key.

    Returns
    -------
    EffectTargetEvidence
        The selected stages and emitted byte digest, or named refusals.
        A probabilistic plan needs the compiler's parsed source.

    Raises
    ------
    ValueError
        If the plan's discharge differs from the independently checked source.
    """
    receipt, _ = self._target_receipt(target)
    return receipt

target_helper_evidence

target_helper_evidence(target: str) -> EffectTargetHelperEvidence

Record the QIEC definitions selected by actual target emission.

PARAMETER DESCRIPTION
target

A public backend key with a checked helper selector.

TYPE: str

RETURNS DESCRIPTION
EffectTargetHelperEvidence

The artifact and its helper selection, or its named export refusal.

RAISES DESCRIPTION
ValueError

If the target is outside this manifest's scope or the plan is stale.

Source code in src/quivers/qiec/effect_plan.py
def target_helper_evidence(self, target: str) -> EffectTargetHelperEvidence:
    """Record the QIEC definitions selected by actual target emission.

    Parameters
    ----------
    target : str
        A public backend key with a checked helper selector.

    Returns
    -------
    EffectTargetHelperEvidence
        The artifact and its helper selection, or its named export refusal.

    Raises
    ------
    ValueError
        If the target is outside this manifest's scope or the plan is stale.
    """
    if target not in _HELPER_MANIFEST_TARGETS:
        raise ValueError(
            f"effect helper evidence is unavailable for target `{target}`"
        )
    emission, report = self._target_receipt(target, include_helpers=True)
    return EffectTargetHelperEvidence(
        emission=emission, helpers=report._helper_stages
    )

verify_target_helper_evidence

verify_target_helper_evidence(evidence: EffectTargetHelperEvidence) -> EffectTargetHelperEvidence

Repeat emission and compare the entire ordered helper selection.

PARAMETER DESCRIPTION
evidence

The detached artifact and helper receipt to verify.

TYPE: EffectTargetHelperEvidence

RETURNS DESCRIPTION
EffectTargetHelperEvidence

The matching observations from this independent checked owner.

RAISES DESCRIPTION
ValueError

If the owner, emission, or complete helper selection differs.

Source code in src/quivers/qiec/effect_plan.py
def verify_target_helper_evidence(
    self, evidence: EffectTargetHelperEvidence
) -> EffectTargetHelperEvidence:
    """Repeat emission and compare the entire ordered helper selection.

    Parameters
    ----------
    evidence : EffectTargetHelperEvidence
        The detached artifact and helper receipt to verify.

    Returns
    -------
    EffectTargetHelperEvidence
        The matching observations from this independent checked owner.

    Raises
    ------
    ValueError
        If the owner, emission, or complete helper selection differs.
    """
    observed = self.target_helper_evidence(evidence.emission.target)
    if observed != evidence:
        raise ValueError("target helper evidence disagrees with checked emission")
    return observed

target_derivative_evidence

target_derivative_evidence(request: EffectDerivativeRequest) -> EffectTargetDerivativeEvidence

Record the selected artifact and the requested exact observations.

PARAMETER DESCRIPTION
request

The target, coordinates, nominal rule and check bounds.

TYPE: EffectDerivativeRequest

RETURNS DESCRIPTION
EffectTargetDerivativeEvidence

The rechecked artifact and its scoped QIEC derivative observations.

RAISES DESCRIPTION
ValueError

If the checked source is stale or the coordinates are malformed.

Source code in src/quivers/qiec/effect_plan.py
def target_derivative_evidence(
    self, request: EffectDerivativeRequest
) -> EffectTargetDerivativeEvidence:
    """Record the selected artifact and the requested exact observations.

    Parameters
    ----------
    request : EffectDerivativeRequest
        The target, coordinates, nominal rule and check bounds.

    Returns
    -------
    EffectTargetDerivativeEvidence
        The rechecked artifact and its scoped QIEC derivative observations.

    Raises
    ------
    ValueError
        If the checked source is stale or the coordinates are malformed.
    """
    emission, report = self._target_receipt(request.target, derivative=request)
    return _derivative_evidence(request, emission, report)

verify_target_derivative_evidence

verify_target_derivative_evidence(evidence: EffectTargetDerivativeEvidence, *, request: EffectDerivativeRequest, artifact: bytes | None = None) -> EffectTargetDerivativeEvidence

Repeat the exact checks under the independently expected request.

PARAMETER DESCRIPTION
evidence

The detached receipt to verify.

TYPE: EffectTargetDerivativeEvidence

request

The verifier's expected target, checks and bounds.

TYPE: EffectDerivativeRequest

artifact

The immutable target bytes the caller intends to use. If provided, check them against the independently emitted artifact.

TYPE: bytes or None DEFAULT: None

RETURNS DESCRIPTION
EffectTargetDerivativeEvidence

The newly checked matching receipt.

RAISES DESCRIPTION
ValueError

If the request, artifact or derivative observation differs, or bytes are provided for a refused export.

TypeError

If the provided artifact is outside the immutable bytes type.

Source code in src/quivers/qiec/effect_plan.py
def verify_target_derivative_evidence(
    self,
    evidence: EffectTargetDerivativeEvidence,
    *,
    request: EffectDerivativeRequest,
    artifact: bytes | None = None,
) -> EffectTargetDerivativeEvidence:
    """Repeat the exact checks under the independently expected request.

    Parameters
    ----------
    evidence : EffectTargetDerivativeEvidence
        The detached receipt to verify.
    request : EffectDerivativeRequest
        The verifier's expected target, checks and bounds.
    artifact : bytes or None
        The immutable target bytes the caller intends to use.
        If provided, check them against the independently emitted artifact.

    Returns
    -------
    EffectTargetDerivativeEvidence
        The newly checked matching receipt.

    Raises
    ------
    ValueError
        If the request, artifact or derivative observation differs, or
        bytes are provided for a refused export.
    TypeError
        If the provided artifact is outside the immutable bytes type.
    """
    if evidence.request != request:
        raise ValueError("target derivative evidence names a different request")
    observed = self.target_derivative_evidence(request)
    if observed != evidence:
        raise ValueError(
            "target derivative evidence disagrees with checked emission or derivatives"
        )
    if artifact is not None:
        _verify_target_artifact(observed.emission, artifact)
    return observed

target_output_evidence

target_output_evidence(target: str, *, request: EffectDerivativeRequest | None = None) -> EffectTargetOutputEvidence

Bind a checked program's output ordinals to emitted coordinates.

Pyro and WebPPL expose coordinates for a unique terminal model return. Other successful exports report a named coordinate obstacle. Any requested native action retains the program's existing refusal. The receipt establishes no external derivative.

PARAMETER DESCRIPTION
target

The requested backend key.

TYPE: str

request

Optional exact coordinates, a nominal rule and their bounds.

TYPE: EffectDerivativeRequest or None DEFAULT: None

RETURNS DESCRIPTION
EffectTargetOutputEvidence

Ordered output observations or named coordinate obstacles.

RAISES DESCRIPTION
ValueError

If the plan has no checked program entry, has duplicate labels, or disagrees with its independently checked source.

Source code in src/quivers/qiec/effect_plan.py
def target_output_evidence(
    self, target: str, *, request: EffectDerivativeRequest | None = None
) -> EffectTargetOutputEvidence:
    """Bind a checked program's output ordinals to emitted coordinates.

    Pyro and WebPPL expose coordinates for a unique terminal model
    return. Other successful exports report a named coordinate
    obstacle. Any requested native action retains the program's
    existing refusal. The receipt establishes no external derivative.

    Parameters
    ----------
    target : str
        The requested backend key.
    request : EffectDerivativeRequest or None
        Optional exact coordinates, a nominal rule and their bounds.

    Returns
    -------
    EffectTargetOutputEvidence
        Ordered output observations or named coordinate obstacles.

    Raises
    ------
    ValueError
        If the plan has no checked program entry, has duplicate labels,
        or disagrees with its independently checked source.
    """
    if request is not None and request.target != target:
        raise ValueError("target output evidence needs a matching target request")
    program = self._output_program()
    if program is None:
        raise ValueError("qiec:target-output:program-return-required")
    emission, report = self._target_receipt(
        target, derivative=request, include_output_layout=True
    )
    derivative = (
        None if request is None else _derivative_evidence(request, emission, report)
    )
    return _output_evidence(program, emission, report, derivative)

verify_target_output_evidence

verify_target_output_evidence(evidence: EffectTargetOutputEvidence, *, target: str, request: EffectDerivativeRequest | None = None, artifact: bytes | None = None) -> EffectTargetOutputEvidence

Repeat program emission and verify the ordered output projection.

PARAMETER DESCRIPTION
evidence

The detached output receipt.

TYPE: EffectTargetOutputEvidence

target

The independently expected backend key.

TYPE: str

request

The independently expected derivative request, if any.

TYPE: EffectDerivativeRequest or None DEFAULT: None

artifact

Optional exact artifact bytes intended for use.

TYPE: bytes or None DEFAULT: None

RETURNS DESCRIPTION
EffectTargetOutputEvidence

The freshly observed matching receipt.

RAISES DESCRIPTION
ValueError

If the request, source, coordinates, or artifact differ.

TypeError

If the provided artifact is outside the immutable bytes type.

Source code in src/quivers/qiec/effect_plan.py
def verify_target_output_evidence(
    self,
    evidence: EffectTargetOutputEvidence,
    *,
    target: str,
    request: EffectDerivativeRequest | None = None,
    artifact: bytes | None = None,
) -> EffectTargetOutputEvidence:
    """Repeat program emission and verify the ordered output projection.

    Parameters
    ----------
    evidence : EffectTargetOutputEvidence
        The detached output receipt.
    target : str
        The independently expected backend key.
    request : EffectDerivativeRequest or None
        The independently expected derivative request, if any.
    artifact : bytes or None
        Optional exact artifact bytes intended for use.

    Returns
    -------
    EffectTargetOutputEvidence
        The freshly observed matching receipt.

    Raises
    ------
    ValueError
        If the request, source, coordinates, or artifact differ.
    TypeError
        If the provided artifact is outside the immutable bytes type.
    """
    derivative = evidence.derivative
    observed_request = derivative.request if derivative is not None else None
    if evidence.emission.target != target or observed_request != request:
        raise ValueError("target output evidence names a different request")
    observed = self.target_output_evidence(target, request=request)
    if evidence != observed:
        raise ValueError("target output evidence disagrees with checked emission")
    if artifact is not None:
        _verify_target_artifact(observed.emission, artifact)
    return observed

verify_target_evidence

verify_target_evidence(evidence: EffectTargetEvidence, *, artifact: bytes | None = None) -> EffectTargetEvidence

Verify a receipt against an independently supplied checked owner.

PARAMETER DESCRIPTION
evidence

A receipt to check, for instance after loading it from the wire.

TYPE: EffectTargetEvidence

artifact

The immutable target bytes the caller intends to use. If provided, check their SHA-256 against the fresh emission.

TYPE: bytes or None DEFAULT: None

RETURNS DESCRIPTION
EffectTargetEvidence

The freshly observed matching receipt.

RAISES DESCRIPTION
ValueError

If the source, selected entry, discharge, target outcome or artifact differs, or bytes are provided for a refused export.

TypeError

If the provided artifact is outside the immutable bytes type.

Source code in src/quivers/qiec/effect_plan.py
def verify_target_evidence(
    self, evidence: EffectTargetEvidence, *, artifact: bytes | None = None
) -> EffectTargetEvidence:
    """Verify a receipt against an independently supplied checked owner.

    Parameters
    ----------
    evidence : EffectTargetEvidence
        A receipt to check, for instance after loading it from the wire.
    artifact : bytes or None
        The immutable target bytes the caller intends to use.
        If provided, check their SHA-256 against the fresh emission.

    Returns
    -------
    EffectTargetEvidence
        The freshly observed matching receipt.

    Raises
    ------
    ValueError
        If the source, selected entry, discharge, target outcome or
        artifact differs, or bytes are provided for a refused export.
    TypeError
        If the provided artifact is outside the immutable bytes type.
    """
    if (
        evidence.source_digest != _module_digest(self.bundle.module)
        or evidence.computation != self.computation
    ):
        raise ValueError(
            "effect target evidence names a different checked source or entry"
        )
    observed = self.target_evidence(evidence.target)
    if observed != evidence:
        difference = (
            ", ".join(observed.refusals) or "emitted stages or bytes differ"
        )
        raise ValueError(
            f"effect target evidence disagrees with checked emission ({difference})"
        )
    if artifact is not None:
        _verify_target_artifact(observed, artifact)
    return observed

target_claim_evidence

target_claim_evidence(target: str) -> EffectTargetClaimEvidence

Record target emission and every independently requested claim check.

PARAMETER DESCRIPTION
target

The public target key.

TYPE: str

RETURNS DESCRIPTION
EffectTargetClaimEvidence

The artifact or refusal and all scoped claim statuses under this plan's exact check bounds.

RAISES DESCRIPTION
ValueError

If the checked claim request or the target projection is stale.

Source code in src/quivers/qiec/effect_plan.py
def target_claim_evidence(self, target: str) -> EffectTargetClaimEvidence:
    """Record target emission and every independently requested claim check.

    Parameters
    ----------
    target : str
        The public target key.

    Returns
    -------
    EffectTargetClaimEvidence
        The artifact or refusal and all scoped claim statuses under this
        plan's exact check bounds.

    Raises
    ------
    ValueError
        If the checked claim request or the target projection is stale.
    """
    request = self._checked_claim_request()
    return _target_claims(request, self.target_evidence(target))

verify_target_claim_evidence

verify_target_claim_evidence(evidence: EffectTargetClaimEvidence) -> EffectTargetClaimEvidence

Recheck a detached receipt against this plan's entire independent request.

PARAMETER DESCRIPTION
evidence

The portable receipt whose target and claim results are being checked.

TYPE: EffectTargetClaimEvidence

RETURNS DESCRIPTION
EffectTargetClaimEvidence

The newly checked matching receipt.

RAISES DESCRIPTION
ValueError

If the bounds, emission, complete request or check results differ.

Source code in src/quivers/qiec/effect_plan.py
def verify_target_claim_evidence(
    self, evidence: EffectTargetClaimEvidence
) -> EffectTargetClaimEvidence:
    """Recheck a detached receipt against this plan's entire independent request.

    Parameters
    ----------
    evidence : EffectTargetClaimEvidence
        The portable receipt whose target and claim results are being checked.

    Returns
    -------
    EffectTargetClaimEvidence
        The newly checked matching receipt.

    Raises
    ------
    ValueError
        If the bounds, emission, complete request or check results differ.
    """
    request = self._checked_claim_request()
    if (evidence.max_assignments, evidence.max_work, evidence.fuel) != (
        request.max_assignments,
        request.max_work,
        request.fuel,
    ):
        raise ValueError("target claim evidence names different check bounds")
    checked = _target_claims(
        request, self.verify_target_evidence(evidence.emission)
    )
    if checked != evidence:
        raise ValueError(
            "target claim evidence disagrees with the complete checked request"
        )
    return checked

checked_effect_plan

checked_effect_plan(bundle: EffectLawBundle, computation: ComputationId, *, interchanges: tuple[FiniteHandlerInterchange, ...] = (), law_evidence: tuple[EffectLawEvidence, ...] = (), max_assignments: int = 65536, max_work: int = 65536, fuel: int = 65536) -> EffectPlan

Report actual carrier shapes, exact law evidence, and ordinary discharge.

Each law is checked against the source in the bundle. An unsupported method or exhausted limit stays visible beside decisions for other obligations. A named guard condition is an open hypothesis. Existing discharge uses its own checks and does not consume law reports.

PARAMETER DESCRIPTION
bundle

The source module and the nominal obligations to inspect.

TYPE: EffectLawBundle

computation

The source declaration whose reachable handlers to classify.

TYPE: ComputationId

interchanges

Named finite observations checked independently of discharge.

TYPE: tuple[FiniteHandlerInterchange, ...] DEFAULT: ()

law_evidence

Bound empirical or assumed evidence for requested obligations.

TYPE: tuple[EffectLawEvidence, ...] DEFAULT: ()

max_assignments

The maximum number of assignments per finite obligation.

TYPE: int DEFAULT: 65536

max_work

The maximum symbolic work per scalar obligation.

TYPE: int DEFAULT: 65536

fuel

The interpreter step limit per side and assignment when used by a finite or rational check.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
EffectPlan

A report over the actual checked source, including every independently unresolved obligation.

RAISES DESCRIPTION
ValueError

If the computation, a bound, or an evidence attachment is invalid.

Source code in src/quivers/qiec/effect_plan.py
def checked_effect_plan(
    bundle: EffectLawBundle,
    computation: ComputationId,
    *,
    interchanges: tuple[FiniteHandlerInterchange, ...] = (),
    law_evidence: tuple[EffectLawEvidence, ...] = (),
    max_assignments: int = 65_536,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> EffectPlan:
    """Report actual carrier shapes, exact law evidence, and ordinary discharge.

    Each law is checked against the source in the bundle. An unsupported
    method or exhausted limit stays visible beside decisions for other
    obligations. A named guard condition is an open hypothesis. Existing
    discharge uses its own checks and does not consume law reports.

    Parameters
    ----------
    bundle : EffectLawBundle
        The source module and the nominal obligations to inspect.
    computation : ComputationId
        The source declaration whose reachable handlers to classify.
    interchanges : tuple[FiniteHandlerInterchange, ...]
        Named finite observations checked independently of discharge.
    law_evidence : tuple[EffectLawEvidence, ...]
        Bound empirical or assumed evidence for requested obligations.
    max_assignments : int
        The maximum number of assignments per finite obligation.
    max_work : int
        The maximum symbolic work per scalar obligation.
    fuel : int
        The interpreter step limit per side and assignment when used by a
        finite or rational check.

    Returns
    -------
    EffectPlan
        A report over the actual checked source, including every
        independently unresolved obligation.

    Raises
    ------
    ValueError
        If the computation, a bound, or an evidence attachment is invalid.
    """
    _validate_claim_limits(max_assignments, max_work, fuel)
    module = bundle.module
    validate_module(module)
    if not any(item.id == computation for item in module.computations):
        raise ValueError(f"unknown computation for effect plan `{computation}`")
    reach = reached_handlers(module, computation)
    carriers = tuple(
        classify_handler_carrier(module, handler.id)
        for handler in module.handlers
        if handler.id in reach
    )
    request = _ClaimRequest(
        bundle, interchanges, law_evidence, max_assignments, max_work, fuel
    )
    laws, comparisons = _checked_claims(request)
    discharge = discharge_module(module)
    return EffectPlan(
        bundle,
        computation,
        carriers,
        laws,
        discharge,
        comparisons,
        _ordinary_stages(module, discharge, computation),
        _claim_request=request,
    )

Use EffectPlan.target_claim_evidence(target) for a portable receipt that includes the ordered law and interchange decisions. verify_target_claim_evidence rechecks emission and every selected claim against an independently prepared plan, using that plan’s own bounds. The target’s external derivative status stays explicit in the emission receipt.

EffectPlan.target_helper_evidence(target) adds the canonical helper definitions selected by the renderer. Each row identifies the stage and, for a generated recursive companion, its owner. verify_target_helper_evidence repeats emission and verifies the complete ordered list against the artifact.

EffectPlan.target_derivative_evidence(request) records the emitted artifact or named refusal, the exact native actions at the requested point and direction, and any checked rational rule for the source. The verifier calls verify_target_derivative_evidence(receipt, request=expected) with its own target, coordinates, rule, and bounds. The receipt records the rule’s nonzero domain when the check can establish it. External derivative status remains unverified.

effect_stage_schema

Portable observations of checked effect target stages.

EffectStageRecord didactic-model

EffectStageRecord(*, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), stage: _Stage, companions: tuple[ComputationId, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), obstacle: _ObstacleKind | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One named source computation's observed target stage.

PARAMETER DESCRIPTION
computation

The original computation identity.

TYPE: ComputationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

stage

A recognized effect execution stage in the emitted projection.

TYPE: str

companions

The generated computations retained by a recursive state rewrite.

TYPE: tuple of ComputationId DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

obstacle

The named discharge obstacle for a retained reference computation.

TYPE: str or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

EffectTargetEvidence didactic-model

EffectTargetEvidence(*, source_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), target: str, projection: _TargetProjection | None, helper_projection: _HelperProjection | None, stages: tuple[EffectStageRecord, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), artifact_digest: str | None, refusals: tuple[str, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

An inert receipt of target emission or a named refusal.

Loading checks the shape. The effect plan that owns the checked source can independently verify the receipt by repeating target preparation.

PARAMETER DESCRIPTION
source_digest

The SHA-256 digest of the canonical checked QIEC module.

TYPE: str

computation

The selected source entry.

TYPE: ComputationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

target

The requested public backend key.

TYPE: str

projection

The observed source, discharged, or program-plan projection, if emitted.

TYPE: str or None

helper_projection

The separate helper projection for an emitted program plan, including checked discharge applied to individual helpers.

TYPE: str or None

stages

The emitted graph's source stage records in report order.

TYPE: tuple of EffectStageRecord DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

artifact_digest

SHA-256 of the exact emitted bytes, if emission succeeded.

TYPE: str or None

refusals

The named refusals returned by the target preparation or emitter.

TYPE: tuple of str DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

external_derivative property

external_derivative: DerivativeSemantics

Report the derivative scope that target emission establishes.

RETURNS DESCRIPTION
DerivativeSemantics

The existing external-unverified or export-refused observation.

EffectHelperStageRecord didactic-model

EffectHelperStageRecord(*, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), stage: _EmittedHelperStage, generated_for: ComputationId | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The selected stage of one QIEC definition carried by a target.

PARAMETER DESCRIPTION
computation

The identity in the target's checked QIEC namespace.

TYPE: ComputationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

stage

The selected rewrite, retained source handler, direct definition, or generated recursive companion.

TYPE: str

generated_for

The originating computation for a generated companion.

TYPE: ComputationId or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

EffectTargetHelperEvidence didactic-model

EffectTargetHelperEvidence(*, emission: EffectTargetEvidence = field(opaque=True, extras=OPAQUE_BY_VALUE), helpers: tuple[EffectHelperStageRecord, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The QIEC definitions carried by a checked target artifact.

A receipt reports the compiler's definition selection. The selected program plan and runtime support code have their own emission paths. Decoding checks structure. The independent effect plan repeats the target preparation and emission to verify the recorded selection.

PARAMETER DESCRIPTION
emission

The existing target receipt with the artifact digest or named refusal.

TYPE: EffectTargetEvidence DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

helpers

The selected QIEC definitions in renderer order. A refused export has no emitted definitions.

TYPE: tuple of EffectHelperStageRecord DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

external_derivative property

external_derivative: DerivativeSemantics

Report the external derivative status of the underlying emission.

RETURNS DESCRIPTION
DerivativeSemantics

The existing external-unverified or export-refused observation.

EffectDerivativeRequest didactic-model

EffectDerivativeRequest(*, target: str, arguments: tuple[Rational, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), direction: tuple[Rational, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), rule: RationalDerivativeDeclaration | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), fuel: int = 65536, max_rule_work: int = 65536)

Bases: QiecModel

Independently select the target and exact derivative checks to verify.

PARAMETER DESCRIPTION
target

The requested public target key.

TYPE: str

arguments

A point and tangent in positional parameter order. An empty tuple requests the scalar check for a computation with no parameters.

TYPE: tuple of Rational or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

direction

A point and tangent in positional parameter order. An empty tuple requests the scalar check for a computation with no parameters.

TYPE: tuple of Rational or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

rule

The nominal source action to check.

TYPE: RationalDerivativeDeclaration or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

fuel

Reference steps per evaluation and symbolic work for the rule check.

TYPE: int DEFAULT: 65536

max_rule_work

Reference steps per evaluation and symbolic work for the rule check.

TYPE: int DEFAULT: 65536

EffectTargetDerivativeEvidence didactic-model

EffectTargetDerivativeEvidence(*, emission: EffectTargetEvidence = field(opaque=True, extras=OPAQUE_BY_VALUE), request: EffectDerivativeRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), native_source: _NativeJvpOutcome | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), native_staged: _NativeJvpOutcome | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), native_obstacle: str | None = None, rule_status: _ClaimStatus | None = None, rule_domain: _RuleDomain | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), rule_obstacle: str | None = None)

Bases: QiecModel

Exact QIEC derivative observations paired with one target receipt.

A native comparison evaluates the two QIEC graphs at the requested point and tangent. A rational rule decision concerns the original source on the nonzero domain of its recorded polynomial. Checking either observation leaves the external derivative unverified.

PARAMETER DESCRIPTION
emission

The selected target artifact or named export refusal.

TYPE: EffectTargetEvidence DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

request

The exact independently selected checks and bounds.

TYPE: EffectDerivativeRequest DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

native_source

Each result as (value, tangent) or the graph's reference refusal.

TYPE: tuple of Rational or str or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

native_staged

Each result as (value, tangent) or the graph's reference refusal.

TYPE: tuple of Rational or str or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

native_obstacle

Why the requested comparison lacks a comparable emitted stage.

TYPE: str or None DEFAULT: None

rule_status

The source rule's checked, refuted or unresolved status.

TYPE: str or None DEFAULT: None

rule_domain

The exact domain polynomial's (exponents, coefficient) terms.

TYPE: tuple or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

rule_obstacle

The source rule's obstacle when its check is unresolved.

TYPE: str or None DEFAULT: None

native_status property

native_status: _ClaimStatus | None

Report the result of the exact comparison when requested.

RETURNS DESCRIPTION
str or None

Agreement, disagreement, unresolved comparison or no request.

external_derivative property

external_derivative: DerivativeSemantics

Read the external scope of the underlying emission.

RETURNS DESCRIPTION
DerivativeSemantics

The existing external-unverified or export-refused observation.

EffectTargetOutputRecord didactic-model

EffectTargetOutputRecord(*, ordinal: int, local: str, label: str | None, coordinate: tuple[int, ...] | None = field(opaque=True, extras=OPAQUE_BY_VALUE), native_obstacle: str | None, external_obstacle: str)

Bases: QiecModel

One logical program output and its observed backend coordinates.

PARAMETER DESCRIPTION
ordinal

The zero-based source return ordinal.

TYPE: int

local

The checked local returned at this ordinal.

TYPE: str

label

The logical source label when the return pattern is labelled.

TYPE: str or None

coordinate

The empty path for a single returned value, a one-element positional path for an element of a tuple or array, or an unverified path.

TYPE: tuple of int or None DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

native_obstacle

The reason a requested native action is unverified. An absent reason means no native action was requested.

TYPE: str or None

external_obstacle

The reason an external derivative is unavailable.

TYPE: str

EffectTargetOutputEvidence didactic-model

EffectTargetOutputEvidence(*, observation: EffectTargetEvidence | EffectTargetDerivativeEvidence = field(opaque=True, extras=OPAQUE_BY_VALUE), outputs: tuple[EffectTargetOutputRecord, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), layout: Literal['single', 'tuple', 'array'] | None, coordinate_obstacle: str | None)

Bases: QiecModel

Bind logical program returns to the target renderer's result layout.

The existing derivative receipt attests the whole target artifact and request. The rows identify separate outputs with their own scope. This observation does not establish external differentiation.

PARAMETER DESCRIPTION
observation

The selected emission with any independently requested derivative checks.

TYPE: EffectTargetEvidence or EffectTargetDerivativeEvidence DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

outputs

The checked program's outputs in source return order.

TYPE: tuple of EffectTargetOutputRecord DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

layout

The actual result layout of an admitted renderer, if verified.

TYPE: ('single', 'tuple', 'array') DEFAULT: "single"

coordinate_obstacle

The reason coordinates cannot be verified, when there is no layout.

TYPE: str or None

emission property

Read the underlying selected artifact or refusal.

RETURNS DESCRIPTION
EffectTargetEvidence

The original target emission receipt.

derivative property

derivative: EffectTargetDerivativeEvidence | None

Read the whole-program derivative request, when present.

RETURNS DESCRIPTION
EffectTargetDerivativeEvidence or None

The existing scoped derivative report.

EffectClaimRecord didactic-model

EffectClaimRecord(*, subject: EffectLawObligation | FiniteHandlerInterchange = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str | None, status: _ClaimStatus, reason: str | None, declared_evidence: EffectLawEvidence | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One requested returned-value check with its independently observed status.

PARAMETER DESCRIPTION
subject

The exact nominal check the owner requested.

TYPE: EffectLawObligation or FiniteHandlerInterchange DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

name

The equation or authored interchange name. A programmatic interchange may be identified only by its two wrapper identities.

TYPE: str or None

status

The exact check's outcome.

TYPE: ('checked', 'refuted', 'unresolved') DEFAULT: "checked"

reason

The diagnostic for an unresolved check.

TYPE: str or None

declared_evidence

An explicitly attached test or assumption of an equation. The exact check's status remains independent of this declaration.

TYPE: EffectLawEvidence or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

EffectTargetClaimEvidence didactic-model

EffectTargetClaimEvidence(*, emission: EffectTargetEvidence = field(opaque=True, extras=OPAQUE_BY_VALUE), max_assignments: int, max_work: int, fuel: int, claims: tuple[EffectClaimRecord, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A target receipt paired with the owner's complete requested claim checks.

The record is inert when decoded. An independent checked plan rechecks the target and every claim under its own request and bounds. The claim checks establish scoped returned-value observations.

PARAMETER DESCRIPTION
emission

The normal target-stage receipt or named export refusal.

TYPE: EffectTargetEvidence DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

max_assignments

Assignment bound per finite check.

TYPE: int

max_work

Exact algebraic work bound per scalar check.

TYPE: int

fuel

Exact interpreter fuel per side and assignment.

TYPE: int

claims

Every law in canonical bundle order, followed by the interchanges in requested order. This includes unproved and refuted requests.

TYPE: tuple of EffectClaimRecord DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

external_derivative property

external_derivative: DerivativeSemantics

Report the external derivative status of the underlying emission.

RETURNS DESCRIPTION
DerivativeSemantics

The emission's external-unverified or export-refused observation.

EffectRankedObservationRequest didactic-model

EffectRankedObservationRequest(*, target: str, observation: Literal['finite-answer', 'addressed-trace'], max_checks: int = 65536, max_weighted_state_cells: int = 65536, max_formal_checks: int = 65536, fuel: int = 65536)

Bases: QiecModel

Select the ranked target observation and exact evaluation limits.

PARAMETER DESCRIPTION
target

The public target key.

TYPE: str

observation

The finite returned value or the original addressed trace.

TYPE: ('finite-answer', 'addressed-trace') DEFAULT: "finite-answer"

max_checks

The finite algebra, suffix table, and formal coefficient limits.

TYPE: int DEFAULT: 65536

max_weighted_state_cells

The finite algebra, suffix table, and formal coefficient limits.

TYPE: int DEFAULT: 65536

max_formal_checks

The finite algebra, suffix table, and formal coefficient limits.

TYPE: int DEFAULT: 65536

fuel

The reference machine step limit per checked call.

TYPE: int DEFAULT: 65536

EffectTargetRankedEvidence didactic-model

EffectTargetRankedEvidence(*, source_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), request: EffectRankedObservationRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), algebra_digest: str, formal_base_digest: str | None, stage: Literal['ranked-weighted-state-tabulation'] | None, tabulation_digest: str | None, artifact_digest: str | None, refusals: tuple[str, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

An inert receipt of a ranked finite answer emission or target refusal.

Verification repeats the actual observation on its checked owner. The artifact observes the finite returned value and any formal coefficients represented in that value.

PARAMETER DESCRIPTION
source_digest

The SHA-256 digest of the checked QIEC module.

TYPE: str

computation

The original nominal source entry.

TYPE: ComputationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

request

The selected target, observation, and bounds.

TYPE: EffectRankedObservationRequest DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

algebra_digest

Digests of the exact nominal operations and units. The formal base digest is absent when there is no formal coefficient request.

TYPE: str or None

formal_base_digest

Digests of the exact nominal operations and units. The formal base digest is absent when there is no formal coefficient request.

TYPE: str or None

stage

The executed stage for an emitted finite answer.

TYPE: 'ranked-weighted-state-tabulation' or None

tabulation_digest

The binding to the checked address scope, algebra proofs, exact answer, and observed work, including any formal coefficients.

TYPE: str or None

artifact_digest

SHA-256 of the emitted bytes.

TYPE: str or None

refusals

The named target refusals if the requested observation cannot emit.

TYPE: tuple of str DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

external_derivative property

external_derivative: DerivativeSemantics

Report the derivative scope of ranked emission.

RETURNS DESCRIPTION
DerivativeSemantics

The external-unverified or export-refused observation.

EffectNativeObservationEvidence didactic-model

EffectNativeObservationEvidence(*, source_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), request_digest: str, stage: _NativeObservationStage, staged_digest: str, observation_digest: str)

Bases: QiecModel

An inert, portable receipt of a checked native observation.

An independent owner can rerun the exact request and check these digests. A scalar receipt concerns the returned value and directional action. An axis receipt concerns the selected outward Random law and its exact directional observations.

PARAMETER DESCRIPTION
source_digest

The canonical digest of the original checked QIEC module.

TYPE: str

computation

The original nominal entry.

TYPE: ComputationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

request_digest

The canonical exact inputs, selection rule, and work limits.

TYPE: str

stage

The native stage that was actually observed.

TYPE: ('ordinary', 'shared-fork', 'finite-bernoulli-batch') DEFAULT: "ordinary"

staged_digest

The canonical digest of the selected native computation module.

TYPE: str

observation_digest

The canonical digest of the exact scoped observations and work.

TYPE: str

EffectScoredBernoulliTensorEvidence didactic-model

EffectScoredBernoulliTensorEvidence(*, source_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), request_digest: str, stage: Literal['scored-bernoulli-tensor-replay'], staged_digest: str, observation_digest: str)

Bases: QiecModel

An inert receipt of a checked float64 score and draw replay.

The verifier independently repeats physical replay and scalar source comparison before comparing the measured bytes. Exact remeasurement binds this observation to the execution domain in its request.

PARAMETER DESCRIPTION
source_digest

The canonical digests of the original module and selected graph.

TYPE: str

staged_digest

The canonical digests of the original module and selected graph.

TYPE: str

computation

The original nominal source entry.

TYPE: ComputationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

request_digest

The exact shapes, values, directions, tapes and work limits.

TYPE: str

stage

The checked physical stage.

TYPE: 'scored-bernoulli-tensor-replay' DEFAULT: "scored-bernoulli-tensor-replay"

observation_digest

The measured values, separate score channels and directional actions, chronological addresses and work.

TYPE: str

EffectRowParallelTensorEvidence didactic-model

EffectRowParallelTensorEvidence(*, source_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), axis: str, operations: tuple[tuple[EffectInstanceId, OperationId, ComputationId], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), request_digest: str, stage: Literal['row-parallel-tensor-replay'], staged_digest: str, observation_digest: str)

Bases: QiecModel

An inert exact measurement of a checked nominal row operation replay.

PARAMETER DESCRIPTION
source_digest

The original checked source and selected graph digests.

TYPE: str

staged_digest

The original checked source and selected graph digests.

TYPE: str

computation

The original entry.

TYPE: ComputationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

axis

The original row-axis label.

TYPE: str

operations

The ordered exact (instance, operation, implementation) declarations.

TYPE: tuple DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

request_digest

The complete independent input, tape, direction and selection digest.

TYPE: str

stage

The actually checked native stage.

TYPE: 'row-parallel-tensor-replay' DEFAULT: "row-parallel-tensor-replay"

observation_digest

The measured answers, actions, separate score channels, addresses and work digest.

TYPE: str

EffectWeightedValueEvidence didactic-model

EffectWeightedValueEvidence(*, source_digest: str, staged_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), request_digest: str, stage: Literal['weighted-shared-value'], observation: Literal['returned-value'], request_sites: tuple[SiteId, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), resume_sites: tuple[SiteId, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), syntax_nodes: int, operand_slots: int, outer_operands: int, requests: int, occurrences: int, leaves: int)

Bases: QiecModel

An inert receipt of selecting a checked weighted returned-value graph.

Verification selects the graph again from the original source under an independent request. The receipt makes a structural claim about the graph and its complete occurrence schedule. It records no point evaluation.

PARAMETER DESCRIPTION
source_digest

The canonical digests of the checked source and selected graph.

TYPE: str

staged_digest

The canonical digests of the checked source and selected graph.

TYPE: str

computation

The original nominal entry.

TYPE: ComputationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

request_digest

The canonical digest of the entry, operators, scope and exact limits.

TYPE: str

stage

The checked weighted sharing rule.

TYPE: 'weighted-shared-value' DEFAULT: "weighted-shared-value"

observation

The observation for which the graph was selected.

TYPE: 'returned-value' DEFAULT: "returned-value"

request_sites

The original written sites in their selected order.

TYPE: tuple of SiteId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

resume_sites

The original written sites in their selected order.

TYPE: tuple of SiteId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

syntax_nodes

The measured syntax, ordinary call operand slots, and generated slots forwarding unchanged outer arguments.

TYPE: int

operand_slots

The measured syntax, ordinary call operand slots, and generated slots forwarding unchanged outer arguments.

TYPE: int

outer_operands

The measured syntax, ordinary call operand slots, and generated slots forwarding unchanged outer arguments.

TYPE: int

requests

The complete weighted request, resumption and terminal counts. These exclude the internal execution work of named helpers.

TYPE: int

occurrences

The complete weighted request, resumption and terminal counts. These exclude the internal execution work of named helpers.

TYPE: int

leaves

The complete weighted request, resumption and terminal counts. These exclude the internal execution work of named helpers.

TYPE: int

Static scoped operations

Declare a static operation with its named instance, its authored elaborator, and the closed effect row of its computation argument. Use the name in a handler installation. Brackets at that use list the lexical scalar values the body may read. The arguments in parentheses set the elaborator's handler parameters. The selected elaborator determines the scalar types, and the residual row contains every body instance except the selected one.

effect Reader
    read_value : Unit -> Real

instance reader : Reader
instance other : Reader

handler fixed for Reader : Real -> Real with (value : Real) [coverage=total, forwards=none, implementation=authored]
    read_value resumes 1 =>
        resume(value)

scoped_operation local [instance=reader, elaborator=fixed, body_effects=[reader, other]]

define region(inside : Real, outside : Real, captured : Real) : Real !{} =
    handle other with fixed(outside) in
        handle reader with local[captured](inside) in
            let first <- perform reader.read_value()
            let second <- perform other.read_value()
            return first + second + captured

At inputs (5, 11, 7), the result is 23. The installation takes an inline computation argument. A named call in that position is outside this checked fragment. The elaborated computation uses the ordinary target capability checks.

elaborate_static_scope checks one computation argument and installs an authored handler around it. The operation declares the computation argument's type, the result type, and the types of the value arguments. An elaborator chooses the original named instance and a handler. Changing the elaborator changes how the requests inside the scope are answered. An enclosing handler still answers requests before and after the scope.

The body can read the immutable scalar bindings listed as captures. Its requests must use named instances in the declared closed body row. The result row removes exactly the selected instance, so enclosing handlers can still answer requests to the remaining instances. Each clause of the selected handler must resume once in tail position, with an identity return and an empty introduced row. The resulting QIEC Handle contains the original body exactly once, preserving its source request addresses. The operation and elaborator are used only during elaboration.

from quivers.dsl import Compiler, parse
from quivers.qiec import (
    EMPTY_ROW, REAL, CheckContext, Handle, LiteralValue,
    ScopedHandlerElaboration, ScopedOperation, elaborate_static_scope, run_named,
)

source = """
effect Reader
    read_value : Unit -> Real

instance reader : Reader
instance outer : Reader

handler fixed for Reader : Real -> Real with (value : Real) [coverage=total, forwards=none, implementation=authored]
    read_value resumes 1 =>
        resume(value)

define region(captured : Real) : Real !{reader, outer} =
    let got <- perform reader.read_value()
    let kept <- perform outer.read_value()
    return got + kept + captured
"""
module = Compiler(parse(source), module_name="scoped-reader-example").qiec_module
assert module is not None
region, = module.computations
captured, = region.parameters
handler, = module.handlers
instances = {item.name: item.entry.instance for item in module.instances}
reader, outer = instances["reader"], instances["outer"]
result = region.type.with_(effects=region.type.effects.without(reader))
operation = ScopedOperation("local", region.type, result, (REAL,))
local = elaborate_static_scope(
    module,
    operation,
    ScopedHandlerElaboration(reader, handler.id),
    region.body,
    (LiteralValue(type=REAL, value=5.0),),
    captures=(captured,),
    context=CheckContext().extend(captured),
)
assert result.effects.contains(outer)
wrapped = Handle(
    instance=outer,
    handler=handler.id,
    arguments=(LiteralValue(type=REAL, value=11.0),),
    computation=local,
)
entry = region.with_(body=wrapped, type=result.with_(effects=EMPTY_ROW))
closed = module.with_(computations=(entry,))
assert run_named(closed, "region", (7.0,)).value == 23.0

scoped_elaboration

Check static computation arguments before elaborating them to QIEC handlers.

ScopedOperation dataclass

ScopedOperation(name: str, body_type: ComputationType, result_type: ComputationType, arguments: tuple[TypeExpr, ...] = ())

The compile-time interface of a scope with one static computation.

PARAMETER DESCRIPTION
name

The source name of the scoped operation.

TYPE: str

body_type

The exact authored type of the computation argument, with a closed row of named effect instances.

TYPE: ComputationType

result_type

The type of the elaborated operation, with the selected instance removed from the body row.

TYPE: ComputationType

arguments

The scalar value arguments available to an implementation.

TYPE: tuple[TypeExpr, ...] DEFAULT: ()

ScopedHandlerElaboration dataclass

ScopedHandlerElaboration(instance: EffectInstanceId, handler: HandlerId)

Implement one static scope with an ordinary authored handler.

PARAMETER DESCRIPTION
instance

The exact named instance to intercept in the static computation.

TYPE: EffectInstanceId

handler

The checked authored handler, receiving the scope's value arguments in order.

TYPE: HandlerId

elaborate_static_scope

elaborate_static_scope(module: QiecModule, operation: ScopedOperation, elaboration: ScopedHandlerElaboration, body: Computation, arguments: tuple[Value, ...] = (), *, captures: tuple[Local, ...] = (), context: CheckContext = CheckContext()) -> Handle

Use a static body once in an ordinary, checked QIEC handler scope.

The authored region remains the exact child of the handler. Its computation and original source provenance are available to the ordinary evaluator, discharge and serialization. The result row retains every body instance except the one handled here. The compile-time operation and elaborator disappear.

PARAMETER DESCRIPTION
module

The module supplying the actual effect instances and handler.

TYPE: QiecModule

operation

The source operation's static body, result and value-argument types.

TYPE: ScopedOperation

elaboration

The selected implementation on the original nominal instance.

TYPE: ScopedHandlerElaboration

body

The exact computation argument written at the operation site.

TYPE: Computation

arguments

The scalar values supplied to the elaboration at installation.

TYPE: tuple[Value, ...] DEFAULT: ()

captures

The lexical bindings the body can read.

TYPE: tuple[Local, ...] DEFAULT: ()

context

The actual enclosing source context.

TYPE: CheckContext DEFAULT: CheckContext()

RETURNS DESCRIPTION
Handle

One ordinary handler installation whose only computation child is the supplied body.

RAISES DESCRIPTION
KernelError

If the types, nominal effect, lexical scope or once-use rule fail.

Source code in src/quivers/qiec/scoped_elaboration.py
def elaborate_static_scope(
    module: QiecModule,
    operation: ScopedOperation,
    elaboration: ScopedHandlerElaboration,
    body: Computation,
    arguments: tuple[Value, ...] = (),
    *,
    captures: tuple[Local, ...] = (),
    context: CheckContext = CheckContext(),
) -> Handle:
    """Use a static body once in an ordinary, checked QIEC handler scope.

    The authored region remains the exact child of the handler. Its
    computation and original source provenance are available to the
    ordinary evaluator, discharge and serialization. The result row
    retains every body instance except the one handled here. The
    compile-time operation and elaborator disappear.

    Parameters
    ----------
    module : QiecModule
        The module supplying the actual effect instances and handler.
    operation : ScopedOperation
        The source operation's static body, result and value-argument types.
    elaboration : ScopedHandlerElaboration
        The selected implementation on the original nominal instance.
    body : Computation
        The exact computation argument written at the operation site.
    arguments : tuple[Value, ...]
        The scalar values supplied to the elaboration at installation.
    captures : tuple[Local, ...]
        The lexical bindings the body can read.
    context : CheckContext
        The actual enclosing source context.

    Returns
    -------
    Handle
        One ordinary handler installation whose only computation child
        is the supplied body.

    Raises
    ------
    KernelError
        If the types, nominal effect, lexical scope or once-use rule fail.
    """
    return _elaborate_static_scope(
        validate_module(module),
        operation,
        elaboration,
        body,
        arguments,
        captures=captures,
        context=context,
    )

Static catch

elaborate_static_catch takes a protected body and a recovery body. The selected authored handler wraps a successful result or a thrown value in a distinct ordinary data constructor. Its exception clause has grade zero. A case after the handler returns the success value or runs recovery once with the thrown value bound. A throw during recovery reaches the next enclosing handler for that instance.

Operations on other instances still use their surrounding handlers. Recovery sees state updates that the protected body made before throwing. The elaboration keeps both bodies' source addresses and uses the usual QIEC handler, bind, and case forms.

from quivers.dsl import Compiler, parse
from quivers.qiec import (
    CheckContext, ScopedHandlerElaboration, SourceOrigin,
    elaborate_static_catch, infer_computation, run_named, validate_module,
)

source = """
family Outcome : Type
    constructor Succeeded : Real -> Outcome
    constructor Failed : Real -> Outcome

effect Throw
    raise_error : Real -> Real

instance errors : Throw

handler tag for Throw : Real -> Outcome [coverage=total, forwards=none, implementation=authored]
    return value =>
        return (Succeeded(value) : Outcome)
    raise_error(problem : Real) resumes 0 =>
        return (Failed(problem) : Outcome)

define protected(problem : Real) : Real !{errors} =
    perform errors.raise_error(problem)

define recover(error : Real) : Real !{} =
    return error + 10.0
"""
module = Compiler(parse(source), module_name="static-catch-example").qiec_module
assert module is not None
entries = {entry.name: entry for entry in module.computations}
attempt, recovery = entries["protected"], entries["recover"]
handler, = module.handlers
instance, = attempt.type.effects.entries
problem, = attempt.parameters
error, = recovery.parameters
context = CheckContext().extend(problem)
body = elaborate_static_catch(
    module, ScopedHandlerElaboration(instance.instance, handler.id),
    attempt.body, recovery.body, error=error, captures=(problem,), context=context,
    origin=SourceOrigin(
        module="static-catch-example", structural_path=("protected", "catch"),
        role="catch", source_protocol="qvr",
    ),
)
type_ = infer_computation(body, validate_module(module), context)
closed = module.with_(computations=(attempt.with_(body=body, type=type_),))
assert run_named(closed, "protected", (4.0,)).value == 14.0

scoped_catch

Elaborate a static catch to a QIEC handler and a first-order case.

elaborate_static_catch

elaborate_static_catch(module: QiecModule, elaboration: ScopedHandlerElaboration, protected: Computation, recovery: Computation, *, error: Local, origin: SourceOrigin, captures: tuple[Local, ...] = (), context: CheckContext = CheckContext()) -> Bind

Catch one named throw inside a static body and recover outside its handler.

The ordinary authored handler returns a success or failure tag with its original payload. A case outside the handler returns the success value or executes the recovery with the thrown value bound. Residual requests go through the surrounding handlers as usual. The catch adds no rollback and no surrounding continuation is copied by it.

PARAMETER DESCRIPTION
module

The source declarations supplying the named instance and handler.

TYPE: QiecModule

elaboration

The handler installation for the exact nominal exception instance.

TYPE: ScopedHandlerElaboration

protected

Authored first-order bodies returning the same immutable scalar type. Recovery may perform the original exception again.

TYPE: Computation

recovery

Authored first-order bodies returning the same immutable scalar type. Recovery may perform the original exception again.

TYPE: Computation

error

The fresh scalar binder available only in the recovery.

TYPE: Local

origin

The lexical catch occurrence, used for fresh static case scopes.

TYPE: SourceOrigin

captures

The existing scalar locals either computation is allowed to read.

TYPE: tuple[Local, ...] DEFAULT: ()

context

The enclosing lexical context of the catch.

TYPE: CheckContext DEFAULT: CheckContext()

RETURNS DESCRIPTION
Bind

The ordinary handler followed by a case with one recovery body.

RAISES DESCRIPTION
KernelError

If a term, capture, nominal instance, payload tag or result fails its structural or ordinary QIEC type check.

Source code in src/quivers/qiec/scoped_catch.py
def elaborate_static_catch(
    module: QiecModule,
    elaboration: ScopedHandlerElaboration,
    protected: Computation,
    recovery: Computation,
    *,
    error: Local,
    origin: SourceOrigin,
    captures: tuple[Local, ...] = (),
    context: CheckContext = CheckContext(),
) -> Bind:
    """Catch one named throw inside a static body and recover outside its handler.

    The ordinary authored handler returns a success or failure tag with
    its original payload. A case outside the handler returns the success
    value or executes the recovery with the thrown value bound. Residual
    requests go through the surrounding handlers as usual. The catch
    adds no rollback and no surrounding continuation is copied by it.

    Parameters
    ----------
    module : QiecModule
        The source declarations supplying the named instance and handler.
    elaboration : ScopedHandlerElaboration
        The handler installation for the exact nominal exception instance.
    protected, recovery : Computation
        Authored first-order bodies returning the same immutable scalar
        type. Recovery may perform the original exception again.
    error : Local
        The fresh scalar binder available only in the recovery.
    origin : SourceOrigin
        The lexical catch occurrence, used for fresh static case scopes.
    captures : tuple[Local, ...]
        The existing scalar locals either computation is allowed to read.
    context : CheckContext
        The enclosing lexical context of the catch.

    Returns
    -------
    Bind
        The ordinary handler followed by a case with one recovery body.

    Raises
    ------
    KernelError
        If a term, capture, nominal instance, payload tag or result fails
        its structural or ordinary QIEC type check.
    """
    if error.type not in _SCALAR_TYPES or any(
        item.name == error.name for item in context.locals
    ):
        raise KernelError("a static catch needs a fresh scalar recovery binder")
    registry = validate_module(module)
    captured = _capture_context(captures, context)
    checked = infer_computation(protected, registry, captured)
    recovered = infer_computation(recovery, registry, captured.extend(error))
    if (
        checked.result not in _SCALAR_TYPES
        or recovered.result != checked.result
        or checked.effects.tail is not None
        or recovered.effects.tail is not None
    ):
        raise KernelError(
            "static catch needs closed effect rows and one scalar result type"
        )
    handler = registry.handler(elaboration.handler)
    if (
        checked.effects.lookup(elaboration.instance) != handler.effect
        or checked.result != handler.input_type
    ):
        raise KernelError(
            "static catch needs its declared named exception instance and input"
        )
    success, failure = _catch_tags(handler, error)
    _check_term(
        protected, instances=tuple(item.instance for item in checked.effects.entries)
    )
    body_names = _check_term(
        recovery, instances=tuple(item.instance for item in recovered.effects.entries)
    )
    used = body_names | {item.name for item in context.locals} | {error.name}
    site = str(origin.site_id())
    prefix = f"_qvr_caught_{site[-24:]}"
    result = _fresh_local(prefix, handler.output_type, used)
    value = _fresh_local(f"{prefix}_value", checked.result, used)
    lowered = Bind(
        first=Handle(
            instance=elaboration.instance,
            handler=elaboration.handler,
            computation=protected,
        ),
        binder=result,
        then=Case(
            scrutinee=Var(local=result),
            motive=CaseMotive(indices=(), result_type=checked.result),
            branches=(
                CaseBranch(
                    constructor=success,
                    static_arguments=(),
                    fields=(value,),
                    body=Return(value=Var(local=value)),
                    scope=StaticScopeId.derive(site, "catch-success"),
                ),
                CaseBranch(
                    constructor=failure,
                    static_arguments=(),
                    fields=(error,),
                    body=recovery,
                    scope=StaticScopeId.derive(site, "catch-failure"),
                ),
            ),
        ),
    )
    expected = ComputationType(
        effects=checked.effects.without(elaboration.instance).union(recovered.effects),
        result=checked.result,
    )
    if infer_computation(lowered, registry, context) != expected:
        raise KernelError("static catch produced a different ordinary QIEC result type")
    return lowered

Nominal forward differentiation

elaborate_forward_diff fills the total linear handler signatures for named forward differentiation instances in one closed Real entry. Each instance declares its own number type, with two fields for its coefficient type. The checked source uses named operations to seed numbers, add or multiply them, and stop. The elaborated module contains ordinary authored QIEC handlers with coefficient arithmetic specialized to Real operations.

stop_primal and stop_tangent project into the coefficient type of the selected instance. For an inner scope this is the enclosing instance's number type, so the projection retains the outer perturbation. Each stop is recorded at its original request address. The source check seals the carrier in the selected entry and requires each named handler installation to occur once. This fragment accepts up to two simultaneously active instances and sixteen source binds, handler installations and conditionals. Larger inputs raise qiec-forward-limit before target rendering.

An instance can also declare less : Number * Number -> Bool. The comparison reads each operand's ground primal, through any enclosing coefficient carriers. Bind its answer and use it as the immediately following if guard. The comparison is defined for distinct finite primals, and evaluation follows only the chosen branch. A reached comparison at equality or on a nonfinite primal fails with qiec-forward-comparison-boundary. The checked native, discharged and Pyro routes implement that behavior. The other targets report a missing strict-scalar-comparison capability for the partial guard.

An instance can declare div : Number * Number -> Number and div resumes 1. The generated clause solves the quotient in the parent coefficient algebra. Each ground quotient uses the same divisor primal. A reached zero or nonfinite divisor raises qiec-forward-division-domain. A nonfinite coefficient computed at working precision raises qiec-forward-division-range, even if the program would discard that coefficient or project a different one. For instance, an intermediate coefficient can overflow even when the exact mixed derivative is zero. Finite coefficients still use rounded arithmetic in the invocation's numeric representation. Pyro implements the same checks. The other targets report strict-scalar-division for this extension.

The ratio example returns the directional derivative of \(x/y\). At \((x,y)=(2,4)\) in direction \((3,2)\), it returns \(3/4 - 2\cdot2/4^2=1/2\).

from quivers.dsl import Compiler, parse
from quivers.qiec import ForwardDiffInstance, elaborate_forward_diff, run_named

declarations = """
family Number : Type
    constructor Jet : Real * Real -> Number

effect Diff
    seed : Real * Real -> Number
    add : Number * Number -> Number
    mul : Number * Number -> Number
    div : Number * Number -> Number
    less : Number * Number -> Bool
    stop_primal : Number -> Real
    stop_tangent : Number -> Real

instance d : Diff

handler forward for Diff : Real -> Real [coverage=total, forwards=none, implementation=foreign]
    seed resumes 1
    add resumes 1
    mul resumes 1
    div resumes 1
    less resumes 1
    stop_primal resumes 1
    stop_tangent resumes 1
"""

def lower_forward(name, definition):
    module = Compiler(parse(declarations + definition), module_name=name).qiec_module
    assert module is not None
    instance, = module.instances
    handler, = module.handlers
    constructor, = module.constructors
    scope = ForwardDiffInstance(instance.entry.instance, handler.id, constructor.id)
    return elaborate_forward_diff(module, (scope,))

square = lower_forward("forward-square", """
define positive_square(x : Real, direction : Real) : Real !{} =
    handle d with forward in
        let seeded <- perform d.seed(x, direction)
        let zero <- perform d.seed(0.0, 0.0)
        let positive <- perform d.less(zero, seeded)
        if positive then
            let product <- perform d.mul(seeded, seeded)
            perform d.stop_tangent(product)
        else
            return 0.0
""")
assert run_named(square, "positive_square", (3.0, 5.0)).value == 30.0
assert run_named(square, "positive_square", (-3.0, 5.0)).value == 0.0

ratio = lower_forward("forward-ratio", """
define ratio(x : Real, y : Real, dx : Real, dy : Real) : Real !{} =
    handle d with forward in
        let numerator <- perform d.seed(x, dx)
        let divisor <- perform d.seed(y, dy)
        let quotient <- perform d.div(numerator, divisor)
        perform d.stop_tangent(quotient)
""")
assert run_named(ratio, "ratio", (2.0, 4.0, 3.0, 2.0)).value == 0.5

forward_diff

Elaborate checked lexical forward differentiation to authored QIEC handlers.

ForwardDiffInstance dataclass

ForwardDiffInstance(instance: EffectInstanceId, handler: HandlerId, constructor: ConstructorId)

A named perturbation with a distinct two-field number type.

PARAMETER DESCRIPTION
instance

The existing lexical instance implementing the forward operations.

TYPE: EffectInstanceId

handler

Its total linear handler signature, to elaborate to authored clauses.

TYPE: HandlerId

constructor

The one constructor of this instance's nominal number type. Its coefficient type is Real or the enclosing instance's number type.

TYPE: ConstructorId

elaborate_forward_diff

elaborate_forward_diff(module: QiecModule, instances: tuple[ForwardDiffInstance, ...]) -> QiecModule

Generate ordinary authored forward handlers for checked nominal scopes.

Each instance's seed embeds a coefficient and a tangent in its own number type. Addition and multiplication use the dual-number rules. Coefficient arithmetic specializes to pure Real operations in each generated clause. The portable fragment admits two simultaneously active instances and sixteen source binds, handlers and branches in total. An optional named less compares only the two ground primals and immediately guards a lazy branch. Equality and nonfinite primals refuse the comparison at runtime. An optional div solves the quotient in the parent coefficient algebra. Each ground quotient checks the common divisor for a finite nonzero primal and refuses a nonfinite coefficient in the invocation's numeric representation. The two explicit stop operations project the primal or tangent into the coefficient algebra, retaining the parent perturbation when nested. Those original requests remain visible in ordinary traces.

PARAMETER DESCRIPTION
module

The single closed Real computation, its ordinary data and effect declarations, and total linear forward handler signatures.

TYPE: QiecModule

instances

The lexical perturbations, with distinct carrier and handler identities.

TYPE: tuple[ForwardDiffInstance, ...]

RETURNS DESCRIPTION
QiecModule

The rechecked ordinary module with the selected authored handlers.

RAISES DESCRIPTION
KernelError

If the module, named operations, carrier abstraction or lexical nesting leaves the checked finite forward fragment. The code qiec-forward-limit identifies an exceeded size or nesting bound.

Source code in src/quivers/qiec/forward_diff.py
def elaborate_forward_diff(
    module: QiecModule, instances: tuple[ForwardDiffInstance, ...]
) -> QiecModule:
    """Generate ordinary authored forward handlers for checked nominal scopes.

    Each instance's seed embeds a coefficient and a tangent in its own
    number type. Addition and multiplication use the dual-number rules.
    Coefficient arithmetic specializes to pure Real operations in each
    generated clause. The portable fragment admits two simultaneously
    active instances and sixteen source binds, handlers and branches in
    total. An optional named `less` compares only the two ground primals
    and immediately guards a lazy branch. Equality and nonfinite primals
    refuse the comparison at runtime.
    An optional `div` solves the quotient in the parent coefficient
    algebra. Each ground quotient checks the common divisor for a
    finite nonzero primal and refuses a nonfinite coefficient in the
    invocation's numeric representation.
    The two explicit stop operations project the primal or tangent into
    the coefficient algebra, retaining the parent perturbation when
    nested. Those original requests remain visible in ordinary traces.

    Parameters
    ----------
    module : QiecModule
        The single closed Real computation, its ordinary data and effect
        declarations, and total linear forward handler signatures.
    instances : tuple[ForwardDiffInstance, ...]
        The lexical perturbations, with distinct carrier and handler identities.

    Returns
    -------
    QiecModule
        The rechecked ordinary module with the selected authored handlers.

    Raises
    ------
    KernelError
        If the module, named operations, carrier abstraction or lexical
        nesting leaves the checked finite forward fragment. The code
        `qiec-forward-limit` identifies an exceeded size or nesting bound.
    """
    if len(module.computations) != 1 or not instances:
        raise KernelError(
            "forward differentiation needs one entry and at least one instance"
        )
    registry = validate_module(module)
    resolved = tuple(_scope(module, registry, item) for item in instances)
    by_instance = {item.entry.instance: item for item in resolved}
    by_number = {item.number: item for item in resolved}
    by_handler = {item.handler.id: item for item in resolved}
    if any(
        len(items) != len(resolved) for items in (by_instance, by_number, by_handler)
    ):
        raise KernelError(
            "forward instances need distinct nominal carriers and handlers"
        )
    _check_source(module.computations[0], by_instance)
    generated = {
        item.handler.id: item.handler.with_(
            implementation="authored",
            clauses=tuple(
                _ForwardOperation(module, item, by_number, operation).clause()
                for operation in item.operations.values()
            ),
        )
        for item in resolved
    }
    lowered = module.with_(
        handlers=tuple(
            generated.get(handler.id, handler) for handler in module.handlers
        )
    )
    validate_module(lowered)
    return lowered

Nominal reverse differentiation

elaborate_reverse_diff checks a common straight-line graph on a named reverse instance. The source seeds its Real inputs in parameter order, seeds any constants after those inputs, and adds, multiplies or divides earlier vertices. Each vertex has a consecutive integer slot starting at zero. The terminal stop names the output vertex. An instance may also declare less : Number * Number -> Bool and less resumes 1. After allocating all vertices, the source can bind a comparison of two existing vertices and immediately branch on its result. Each arm can perform another such comparison or stop on an existing vertex.

The effect may also declare div : Int * Number * Number -> Number with div resumes 1. For the primal \(q=x/y\), differentiating \(qy=x\) gives \(dq=(dx-q\,dy)/y\). With incoming cotangent \(g\), the two increments are \(g/y\) at the numerator and \(-q(g/y)\) at the denominator. The handler computes the checked primal before resuming. A reached zero or nonfinite divisor fails with qiec-forward-division-domain even when the final cotangent of the quotient is zero. A nonfinite quotient or quotient contribution fails with qiec-forward-division-range. An ordinary lazy branch that skips the whole call leaves these checks unevaluated. Backends that lack strict-scalar-division refuse an entry that requires it.

Only reached comparisons are evaluated. Equality or a nonfinite primal at a reached comparison raises qiec-forward-comparison-boundary. In exact real arithmetic, each strict difference of vertex primals has a constant sign in some neighborhood of the point. Intersect these neighborhoods for the reached comparisons. Throughout that intersection, execution selects the same output, whose derivative the reverse sweep computes wherever the reached divisors remain nonzero. The checker admits up to 15 nested and 256 total comparisons and reports qiec-reverse-sink-limit for larger selections. Backends without the partial comparison report strict-scalar-comparison when the computation requires it.

The generated return clause puts a unit cotangent at that output's slot. Each arithmetic clause resumes once, then adds both operand contributions to the tuple it receives. Two uses of the same operand both contribute. The result contains the primal followed by all vertex cotangents, with the input cotangents first. The graph allows up to six vertices and rejects larger inputs with qiec-reverse-limit.

from quivers.dsl import Compiler, parse
from quivers.qiec import compile_reverse_diff, elaborate_reverse_diff, run_named
from quivers.qiec.numbers import host_value

source = """
family Number : Type
    constructor Vertex : Real * Int -> Number

effect Reverse
    seed : Int * Real -> Number
    add : Int * Number * Number -> Number
    mul : Int * Number * Number -> Number
    less : Number * Number -> Bool
    stop : Number -> Number

instance d : Reverse

handler reverse for Reverse : Number -> (Real * Real * Real) [coverage=total, forwards=none, implementation=foreign]
    seed resumes 1
    add resumes 1
    mul resumes 1
    less resumes 1
    stop resumes 1

define squared(x : Real) : (Real * Real * Real) !{} =
    handle d with reverse in
        let input <- perform d.seed(0, x)
        let product <- perform d.mul(1, input, input)
        let larger <- perform d.less(input, product)
        if larger then
            perform d.stop(product)
        else
            perform d.stop(input)
"""
module = Compiler(parse(source), module_name="reverse-square").qiec_module
assert module is not None
instance, = module.instances
handler, = module.handlers
constructor, = module.constructors
lowered = elaborate_reverse_diff(module, instance.entry.instance, handler.id, constructor.id)
compiled = compile_reverse_diff(module, instance.entry.instance, handler.id, constructor.id)
for graph in (lowered, compiled):
    assert host_value(run_named(graph, "squared", (3.0,)).value) == (9.0, 6.0, 1.0)
    assert host_value(run_named(graph, "squared", (0.5,)).value) == (0.5, 1.0, 0.0)

compile_reverse_diff produces a standalone pure QIEC module for the same checked graph and supports up to 256 vertices. It retains the entry's identity and result type. The source vertex at slot \(i\) supplies primal binding \(i\) and cotangent \(i+1\) in the returned tuple. The first tuple element is the primal at the selected stop. Forward arithmetic and comparisons retain the origin of their source requests. Multiplication and division edge contributions use the origin of the consumer, and an adjoint sum uses the origin of its vertex. The pure module emits no named-operation events. The bounded elaboration retains those operations and their addresses.

The compiler binds primals in allocation order and completes cotangents in reverse order. Each operand occurrence contributes once to its predecessor. For \(B\) binary vertices with \(M\) multiplications and \(D\) divisions, the sweep uses \(B\) primal operations, \(2M\) reverse multiplications, \(4D\) operations for quotient contributions including range checks, and at most \(2B\) adjoint additions. This gives a bound of \(5B+2D\) scalar operations. A lazy selection adds \(H\) reached comparisons and two scalar operations per vertex to seed the reverse pass at the selected slot. The compiler uses one sequence of primal bindings and one reverse sweep for all choices. The cost counts evaluation of the checked graph. Source parsing, module validation and target rendering have their own costs. In particular, the QVR text parser can reach its nesting limit for a long written result product before the compiler's graph limit. The derivative recurrence is exact over the reals. Machine arithmetic uses the invocation's numeric representation and may round or overflow.

Binary multi-shot reverse projection

compile_multishot_reverse_diff checks a named reverse graph with one authored handler that forks in tail position. The fork has an identity return, resumes twice with Real literals, combines the first and second results in that order with one named addition, multiplication or division, and stops on the result. Each shot runs the same straight-line suffix of seeds and checked arithmetic. The compiler numbers the common prefix once and gives each copied suffix its own slots, even when both shots use the same literal. It checks the shot ordinals and each substituted operand against the discharged requests before assigning the slots.

For a prefix of size \(P\) and a suffix of size \(S\), the source result type declares one Real for the primal and \(P+2S+1\) Reals for the cotangents. The cotangents are ordered by the prefix, first shot, second shot, and join. Each shot receives the derivative of the join with respect to its own result. For a product of results \(a\) and \(b\), these coefficients are \(b\) and \(a\). For \(q=a/b\) they are \(1/b\) and \(-q/b\). Both shot suffixes run in order before the join. A reached quotient in the prefix, in either shot or at the join retains the strict scalar division checks, even if a cancellation could remove it from a simplified expression. The two contributions to a shared producer are added before its adjoint is propagated. At most 256 expanded vertices may be allocated. The generated graph stores one primal and adjoint per vertex and processes each operand occurrence once. The pure result has the same source origins as the corresponding arithmetic and emits no operation events.

from quivers.dsl import Compiler, parse
from quivers.qiec import compile_multishot_reverse_diff, run_named
from quivers.qiec.numbers import host_value

source = """
family Number : Type
    constructor Vertex : Real * Int -> Number

effect Reverse
    seed : Int * Real -> Number
    add : Int * Number * Number -> Number
    mul : Int * Number * Number -> Number
    div : Int * Number * Number -> Number
    stop : Number -> Number

effect Choice
    fork : Unit -> Real

instance d : Reverse
instance choice : Choice

handler reverse for Reverse : Number -> (Real * Real * Real * Real * Real * Real * Real * Real) [coverage=total, forwards=none, implementation=foreign]
    seed resumes 1
    add resumes 1
    mul resumes 1
    div resumes 1
    stop resumes 1

handler fork_product for Choice : Number -> Number [coverage=total, forwards=none, introduces=!{d}, implementation=authored]
    return value =>
        return value
    fork resumes omega =>
        let left <- resume(2.0)
        let right <- resume(3.0)
        let joined <- perform d.mul(4, left, right)
        perform d.stop(joined)

define objective(x : Real) : (Real * Real * Real * Real * Real * Real * Real * Real) !{} =
    handle d with reverse in
        let argument <- perform d.seed(0, x)
        let square <- perform d.mul(1, argument, argument)
        handle choice with fork_product in
            let scale <- perform choice.fork()
            let weight <- perform d.seed(2, scale)
            let term <- perform d.mul(3, square, weight)
            return term
"""
def reverse_at_two(text):
    module = Compiler(parse(text), module_name="binary-reverse").qiec_module
    assert module is not None
    instance = next(item.entry.instance for item in module.instances if item.name == "d")
    handler = next(item for item in module.handlers if item.name == "reverse")
    (constructor,) = module.constructors
    compiled = compile_multishot_reverse_diff(module, instance, handler.id, constructor.id)
    return host_value(run_named(compiled, "objective", (2.0,)).value)

assert reverse_at_two(source) == (96.0, 192.0, 48.0, 48.0, 12.0, 32.0, 8.0, 1.0)
quotient_join = source.replace("resume(3.0)", "resume(4.0)").replace(
    "d.mul(4, left, right)", "d.div(4, left, right)"
)
# The quotient of 2*x*x and 4*x*x is locally constant at x=2.
assert reverse_at_two(quotient_join) == (0.5, 0.0, 0.0, 0.25, 0.0625, -0.125, -0.03125, 1.0)

reverse_diff

Elaborate or compile a nominal reverse graph with immutable cotangents.

elaborate_reverse_diff

elaborate_reverse_diff(module: QiecModule, instance: EffectInstanceId, handler: HandlerId, constructor: ConstructorId) -> QiecModule

Fill a named reverse handler with a bounded immutable cotangent sweep.

The source seeds its Real parameters in order, can seed Real constants thereafter, and adds, multiplies or divides earlier vertices. Division requires a nominal div operation with the same carrier and grade as mul. Each reached divisor must be finite and nonzero, and each quotient and quotient contribution must be finite. A terminal stop chooses the output vertex. Optional named comparisons may choose between stops on that same graph. Each reached comparison needs finite distinct primals and resumes once with its Boolean result. Arithmetic clauses resume once with the primal, then update both operand slots in the returned answer. The answer consists of the primal followed by one cotangent per vertex in source order. Parameter cotangents come first.

PARAMETER DESCRIPTION
module

One checked named reverse graph with an optional lazy sink selection.

TYPE: QiecModule

instance

The actual declared lexical reverse instance.

TYPE: EffectInstanceId

handler

Its total grade-one handler signature.

TYPE: HandlerId

constructor

Its one nominal constructor with Real and Int fields.

TYPE: ConstructorId

RETURNS DESCRIPTION
QiecModule

The ordinary revalidated module with an authored reverse handler.

RAISES DESCRIPTION
KernelError

If the numeric carrier, signature or source violates the exact graph shape. The code qiec-reverse-limit identifies a graph with more than six vertices. The code qiec-reverse-sink-limit identifies more than 15 nested or 256 total comparisons.

Source code in src/quivers/qiec/reverse_diff.py
def elaborate_reverse_diff(
    module: QiecModule,
    instance: EffectInstanceId,
    handler: HandlerId,
    constructor: ConstructorId,
) -> QiecModule:
    """Fill a named reverse handler with a bounded immutable cotangent sweep.

    The source seeds its Real parameters in order, can seed Real constants
    thereafter, and adds, multiplies or divides earlier vertices. Division
    requires a nominal `div` operation with the same carrier and grade as
    `mul`. Each reached divisor must be finite and nonzero, and each
    quotient and quotient contribution must be finite. A terminal stop
    chooses the output vertex. Optional named comparisons may choose
    between stops on that same graph. Each reached comparison needs finite
    distinct primals and resumes once with its Boolean result. Arithmetic
    clauses resume once with the primal, then update both operand slots in
    the returned answer. The answer consists of the primal followed by one cotangent
    per vertex in source order. Parameter cotangents come first.

    Parameters
    ----------
    module : QiecModule
        One checked named reverse graph with an optional lazy sink selection.
    instance : EffectInstanceId
        The actual declared lexical reverse instance.
    handler : HandlerId
        Its total grade-one handler signature.
    constructor : ConstructorId
        Its one nominal constructor with Real and Int fields.

    Returns
    -------
    QiecModule
        The ordinary revalidated module with an authored reverse handler.

    Raises
    ------
    KernelError
        If the numeric carrier, signature or source violates the exact
        graph shape. The code `qiec-reverse-limit` identifies a graph
        with more than six vertices. The code `qiec-reverse-sink-limit`
        identifies more than 15 nested or 256 total comparisons.
    """
    declaration, operations, vertices, _ = _checked_reverse_graph(
        module,
        instance,
        handler,
        constructor,
        maximum=_MAX_VERTICES,
        limit_code="qiec-reverse-limit",
    )
    builder = _ReverseHandler(module, declaration, constructor, len(vertices))
    authored = declaration.with_(
        implementation="authored",
        return_clause=builder.return_clause(),
        clauses=tuple(builder.clause(operation) for operation in operations),
    )
    lowered = module.with_(
        handlers=tuple(
            authored if item.id == handler else item for item in module.handlers
        )
    )
    validate_module(lowered)
    return lowered

compile_reverse_diff

compile_reverse_diff(module: QiecModule, instance: EffectInstanceId, handler: HandlerId, constructor: ConstructorId) -> QiecModule

Compile a checked nominal reverse graph to an immutable pure computation.

The compiled module contains the specialized computation and its entry points. Its arithmetic retains source vertex origins and emits no original operation events. Use elaborate_reverse_diff to run the named handler and observe those events.

Each binary vertex adds one primal operation and sends a contribution along each ordered operand edge, including two uses of the same operand. All contributions to a vertex are added before its adjoint is passed down. With B binary vertices and D divisions the computation executes at most 5B + 2D scalar arithmetic operations, including the range checks on quotient contributions. Lazy sink selection adds one comparison per reached test and two scalar operations per vertex to seed the one shared backward sweep. The bound excludes parsing and validation. The recurrence gives the exact selected derivative where the reached comparisons are strict and the divisors are nonzero. Runtime Real values can round or overflow. Division refuses a reached invalid divisor or a nonfinite quotient or quotient contribution.

PARAMETER DESCRIPTION
module

One checked named reverse graph with an optional lazy sink selection.

TYPE: QiecModule

instance

The actual declared lexical reverse instance.

TYPE: EffectInstanceId

handler

Its total grade-one handler signature.

TYPE: HandlerId

constructor

Its one nominal constructor with Real and Int fields.

TYPE: ConstructorId

RETURNS DESCRIPTION
QiecModule

The revalidated pure computation and its entry points. The result is the selected primal followed by all vertex cotangents in the original allocation order.

RAISES DESCRIPTION
KernelError

If the carrier, handler or source violates the nominal graph contract. The code qiec-reverse-compile-limit identifies a graph with more than 256 vertices. The code qiec-reverse-sink-limit identifies more than 15 nested or 256 total comparisons.

Source code in src/quivers/qiec/reverse_diff.py
def compile_reverse_diff(
    module: QiecModule,
    instance: EffectInstanceId,
    handler: HandlerId,
    constructor: ConstructorId,
) -> QiecModule:
    """Compile a checked nominal reverse graph to an immutable pure computation.

    The compiled module contains the specialized computation and its entry
    points. Its arithmetic retains source vertex origins and emits no
    original operation events. Use `elaborate_reverse_diff` to run the
    named handler and observe those events.

    Each binary vertex adds one primal operation and sends a contribution
    along each ordered operand edge, including two uses of the same
    operand. All contributions to a vertex are added before its adjoint is
    passed down. With B binary vertices and D divisions the computation
    executes at most 5B + 2D scalar arithmetic operations, including the
    range checks on quotient contributions. Lazy sink selection adds one
    comparison per reached test and two scalar operations per vertex to
    seed the one shared backward sweep. The bound excludes parsing and
    validation. The recurrence gives the exact selected derivative
    where the reached comparisons are strict and the divisors are nonzero.
    Runtime Real values can round or overflow. Division refuses a reached
    invalid divisor or a nonfinite quotient or quotient contribution.

    Parameters
    ----------
    module : QiecModule
        One checked named reverse graph with an optional lazy sink selection.
    instance : EffectInstanceId
        The actual declared lexical reverse instance.
    handler : HandlerId
        Its total grade-one handler signature.
    constructor : ConstructorId
        Its one nominal constructor with Real and Int fields.

    Returns
    -------
    QiecModule
        The revalidated pure computation and its entry points. The result
        is the selected primal followed by all vertex cotangents in the
        original allocation order.

    Raises
    ------
    KernelError
        If the carrier, handler or source violates the nominal graph
        contract. The code `qiec-reverse-compile-limit` identifies a graph
        with more than 256 vertices. The code `qiec-reverse-sink-limit`
        identifies more than 15 nested or 256 total comparisons.
    """
    _, _, vertices, chosen = _checked_reverse_graph(
        module,
        instance,
        handler,
        constructor,
        maximum=_MAX_COMPILED_VERTICES,
        limit_code="qiec-reverse-compile-limit",
    )
    (entry,) = module.computations
    compiled = QiecModule(
        module=module.module,
        source_protocol=module.source_protocol,
        computations=(entry.with_(body=_compiled_body(entry, vertices, chosen)),),
        entries=module.entries,
        gap=module.gap,
    )
    validate_module(compiled)
    return compiled

compile_multishot_reverse_diff

compile_multishot_reverse_diff(module: QiecModule, instance: EffectInstanceId, handler: HandlerId, constructor: ConstructorId) -> QiecModule

Compile a bounded named reverse scope containing one authored binary fork.

The outer handler has the signature of :func:compile_reverse_diff. A common prefix allocates the input vertices and may allocate more vertices before entering a tail Choice scope. That scope forks once, resumes twice with finite Real literals, and executes the same nonempty straight-line suffix for each shot. The clause combines the results in shot order by one named addition, multiplication or division and stops on the result. The prefix, both executed shots and the final join retain the strict checks of every reached division.

The result contains the primal followed by cotangents in occurrence order: prefix, first shot, second shot, and clause join. Equal shot values still receive separate slots. The pure result retains the source operation origins and emits no operation events.

Each numeric occurrence is evaluated once in the generated primal graph. Each operand occurrence sends one adjoint contribution in the reverse sweep. For a graph with V vertices and E edges the generated storage and scalar work are O(V + E). This bound excludes source validation, discharge, and target emission.

PARAMETER DESCRIPTION
module

The checked source containing the named reverse and fork handlers.

TYPE: QiecModule

instance

The actual declared lexical reverse instance.

TYPE: EffectInstanceId

handler

The total grade-one reverse handler signature.

TYPE: HandlerId

constructor

The nominal Real and Int carrier constructor.

TYPE: ConstructorId

RETURNS DESCRIPTION
QiecModule

The revalidated pure module with one immutable reverse sweep.

RAISES DESCRIPTION
KernelError

If the source or residual violates the checked fragment. The code qiec-reverse-multishot-limit identifies graphs exceeding 256 expanded vertices and a nested discharge reaching its budget.

Source code in src/quivers/qiec/reverse_diff.py
def compile_multishot_reverse_diff(
    module: QiecModule,
    instance: EffectInstanceId,
    handler: HandlerId,
    constructor: ConstructorId,
) -> QiecModule:
    """Compile a bounded named reverse scope containing one authored binary fork.

    The outer handler has the signature of :func:`compile_reverse_diff`.
    A common prefix allocates the input vertices and may allocate more
    vertices before entering a tail Choice scope. That scope forks once,
    resumes twice with finite Real literals, and executes the same
    nonempty straight-line suffix for each shot. The clause combines the
    results in shot order by one named addition, multiplication or
    division and stops on the result. The prefix, both executed shots
    and the final join retain the strict checks of every reached division.

    The result contains the primal followed by cotangents in occurrence
    order: prefix, first shot, second shot, and clause join. Equal shot
    values still receive separate slots. The pure result retains the
    source operation origins and emits no operation events.

    Each numeric occurrence is evaluated once in the generated primal
    graph. Each operand occurrence sends one adjoint contribution in
    the reverse sweep. For a graph with `V` vertices and `E` edges the
    generated storage and scalar work are O(V + E). This bound excludes
    source validation, discharge, and target emission.

    Parameters
    ----------
    module : QiecModule
        The checked source containing the named reverse and fork handlers.
    instance : EffectInstanceId
        The actual declared lexical reverse instance.
    handler : HandlerId
        The total grade-one reverse handler signature.
    constructor : ConstructorId
        The nominal Real and Int carrier constructor.

    Returns
    -------
    QiecModule
        The revalidated pure module with one immutable reverse sweep.

    Raises
    ------
    KernelError
        If the source or residual violates the checked fragment. The code
        `qiec-reverse-multishot-limit` identifies graphs exceeding 256
        expanded vertices and a nested discharge reaching its budget.
    """
    if len(module.computations) != 1:
        raise KernelError(
            "binary reverse needs one selected source entry", _MULTISHOT_SHAPE
        )
    registry = validate_module(module)
    (entry,) = module.computations
    outer = entry.body
    row_entry = next(
        (item.entry for item in module.instances if item.entry.instance == instance),
        None,
    )
    if (
        not isinstance(outer, Handle)
        or outer.instance != instance
        or outer.handler != handler
        or outer.arguments
        or outer.static_arguments
        or row_entry is None
    ):
        raise KernelError(
            "binary reverse needs its outer named handler", _MULTISHOT_SHAPE
        )
    numeric = registry.handler(handler)
    reverse = {op.name: op for op in registry.effects[row_entry.effect.id].operations}
    if not {"seed", "add", "mul", "stop"} <= reverse.keys():
        raise KernelError(
            "binary reverse needs its nominal operations", _MULTISHOT_SHAPE
        )
    join_ops = frozenset(
        reverse[name].id for name in ("add", "mul", "div") if name in reverse
    )
    allocation_ops = join_ops | {reverse["seed"].id}
    prefix, choice = _multishot_allocations(
        outer.computation, instance, allocation_ops, _MAX_COMPILED_VERTICES - 3
    )
    if (
        len(prefix) < len(entry.parameters)
        or not isinstance(choice, Handle)
        or choice.instance == instance
        or choice.arguments
        or choice.static_arguments
        or not isinstance(fork_binding := choice.computation, Bind)
        or not isinstance(fork_request := fork_binding.first, Perform)
        or fork_request.request.instance != choice.instance
        or fork_request.request.arguments
        or fork_request.request.static_arguments
    ):
        raise KernelError("binary reverse needs one tail fork", _MULTISHOT_SHAPE)
    choice_row = EffectRow(entries=(row_entry,))
    fork_handler = registry.handler(choice.handler)
    (fork_interface, fork) = registry.operations[fork_request.request.operation]
    if (
        fork_interface.telescope
        or fork.telescope
        or fork.arguments
        or fork.result_type != REAL
        or fork_handler.input_type != numeric.input_type
        or fork_handler.output_type != numeric.input_type
        or fork_handler.introduced != choice_row
    ):
        raise KernelError("binary reverse needs a nominal Real fork", _MULTISHOT_SHAPE)
    shots, join, stop = _multishot_clause(
        fork_handler, fork, instance, join_ops, reverse["stop"].id
    )
    maximum_suffix = (_MAX_COMPILED_VERTICES - len(prefix) - 1) // 2
    suffix, answer = _multishot_allocations(
        fork_binding.then, instance, allocation_ops, maximum_suffix
    )
    if not suffix or answer != Return(value=Var(local=suffix[-1][0].binder)):
        raise KernelError(
            "binary reverse suffix must return its last allocated vertex",
            _MULTISHOT_SHAPE,
        )
    size = len(prefix) + 2 * len(suffix) + 1
    if entry.type.result != product_type(*((REAL,) * (1 + size))):
        raise KernelError(
            "binary reverse answer needs one cotangent per expanded vertex",
            _MULTISHOT_SHAPE,
        )
    join_perform = join.first
    assert isinstance(join_perform, Perform)
    original = [
        *(perform.request for _, perform in prefix + suffix),
        fork_request.request,
        join_perform.request,
        stop.request,
    ]
    if len({request.origin.static_site for request in original}) != len(
        original
    ) or any(
        request.origin.resumption_path or request.origin.dynamic_path
        for request in original
    ):
        raise KernelError(
            "binary reverse needs distinct undisplaced source request sites",
            _MULTISHOT_SHAPE,
        )
    for slot, request in enumerate(
        original[: len(prefix) + len(suffix)] + [join_perform.request]
    ):
        if request.arguments[0] != LiteralValue(value=slot, type=INT):
            raise KernelError(
                "binary reverse lexical slots must be consecutive", _MULTISHOT_SHAPE
            )
    scoped_entry = entry.with_(
        parameters=(*entry.parameters, *(binding.binder for binding, _ in prefix)),
        body=choice,
        type=ComputationType(effects=choice_row, result=fork_handler.output_type),
    )
    validate_module(module.with_(computations=(scoped_entry,), entries=()))
    discharged = discharge_computation(scoped_entry, module)
    if not isinstance(discharged, NamedComputation):
        code = _MULTISHOT_LIMIT if discharged.kind == "growth" else _MULTISHOT_SHAPE
        raise KernelError(f"binary reverse fork discharge: {discharged.reason}", code)
    residual, tail = _multishot_allocations(
        discharged.body, instance, allocation_ops, 2 * len(suffix) + 1
    )
    if len(residual) != 2 * len(suffix) + 1 or not isinstance(tail, Perform):
        raise KernelError(
            "binary reverse needs every discharged vertex and stop", _MULTISHOT_SHAPE
        )
    cursor = 0
    destinations: dict[Local, Value] = {}
    for ordinal, shot_binding in enumerate(shots):
        shot = shot_binding.first
        assert isinstance(shot, Resume)
        scope: dict[Local, Value] = {fork_binding.binder: shot.value}
        for binding, perform in suffix:
            new_binding, new_perform = residual[cursor]
            _check_occurrence(perform.request, new_perform.request, (ordinal,), scope)
            scope[binding.binder] = Var(local=new_binding.binder)
            cursor += 1
        destinations[shot_binding.binder] = scope[suffix[-1][0].binder]
    merged, merged_perform = residual[cursor]
    _check_occurrence(join_perform.request, merged_perform.request, (), destinations)
    _check_occurrence(
        stop.request, tail.request, (), {join.binder: Var(local=merged.binder)}
    )
    spliced: Computation = tail
    for slot, (binding, perform) in reversed(tuple(enumerate(prefix + residual))):
        request = perform.request
        arguments = (LiteralValue(value=slot, type=INT), *request.arguments[1:])
        spliced = binding.with_(
            first=perform.with_(request=request.with_(arguments=arguments)),
            then=spliced,
        )
    expanded = module.with_(
        computations=(entry.with_(body=outer.with_(computation=spliced)),),
    )
    return compile_reverse_diff(expanded, instance, handler, constructor)

Finite elimination

eliminate_finite contracts explicit finite tables. Each factor gives its axes in table order, with the last axis varying fastest. The order of the factors is the written product order.

The checker evaluates the actual named QIEC operations on every pair of carrier values. It checks the additive and multiplicative identities, associativity, additive commutativity, both distributive laws and the annihilating zero. Carrier values are Booleans, unit values and their finite products. A failing law returns unequal answers and their exact arguments in a FiniteAlgebraLawError.

With a noncommutative product, eliminating a variable joins the interval from its first to last participating factor, including intervening factors. Each resulting factor occupies the original interval's position. With a commutative product, the planner may join a smaller bucket by leaving those intervening factors in place. The report records each step's factor positions and the largest table cardinality. For a bag with \(s\) assignments and \(f\) selected factors, contraction executes \(s\) sum-table lookups and \(sf\) product-table lookups. The total counters include the final product on the output axes. Reading each factor cell also takes work proportional to its arity to form its index. This contract on explicit factors assumes that their cells are already given.

from quivers.dsl import Compiler, parse
from quivers.qiec import (
    FiniteAlgebra, FiniteFactor, FiniteSourceFactor, eliminate_finite, eliminate_finite_source,
)

source = """
define add(a : Bool, b : Bool) : Bool !{} =
    if a then
        return true
    else
        return b

define multiply(a : Bool, b : Bool) : Bool !{} =
    if a then
        return b
    else
        return false

define indicator(a : Bool) : Bool !{} =
    return a

define negate(a : Bool) : Bool !{} =
    if a then
        return false
    else
        return true

define unit() : Bool !{} =
    return true
"""
module = Compiler(parse(source), module_name="boolean-elimination").qiec_module
assert module is not None
ids = {item.name: item.id for item in module.computations}
algebra = FiniteAlgebra(ids["add"], ids["multiply"], zero=False, one=True)
factors = (
    FiniteFactor(("x",), (True, False)),
    FiniteFactor(("y",), (False, True)),
    FiniteFactor(("x",), (True, True)),
)
answer = eliminate_finite(module, algebra, factors, ("y",), {"x": 2, "y": 2})
assert answer.factor.cells == (False, True)
assert answer.steps[0].positions == (0, 2)
assert answer.work.additions == 4
assert answer.work.multiplications == 8

eliminate_finite_source derives factor cells from named checked QIEC computations. Each axis takes the exact type of its parameter and has the same type in every factor that names it. Booleans order false before true, unit has one value, and products order lexicographically. The last parameter varies fastest. By default, source bodies and their transitive callees must be pure finite computations. A local handler can close the type's effect row while leaving a draw in its body, so the checker examines the reachable bodies before it builds any table.

The planner checks source cell counts, factor areas and intermediate bag areas before evaluating the factors. source_evaluations counts one reference evaluation per source cell. result.work counts the operator table lookups used to contract those cells. Continuing the example, two unary factors and one constant require five evaluations.

source_factors = (
    FiniteSourceFactor(("x",), ids["negate"]),
    FiniteSourceFactor(("y",), ids["indicator"]),
    FiniteSourceFactor((), ids["unit"]),
)
compiled = eliminate_finite_source(module, algebra, source_factors, ("y",))
assert compiled.result.factor.cells == (False, True)
assert compiled.source_evaluations == 5

Factors with local linear handlers

Pass discharge_linear_handlers=True to tabulate a closed factor after checking and discharging its local handlers. This projection requires monomorphic custom effects and authored grade-one tail resumptions with ordinary prefixes and identity returns. Linearity here means that each operation resumes its continuation exactly once. The checker inspects transitive callees and requires a pure finite residual factor. It refuses stochastic requests, foreign providers and other resumption shapes before factor evaluation.

The contraction combines the completed factor values using the checked algebra. This includes formal tangent coefficients when the declared carrier supplies them. Every handled operation still has its ordinary address in an original source run. The table observes only the returned carrier value after the handler has been discharged. The result's discharged_computations lists the original nominal identities whose bodies the planner rewrote.

handled_source = source + """
effect ReadFlag
    read_flag : Unit -> Bool

instance flag : ReadFlag

handler local_flag for ReadFlag : Bool -> Bool with (saved : Bool) [coverage=total, implementation=authored]
    return answer =>
        return answer
    read_flag resumes 1 =>
        resume(saved)

define read_local(value : Bool) : Bool !{} =
    handle flag with local_flag(value) in
        perform flag.read_flag()
"""
handled = Compiler(parse(handled_source), module_name="local-factor").qiec_module
assert handled is not None
ids = {item.name: item.id for item in handled.computations}
local_algebra = FiniteAlgebra(ids["add"], ids["multiply"], zero=False, one=True)
local = FiniteSourceFactor(("x",), ids["read_local"])
projected = eliminate_finite_source(
    handled, local_algebra, (local,), ("x",), discharge_linear_handlers=True
)
assert projected.result.factor.cells == (False, True)
assert projected.discharged_computations == (ids["read_local"],)

Factors with a local weighted handler

Pass discharge_weighted_handlers=True when a factor begins by installing a stateless authored handler around one Boolean request. The request takes two weights in the factor's finite carrier. Its clause resumes with false and then with true, obtaining answers \(v_0\) and \(v_1\). It returns \(w_0v_0+w_1v_1\) using the exact named product and sum supplied in FiniteAlgebra. The checker establishes the finite algebra laws from the original declarations and requires an identity return and an acyclic pure continuation. Both resumptions run even when a weight is zero.

The resulting table observes the completed factor value, including any formal tangent coefficients in its carrier. An original source run also records the handled request and the two resumptions. The scope check refuses other effects in the continuation, including effects hidden by a callee's local handler. An enclosing observer \(F\) can distinguish \(F(w_0v_0+w_1v_1)\) from \(w_0F(v_0)+w_1F(v_1)\).

weighted_source = source + """
effect Weighted
    pick : Bool * Bool -> Bool

instance choice : Weighted

handler weighted_sum for Weighted : Bool -> Bool [coverage=total, forwards=none, implementation=authored]
    return answer =>
        return answer
    pick(w0 : Bool, w1 : Bool) resumes omega =>
        let v0 <- resume(false)
        let v1 <- resume(true)
        let left <- multiply(w0, v0)
        let right <- multiply(w1, v1)
        add(left, right)

define pick_flag(x : Bool, y : Bool) : Bool !{} =
    handle choice with weighted_sum in
        let picked <- perform choice.pick(x, y)
        if picked then
            return true
        else
            return x
"""
weighted_module = Compiler(parse(weighted_source), module_name="weighted-factor").qiec_module
assert weighted_module is not None
ids = {item.name: item.id for item in weighted_module.computations}
algebra = FiniteAlgebra(ids["add"], ids["multiply"], zero=False, one=True)
factor = FiniteSourceFactor(("x", "y"), ids["pick_flag"])
weighted_table = eliminate_finite_source(
    weighted_module, algebra, (factor,), ("x", "y"), discharge_weighted_handlers=True
)
assert weighted_table.result.factor.cells == (False, True, True, True)
assert weighted_table.source_evaluations == 4

Weighted chains with a finite state

The same weighted opt-in accepts a fixed sequence of requests when the source carries a state of type Bool, Unit, or a finite product of these types. A named pure initializer takes the factor inputs. Each transition returns that same checked state type. The binary clause resumes with false and then true. A multiway chain can use an authored clause with three or more explicit literal responses of one finite type. Each response occurrence has a corresponding weight and left product. The clause adds the products from left to right with the declared algebra.

At each layer, one named pure call per occurrence takes the fixed inputs, current state, and the corresponding response literal to form its weight. The request uses those weights in order on the installed instance. A named pure transition uses the fixed inputs, state, and actual response. The terminal call sees the factor inputs and final state. Each helper has an acyclic pure finite call graph.

Write \(s_j=T_i(a,s,c_j)\) for the transition at layer \(i\) on response \(c_j\), with fixed factor input \(a\). The table shares the suffix value for histories with the same layer and state. The ordered sum \(V_i(s)=\sum_j w_{i,j}(a,s)V_{i+1}(s_j)\) retains every term, including terms with equal responses or successors. This keeps the order of multiplication and works for noncommutative products. Request addresses and individual shot visits remain observable in a source run. The projected table records the completed carrier value, including any formal tangent coefficients.

For a state type with \(D\) inhabitants and \(U\) distinct response literals, layer \(i\) reaches at most \(\min(D,U^i)\) states, including the terminal layer at the chain's depth. The planner sums these bounds over all layers and factor cells against max_weighted_state_cells before evaluating helpers. The bound counts logical state cells. For \(m\) written occurrences, each reached nonterminal cell retains \(m\) edges. It makes \(m\) weight calls and \(m\) transition calls, then uses \(m\) multiplications and \(m-1\) additions. Storing and comparing a product key also takes work in its tuple payload. The result reports actual state, helper call, and suffix arithmetic counts. The contraction reports its arithmetic separately.

For one closed ranked factor without arguments, EffectPlan.check_ranked_weighted_elimination checks its original static requests and ordered shots and runs the finite tabulation with the actual named operators. Its result records the typed algebra proof, the output cell, the proof and state caps, and the measured helper and arithmetic work. The native address projection describes a source run. The suffix table retains finite state values and their arithmetic. This report uses the same carrier for weights and answers. Distinct answer carriers use the separate tabulate_ranked_weighted_answers interface.

An optional formal_base asks for a separate proof that the executed carrier is the nominal pair of that base type and that its units, addition and ordered multiplication are those of a square-zero extension. The check verifies every operator entry. Its additional proof work has a separate cap. A successful report exposes the constant and linear coefficients of the weighted expression in its checked weights and terminal values. These finite coefficients do not assign a Real JVP to the state transitions or their inputs.

ranked_elimination

Bind a checked ranked address projection to its finite tabulation.

FiniteFormalDualValue dataclass

FiniteFormalDualValue(base: FiniteAlgebraProof, primal: FiniteValue, tangent: FiniteValue, checks: int)

A checked constant and linear coefficient in a finite dual algebra.

PARAMETER DESCRIPTION
base

The declared finite base algebra and its checked law evidence.

TYPE: FiniteAlgebraProof

primal

The two components of the same eliminated value in the exact checked base carrier. The second is a formal coefficient of the extracted expression in its weights and terminal values.

TYPE: FiniteValue

tangent

The two components of the same eliminated value in the exact checked base carrier. The second is a formal coefficient of the extracted expression in its weights and terminal values.

TYPE: FiniteValue

checks

The additional operator-table entries and comparisons in this optional proof, separate from the executed tabulation.

TYPE: int

RankedWeightedEliminationCheck dataclass

RankedWeightedEliminationCheck(addresses: RankedWeightedAddressEvidence, tabulation: FiniteSourceEliminationResult, max_checks: int, max_weighted_state_cells: int, fuel: int, formal_dual: FiniteFormalDualValue | None, max_formal_checks: int)

The checked ranked source and its actual finite scalar tabulation.

PARAMETER DESCRIPTION
addresses

The bound native static sites and ordered shot projection.

TYPE: RankedWeightedAddressEvidence

tabulation

The actual finite result, nominal algebra proof, and counted suffix and contraction work.

TYPE: FiniteSourceEliminationResult

max_checks

The operator proof limit, state-cell limit, and per-call step limit used by this observation.

TYPE: int

max_weighted_state_cells

The operator proof limit, state-cell limit, and per-call step limit used by this observation.

TYPE: int

fuel

The operator proof limit, state-cell limit, and per-call step limit used by this observation.

TYPE: int

formal_dual

The optional independently checked finite dual coefficient.

TYPE: FiniteFormalDualValue or None

max_formal_checks

The separate cap for the optional dual operation check.

TYPE: int

check_ranked_weighted_elimination

check_ranked_weighted_elimination(module: QiecModule, computation: ComputationId, algebra: FiniteAlgebra, *, formal_base: FiniteAlgebra | None = None, max_checks: int = 65536, max_weighted_state_cells: int = 65536, max_formal_checks: int = 65536, fuel: int = 65536) -> RankedWeightedEliminationCheck

Check and tabulate one closed nullary ranked weighted source factor.

This check binds the same original nominal factor to its static address projection and to the regular finite source elimination entry point. The native address projection concerns the source trace. The tabulated result describes suffix sharing and finite arithmetic. A formal base explicitly requests a separate finite dual operation proof. Finite coefficients here give no Real JVP.

PARAMETER DESCRIPTION
module

The actual checked source containing the factor and its operators.

TYPE: QiecModule

computation

The selected closed ranked factor.

TYPE: ComputationId

algebra

The nominal addition and multiplication and their declared units.

TYPE: FiniteAlgebra

formal_base

Require the executed algebra to implement the finite dual lift of this exact base carrier, and report its two coefficients.

TYPE: FiniteAlgebra or None DEFAULT: None

max_checks

Limits on finite operator proof work and weighted state cells.

TYPE: int DEFAULT: 65536

max_weighted_state_cells

Limits on finite operator proof work and weighted state cells.

TYPE: int DEFAULT: 65536

max_formal_checks

The independent limit on the additional finite dual proof.

TYPE: int DEFAULT: 65536

fuel

The reference step limit for each individual checked call.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
RankedWeightedEliminationCheck

Source scope, executed finite result, and counted work.

RAISES DESCRIPTION
ValueError

If a limit or a declaration is invalid.

FiniteLawUnsupported

If the checked source or its carrier is outside the fragment.

FiniteLawLimit

If a required proof, source table, or operator exceeds a limit.

FiniteAlgebraLawError

If an exact operator equation fails.

RuntimeError

If the executed stage or its algebra differs from the checked scope.

Source code in src/quivers/qiec/ranked_elimination.py
def check_ranked_weighted_elimination(
    module: QiecModule,
    computation: ComputationId,
    algebra: FiniteAlgebra,
    *,
    formal_base: FiniteAlgebra | None = None,
    max_checks: int = 65_536,
    max_weighted_state_cells: int = 65_536,
    max_formal_checks: int = 65_536,
    fuel: int = 65_536,
) -> RankedWeightedEliminationCheck:
    """Check and tabulate one closed nullary ranked weighted source factor.

    This check binds the same original nominal factor to its static
    address projection and to the regular finite source elimination
    entry point. The native address projection concerns the source
    trace. The tabulated result describes suffix sharing and finite
    arithmetic. A formal base explicitly requests a separate finite
    dual operation proof. Finite coefficients here give no Real JVP.

    Parameters
    ----------
    module : QiecModule
        The actual checked source containing the factor and its operators.
    computation : ComputationId
        The selected closed ranked factor.
    algebra : FiniteAlgebra
        The nominal addition and multiplication and their declared units.
    formal_base : FiniteAlgebra or None
        Require the executed algebra to implement the finite dual lift
        of this exact base carrier, and report its two coefficients.
    max_checks, max_weighted_state_cells : int
        Limits on finite operator proof work and weighted state cells.
    max_formal_checks : int
        The independent limit on the additional finite dual proof.
    fuel : int
        The reference step limit for each individual checked call.

    Returns
    -------
    RankedWeightedEliminationCheck
        Source scope, executed finite result, and counted work.

    Raises
    ------
    ValueError
        If a limit or a declaration is invalid.
    FiniteLawUnsupported
        If the checked source or its carrier is outside the fragment.
    FiniteLawLimit
        If a required proof, source table, or operator exceeds a limit.
    FiniteAlgebraLawError
        If an exact operator equation fails.
    RuntimeError
        If the executed stage or its algebra differs from the checked scope.
    """
    _validate_limit("max_checks", max_checks)
    _validate_limit("max_weighted_state_cells", max_weighted_state_cells)
    _validate_limit("max_formal_checks", max_formal_checks)
    _validate_limit("fuel", fuel)
    if not isinstance(algebra, FiniteAlgebra):
        raise FiniteLawUnsupported(
            "ranked elimination check needs one finite algebra for weights and answers"
        )
    if formal_base is not None and not isinstance(formal_base, FiniteAlgebra):
        raise FiniteLawUnsupported(
            "formal dual reporting needs a declared finite base algebra"
        )

    addresses = _ranked_weighted_address_evidence(module, computation, algebra)
    tabulation = eliminate_finite_source(
        module,
        algebra,
        (FiniteSourceFactor((), computation),),
        (),
        max_checks=max_checks,
        max_cells=1,
        max_source_cells=1,
        max_weighted_state_cells=max_weighted_state_cells,
        discharge_weighted_handlers=True,
        fuel=fuel,
    )
    if tabulation.weighted_chain_computations != (computation,):
        raise RuntimeError(
            "expected the selected ranked factor to use weighted chain tabulation"
        )
    formal = None
    if formal_base is not None:
        formal = _formal_dual_value(
            module,
            tabulation.result.proof,
            tabulation.result.factor.cells[0],
            formal_base,
            max_formal_checks,
            fuel,
        )
    return RankedWeightedEliminationCheck(
        addresses,
        tabulation,
        max_checks,
        max_weighted_state_cells,
        fuel,
        formal,
        max_formal_checks,
    )

A factor can also initialize its state and tail-call one recursive callee under this handler with a nonnegative Int literal rank. The callee tests n <= 0 and calls the terminal helper at zero. Its positive branch has one weighted layer and tail-calls the same declaration at n - 1 with the same outer inputs and the new state of the same type. All branches of the request reduce the rank, so the suffix table applies the same ordered recurrence at each smaller rank. The planner checks the entire cell bound before it iterates the repeated layer. The rank check admits this guarded form. The ordinary helpers remain finite, acyclic and pure, including through any calls they make.

chain_source = weighted_source + """
define initial(x : Bool) : Bool !{} =
    return false

define chain_weight(x : Bool, s : Bool, b : Bool) : Bool !{} =
    if b then
        return x
    else
        return true

define advance(x : Bool, s : Bool, b : Bool) : Bool !{} =
    add(s, b)

define terminal(x : Bool, s : Bool) : Bool !{} =
    return s

define chain(x : Bool) : Bool !{} =
    handle choice with weighted_sum in
        let s0 <- initial(x)
        let w00 <- chain_weight(x, s0, false)
        let w01 <- chain_weight(x, s0, true)
        let b0 <- perform choice.pick(w00, w01)
        let s1 <- advance(x, s0, b0)
        let w10 <- chain_weight(x, s1, false)
        let w11 <- chain_weight(x, s1, true)
        let b1 <- perform choice.pick(w10, w11)
        let s2 <- advance(x, s1, b1)
        terminal(x, s2)
"""
chain_module = Compiler(parse(chain_source), module_name="weighted-chain").qiec_module
assert chain_module is not None
ids = {item.name: item.id for item in chain_module.computations}
chain_algebra = FiniteAlgebra(ids["add"], ids["multiply"], zero=False, one=True)
factor = FiniteSourceFactor(("x",), ids["chain"])
chain_table = eliminate_finite_source(
    chain_module, chain_algebra, (factor,), ("x",),
    discharge_weighted_handlers=True, max_weighted_state_cells=10,
)
assert chain_table.result.factor.cells == (False, True)
assert chain_table.weighted_chain_state_cells == 10
assert chain_table.weighted_chain_computations == (ids["chain"],)

Ranked multiway example

With two requests and three written responses per request, there are nine response words. Eight contain at least one true, so their sum under XOR is false. Dropping one of the two true occurrences leaves three accepted words, which sum to true. The table reaches five cells, of which three are nonterminal. Each nonterminal cell retains all three weighted edges.

from quivers.qiec import FiniteEliminationWork, run_named

ranked_source = source + """
define parity(a : Bool, b : Bool) : Bool !{} =
    if a then
        negate(b)
    else
        return b

effect WeightedThree
    pick : Bool * Bool * Bool -> Bool

instance branches : WeightedThree

handler sum_three for WeightedThree : Bool -> Bool [coverage=total, forwards=none, implementation=authored]
    pick(w0 : Bool, w1 : Bool, w2 : Bool) resumes omega =>
        let v0 <- resume(false)
        let v1 <- resume(true)
        let v2 <- resume(true)
        let p0 <- multiply(w0, v0)
        let p1 <- multiply(w1, v1)
        let p2 <- multiply(w2, v2)
        let subtotal <- parity(p0, p1)
        parity(subtotal, p2)

define initial() : Bool !{} =
    return false

define weight(seen : Bool, response : Bool) : Bool !{} =
    return true

define loop(n : Int, seen : Bool) : Bool !{branches} =
    if n <= 0 then
        indicator(seen)
    else
        let w0 <- weight(seen, false)
        let w1 <- weight(seen, true)
        let w2 <- weight(seen, true)
        let response <- perform branches.pick(w0, w1, w2)
        let next_seen <- add(seen, response)
        loop(n - 1, next_seen)

define ranked() : Bool !{} =
    handle branches with sum_three in
        let seen <- initial()
        loop(2, seen)
"""
ranked_module = Compiler(parse(ranked_source), module_name="ranked-multiway").qiec_module
assert ranked_module is not None
ids = {item.name: item.id for item in ranked_module.computations}
ranked_algebra = FiniteAlgebra(ids["parity"], ids["multiply"], zero=False, one=True)
ranked_factor = FiniteSourceFactor((), ids["ranked"])
ranked_table = eliminate_finite_source(
    ranked_module, ranked_algebra, (ranked_factor,), (),
    discharge_weighted_handlers=True, max_weighted_state_cells=5,
)
expected = bool((3**2 - 1) % 2)
assert ranked_table.result.factor.cells == (expected,)
assert bool(run_named(ranked_module, "ranked").value) == expected
assert ranked_table.weighted_chain_state_cells == 5
assert ranked_table.weighted_chain_work == FiniteEliminationWork(6, 9)

For a closed ranked factor without arguments, EffectPlan.check_ranked_weighted_addresses checks a source digest, the nominal installation and request site, and the written resume sites in shot order. After projecting a native run to its static site and shot path, request words have length less than the rank. Each request visits its shots in the written depth-first order. Both true responses above have separate ordinals. Full dynamic frames, including call activations, remain observable in the native run. Address and derivative checks have separate scope.

ranked_plan = Compiler(parse(ranked_source), module_name="ranked-multiway").effect_plan("ranked")
addresses = ranked_plan.check_ranked_weighted_addresses(ranked_algebra)
assert addresses.rank == 2
assert len(set(addresses.resume_sites)) == 3
assert ranked_plan.verify_ranked_weighted_address_evidence(addresses, ranked_algebra) == addresses

Ranked handlers with a finite answer module

tabulate_ranked_weighted_answers specializes one checked ranked handler whose scalar type \(K\) may differ from its answer type \(A\). It verifies the actual named scalar operations, a commutative additive monoid on \(A\), and a left action \(K \times A \to A\). The action respects both sums, the scalar product and unit, and both zeros. Every check ranges over the complete finite carriers of the named operations. An answer multiplication is unnecessary.

For fixed outer inputs, let \(V_i(s)\) be the value from state \(s\) at layer \(i\). The terminal helper defines \(V_n\). Each nonterminal cell applies the checked left action to its ordered resumption occurrences and adds their answers.

\[ V_i(s) = \bigoplus_j w_{ij}(s) \cdot V_{i+1}(t_{ij}(s)). \]

The table equals the native clause value by induction from the terminal helper. Distribution over answer addition and composition of the action give the equivalent sum over response words, with scalar multiplication in written order. Distinct resume occurrences contribute separately when their successors coincide. Native execution retains each request and its shots. The table retains their combined answer value.

With rank \(n\), state domain size \(D\), and \(U\) distinct literal responses, the preflight bounds the number of layer-state cells by \(\sum_{i=0}^{n}\min(D,U^i)\) per outer input. If the table reaches \(N\) nonterminal cells and the clause writes \(m\) resumes, it performs \(mN\) action lookups and \((m-1)N\) answer additions. Its reached transition rows contain \(mN\) edges and answer reduction uses the current and next frontiers. These counts exclude tuple representation and hashing costs, operator preparation, and the cost of the checked helper calls. The separate proof budget counts both operator tables and equality checks. For \(k=|K|\) and \(a=|A|\), the scalar proof has \(4k^3+4k^2+6k\) checks. Answer addition contributes \(a^2\) table entries and \(a^3+a^2+2a\) comparisons. The action contributes \(ka\) entries and \(2k^2a+ka^2+2a+k\) comparisons. The operator tables store \(2k^2+a^2+ka\) entries during the proof.

The matrix-action example uses \(2\times2\) matrices over \(\mathbb{F}_2\) acting on Boolean columns. Two of its three tags have the same successor. At rank six, native execution visits 364 requests and 1,092 shots per input. The table uses 26 state cells across both inputs. With the third branch's weight zero, seven response words contribute the first basis vector and the rest contribute zero. With the third weight present, 64 words contribute the first basis vector and 63 contribute the second. Addition in \(\mathbb{F}_2\) gives the first and second basis vectors, respectively.

from pathlib import Path

from quivers.dsl import Compiler, parse
from quivers.qiec import (
    FiniteAlgebra, FiniteAnswerModule, FiniteSourceFactor,
    run_named, tabulate_ranked_weighted_answers,
)

matrix_source = Path("docs/examples/qiec/ranked-weighted-answer-module.qvr").read_text(encoding="utf-8")
matrix_module = Compiler(parse(matrix_source), module_name="matrix-action").qiec_module
assert matrix_module is not None
ids = {item.name: item.id for item in matrix_module.computations}
scalars = FiniteAlgebra(
    ids["add"], ids["multiply"], (False,) * 4, (True, False, False, True),
)
answers = FiniteAnswerModule(scalars, ids["plus"], (False, False), ids["act"])
ranked_factor = FiniteSourceFactor(("include",), ids["chain"])
matrix_table = tabulate_ranked_weighted_answers(
    matrix_module, answers, ranked_factor, max_checks=20_000,
    max_weighted_state_cells=26,
)
assert matrix_table.table.cells == ((True, False), (False, True))
assert matrix_table.state_cells == 26
assert matrix_table.actions == 66
assert matrix_table.additions == 44
assert run_named(matrix_module, "chain", (True,), fuel=2_000_000).value == (False, True)

Variables shared by scalar and answer factors

eliminate_finite_answer_module takes scalar tables \(f_i\) and one distinguished answer table \(g\). For fixed retained coordinates \(x\), its value is the following sum over the eliminated coordinates \(z\).

\[ F(x)=\bigoplus_z\left(\prod_i f_i(x,z)\right)\cdot g(x,z). \]

The default permute=True requires proved commutative scalar multiplication. Its buckets collect the factors that contain the eliminated axis and can move them together. With permute=False the planner uses contiguous intervals, including any intervening factors that lack the eliminated axis. Every active table then represents a consecutive interval of the original factor list and the sums already taken within it. The single answer table starts at the right end. A mixed interval is thus a suffix, and its replacement remains rightmost.

For a scalar interval, both distributive laws move the sum into that interval under the fixed factors on either side. For a mixed suffix, each scalar product acts on the answer on its right. Composition of left actions preserves the scalar order, and the outside prefix action distributes over the suffix's answer sum. Every occurrence of the eliminated axis is in the selected interval. The two zero-action laws give the same interpretation for empty summation domains.

The planner checks the largest logical input, bag, kept table and output area for the selected strategy before evaluating the operators. The ordered strategy chooses a smallest current interval bag, with ties broken by first axis occurrence. Finding a globally optimal interval order is a separate problem. With \(c\) assignments in a bucket and \(d\) scalar factors, the contraction uses \(cd\) scalar products and \(c\) sums. A scalar bucket adds in \(K\). A mixed bucket applies \(c\) actions and adds in \(A\). The final retained-coordinate pass is another mixed contraction. The cell bound concerns the largest logical area. The shape of each factor determines the separate cost of looking up its entries.

The Boolean-column example uses XOR and AND on Boolean scalars and coordinatewise XOR on answers. Eliminating x in the first scalar bucket leaves a nonzero coefficient only when p is false. The second bucket eliminates z and returns a column. Its coefficient forces z to be true at p=false, so q selects between the two coordinate vectors.

from itertools import product
from pathlib import Path

from quivers.dsl import Compiler, parse
from quivers.qiec import (
    FiniteAlgebra, FiniteAnswerModule, FiniteEliminationWork, FiniteFactor,
    eliminate_finite_answer_module, host_value, run_named,
)

bucket_path = Path("docs/examples/qiec/finite-answer-elimination.qvr")
bucket_module = Compiler(parse(bucket_path.read_text(encoding="utf-8"))).qiec_module
assert bucket_module is not None
ids = {entry.name: entry.id for entry in bucket_module.computations}
bit_algebra = FiniteAlgebra(ids["add"], ids["multiply"], False, True)
columns = FiniteAnswerModule(bit_algebra, ids["plus"], (False, False), ids["scale"])
bit_factors = (
    FiniteFactor(("p", "x"), (False, True, True, False)),
    FiniteFactor(("x",), (False, True)),
    FiniteFactor(("z", "p"), (False, True, True, False)),
)
column_factor = FiniteFactor(("z", "q"), tuple(
    host_value(run_named(bucket_module, "answer", (z, q)).value)
    for z, q in product((False, True), repeat=2)
))
eliminated = eliminate_finite_answer_module(
    bucket_module, columns, bit_factors, column_factor, ("q", "p"),
    dict.fromkeys(("p", "q", "x", "z"), 2), max_cells=8,
)
assert eliminated.factor.cells == ((True, False), (False, False), (False, True), (False, False))
assert eliminated.largest == 8
assert eliminated.scalar_work == FiniteEliminationWork(4, 20)
assert (eliminated.answer_additions, eliminated.actions) == (12, 12)

Bounded weighted totals in QVR

A stateless resumes omega operation clause can write a weighted sum with a list of 2 to 32 responses. The checked example weights pairs of Boolean answers by Boolean scalars, with coordinatewise exclusive or as plus and, as act, a weight that keeps a pair when it is true and zeroes it when it is false:

define xor_bit(a : Bool, b : Bool) : Bool !{} =
    if a then
        if b then
            return false
        else
            return true
    else
        return b

define plus(u : (Bool * Bool), v : (Bool * Bool)) : (Bool * Bool) !{} =
    let a <- xor_bit(u[0], v[0])
    let b <- xor_bit(u[1], v[1])
    return (a, b)

define act(weight : Bool, v : (Bool * Bool)) : (Bool * Bool) !{} =
    if weight then
        return v
    else
        return (false, false)

effect WeightedBranches
    pick : Bool * Bool * Bool -> Bool

instance choices : WeightedBranches

handler fold for WeightedBranches : (Bool * Bool) -> (Bool * Bool) [coverage=total]
    pick(w0 : Bool, w1 : Bool, w2 : Bool) resumes omega =>
        resume [false, true, true] using (plus, act)

define weighted(include : Bool) : (Bool * Bool) !{} =
    handle choices with fold in
        let x <- perform choices.pick(true, true, include)
        let y <- perform choices.pick(x, false, include)
        return (x, y)

The clause pairs the operation's weights in declaration order with the responses in list order. Each response is a closed literal of the operation's result type. The named left action act takes a weight and a resumed answer, and plus adds two answers. Both computations must be closed, pure and acyclic over the checked finite types. The clause type-checks the selected operations. A planner that relies on their laws checks those laws separately.

The clause resumes once per written occurrence, in order, then applies the weights in order and adds the answers from the left. Repeated responses retain separate sites and shots. A zero weight still runs its resumption. At width \(n\) the checked body has \(n\) resumes, \(n\) action calls and \(n-1\) addition calls, with the same ordinary kernel terms as an explicitly expanded handler.

In weighted, each request resumes with false once and true twice, and the final weight is zero when include is false. Both native runs still issue four requests and make twelve shots.

from pathlib import Path

from quivers.dsl import Compiler, parse
from quivers.qiec import host_value, run_named

weighted_path = Path("docs/examples/qiec/bounded-weighted-total.qvr")
weighted_module = Compiler(parse(weighted_path.read_text(encoding="utf-8"))).qiec_module
assert weighted_module is not None
for include, expected in ((False, (True, False)), (True, (False, True))):
    result = run_named(weighted_module, "weighted", (include,))
    assert host_value(result.value) == expected
    assert sum(event.event == "resumption.invoked" for event in result.trace) == 12

For the isolated weighted value observation, EffectPlan.select_weighted_value can share the continuation before its ordered combination. weighted_value_evidence records digests of the source, request, and selected QIEC graph, together with the checked sites and structural counts. verify_weighted_value_evidence reconstructs the selection from the independently expected WeightedValueRequest, which names the entry, operations, observation and work bounds.

Change of base

FiniteBaseChange names a closed QIEC map from the input carrier to a second finite algebra. The checker evaluates the map once per input carrier value. It checks preservation of zero and one and preservation of the sum and product on every ordered pair. A failed equation reports the source arguments and both target values.

Let \(h\) be the checked map. Repeated use of the binary product equation gives \(h(\prod_i w_i)=\prod_i h(w_i)\) in the written order. Repeated use of the sum equation then moves \(h\) through the finite sum over assignments. Preservation of the units covers empty products and sums. Thus the elimination planner can map each factor table first and use the target's product laws when it chooses a contraction order.

For input and target carriers of sizes \(n\) and \(m\), the map adds \(n\) checked calls and \(2n^2+2\) comparisons to the two algebra proofs. The proof budget counts all three. Mapping factor cells uses a lookup per cell in the checked table. The existing bound on factor, bag, and output cardinalities applies to the target contraction.

FiniteAnswerBaseChange specifies separate maps on the scalar and answer carriers. When it is passed as base_change, eliminate_finite_answer_module checks the four scalar laws above and preservation of answer zero, addition, and the left action \(h_A(k\cdot a)=h_K(k)\cdot h_A(a)\) on the actual finite domains. The elimination uses the checked target action and orders products according to the target algebra. A map to a commutative target permits exchanging target factors even when scalar multiplication in the source depends on order.

finite_elimination

Exact elimination of finite factor tables with checked QIEC operators.

FiniteAlgebra dataclass

FiniteAlgebra(addition: ComputationId, multiplication: ComputationId, zero: FiniteValue, one: FiniteValue)

The declared binary operations and identities of a finite algebra.

PARAMETER DESCRIPTION
addition

The closed named binary sum.

TYPE: ComputationId

multiplication

The closed named binary product.

TYPE: ComputationId

zero

The declared additive identity and product annihilator.

TYPE: FiniteValue

one

The declared multiplicative identity.

TYPE: FiniteValue

FiniteAlgebraLawError

FiniteAlgebraLawError(law: str, counterexample: FiniteLawCounterexample)

Bases: ValueError

A required law fails on a concrete tuple of carrier values.

PARAMETER DESCRIPTION
law

The name of the failed law.

TYPE: str

counterexample

The arguments and the two exact unequal results.

TYPE: FiniteLawCounterexample

Source code in src/quivers/qiec/finite_elimination.py
def __init__(self, law: str, counterexample: FiniteLawCounterexample) -> None:
    super().__init__(f"{law} fails at {counterexample.arguments!r}")
    self.law = law
    self.counterexample = counterexample

FiniteAlgebraProof dataclass

FiniteAlgebraProof(algebra: FiniteAlgebra, carrier: TypeExpr, fingerprint: str, values: int, checks: int, noncommutative: FiniteLawCounterexample | None)

Evidence from exhaustive tables for the actual checked operators.

PARAMETER DESCRIPTION
algebra

The nominal subject and its checked identities.

TYPE: FiniteAlgebra

carrier

The common finite QIEC type at every argument and result.

TYPE: TypeExpr

fingerprint

A binding to the checked source and exact named algebra.

TYPE: str

values

The size of the complete finite carrier.

TYPE: int

checks

The number of operator table entries and equality checks.

TYPE: int

noncommutative

An exact witness if the product cannot be permuted.

TYPE: FiniteLawCounterexample or None

FiniteBaseChange dataclass

FiniteBaseChange(target: FiniteAlgebra, mapping: ComputationId)

A named QIEC map from the input algebra to another finite algebra.

PARAMETER DESCRIPTION
target

The algebra in which to contract the mapped factors.

TYPE: FiniteAlgebra

mapping

A closed unary computation from the source to the target carrier.

TYPE: ComputationId

FiniteBaseChangeProof dataclass

FiniteBaseChangeProof(source: FiniteAlgebraProof, target: FiniteAlgebraProof, mapping: ComputationId, checks: int)

Evidence that a checked map preserves both operations and units.

PARAMETER DESCRIPTION
source

The input algebra and its binding to the checked module.

TYPE: FiniteAlgebraProof

target

The algebra used for elimination in that same module.

TYPE: FiniteAlgebraProof

mapping

The checked nominal unary computation in the module.

TYPE: ComputationId

checks

The combined number of table entries and equality checks.

TYPE: int

FiniteFactor dataclass

FiniteFactor(axes: tuple[str, ...], cells: tuple[FiniteValue, ...])

A finite table in its written axis order.

PARAMETER DESCRIPTION
axes

The table's distinct axes, with the last axis varying fastest.

TYPE: tuple[str, ...]

cells

The table entries in that order.

TYPE: tuple[FiniteValue, ...]

FiniteSourceFactor dataclass

FiniteSourceFactor(axes: tuple[str, ...], computation: ComputationId)

One finite factor supplied by a checked named computation.

PARAMETER DESCRIPTION
axes

One distinct axis per parameter, in the computation's parameter order.

TYPE: tuple[str, ...]

computation

The source computation evaluated for each assignment.

TYPE: ComputationId

FiniteEliminationStep dataclass

FiniteEliminationStep(variable: str, positions: tuple[int, ...], bag: tuple[str, ...], cells: int)

One exact sum of an ordered product of factor tables.

PARAMETER DESCRIPTION
variable

The variable summed out at the step.

TYPE: str

positions

Zero-based positions in the current ordered list of factors.

TYPE: tuple[int, ...]

bag

The full axis set of the joined factors, in table order.

TYPE: tuple[str, ...]

cells

The number of assignments in that bag.

TYPE: int

FiniteEliminationWork dataclass

FiniteEliminationWork(additions: int, multiplications: int)

The executed operations on cells of the checked answer algebra.

PARAMETER DESCRIPTION
additions

Sum-table lookups during contraction.

TYPE: int

multiplications

Product-table lookups during contraction.

TYPE: int

FiniteEliminationResult dataclass

FiniteEliminationResult(factor: FiniteFactor, proof: FiniteAlgebraProof, steps: tuple[FiniteEliminationStep, ...], largest: int, base_change: FiniteBaseChangeProof | None = None, work: FiniteEliminationWork = FiniteEliminationWork(0, 0))

The contracted factor, its exact algebra, and the chosen elimination.

PARAMETER DESCRIPTION
factor

The value indexed in the requested output order.

TYPE: FiniteFactor

proof

The fresh proof used to permit elimination for the actual operators.

TYPE: FiniteAlgebraProof

steps

The finite sums and the product positions they cover.

TYPE: tuple[FiniteEliminationStep, ...]

largest

The largest number of assignments in an input, intermediate bag or factor, or output.

TYPE: int

base_change

The proved map when the input was contracted in a different algebra.

TYPE: FiniteBaseChangeProof or None DEFAULT: None

work

The counted table lookups performed by the contractions.

TYPE: FiniteEliminationWork DEFAULT: FiniteEliminationWork(0, 0)

FiniteSourceEliminationResult dataclass

FiniteSourceEliminationResult(result: FiniteEliminationResult, source_evaluations: int, discharged_computations: tuple[ComputationId, ...] = (), weighted_chain_computations: tuple[ComputationId, ...] = (), weighted_chain_state_cells: int = 0, weighted_chain_helper_calls: int = 0, weighted_chain_work: FiniteEliminationWork = FiniteEliminationWork(0, 0))

A contraction with its independently counted source evaluation work.

PARAMETER DESCRIPTION
result

The finite contraction and the counts of its operator table lookups.

TYPE: FiniteEliminationResult

source_evaluations

The number of top-level factor evaluations, one per factor cell. Operator proof evaluations and calls within each factor are separate.

TYPE: int

discharged_computations

Reachable computation bodies discharged before tabulation, in module order, with their original nominal identities. The contraction observes their returned values, including any coefficients in the carrier.

TYPE: tuple[ComputationId, ...] DEFAULT: ()

weighted_chain_computations

The nominal factors tabulated by finite-state suffix evaluation, in module order.

TYPE: tuple[ComputationId, ...] DEFAULT: ()

weighted_chain_state_cells

The evaluated pairs of layer and state across weighted factor cells, including terminal states.

TYPE: int DEFAULT: 0

weighted_chain_helper_calls

The initial, weight, transition, and terminal calls in those cells.

TYPE: int DEFAULT: 0

weighted_chain_work

The sum and product lookups in the weighted chains, before contraction.

TYPE: FiniteEliminationWork DEFAULT: FiniteEliminationWork(0, 0)

RankedWeightedAddressEvidence dataclass

RankedWeightedAddressEvidence(source_digest: str, computation: ComputationId, callee: ComputationId, handler: HandlerId, instance: EffectInstanceId, operation: OperationId, request_site: SiteId, resume_sites: tuple[SiteId, ...], rank: int)

The static request and ordered shots of a checked ranked source factor.

For one ordinary native invocation, the projected requests have this static site and every word of shot ordinals shorter than the rank. Each request takes every shot in clause order, giving a depth-first traversal. A shot at the final layer has no child request. This is a source check for the static site and shot path. Dynamic frames and derivatives have separate execution contracts.

PARAMETER DESCRIPTION
source_digest

The digest of the exact canonical checked module.

TYPE: str

computation

The closed factor entry and the ranked declaration it handles.

TYPE: ComputationId

callee

The closed factor entry and the ranked declaration it handles.

TYPE: ComputationId

handler

The authored handler of the weighted operation.

TYPE: HandlerId

instance

The exact lexical installation instance.

TYPE: EffectInstanceId

operation

The installed operation at the one written request.

TYPE: OperationId

request_site

The static source identity of that request.

TYPE: SiteId

resume_sites

Written Resume sites in order, indexed by zero-based shot ordinal.

TYPE: tuple[SiteId, ...]

rank

The checked initial nonnegative literal rank.

TYPE: int

check_finite_algebra

check_finite_algebra(module: QiecModule, algebra: FiniteAlgebra, *, max_checks: int = 65536, fuel: int = 65536) -> FiniteAlgebraProof

Prove the complete finite operator tables before choosing a product order.

Addition must form a commutative monoid and multiplication a monoid whose zero annihilates. The product distributes over addition on both sides. Product commutativity is checked separately.

PARAMETER DESCRIPTION
module

The checked source containing both binary computations.

TYPE: QiecModule

algebra

The nominal operations and two identities.

TYPE: FiniteAlgebra

max_checks

The bound on the required operator entries and law comparisons.

TYPE: int DEFAULT: 65536

fuel

The evaluation step limit for each entry in either operation table.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
FiniteAlgebraProof

The exact evidence and any witness preventing a product swap.

RAISES DESCRIPTION
FiniteAlgebraLawError

If any required law fails, with a concrete equation witness.

FiniteLawUnsupported

If the signature, operator bodies, or units leave the finite fragment.

FiniteLawLimit

If the complete proof or an operator runs past its bound.

Source code in src/quivers/qiec/finite_elimination.py
def check_finite_algebra(
    module: QiecModule,
    algebra: FiniteAlgebra,
    *,
    max_checks: int = 65_536,
    fuel: int = 65_536,
) -> FiniteAlgebraProof:
    """Prove the complete finite operator tables before choosing a product order.

    Addition must form a commutative monoid and multiplication a monoid
    whose zero annihilates. The product distributes over addition on
    both sides. Product commutativity is checked separately.

    Parameters
    ----------
    module : QiecModule
        The checked source containing both binary computations.
    algebra : FiniteAlgebra
        The nominal operations and two identities.
    max_checks : int
        The bound on the required operator entries and law comparisons.
    fuel : int
        The evaluation step limit for each entry in either operation table.

    Returns
    -------
    FiniteAlgebraProof
        The exact evidence and any witness preventing a product swap.

    Raises
    ------
    FiniteAlgebraLawError
        If any required law fails, with a concrete equation witness.
    FiniteLawUnsupported
        If the signature, operator bodies, or units leave the finite fragment.
    FiniteLawLimit
        If the complete proof or an operator runs past its bound.
    """
    return _tables(module, algebra, max_checks, fuel).proof

eliminate_finite

eliminate_finite(module: QiecModule, algebra: FiniteAlgebra, factors: tuple[FiniteFactor, ...], output: tuple[str, ...], extents: Mapping[str, int], *, base_change: FiniteBaseChange | None = None, max_checks: int = 65536, max_cells: int = 65536, fuel: int = 65536) -> FiniteEliminationResult

Eliminate named axes of explicit finite factors using checked operators.

Every run proves the required laws against the actual closed named operations. With a noncommutative product, a step contracts the interval from the first to the last participating factor, preserving their order and including any factors in between. With commutativity, a step may select a smaller bucket. Empty sums yield the checked zero.

If a map preserves both binary operations and both units, mapping every input factor before elimination has the same result as mapping the contracted value. The target's proved multiplication determines the target plan's order.

PARAMETER DESCRIPTION
module

The checked source supplying the actual operations.

TYPE: QiecModule

algebra

The two nominal binary operations and their identities.

TYPE: FiniteAlgebra

factors

At least one factor, in written product order.

TYPE: tuple[FiniteFactor, ...]

output

The retained axes in output order. An empty tuple returns a scalar.

TYPE: tuple[str, ...]

extents

Exactly one nonnegative cardinality for each input axis.

TYPE: Mapping[str, int]

base_change

An optional named homomorphism to a different finite answer algebra.

TYPE: FiniteBaseChange or None DEFAULT: None

max_checks

Maximum operator entries and comparisons in all required law proofs.

TYPE: int DEFAULT: 65536

max_cells

Maximum cardinality of an input, intermediate bag or factor, or output.

TYPE: int DEFAULT: 65536

fuel

The evaluation step limit for an individual operator call.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
FiniteEliminationResult

Exact factor entries and the proved, bounded elimination plan.

RAISES DESCRIPTION
ValueError

If factor axes, cardinalities, shapes, output, or limits are invalid.

FiniteLawUnsupported

If the factor entries or operators are outside the finite carrier.

FiniteAlgebraLawError

If a required law fails, with its exact counterexample.

FiniteLawLimit

If the law proof, operator evaluation, or a table exceeds a bound.

Source code in src/quivers/qiec/finite_elimination.py
def eliminate_finite(
    module: QiecModule,
    algebra: FiniteAlgebra,
    factors: tuple[FiniteFactor, ...],
    output: tuple[str, ...],
    extents: Mapping[str, int],
    *,
    base_change: FiniteBaseChange | None = None,
    max_checks: int = 65_536,
    max_cells: int = 65_536,
    fuel: int = 65_536,
) -> FiniteEliminationResult:
    """Eliminate named axes of explicit finite factors using checked operators.

    Every run proves the required laws against the actual closed named
    operations. With a noncommutative product, a step contracts the interval
    from the first to the last participating factor, preserving their order
    and including any factors in between. With commutativity, a step may
    select a smaller bucket. Empty sums yield the checked zero.

    If a map preserves both binary operations and both units, mapping
    every input factor before elimination has the same result as mapping
    the contracted value. The target's proved multiplication determines
    the target plan's order.

    Parameters
    ----------
    module : QiecModule
        The checked source supplying the actual operations.
    algebra : FiniteAlgebra
        The two nominal binary operations and their identities.
    factors : tuple[FiniteFactor, ...]
        At least one factor, in written product order.
    output : tuple[str, ...]
        The retained axes in output order. An empty tuple returns a scalar.
    extents : Mapping[str, int]
        Exactly one nonnegative cardinality for each input axis.
    base_change : FiniteBaseChange or None
        An optional named homomorphism to a different finite answer algebra.
    max_checks : int
        Maximum operator entries and comparisons in all required law proofs.
    max_cells : int
        Maximum cardinality of an input, intermediate bag or factor, or output.
    fuel : int
        The evaluation step limit for an individual operator call.

    Returns
    -------
    FiniteEliminationResult
        Exact factor entries and the proved, bounded elimination plan.

    Raises
    ------
    ValueError
        If factor axes, cardinalities, shapes, output, or limits are invalid.
    FiniteLawUnsupported
        If the factor entries or operators are outside the finite carrier.
    FiniteAlgebraLawError
        If a required law fails, with its exact counterexample.
    FiniteLawLimit
        If the law proof, operator evaluation, or a table exceeds a bound.
    """
    _validate_limit("max_cells", max_cells)
    scopes = tuple(factor.axes for factor in factors)
    axes, sizes = _factor_geometry(scopes, output, extents)
    if any(
        len(factor.cells) != size for factor, size in zip(factors, sizes, strict=True)
    ):
        raise ValueError("finite factor cells do not match their axis extents")
    return _eliminate_factors(
        module,
        algebra,
        scopes,
        axes,
        sizes,
        output,
        extents,
        lambda _: factors,
        base_change=base_change,
        max_checks=max_checks,
        max_cells=max_cells,
        fuel=fuel,
    )

eliminate_finite_source

eliminate_finite_source(module: QiecModule, algebra: FiniteAlgebra, factors: tuple[FiniteSourceFactor, ...], output: tuple[str, ...], *, base_change: FiniteBaseChange | None = None, max_checks: int = 65536, max_cells: int = 65536, max_source_cells: int = 65536, max_weighted_state_cells: int = 65536, discharge_linear_handlers: bool = False, discharge_weighted_handlers: bool = False, fuel: int = 65536) -> FiniteSourceEliminationResult

Eliminate finite factors defined by checked named QIEC computations.

The axis at each position has that parameter's exact finite type. A repeated axis name denotes the same type and value order in every factor. The compiler bounds the total source cells and every bag of the proved elimination plan before asking the reference evaluator for a factor cell. The last parameter varies fastest. Reachable requests, including locally handled draws in computations with an empty row, are refused before tabulation by default. The optional projection checks authored linear tail handlers on monomorphic custom effects. A separate opt-in checks a direct local binary weighted handler whose two ordered resumptions have a finite continuation and whose clause calls the input algebra's exact sum and product. One direct request is discharged. A fixed sequence of requests with a checked Boolean state uses shared suffix values to tabulate the factor. Contraction starts after the factor returns and exposes its finite value. Handled request events remain available in the original run.

PARAMETER DESCRIPTION
module

The checked source defining the factors and algebra operations.

TYPE: QiecModule

algebra

The nominal binary operations and identities of the input algebra.

TYPE: FiniteAlgebra

factors

The computations and their positional axis names, in product order.

TYPE: tuple[FiniteSourceFactor, ...]

output

The retained axes in output order. An empty tuple returns a scalar.

TYPE: tuple[str, ...]

base_change

An optional checked map to a different finite answer algebra.

TYPE: FiniteBaseChange or None DEFAULT: None

max_checks

Maximum operator entries and comparisons in the algebra proofs.

TYPE: int DEFAULT: 65536

max_cells

Maximum area of any input, intermediate bag or factor, or output.

TYPE: int DEFAULT: 65536

max_source_cells

Maximum total number of top-level source factor evaluations.

TYPE: int DEFAULT: 65536

max_weighted_state_cells

Maximum total upper bound of layer and finite state pairs across weighted chain factor cells, including their terminal states.

TYPE: int DEFAULT: 65536

discharge_linear_handlers

Allow checked grade-one handlers with closed ordinary prefixes and identity returns inside factors. Algebra operations and the base map still run on the original checked module.

TYPE: bool DEFAULT: False

discharge_weighted_handlers

Allow a stateless authored weighted handler directly in a factor body. Each answer is multiplied by its corresponding weight on the left before summing in written order. Binary clauses resume with false and then true. A checked finite-state chain also admits multiway literal responses or a guarded tail call with a fixed, decreasing integer rank. Ordinary helpers and algebra operators must have acyclic pure finite call graphs.

TYPE: bool DEFAULT: False

fuel

The reference step limit for each source or operator evaluation.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
FiniteSourceEliminationResult

The exact contraction and its distinctly counted source work.

RAISES DESCRIPTION
ValueError

If an axis, extent, output, bound, or parameter count is invalid.

FiniteLawUnsupported

If a computation has an unknown identity, an inconsistent axis type, an inadmissible value, or reaches an effect.

FiniteLawLimit

If a proof, table, or evaluation exceeds a checked bound.

FiniteAlgebraLawError

If a required algebra law fails.

Source code in src/quivers/qiec/finite_elimination.py
def eliminate_finite_source(
    module: QiecModule,
    algebra: FiniteAlgebra,
    factors: tuple[FiniteSourceFactor, ...],
    output: tuple[str, ...],
    *,
    base_change: FiniteBaseChange | None = None,
    max_checks: int = 65_536,
    max_cells: int = 65_536,
    max_source_cells: int = 65_536,
    max_weighted_state_cells: int = 65_536,
    discharge_linear_handlers: bool = False,
    discharge_weighted_handlers: bool = False,
    fuel: int = 65_536,
) -> FiniteSourceEliminationResult:
    """Eliminate finite factors defined by checked named QIEC computations.

    The axis at each position has that parameter's exact finite type. A
    repeated axis name denotes the same type and value order in every
    factor. The compiler bounds the total source cells and every bag of
    the proved elimination plan before asking the reference evaluator for
    a factor cell. The last parameter varies fastest. Reachable requests,
    including locally handled draws in computations with an empty row,
    are refused before tabulation by default. The optional projection
    checks authored linear tail handlers on monomorphic custom effects.
    A separate opt-in checks a direct local binary weighted handler
    whose two ordered resumptions have a finite continuation and whose
    clause calls the input algebra's exact sum and product. One direct
    request is discharged. A fixed sequence of requests with a checked
    Boolean state uses shared suffix values to tabulate the factor.
    Contraction starts after the factor returns and exposes its finite
    value. Handled request events remain available in the original run.

    Parameters
    ----------
    module : QiecModule
        The checked source defining the factors and algebra operations.
    algebra : FiniteAlgebra
        The nominal binary operations and identities of the input algebra.
    factors : tuple[FiniteSourceFactor, ...]
        The computations and their positional axis names, in product order.
    output : tuple[str, ...]
        The retained axes in output order. An empty tuple returns a scalar.
    base_change : FiniteBaseChange or None
        An optional checked map to a different finite answer algebra.
    max_checks : int
        Maximum operator entries and comparisons in the algebra proofs.
    max_cells : int
        Maximum area of any input, intermediate bag or factor, or output.
    max_source_cells : int
        Maximum total number of top-level source factor evaluations.
    max_weighted_state_cells : int
        Maximum total upper bound of layer and finite state pairs across
        weighted chain factor cells, including their terminal states.
    discharge_linear_handlers : bool
        Allow checked grade-one handlers with closed ordinary prefixes
        and identity returns inside factors. Algebra operations and the
        base map still run on the original checked module.
    discharge_weighted_handlers : bool
        Allow a stateless authored weighted handler directly in a factor
        body. Each answer is multiplied by its corresponding weight on
        the left before summing in written order. Binary clauses resume
        with false and then true. A checked finite-state chain also admits
        multiway literal responses or a guarded tail call with a fixed,
        decreasing integer rank. Ordinary helpers and algebra operators
        must have acyclic pure finite call graphs.
    fuel : int
        The reference step limit for each source or operator evaluation.

    Returns
    -------
    FiniteSourceEliminationResult
        The exact contraction and its distinctly counted source work.

    Raises
    ------
    ValueError
        If an axis, extent, output, bound, or parameter count is invalid.
    FiniteLawUnsupported
        If a computation has an unknown identity, an inconsistent axis
        type, an inadmissible value, or reaches an effect.
    FiniteLawLimit
        If a proof, table, or evaluation exceeds a checked bound.
    FiniteAlgebraLawError
        If a required algebra law fails.
    """
    _validate_limit("max_cells", max_cells)
    _validate_limit("max_source_cells", max_source_cells)
    _validate_limit("max_weighted_state_cells", max_weighted_state_cells)
    registry = validate_module(module)
    source_owners = {owner.id: owner for owner in module.computations}
    owners = source_owners
    if algebra.addition not in owners or any(
        factor.computation not in owners for factor in factors
    ):
        raise FiniteLawUnsupported("unknown named factor or finite algebra operator")
    roots = tuple(owners[factor.computation] for factor in factors)
    carrier = owners[algebra.addition].type.result
    shape = _shape(carrier)
    axis_types: dict[str, TypeExpr] = {}
    scopes = tuple(factor.axes for factor in factors)
    for scope, owner in zip(scopes, roots, strict=True):
        if owner.type.result != carrier:
            raise FiniteLawUnsupported(
                f"source factor `{owner.name}` has a different carrier"
            )
        if len(scope) != len(owner.parameters):
            raise ValueError(
                f"source factor `{owner.name}` needs one axis per parameter"
            )
        for axis, parameter in zip(scope, owner.parameters, strict=True):
            if not isinstance(axis, str) or not axis:
                raise ValueError("finite axes need nonempty names")
            if axis_types.setdefault(axis, parameter.type) != parameter.type:
                raise FiniteLawUnsupported(
                    f"source factor axis {axis!r} has inconsistent types"
                )
    shapes = {axis: _shape(type_) for axis, type_ in axis_types.items()}
    extents = {axis: _size(domain) for axis, domain in shapes.items()}
    axes, sizes = _factor_geometry(scopes, output, extents)
    needed = sum(sizes)
    if needed > max_source_cells:
        raise FiniteLawLimit(
            f"source factors need {needed} cells, exceeding {max_source_cells}"
        )
    weighted_installations: set[ComputationId] = set()
    chains: dict[ComputationId, _WeightedChain] = {}
    if discharge_weighted_handlers:
        weighted_installations, chains = _check_weighted_factor_handlers(
            roots,
            owners,
            registry,
            _WeightedOperations(
                carrier, carrier, algebra.addition, algebra.multiplication
            ),
        )
    chain_bounds = {
        identity: _weighted_chain_bound(chain, max_weighted_state_cells)
        for identity, chain in chains.items()
    }
    weighted_bound = 0
    exact_bound = True
    for owner, size in zip(roots, sizes, strict=True):
        if owner.id in chain_bounds:
            per_point, exact = chain_bounds[owner.id]
            weighted_bound += size * per_point
            exact_bound = exact_bound and exact
    if weighted_bound > max_weighted_state_cells:
        qualifier = "" if exact_bound else "at least "
        raise FiniteLawLimit(
            f"weighted chains need a bound of {qualifier}{weighted_bound} state cells, "
            f"exceeding {max_weighted_state_cells}"
        )
    evaluation_module, discharged = _discharge_factor_installations(
        module, weighted_installations
    )
    if discharged:
        owners = {owner.id: owner for owner in evaluation_module.computations}
        roots = tuple(owners[factor.computation] for factor in factors)
    if discharge_linear_handlers:
        evaluation_module, linear = _discharge_factor_handlers(
            evaluation_module,
            tuple(owner for owner in roots if owner.id not in chains),
            owners,
            registry.handlers,
        )
        if linear:
            owners = {owner.id: owner for owner in evaluation_module.computations}
            roots = tuple(owners[factor.computation] for factor in factors)
            rewritten = set(discharged).union(linear)
            discharged = tuple(
                owner.id for owner in module.computations if owner.id in rewritten
            )
    _require_pure_factors(
        tuple(owner for owner in roots if owner.id not in chains), owners
    )
    weighted_cells, weighted_calls = 0, 0
    weighted_adds, weighted_products = 0, 0

    def load_factors(source: _Tables) -> tuple[FiniteFactor, ...]:
        """Evaluate each checked factor once per cell in positional order.

        Parameters
        ----------
        source : _Tables
            The checked algebra for the source carrier.

        Returns
        -------
        tuple[FiniteFactor, ...]
            The actual observed factor values in written product order.

        Raises
        ------
        FiniteLawLimit
            If a source computation exhausts its evaluation fuel.
        """
        nonlocal weighted_cells, weighted_calls, weighted_adds, weighted_products
        domains = {axis: _values(domain) for axis, domain in shapes.items()}
        weighted_tables = None
        if chains:
            indices = {value: index for index, value in enumerate(source.values)}
            weighted_tables = _WeightedTables(
                shape,
                shape,
                indices,
                indices,
                source.values,
                source.add,
                source.multiply,
            )
        loaded = []
        for scope, owner in zip(scopes, roots, strict=True):
            values: list[FiniteValue] = []
            chain = chains.get(owner.id)
            for point in product(*(domains[axis] for axis in scope)):
                if chain is None:
                    value = _evaluate_finite(
                        evaluation_module, owner.name, point, shape, fuel
                    )
                else:
                    assert weighted_tables is not None
                    value, cells, calls, arithmetic = _weighted_chain_cell(
                        module,
                        source_owners,
                        chain,
                        point,
                        weighted_tables,
                        fuel,
                    )
                    weighted_cells += cells
                    weighted_calls += calls
                    weighted_adds += arithmetic.additions
                    weighted_products += arithmetic.multiplications
                values.append(value)
            loaded.append(FiniteFactor(scope, tuple(values)))
        return tuple(loaded)

    result = _eliminate_factors(
        module,
        algebra,
        scopes,
        axes,
        sizes,
        output,
        extents,
        load_factors,
        base_change=base_change,
        max_checks=max_checks,
        max_cells=max_cells,
        fuel=fuel,
    )
    return FiniteSourceEliminationResult(
        result,
        needed,
        discharged,
        tuple(owner.id for owner in module.computations if owner.id in chains),
        weighted_cells,
        weighted_calls,
        FiniteEliminationWork(weighted_adds, weighted_products),
    )

finite_answer_module

Exact answer tables for one checked ranked weighted handler.

FiniteAnswerModule dataclass

FiniteAnswerModule(scalar: FiniteAlgebra, addition: ComputationId, zero: FiniteValue, action: ComputationId)

A finite scalar algebra acting on a finite additive answer carrier.

PARAMETER DESCRIPTION
scalar

The named scalar operations and their identities.

TYPE: FiniteAlgebra

addition

The closed named sum of two answers.

TYPE: ComputationId

zero

The declared additive identity of the answer carrier.

TYPE: FiniteValue

action

The closed named left action of a scalar on an answer.

TYPE: ComputationId

FiniteAnswerModuleProof dataclass

FiniteAnswerModuleProof(answer_module: FiniteAnswerModule, scalar: FiniteAlgebraProof, answer_type: TypeExpr, answer_values: int, fingerprint: str, checks: int)

Exhaustive evidence for the checked operations at both carrier types.

PARAMETER DESCRIPTION
answer_module

The nominal answer operators and declared identity.

TYPE: FiniteAnswerModule

scalar

The exact scalar law evidence from the same checked module.

TYPE: FiniteAlgebraProof

answer_type

The common checked argument and result type of answer addition.

TYPE: TypeExpr

answer_values

The cardinality of the complete answer domain.

TYPE: int

fingerprint

The binding to the module, all operator identities and both carriers' units.

TYPE: str

checks

The combined count of scalar and answer-module entries and comparisons.

TYPE: int

FiniteAnswerBaseChange dataclass

FiniteAnswerBaseChange(target: FiniteAnswerModule, scalar_mapping: ComputationId, answer_mapping: ComputationId)

Named scalar and answer maps between two checked finite modules.

PARAMETER DESCRIPTION
target

The operations and units used for contraction after mapping.

TYPE: FiniteAnswerModule

scalar_mapping

The closed unary maps from the input scalar and answer carriers.

TYPE: ComputationId

answer_mapping

The closed unary maps from the input scalar and answer carriers.

TYPE: ComputationId

FiniteAnswerBaseChangeProof dataclass

FiniteAnswerBaseChangeProof(source: FiniteAnswerModuleProof, target: FiniteAnswerModuleProof, scalar: FiniteBaseChangeProof, answer_mapping: ComputationId, checks: int)

Exhaustive nominal proof of a paired scalar and answer base change.

PARAMETER DESCRIPTION
source

The independently checked input and output modules.

TYPE: FiniteAnswerModuleProof

target

The independently checked input and output modules.

TYPE: FiniteAnswerModuleProof

scalar

The proof that the scalar map preserves both operations and both units. Its check count includes the two scalar-algebra proofs.

TYPE: FiniteBaseChangeProof

answer_mapping

The checked unary map that preserves answer zero, addition and the left scalar action relative to the scalar map.

TYPE: ComputationId

checks

The total count of table entries and comparisons, counting each algebra, answer module and map obligation once.

TYPE: int

FiniteWeightedAnswerResult dataclass

FiniteWeightedAnswerResult(table: FiniteFactor, proof: FiniteAnswerModuleProof, state_bound: int, state_cells: int, helper_calls: int, actions: int, additions: int)

A complete ranked answer table and separately counted proof and work.

PARAMETER DESCRIPTION
table

The output of each outer argument tuple in positional table order.

TYPE: FiniteFactor

proof

The checked named operators used by the tabulation.

TYPE: FiniteAnswerModuleProof

state_bound

The total preflight bound on reached layer and state pairs, including terminal states, across every outer argument tuple.

TYPE: int

state_cells

The number of reached layer and state pairs actually evaluated.

TYPE: int

helper_calls

The checked calls to initialize, weight, advance and finish the chain.

TYPE: int

actions

The scalar-action lookups for its ordered resumption occurrences.

TYPE: int

additions

The answer addition lookups within each weighted clause.

TYPE: int

FiniteAnswerEliminationResult dataclass

FiniteAnswerEliminationResult(factor: FiniteFactor, proof: FiniteAnswerModuleProof, steps: tuple[FiniteEliminationStep, ...], largest: int, scalar_work: FiniteEliminationWork, answer_additions: int, actions: int)

Elimination with one answer factor and checked scalar weights.

PARAMETER DESCRIPTION
factor

The resulting answer table in the requested axis order.

TYPE: FiniteFactor

proof

The exhaustive proof for the actual scalar and answer operators.

TYPE: FiniteAnswerModuleProof

steps

The scheduled buckets, with positions in the current factor list. The input order places the distinguished answer after the scalars.

TYPE: tuple[FiniteEliminationStep, ...]

largest

The largest logical table area, including inputs, bags and output.

TYPE: int

scalar_work

Scalar sums and products across all contractions.

TYPE: FiniteEliminationWork

answer_additions

Answer additions and scalar actions across the mixed contractions.

TYPE: int

actions

Answer additions and scalar actions across the mixed contractions.

TYPE: int

FiniteAnswerBaseChangeResult dataclass

FiniteAnswerBaseChangeResult(factor: FiniteFactor, proof: FiniteAnswerModuleProof, steps: tuple[FiniteEliminationStep, ...], largest: int, scalar_work: FiniteEliminationWork, answer_additions: int, actions: int, base_change: FiniteAnswerBaseChangeProof)

Bases: FiniteAnswerEliminationResult

The target answer contraction with a checked pair of base maps.

The inherited result records the target proof and the executed target contraction. The combined proof also records the source laws.

PARAMETER DESCRIPTION
base_change

The checked scalar and answer maps and their total proof budget.

TYPE: FiniteAnswerBaseChangeProof

tabulate_ranked_weighted_answers

tabulate_ranked_weighted_answers(module: QiecModule, answer_module: FiniteAnswerModule, factor: FiniteSourceFactor, *, max_checks: int = 65536, max_source_cells: int = 65536, max_weighted_state_cells: int = 65536, fuel: int = 65536) -> FiniteWeightedAnswerResult

Tabulate a ranked weighted handler with a checked finite answer module.

The computation directly installs one authored weighted clause. Its exact left action and answer sum match the operators in the declaration. Ordinary helpers have closed acyclic pure call graphs. The guarded recursive callee starts at a fixed nonnegative literal rank and may inspect the outer arguments, current finite state and current response through the checked helper calls. Tabulation preserves the branch occurrence order and shares equal suffix states at each layer. It returns the finite answer for every input and discards dynamic request and shot traces. An answer multiplication is unnecessary.

PARAMETER DESCRIPTION
module

The original checked source and its nominal definitions.

TYPE: QiecModule

answer_module

The declared scalar semiring and its left action on the answers.

TYPE: FiniteAnswerModule

factor

The ranked entry and its positional finite argument axis names.

TYPE: FiniteSourceFactor

max_checks

The combined bound on operator table entries and law comparisons.

TYPE: int DEFAULT: 65536

max_source_cells

The bound on the size of the returned table.

TYPE: int DEFAULT: 65536

max_weighted_state_cells

The total logical state-cell bound, including terminal cells and every input point. Tuple representations and evaluator fuel have separate costs.

TYPE: int DEFAULT: 65536

fuel

The evaluation step limit for each individual checked call.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
FiniteWeightedAnswerResult

The exact answer table, law evidence and measured tabulation work.

RAISES DESCRIPTION
ValueError

If the axis names, axis count or limits are invalid.

FiniteLawUnsupported

If the clause, scope, operators or types are outside the fragment.

FiniteLawLimit

If the proof, output, state bound or an evaluation exceeds its limit.

FiniteAlgebraLawError

If any required equation fails on a finite assignment.

Source code in src/quivers/qiec/finite_answer_module.py
def tabulate_ranked_weighted_answers(
    module: QiecModule,
    answer_module: FiniteAnswerModule,
    factor: FiniteSourceFactor,
    *,
    max_checks: int = 65_536,
    max_source_cells: int = 65_536,
    max_weighted_state_cells: int = 65_536,
    fuel: int = 65_536,
) -> FiniteWeightedAnswerResult:
    """Tabulate a ranked weighted handler with a checked finite answer module.

    The computation directly installs one authored weighted clause. Its
    exact left action and answer sum match the operators in the declaration.
    Ordinary helpers have closed acyclic pure call graphs. The guarded
    recursive callee starts at a fixed nonnegative literal rank and may
    inspect the outer arguments, current finite state and current response
    through the checked helper calls. Tabulation preserves the branch
    occurrence order and shares equal suffix states at each layer. It
    returns the finite answer for every input and discards dynamic request
    and shot traces. An answer multiplication is unnecessary.

    Parameters
    ----------
    module : QiecModule
        The original checked source and its nominal definitions.
    answer_module : FiniteAnswerModule
        The declared scalar semiring and its left action on the answers.
    factor : FiniteSourceFactor
        The ranked entry and its positional finite argument axis names.
    max_checks : int
        The combined bound on operator table entries and law comparisons.
    max_source_cells : int
        The bound on the size of the returned table.
    max_weighted_state_cells : int
        The total logical state-cell bound, including terminal cells and
        every input point. Tuple representations and evaluator fuel have
        separate costs.
    fuel : int
        The evaluation step limit for each individual checked call.

    Returns
    -------
    FiniteWeightedAnswerResult
        The exact answer table, law evidence and measured tabulation work.

    Raises
    ------
    ValueError
        If the axis names, axis count or limits are invalid.
    FiniteLawUnsupported
        If the clause, scope, operators or types are outside the fragment.
    FiniteLawLimit
        If the proof, output, state bound or an evaluation exceeds its limit.
    FiniteAlgebraLawError
        If any required equation fails on a finite assignment.
    """
    _validate_limit("max_checks", max_checks)
    _validate_limit("max_source_cells", max_source_cells)
    _validate_limit("max_weighted_state_cells", max_weighted_state_cells)
    _validate_limit("fuel", fuel)
    registry = validate_module(module)
    owners = {item.id: item for item in module.computations}
    signature = _answer_signature(owners, answer_module)
    owner = owners.get(factor.computation)
    if owner is None or owner.type.result != signature.answer_type:
        raise FiniteLawUnsupported(
            "ranked weighted answer tabulation needs a named factor at the exact answer type"
        )
    if len(factor.axes) != len(owner.parameters):
        raise ValueError(f"source factor `{owner.name}` needs one axis per parameter")
    shapes = tuple(_shape(parameter.type) for parameter in owner.parameters)
    extents = {
        axis: _size(shape) for axis, shape in zip(factor.axes, shapes, strict=True)
    }
    _, (source_cells,) = _factor_geometry((factor.axes,), factor.axes, extents)
    if source_cells > max_source_cells:
        raise FiniteLawLimit(
            f"weighted answer table needs {source_cells} source cells, exceeding {max_source_cells}"
        )
    _, chains = _check_weighted_factor_handlers(
        (owner,), owners, registry, signature, ranked_only=True
    )
    chain = chains.get(owner.id)
    if chain is None:
        raise FiniteLawUnsupported(
            "weighted answer tabulation requires a literal-rank source tail call"
        )
    per_point, exact = _weighted_chain_bound(chain, max_weighted_state_cells)
    bound = per_point * source_cells
    if bound > max_weighted_state_cells:
        qualifier = "" if exact else "at least "
        raise FiniteLawLimit(
            f"weighted answers need a bound of {qualifier}{bound} state cells, "
            f"exceeding {max_weighted_state_cells}"
        )
    proof, _, tables = _answer_tables(
        module, owners, answer_module, signature, max_checks, fuel
    )
    values: list[FiniteValue] = []
    state_cells = helper_calls = actions = additions = 0
    for point in product(*(_values(shape) for shape in shapes)):
        value, cells, calls, work = _weighted_chain_cell(
            module, owners, chain, point, tables, fuel
        )
        values.append(value)
        state_cells += cells
        helper_calls += calls
        actions += work.multiplications
        additions += work.additions
    return FiniteWeightedAnswerResult(
        FiniteFactor(factor.axes, tuple(values)),
        proof,
        bound,
        state_cells,
        helper_calls,
        actions,
        additions,
    )

eliminate_finite_answer_module

eliminate_finite_answer_module(module: QiecModule, answer_module: FiniteAnswerModule, scalar_factors: tuple[FiniteFactor, ...], answer_factor: FiniteFactor, output: tuple[str, ...], extents: Mapping[str, int], *, permute: bool = True, base_change: FiniteAnswerBaseChange | None = None, max_checks: int = 65536, max_cells: int = 65536, fuel: int = 65536) -> FiniteAnswerEliminationResult

Sum a scalar product acting on one distinguished finite answer.

Each assignment contributes its scalar factors' product acting on its answer cell. With permute=True, proved scalar commutativity allows noncontiguous buckets. With permute=False, each bucket takes a contiguous interval in written order. The rightmost factor carries the answer, so a mixed interval replaces a suffix and leaves the new answer factor rightmost. The last axis of each table varies fastest. An optional base change proves both maps over the complete domains before mapping input cells. Every contraction then uses the target scalar and answer operations, including the checked zero and one.

PARAMETER DESCRIPTION
module

The checked source containing the named operators.

TYPE: QiecModule

answer_module

The scalar and answer operations and their declared identities.

TYPE: FiniteAnswerModule

scalar_factors

Zero or more tables of scalar entries.

TYPE: tuple[FiniteFactor, ...]

answer_factor

The distinguished table in the answer carrier.

TYPE: FiniteFactor

output

The distinct retained axes in result order, possibly empty.

TYPE: tuple[str, ...]

extents

Nonnegative cardinality of each axis occurring in the input tables.

TYPE: Mapping[str, int]

permute

Permit noncontiguous buckets only with proved scalar commutativity. False chooses ordered intervals for every admitted scalar algebra. When changing base the target scalar multiplication decides.

TYPE: bool DEFAULT: True

base_change

The optional target module and named scalar and answer maps.

TYPE: FiniteAnswerBaseChange or None DEFAULT: None

max_checks

Bound on operator entries and comparisons in the finite proof, including both modules and both map proofs when changing base.

TYPE: int DEFAULT: 65536

max_cells

Bound on any one input, intermediate bag or table, or output. The selected schedule is checked before evaluating the operators.

TYPE: int DEFAULT: 65536

fuel

The evaluation step limit for each checked operator call.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
FiniteAnswerEliminationResult

The exact answer table, proved laws, schedule and lookup counts. With a base change, the result is a FiniteAnswerBaseChangeResult carrying the paired source and target evidence.

RAISES DESCRIPTION
ValueError

If the axes, extents, cell counts or limits are invalid.

FiniteLawUnsupported

If a factor value fails its carrier check or scalar products may depend on order while permute=True.

FiniteLawLimit

If the finite proof, one table or an operator call exceeds its bound.

FiniteAlgebraLawError

If a required scalar or answer-module law fails.

Source code in src/quivers/qiec/finite_answer_module.py
def eliminate_finite_answer_module(
    module: QiecModule,
    answer_module: FiniteAnswerModule,
    scalar_factors: tuple[FiniteFactor, ...],
    answer_factor: FiniteFactor,
    output: tuple[str, ...],
    extents: Mapping[str, int],
    *,
    permute: bool = True,
    base_change: FiniteAnswerBaseChange | None = None,
    max_checks: int = 65_536,
    max_cells: int = 65_536,
    fuel: int = 65_536,
) -> FiniteAnswerEliminationResult:
    """Sum a scalar product acting on one distinguished finite answer.

    Each assignment contributes its scalar factors' product acting on
    its answer cell. With ``permute=True``, proved scalar commutativity
    allows noncontiguous buckets. With ``permute=False``, each bucket takes
    a contiguous interval in written order. The rightmost factor carries
    the answer, so a mixed interval replaces a suffix and leaves the new
    answer factor rightmost. The last axis of each table varies fastest.
    An optional base change proves both maps over the complete domains
    before mapping input cells. Every contraction then uses the target
    scalar and answer operations, including the checked zero and one.

    Parameters
    ----------
    module : QiecModule
        The checked source containing the named operators.
    answer_module : FiniteAnswerModule
        The scalar and answer operations and their declared identities.
    scalar_factors : tuple[FiniteFactor, ...]
        Zero or more tables of scalar entries.
    answer_factor : FiniteFactor
        The distinguished table in the answer carrier.
    output : tuple[str, ...]
        The distinct retained axes in result order, possibly empty.
    extents : Mapping[str, int]
        Nonnegative cardinality of each axis occurring in the input tables.
    permute : bool
        Permit noncontiguous buckets only with proved scalar commutativity.
        False chooses ordered intervals for every admitted scalar algebra.
        When changing base the target scalar multiplication decides.
    base_change : FiniteAnswerBaseChange or None
        The optional target module and named scalar and answer maps.
    max_checks : int
        Bound on operator entries and comparisons in the finite proof,
        including both modules and both map proofs when changing base.
    max_cells : int
        Bound on any one input, intermediate bag or table, or output.
        The selected schedule is checked before evaluating the operators.
    fuel : int
        The evaluation step limit for each checked operator call.

    Returns
    -------
    FiniteAnswerEliminationResult
        The exact answer table, proved laws, schedule and lookup counts.
        With a base change, the result is a FiniteAnswerBaseChangeResult
        carrying the paired source and target evidence.

    Raises
    ------
    ValueError
        If the axes, extents, cell counts or limits are invalid.
    FiniteLawUnsupported
        If a factor value fails its carrier check or scalar products
        may depend on order while ``permute=True``.
    FiniteLawLimit
        If the finite proof, one table or an operator call exceeds its bound.
    FiniteAlgebraLawError
        If a required scalar or answer-module law fails.
    """
    _validate_limit("max_checks", max_checks)
    _validate_limit("max_cells", max_cells)
    _validate_limit("fuel", fuel)
    factors = (*scalar_factors, answer_factor)
    scopes = tuple(factor.axes for factor in factors)
    axes, sizes = _factor_geometry(scopes, output, extents)
    if any(
        len(factor.cells) != size for factor, size in zip(factors, sizes, strict=True)
    ):
        raise ValueError("finite factor cells do not match their axis extents")
    initial = max((*sizes, prod(extents[axis] for axis in output)))
    if initial > max_cells:
        raise FiniteLawLimit(
            f"finite table needs {initial} cells, exceeding {max_cells}"
        )
    steps = _elimination_steps(scopes, output, axes, extents, permute=permute)
    largest = _checked_bag_area(initial, steps, extents, max_cells)
    validate_module(module)
    owners = {item.id: item for item in module.computations}
    signature = _answer_signature(owners, answer_module)
    base_proof = None
    if base_change is None:
        proof, scalar, tables = _answer_tables(
            module, owners, answer_module, signature, max_checks, fuel
        )
        weight_indices, answer_indices = tables.weight_indices, tables.answer_indices
        weight_shape, answer_shape = tables.weight_shape, tables.answer_shape
    else:
        base_proof, scalar, tables, weight_indices, answer_indices = (
            _base_change_tables(
                module, owners, answer_module, signature, base_change, max_checks, fuel
            )
        )
        proof = base_proof.target
        weight_shape = _shape(signature.weight_type)
        answer_shape = _shape(signature.answer_type)
    if permute and proof.scalar.noncommutative is not None:
        raise FiniteLawUnsupported(
            "finite answer elimination requires commutative scalar multiplication"
        )
    active = [
        _IndexedFactor(
            factor.axes,
            tuple(
                weight_indices[_observed(weight_shape, cell)] for cell in factor.cells
            ),
        )
        for factor in scalar_factors
    ]
    answer = _IndexedFactor(
        answer_factor.axes,
        tuple(
            answer_indices[_observed(answer_shape, cell)]
            for cell in answer_factor.cells
        ),
    )
    active.append(answer)
    zero = tables.answer_indices[
        _observed(tables.answer_shape, proof.answer_module.zero)
    ]
    scalar_additions = scalar_products = answer_terms = 0
    for step in steps:
        selected = tuple(active[index] for index in step.positions)
        kept = tuple(axis for axis in step.bag if axis != step.variable)
        if any(factor is answer for factor in selected):
            weights = tuple(factor for factor in selected if factor is not answer)
            answer, assignments = _contract_answer(
                scalar, tables, zero, weights, answer, kept, (step.variable,), extents
            )
            result = answer
            scalar_products += len(weights) * assignments
            answer_terms += assignments
        else:
            result, work = _contract(scalar, selected, kept, (step.variable,), extents)
            scalar_additions += work.additions
            scalar_products += work.multiplications
        _replace_factors(active, step.positions, result)
    weights = tuple(factor for factor in active if factor is not answer)
    result, assignments = _contract_answer(
        scalar, tables, zero, weights, answer, output, (), extents
    )
    scalar_products += len(weights) * assignments
    answer_terms += assignments
    observations = (
        FiniteFactor(
            output, tuple(tables.answer_values[index] for index in result.cells)
        ),
        proof,
        steps,
        largest,
        FiniteEliminationWork(scalar_additions, scalar_products),
        answer_terms,
        answer_terms,
    )
    if base_proof is None:
        return FiniteAnswerEliminationResult(*observations)
    return FiniteAnswerBaseChangeResult(*observations, base_change=base_proof)

Finite Bernoulli estimators

plan_bernoulli_gradient checks a named scalar computation that performs direct, unplated Boolean Bernoulli draws on one nominal Random instance. Each reached static site needs an explicit enumerate, score, or measure policy. Repeated calls to the same site share its policy and keep their distinct request addresses. At an adaptive site, the report gives the conditional probability and its derivative for each preceding history.

The scalar check admits runtime cases over closed monomorphic data with Real, Bool, or Unit fields. Total monomorphic authored handlers may handle a separate effect instance with scalar parameters and an empty introduced row. The reference machine runs their actual clauses. An admitted discharged graph can restore call addresses and shot ordinals. Each reached shot contributes its own Bernoulli factor. An inactive branch or a discarded continuation contributes no draw. Each point needs policies for exactly the sites reached across its complete histories.

For a complete history, the probability is the ordered product of conditional Bernoulli factors evaluated at its successive prefixes. The plan differentiates that product and the final return in exact rational arithmetic. For \(B\) complete histories it runs \(2B-1\) complete or suspended replays, at most fuel steps each.

The plan enumerates the finite source traces at the supplied point. Its exact result is the expected return and its directional derivative. Calling sample runs the chosen estimator over that tree. Enumeration evaluates both branches. The score estimator draws one branch and adds the return times the directional derivative of that branch's log probability. The weak derivative, selected by measure, draws one primal branch and evaluates both branches. It adds \(p'(V_1 - V_0)\) to the selected branch's tangent. Both estimators are unbiased in the checked local domain. Here \(p\) is the probability of true and \(V_1\) and \(V_0\) are the branch values. The result records visited requests, score draws, weak selectors, and the ordered launch of each weak branch.

Conditional probabilities must lie strictly between zero and one. The exact scalar checker also requires comparisons to be stable at the supplied point. Construction checks a complete-path bound and a step bound for each replay. With \(n\) complete paths it needs \(2n - 1\) reference replays and reports their total steps. The sampled estimator does not truncate rare large score weights.

from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, plan_bernoulli_gradient

source = """
instance random : Random

define reward(p : Real) : Real !{random} =
    let chosen <- perform random.sample[Bool](site("chosen"), Bernoulli(probs=p))
    if chosen then
        return 1.0
    else
        return 0.0
"""
module = Compiler(parse(source), module_name="bernoulli-gradient").qiec_module
assert module is not None
owner = next(item for item in module.computations if item.name == "reward")
assert isinstance(owner.body, Bind) and isinstance(owner.body.first, Perform)
site = owner.body.first.request.origin.static_site
policy = SiteEstimator(site=site, estimator="score")
plan = plan_bernoulli_gradient(module, owner.id, (Fraction(1, 3),), (2,), (policy,))
assert (plan.exact.value, plan.exact.tangent) == (Fraction(1, 3), 2)
assert len(plan.sample(seed=42).draws) == 1

weak_policy = SiteEstimator(site=site, estimator="measure")
weak = plan_bernoulli_gradient(module, owner.id, (Fraction(1, 3),), (2,), (weak_policy,))
estimate = weak.sample(seed=42)
assert estimate.tangent == 2
assert len(estimate.selectors) == 1
assert estimate.virtual_branches == ((False,), (True,))

bernoulli_estimators

Exact and stochastic directional derivatives for checked finite Bernoulli sites.

BernoulliVisit dataclass

BernoulliVisit(site: SiteId, address: _Address, prefix: tuple[bool, ...], estimator: _Estimator, probability: Fraction, tangent: Fraction, omitted_score_cost: ExactJvp | None = None)

A reached draw and its conditional probability at a source history.

PARAMETER DESCRIPTION
site

The static identity named by the policy.

TYPE: SiteId

address

The checked evaluator's request address.

TYPE: tuple

prefix

The source choices preceding this request in the trace.

TYPE: tuple[bool, ...]

estimator

The policy declared for the static site of this occurrence.

TYPE: ('enumerate', 'score', 'measure') DEFAULT: "enumerate"

probability

The conditional probability of true.

TYPE: Fraction

tangent

The exact directional derivative of that probability.

TYPE: Fraction

omitted_score_cost

The source prefix cost whose primal is omitted from this score product. The full return and the cost's direct tangent remain.

TYPE: ExactJvp or None DEFAULT: None

BernoulliScoreDraw dataclass

BernoulliScoreDraw(visit: BernoulliVisit, choice: bool)

One stochastic choice made by the score estimator.

PARAMETER DESCRIPTION
visit

The source occurrence and conditional law.

TYPE: BernoulliVisit

choice

The outcome selected. Enumerated branches do not make these draws.

TYPE: bool

BernoulliWeakSelector dataclass

BernoulliWeakSelector(visit: BernoulliVisit, choice: bool)

One primal branch selector for a weak derivative.

PARAMETER DESCRIPTION
visit

The source occurrence and conditional law.

TYPE: BernoulliVisit

choice

The selected primal branch. Both branches contribute to the weak derivative, including the one this selector did not choose.

TYPE: bool

BernoulliGradientSample dataclass

BernoulliGradientSample(value: Fraction, tangent: Fraction, visits: tuple[BernoulliVisit, ...], draws: tuple[BernoulliScoreDraw, ...], selectors: tuple[BernoulliWeakSelector, ...] = (), virtual_branches: tuple[tuple[bool, ...], ...] = ())

One realization of the chosen per-site derivative estimator.

PARAMETER DESCRIPTION
value

The resulting estimate of the expected return.

TYPE: Fraction

tangent

The resulting unbiased estimate of its directional derivative within the checked local fragment.

TYPE: Fraction

visits

All visited requests in order, including deterministic enumeration.

TYPE: tuple[BernoulliVisit, ...]

draws

The stochastic choices in order. Enumeration may visit both conditional branches and a score choice visits only its own.

TYPE: tuple[BernoulliScoreDraw, ...]

selectors

The primal selectors of weak derivative sites, in execution order.

TYPE: tuple[BernoulliWeakSelector, ...] DEFAULT: ()

virtual_branches

The actually launched weak derivative arms, as source prefixes. Both arms of each weak derivative appear in execution order.

TYPE: tuple[tuple[bool, ...], ...] DEFAULT: ()

BernoulliBranch dataclass

BernoulliBranch(visit: BernoulliVisit, no: ExactJvp | BernoulliBranch, yes: ExactJvp | BernoulliBranch)

A conditional visit with one continuation for each Boolean result.

PARAMETER DESCRIPTION
visit

The checked conditional draw.

TYPE: BernoulliVisit

no

What the source does after false and true, respectively.

TYPE: ExactJvp or BernoulliBranch

yes

What the source does after false and true, respectively.

TYPE: ExactJvp or BernoulliBranch

BernoulliGradientPlan dataclass

BernoulliGradientPlan(computation: ComputationId, exact: ExactJvp, policies: tuple[SiteEstimator, ...], visits: tuple[BernoulliVisit, ...], paths: int, source_steps: int, tree: ExactJvp | BernoulliBranch)

A finite addressed tree and its expected return and derivative.

PARAMETER DESCRIPTION
computation

The checked source computation being differentiated.

TYPE: ComputationId

exact

The exact expected return and its directional derivative, computed by enumerating every source trace.

TYPE: ExactJvp

policies

The explicit policies, ordered by static site identity.

TYPE: tuple[SiteEstimator, ...]

visits

The adaptive occurrences in the exhaustive trace tree.

TYPE: tuple[BernoulliVisit, ...]

paths

The number of complete source traces in that tree.

TYPE: int

source_steps

The total measured reference-machine steps used to build the tree.

TYPE: int

tree

The checked tree supplying both the exact and sampled results.

TYPE: ExactJvp or BernoulliBranch

replays property

replays: int

Count the checked reference runs used during tree construction.

RETURNS DESCRIPTION
int

The number of finished or choice-suspended replays.

sample

sample(*, seed: int | None = None) -> BernoulliGradientSample

Run the chosen mixture of enumeration, score and weak derivatives.

The result estimates the same objective as exact. The draw list records only the score choices. The weak selector and virtual branch lists report the effects of the weak derivative separately. The execution does not rerun the original probabilistic program. Exact rational score weights may be large near the boundary.

PARAMETER DESCRIPTION
seed

An optional seed for the estimator's independent random draws.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
BernoulliGradientSample

A value, derivative estimate, and ordered stochastic choices.

Source code in src/quivers/qiec/bernoulli_estimators.py
def sample(self, *, seed: int | None = None) -> BernoulliGradientSample:
    """Run the chosen mixture of enumeration, score and weak derivatives.

    The result estimates the same objective as `exact`. The draw list
    records only the score choices. The weak selector and virtual
    branch lists report the effects of the weak derivative separately.
    The execution does not rerun the original probabilistic program.
    Exact rational score weights may be large near the boundary.

    Parameters
    ----------
    seed : int or None
        An optional seed for the estimator's independent random draws.

    Returns
    -------
    BernoulliGradientSample
        A value, derivative estimate, and ordered stochastic choices.
    """
    return _draw(self.tree, Random(seed))

plan_bernoulli_gradient

plan_bernoulli_gradient(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_paths: int = 1024, fuel: int = 65536, omit_independent_cost: bool = False) -> BernoulliGradientPlan

Build a checked, bounded per-site Bernoulli estimator.

The entry must take scalar reals and return a scalar real with one nominal Random instance in its row. The fragment admits ordinary sequencing, conditionals, calls and direct scalar Boolean draws from Bernoulli probabilities. It also admits cases over closed monomorphic families with scalar fields, and total authored handlers on non-Random instances with scalar parameters and no introduced effects. Enumeration preserves the distinct shots of those handlers and of their checked discharge. Every reached site needs one explicit enumerate, score or measure policy. The conditional probabilities must be strictly interior, and comparisons must be locally stable under the exact scalar derivative rules.

The plan exhausts every source choice at the given point to get the exact expected value and directional derivative. Sampling its chosen estimator is a separate operation with its own draw record. A checked opt-in can omit an additive prefix cost from a single Bernoulli score product while retaining all direct derivatives.

PARAMETER DESCRIPTION
module

The checked source compilation unit.

TYPE: QiecModule

computation

The named computation whose expected return is differentiated.

TYPE: ComputationId

arguments

Exact parameter values in source order.

TYPE: tuple[int or Fraction, ...]

direction

Their exact directional tangents.

TYPE: tuple[int or Fraction, ...]

policies

One method declaration for every reached static site.

TYPE: tuple[SiteEstimator, ...]

max_paths

The maximum number of complete source traces.

TYPE: int DEFAULT: 1024

fuel

The maximum reference evaluator steps for each replay.

TYPE: int DEFAULT: 65536

omit_independent_cost

Certify one original score draw following a pure Real cost call and a return that adds its binding to a pure Real continuation result. Omit the cost only from the random score product.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
BernoulliGradientPlan

The exhaustive checked expectation and sampled estimator.

RAISES DESCRIPTION
JvpUnsupported

If the source, a probability, or its estimator policy is outside the finite first-order fragment.

JvpLimit

If exhaustion requires too many traces or steps.

ValueError

If an input, declaration name, or resource limit is malformed.

Source code in src/quivers/qiec/bernoulli_estimators.py
def plan_bernoulli_gradient(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    max_paths: int = 1_024,
    fuel: int = 65_536,
    omit_independent_cost: bool = False,
) -> BernoulliGradientPlan:
    """Build a checked, bounded per-site Bernoulli estimator.

    The entry must take scalar reals and return a scalar real with one
    nominal Random instance in its row. The fragment admits ordinary
    sequencing, conditionals, calls and direct scalar Boolean draws
    from Bernoulli probabilities. It also admits cases over closed
    monomorphic families with scalar fields, and total authored handlers
    on non-Random instances with scalar parameters and no introduced
    effects. Enumeration preserves the distinct shots of those handlers
    and of their checked discharge. Every reached site needs one explicit
    `enumerate`, `score` or `measure` policy. The conditional probabilities must
    be strictly interior, and comparisons must be locally stable under
    the exact scalar derivative rules.

    The plan exhausts every source choice at the given point to get
    the exact expected value and directional derivative. Sampling its
    chosen estimator is a separate operation with its own draw record.
    A checked opt-in can omit an additive prefix cost from a single
    Bernoulli score product while retaining all direct derivatives.

    Parameters
    ----------
    module : QiecModule
        The checked source compilation unit.
    computation : ComputationId
        The named computation whose expected return is differentiated.
    arguments : tuple[int or Fraction, ...]
        Exact parameter values in source order.
    direction : tuple[int or Fraction, ...]
        Their exact directional tangents.
    policies : tuple[SiteEstimator, ...]
        One method declaration for every reached static site.
    max_paths : int
        The maximum number of complete source traces.
    fuel : int
        The maximum reference evaluator steps for each replay.
    omit_independent_cost : bool
        Certify one original score draw following a pure Real cost call
        and a return that adds its binding to a pure Real continuation
        result. Omit the cost only from the random score product.

    Returns
    -------
    BernoulliGradientPlan
        The exhaustive checked expectation and sampled estimator.

    Raises
    ------
    JvpUnsupported
        If the source, a probability, or its estimator policy is outside
        the finite first-order fragment.
    JvpLimit
        If exhaustion requires too many traces or steps.
    ValueError
        If an input, declaration name, or resource limit is malformed.
    """
    return _plan_bernoulli_gradient(
        module,
        computation,
        arguments,
        direction,
        policies,
        max_paths=max_paths,
        fuel=fuel,
        omit_independent_cost=omit_independent_cost,
    )

Finite handler interchange

A FiniteHandlerInterchange names two checked computations whose only structural difference is the order of two distinct handler installations. They supply the same initial state to each installation and invoke the same body. check_finite_handler_interchange tests the returned value on every assignment to the finite inputs.

In the example below, cells_lr and cells_rl agree on all eight Boolean input triples. Each cell updates its own component of the product state, and the body still sequences every read and write. With a multi-shot choice, state_first(false) returns true because the first resumption updates the outer cell before the second reads it. choice_first(false) returns false because each resumption of the inner cell starts from the captured initial state. The certificate concerns the returned value for this body. Trace observations and other computations require their own evidence. Add effect_law independent_cells [interchange=[cells_lr, cells_rl]] and effect_law state_choice [interchange=[state_first, choice_first]] to declare these checks in source. Each declaration names two distinct computation wrappers in the same module. Compiler.effect_plan reports the claim name and a checked, refuted, or unresolved outcome. interchanges=... can still request additional finite comparisons from Python. Ordinary discharge uses its own rules.

effect Cell
    get : Unit -> Bool
    put : Bool -> Unit

instance left_cell : Cell
instance right_cell : Cell

effect Choice
    pick : Unit -> Bool

instance choice : Choice

handler state for Cell : Bool -> Bool with (current : Bool) [coverage=total, forwards=none, implementation=authored]
    return v =>
        return v
    get resumes 1 =>
        resume(current)
    put(v : Bool) resumes 1 =>
        resume(unit) with (v)

handler some for Choice : Bool -> Bool [coverage=total, forwards=none, implementation=authored]
    return v =>
        return v
    pick resumes omega =>
        let a <- resume(true)
        let b <- resume(false)
        if a then
            return true
        else
            return b

define two_cells(new : Bool) : Bool !{left_cell, right_cell} =
    let old <- perform right_cell.get()
    perform left_cell.put(new)
    let current <- perform left_cell.get()
    perform right_cell.put(current)
    let check <- perform right_cell.get()
    if old then
        return check
    else
        if check then
            return false
        else
            return true

define cells_lr(a : Bool, b : Bool, new : Bool) : Bool !{} =
    handle left_cell with state(a) in
        handle right_cell with state(b) in
            two_cells(new)

define cells_rl(a : Bool, b : Bool, new : Bool) : Bool !{} =
    handle right_cell with state(b) in
        handle left_cell with state(a) in
            two_cells(new)

define cell_choice() : Bool !{left_cell, choice} =
    let positive <- perform choice.pick()
    if positive then
        perform left_cell.put(true)
        return false
    else
        perform left_cell.get()

define state_first(initial : Bool) : Bool !{} =
    handle left_cell with state(initial) in
        handle choice with some in
            cell_choice()

define choice_first(initial : Bool) : Bool !{} =
    handle choice with some in
        handle left_cell with state(initial) in
            cell_choice()

handler_interchange

Check the finite value observation of a declared handler interchange.

FiniteHandlerInterchange didactic-model

FiniteHandlerInterchange(*, left: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), right: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Declare the two source computations of a finite interchange check.

PARAMETER DESCRIPTION
left

Computations with the same finite inputs that install the same two distinct effect instances in opposite orders around one common call. Each installation retains its handler and initial arguments.

TYPE: ComputationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

right

Computations with the same finite inputs that install the same two distinct effect instances in opposite orders around one common call. Each installation retains its handler and initial arguments.

TYPE: ComputationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

check_finite_handler_interchange

check_finite_handler_interchange(module: QiecModule, statement: FiniteHandlerInterchange, *, max_assignments: int = 65536, fuel: int = 65536) -> FiniteLawDecision

Decide equality of returned values for one finite handler interchange.

The two sides call the same checked body with identical arguments. Both orders must type check, and the existing finite law evaluator checks every input assignment or returns a counterexample. The result is scoped to these bodies and returned values. It supplies no rewrite permission for another body or for trace observations.

PARAMETER DESCRIPTION
module

The source defining the handlers and the two computations.

TYPE: QiecModule

statement

The pair of nominal computations to compare.

TYPE: FiniteHandlerInterchange

max_assignments

The largest finite carrier product to enumerate.

TYPE: int DEFAULT: 65536

fuel

The reference machine's fuel per side and assignment.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
FiniteLawDecision

The complete finite comparison or a separating assignment.

RAISES DESCRIPTION
FiniteLawUnsupported

If the pair is outside the finite fragment or changes more than the order of the two handler installations.

FiniteLawLimit

If the resource limits prevent a decision.

Source code in src/quivers/qiec/handler_interchange.py
def check_finite_handler_interchange(
    module: QiecModule,
    statement: FiniteHandlerInterchange,
    *,
    max_assignments: int = 65_536,
    fuel: int = 65_536,
) -> FiniteLawDecision:
    """Decide equality of returned values for one finite handler interchange.

    The two sides call the same checked body with identical arguments.
    Both orders must type check, and the existing finite law evaluator
    checks every input assignment or returns a counterexample. The
    result is scoped to these bodies and returned values. It supplies
    no rewrite permission for another body or for trace observations.

    Parameters
    ----------
    module : QiecModule
        The source defining the handlers and the two computations.
    statement : FiniteHandlerInterchange
        The pair of nominal computations to compare.
    max_assignments : int
        The largest finite carrier product to enumerate.
    fuel : int
        The reference machine's fuel per side and assignment.

    Returns
    -------
    FiniteLawDecision
        The complete finite comparison or a separating assignment.

    Raises
    ------
    FiniteLawUnsupported
        If the pair is outside the finite fragment or changes more than
        the order of the two handler installations.
    FiniteLawLimit
        If the resource limits prevent a decision.
    """
    computations = {item.id: item for item in module.computations}
    lhs, rhs = computations.get(statement.left), computations.get(statement.right)
    if lhs is None or rhs is None:
        raise FiniteLawUnsupported("an interchange names an unknown computation")
    if lhs.parameters != rhs.parameters:
        raise FiniteLawUnsupported("interchange sides need identical named inputs")
    outer, inner, left_call = _installations(lhs.body)
    swapped_inner, swapped_outer, right_call = _installations(rhs.body)
    if outer.instance == inner.instance:
        raise FiniteLawUnsupported("interchange requires distinct effect instances")
    if outer != swapped_outer.with_(
        computation=outer.computation
    ) or inner != swapped_inner.with_(computation=inner.computation):
        raise FiniteLawUnsupported("interchange sides change a handler installation")
    if left_call != right_call.with_(origin=left_call.origin):
        raise FiniteLawUnsupported("interchange sides need the same named call")
    return check_finite_law(
        module, lhs.name, rhs.name, max_assignments=max_assignments, fuel=fuel
    )

Scalar Normal pathwise derivatives

plan_normal_pathwise checks a named scalar computation with direct, unplated Normal draws on one nominal Random instance. Each reached static site needs an explicit reparam policy. The plan assigns a fresh standard Normal coordinate to each addressed occurrence, including repeated calls to the same site.

A location can depend polynomially on earlier draws. The checker requires a strictly positive, noise-independent scale, noise-independent comparisons and divisors, and fixed integral exponents. It also checks that parameter-dependent decisions stay on the same branch near the supplied point. In this fragment the return and its directional derivative are polynomials in the base noise with locally bounded coefficients. Their growth has an integrable Gaussian bound, which permits differentiation under the expectation.

plan.exact gives the expected return and its directional derivative from exact Normal moments. plan.at_noise evaluates the return and its directional derivative at the supplied base-noise coordinates. Coordinates follow the order in plan.visits and use integers or fractions. Construction checks limits on source steps, noise coordinates, and polynomial and moment work.

For a draw \(x = \mu + \sigma z\), holding the base noise \(z\) fixed makes the directional derivative of its trace log density \(-\dot{\sigma}/\sigma\), even when its location \(\mu\) depends on earlier draws. Conditioning on the sampled value holds \(x\) fixed and can give a different derivative at the same value and log density. The native trace attributes each density contribution to its originating draw. The emitted Pyro model carries that density on the addressed sample node and emits authored score requests as separate factors.

from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, plan_normal_pathwise

source = """
instance random : Random

define squared(m : Real, s : Real) : Real !{random} =
    let x <- perform random.sample[Real](site("x"), Normal(loc=m, scale=s))
    return x * x
"""
module = Compiler(parse(source), module_name="normal-pathwise").qiec_module
assert module is not None
owner = next(item for item in module.computations if item.name == "squared")
assert isinstance(owner.body, Bind) and isinstance(owner.body.first, Perform)
site = owner.body.first.request.origin.static_site
policy = SiteEstimator(site=site, estimator="reparam")
plan = plan_normal_pathwise(module, owner.id, (2, 3), (1, 2), (policy,))
assert (plan.exact.value, plan.exact.tangent) == (13, 16)
action = plan.at_noise((1,))
assert (action.value, action.tangent) == (25, 30)

normal_pathwise

Locally dominated scalar Normal pathwise derivatives and exact moments.

NormalVisit dataclass

NormalVisit(site: SiteId, address: _Address, scale: Fraction, scale_tangent: Fraction)

The checked occurrence of one scalar location-scale draw.

PARAMETER DESCRIPTION
site

The static site carrying the explicit Normal estimator policy.

TYPE: SiteId

address

Its full request address in the reference machine.

TYPE: tuple

scale

The strictly positive, noise-independent scale.

TYPE: Fraction

scale_tangent

The directional derivative of that scale.

TYPE: Fraction

NormalPathwisePlan dataclass

NormalPathwisePlan(computation: ComputationId, exact: ExactJvp, visits: tuple[NormalVisit, ...], primal: _Terms, tangent: _Terms, source_steps: int, polynomial_work: int)

Bases: _NormalNoisePlan

A checked Normal derivative using only reparameterized draws.

plan_normal_pathwise

plan_normal_pathwise(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_sites: int = 16, max_work: int = 65536, fuel: int = 65536) -> NormalPathwisePlan

License a locally dominated Normal pathwise directional derivative.

Draws use independent standard-normal coordinates in source order. Ordinary first-order code runs over noise polynomials, with locally regular rational coefficients. Source decisions must be independent of noise and the Normal scales must be noise-independent and positive. Locations may depend on earlier draws through admitted expressions.

The exact result integrates the return and its directional derivative. The plan's pointwise action evaluates the same polynomials at a fixed supplied vector of noise coordinates.

PARAMETER DESCRIPTION
module

The checked source supplying the actual first-order graph.

TYPE: QiecModule

computation

The scalar-returning entry with one nominal Random instance.

TYPE: ComputationId

arguments

The exact parameter point.

TYPE: tuple[int or Fraction, ...]

direction

The exact directional tangent in the same parameter order.

TYPE: tuple[int or Fraction, ...]

policies

One explicit reparam policy for each reached static site.

TYPE: tuple[SiteEstimator, ...]

max_sites

Maximum number of distinct noise coordinates in the checked path.

TYPE: int DEFAULT: 16

max_work

Maximum sparse coefficient and moment work.

TYPE: int DEFAULT: 65536

fuel

Maximum reference steps to assemble the plan.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
NormalPathwisePlan

The addressed noise polynomials and their exact expected JVP.

RAISES DESCRIPTION
ValueError

If the entry or input vectors are absent or malformed.

JvpUnsupported

If the actual source leaves the licensed fragment.

JvpBoundaryError

If a source decision hits an input-dependent equality boundary.

JvpLimit

If a step, noise coordinate, coefficient or work bound is exceeded.

Source code in src/quivers/qiec/normal_pathwise.py
def plan_normal_pathwise(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    max_sites: int = 16,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> NormalPathwisePlan:
    """License a locally dominated Normal pathwise directional derivative.

    Draws use independent standard-normal coordinates in source order.
    Ordinary first-order code runs over noise polynomials, with locally
    regular rational coefficients. Source decisions must be independent of
    noise and the Normal scales must be noise-independent and positive.
    Locations may depend on earlier draws through admitted expressions.

    The exact result integrates the return and its directional derivative.
    The plan's pointwise action evaluates the same polynomials at a fixed
    supplied vector of noise coordinates.

    Parameters
    ----------
    module : QiecModule
        The checked source supplying the actual first-order graph.
    computation : ComputationId
        The scalar-returning entry with one nominal Random instance.
    arguments : tuple[int or Fraction, ...]
        The exact parameter point.
    direction : tuple[int or Fraction, ...]
        The exact directional tangent in the same parameter order.
    policies : tuple[SiteEstimator, ...]
        One explicit `reparam` policy for each reached static site.
    max_sites : int
        Maximum number of distinct noise coordinates in the checked path.
    max_work : int
        Maximum sparse coefficient and moment work.
    fuel : int
        Maximum reference steps to assemble the plan.

    Returns
    -------
    NormalPathwisePlan
        The addressed noise polynomials and their exact expected JVP.

    Raises
    ------
    ValueError
        If the entry or input vectors are absent or malformed.
    JvpUnsupported
        If the actual source leaves the licensed fragment.
    JvpBoundaryError
        If a source decision hits an input-dependent equality boundary.
    JvpLimit
        If a step, noise coordinate, coefficient or work bound is exceeded.
    """
    for name, limit in (
        ("max_sites", max_sites),
        ("max_work", max_work),
        ("fuel", fuel),
    ):
        _validate_limit(name, limit)
    registry, owner = _random_computation(module, computation, "Normal pathwise")
    if not len(arguments) == len(direction) == len(owner.parameters):
        raise ValueError("arguments and direction must match the computation's arity")
    methods = frozenset(policy.site for policy in policies)
    if len(methods) != len(policies):
        raise ValueError("duplicate pathwise estimator for one site")
    if any(policy.estimator != "reparam" for policy in policies):
        raise JvpUnsupported(
            "Normal pathwise estimation needs an explicit reparam policy"
        )
    _check_first_order_graph(module, owner, "Normal pathwise", _check_request)
    ring = _PolynomialRing(min(max_sites, max_work, fuel), max_work)
    evaluator = _NormalEvaluator(module, fuel, ring, methods)
    environment = {
        parameter: evaluator.input(_fraction(value), _fraction(tangent), parameter=True)
        for parameter, value, tangent in zip(
            owner.parameters, arguments, direction, strict=True
        )
    }
    try:
        result = evaluator.evaluate_validated(owner.body, registry, environment)
        assert isinstance(result, _NoiseDual)
        path = _normal_path(
            computation, evaluator, result, max_work, NormalPathwisePlan
        )
    except FuelExhaustedError as error:
        raise JvpLimit(
            f"Normal pathwise run exceeded its step budget of {fuel}"
        ) from error
    except PolynomialLawLimit as error:
        raise JvpLimit(f"Normal pathwise expansion: {error}") from error
    unused = methods - {visit.site for visit in evaluator.visits}
    if unused:
        raise JvpUnsupported(
            f"estimator policies name unreached sites: {', '.join(sorted(map(str, unused)))}"
        )
    return path

Continuous affine payoffs

plan_normal_piecewise_pathwise checks a computation with location and scale parameters, one direct Normal draw, and a final greater-than comparison of that draw to a fixed real threshold. The two pure return expressions must be affine in the draw. The planner normalizes the actual arms with the exact polynomial checker and requires the same value at the threshold. A step with differing boundary values is refused. The plan retains the original site's explicit reparam policy and request address.

For \(X=\mu+\sigma Z\) with \(\sigma>0\) and standard Normal \(Z\), let \(c\) be the threshold, \(b\) the common boundary value, and \(s_-,s_+\) the two slopes. The continuous payoff is globally Lipschitz with constant \(L=\max(|s_-|,|s_+|)\). Its difference quotients in direction \((u,v)\) are bounded by the integrable function \(L(|u|+|v|\,|Z|)\). The threshold has probability zero, so the expected derivative integrates the ordinary derivative of the selected arm.

Write \(a=(\mu-c)/\sigma\) and \(\Delta=s_+-s_-\). For the standard Normal CDF \(\Phi\) and density \(\varphi\), the mean and directional derivative are \(b+s_-(\mu-c)+\Delta[(\mu-c)\Phi(a)+\sigma\varphi(a)]\) and \((s_-+\Delta\Phi(a))u+\Delta\varphi(a)v\). The plan retains their exact rational coefficients and \(\Phi(a),\varphi(a)\) as analytic terms. evaluate() evaluates these expressions in binary64. At a given exact noise coordinate, at_noise returns a rational JVP and refuses a coordinate on the boundary.

From a compiler-owned plan, check_normal_piecewise_pathwise checks the selected original computation with the same explicit policy, point, direction, and work budget. Its result concerns the source expectation. check_jvp continues to compare deterministic scalar JVPs. A successful target receipt describes emission and records external derivatives as unverified.

The Pyro conformance test fixes the base Normal coordinate before the sampler applies location and scale. At the tested strict-side points, the emitted branch, return, and directional derivative agree with the checked source. The native trace includes the program call frames. The emitted trace identifies the draw relative to its helper. Pyro's ordinary replay holds the sampled value fixed and matches sites by name, so it can carry the address of a different same-named draw. At equality the emitted program takes its else branch. The checked fixed-noise action reports the boundary.

from fractions import Fraction

from quivers.dsl import Compiler, parse
from quivers.qiec import (
    ExactJvp,
    NormalTailMoment,
    SiteEstimator,
)

source = """
instance random : Random

define payoff(location : Real, scale : Real) : Real !{random} =
    let x <- perform random.sample[Real](site("value"), Normal(loc=location, scale=scale))
    if x > 0.0 then
        return x
    else
        return 0.0
"""
compiler = Compiler(parse(source), module_name="continuous-payoff")
effect_plan = compiler.effect_plan("payoff")
(owner,) = effect_plan.bundle.module.computations
site = owner.body.first.request.origin.static_site
plan = effect_plan.check_normal_piecewise_pathwise(
    (1, 2), (1, 0), (SiteEstimator(site=site, estimator="reparam"),)
)
assert plan.expected_value == NormalTailMoment(Fraction(1, 2), 0, 1, 2)
assert plan.expected_tangent == NormalTailMoment(Fraction(1, 2), 0, 1, 0)
assert plan.at_noise((0,)) == ExactJvp(Fraction(1), Fraction(1))

normal_piecewise_pathwise

Pathwise derivatives for one Normal draw and a checked affine boundary.

NormalTailMoment dataclass

NormalTailMoment(argument: Fraction, constant: Fraction, cdf_coefficient: Fraction, density_coefficient: Fraction)

An exact rational combination of the standard Normal CDF and PDF.

The expression is constant + cdf_coefficient * Phi(argument) + density_coefficient * phi(argument).

PARAMETER DESCRIPTION
argument

The common argument of the standard Normal CDF and density.

TYPE: Fraction

constant

The unweighted rational part.

TYPE: Fraction

cdf_coefficient

The coefficient of the CDF.

TYPE: Fraction

density_coefficient

The coefficient of the density.

TYPE: Fraction

evaluate

evaluate() -> float

Evaluate the expression in binary64 working precision.

RETURNS DESCRIPTION
float

The numerical value. Cancellation and underflow can occur.

RAISES DESCRIPTION
JvpLimit

If the argument, coefficients, or result exceed working range.

Source code in src/quivers/qiec/normal_piecewise_pathwise.py
def evaluate(self) -> float:
    """Evaluate the expression in binary64 working precision.

    Returns
    -------
    float
        The numerical value. Cancellation and underflow can occur.

    Raises
    ------
    JvpLimit
        If the argument, coefficients, or result exceed working range.
    """
    try:
        argument = float(self.argument)
        cdf = erfc(-argument / sqrt(2.0)) / 2.0
        density = exp(-argument * argument / 2.0) / sqrt(2.0 * pi)
        return fsum(
            (
                float(self.constant),
                float(self.cdf_coefficient) * cdf,
                float(self.density_coefficient) * density,
            )
        )
    except OverflowError as error:
        raise JvpLimit(
            "Normal tail moment exceeds binary64 working range"
        ) from error

NormalPiecewisePathwisePlan dataclass

NormalPiecewisePathwisePlan(computation: ComputationId, visit: NormalVisit, location: Fraction, location_tangent: Fraction, threshold: Fraction, boundary_value: Fraction, lower_slope: Fraction, upper_slope: Fraction, expected_value: NormalTailMoment, expected_tangent: NormalTailMoment)

A checked affine payoff with one continuous boundary.

PARAMETER DESCRIPTION
computation

The actual checked source entry.

TYPE: ComputationId

visit

Its one addressed Normal draw and exact scale.

TYPE: NormalVisit

location

The location and its directional derivative.

TYPE: Fraction

location_tangent

The location and its directional derivative.

TYPE: Fraction

threshold

The literal threshold and the proved common value of its two arms.

TYPE: Fraction

boundary_value

The literal threshold and the proved common value of its two arms.

TYPE: Fraction

lower_slope

The exact affine slopes below and above the threshold.

TYPE: Fraction

upper_slope

The exact affine slopes below and above the threshold.

TYPE: Fraction

expected_value

The exact symbolic expected return and directional derivative.

TYPE: NormalTailMoment

expected_tangent

The exact symbolic expected return and directional derivative.

TYPE: NormalTailMoment

at_noise

at_noise(noise: tuple[int | Fraction, ...]) -> ExactJvp

Evaluate the payoff and its directional action at one exact seed.

PARAMETER DESCRIPTION
noise

The single fixed standard Normal coordinate.

TYPE: tuple of int or Fraction

RETURNS DESCRIPTION
ExactJvp

The exact return and tangent of the reached affine arm.

RAISES DESCRIPTION
ValueError

If the noise vector or coefficient is malformed.

JvpBoundaryError

If the seed is exactly on the threshold.

JvpLimit

If an exact coefficient exceeds its size bound.

Source code in src/quivers/qiec/normal_piecewise_pathwise.py
def at_noise(self, noise: tuple[int | Fraction, ...]) -> ExactJvp:
    """Evaluate the payoff and its directional action at one exact seed.

    Parameters
    ----------
    noise : tuple of int or Fraction
        The single fixed standard Normal coordinate.

    Returns
    -------
    ExactJvp
        The exact return and tangent of the reached affine arm.

    Raises
    ------
    ValueError
        If the noise vector or coefficient is malformed.
    JvpBoundaryError
        If the seed is exactly on the threshold.
    JvpLimit
        If an exact coefficient exceeds its size bound.
    """
    if len(noise) != 1:
        raise ValueError("a piecewise Normal plan needs one noise coordinate")
    (coordinate,) = map(_fraction, noise)
    _bound(coordinate)
    offset = self.location + self.visit.scale * coordinate - self.threshold
    if not offset:
        raise JvpBoundaryError("fixed Normal noise reaches the payoff boundary")
    slope = self.lower_slope if offset < 0 else self.upper_slope
    value = self.boundary_value + slope * offset
    tangent = slope * (
        self.location_tangent + self.visit.scale_tangent * coordinate
    )
    _bound(offset, value, tangent)
    return ExactJvp(value, tangent)

plan_normal_piecewise_pathwise

plan_normal_piecewise_pathwise(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_work: int = 65536) -> NormalPiecewisePathwisePlan

License a pathwise derivative for one continuous piecewise-affine payoff.

The computation takes two Real parameters in location and positive scale order and uses them directly at one unplated Normal site. Its terminal greater-than test compares that draw with one finite literal. The two returned expressions use only the draw. Their exact polynomial normal forms must be affine and agree at the literal threshold.

The shared boundary value makes the payoff Lipschitz. For fixed noise z, its directional difference quotient is bounded by the larger absolute slope times abs(dloc) + abs(dscale) * abs(z). Its expected directional derivative is consequently the integral of its pathwise derivative. The two integrated results retain the analytic Normal density and CDF with exact rational coefficients.

PARAMETER DESCRIPTION
module

The source containing the actual nominal draw, guard and arms.

TYPE: QiecModule

computation

The scalar entry being differentiated.

TYPE: ComputationId

arguments

The exact location and scale and their two directional tangents.

TYPE: tuple of int or Fraction

direction

The exact location and scale and their two directional tangents.

TYPE: tuple of int or Fraction

policies

Exactly one explicit reparam policy for the actual source site.

TYPE: tuple of SiteEstimator

max_work

The exact polynomial work budget for checking both arms.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
NormalPiecewisePathwisePlan

The checked boundary, exact symbolic mean and tangent, and fixed-noise action.

RAISES DESCRIPTION
ValueError

If the owner or the exact inputs are absent or malformed.

JvpUnsupported

If the source, site policy, scale, or continuity leaves this fragment.

JvpLimit

If the exact coefficients or proof work exceed a bound.

Source code in src/quivers/qiec/normal_piecewise_pathwise.py
def plan_normal_piecewise_pathwise(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    max_work: int = 65_536,
) -> NormalPiecewisePathwisePlan:
    """License a pathwise derivative for one continuous piecewise-affine payoff.

    The computation takes two Real parameters in location and positive scale
    order and uses them directly at one unplated Normal site. Its terminal
    greater-than test compares that draw with one finite literal. The two
    returned expressions use only the draw. Their exact polynomial normal
    forms must be affine and agree at the literal threshold.

    The shared boundary value makes the payoff Lipschitz. For fixed noise
    `z`, its directional difference quotient is bounded by the larger
    absolute slope times `abs(dloc) + abs(dscale) * abs(z)`. Its expected
    directional derivative is consequently the integral of its pathwise
    derivative. The two integrated results retain the analytic Normal
    density and CDF with exact rational coefficients.

    Parameters
    ----------
    module : QiecModule
        The source containing the actual nominal draw, guard and arms.
    computation : ComputationId
        The scalar entry being differentiated.
    arguments, direction : tuple of int or Fraction
        The exact location and scale and their two directional tangents.
    policies : tuple of SiteEstimator
        Exactly one explicit reparam policy for the actual source site.
    max_work : int
        The exact polynomial work budget for checking both arms.

    Returns
    -------
    NormalPiecewisePathwisePlan
        The checked boundary, exact symbolic mean and tangent, and
        fixed-noise action.

    Raises
    ------
    ValueError
        If the owner or the exact inputs are absent or malformed.
    JvpUnsupported
        If the source, site policy, scale, or continuity leaves this fragment.
    JvpLimit
        If the exact coefficients or proof work exceed a bound.
    """
    _validate_limit("max_work", max_work)
    _, owner = _random_computation(module, computation, "piecewise Normal pathwise")
    if len(owner.parameters) != 2:
        raise JvpUnsupported(
            "piecewise Normal pathwise needs location and scale inputs"
        )
    if len(arguments) != 2 or len(direction) != 2:
        raise ValueError("piecewise Normal arguments and direction must have arity two")
    location, scale = map(_fraction, arguments)
    dlocation, dscale = map(_fraction, direction)
    _bound(location, scale, dlocation, dscale)
    if scale <= 0:
        raise JvpUnsupported("piecewise Normal pathwise needs positive scale")
    body = owner.body
    if (
        not isinstance(body, Bind)
        or not isinstance(body.first, Perform)
        or not isinstance(branch := body.then, If)
        or not isinstance(branch.then, Return)
        or not isinstance(branch.otherwise, Return)
    ):
        raise JvpUnsupported(
            "piecewise Normal pathwise needs one draw and terminal test"
        )
    request = body.first.request
    _check_request(request, owner.type.effects.entries[0].instance)
    distribution = request.arguments[1]
    assert isinstance(distribution, DistributionValue)
    if tuple(value for _, value in distribution.arguments) != tuple(
        Var(local=parameter) for parameter in owner.parameters
    ):
        raise JvpUnsupported(
            "piecewise Normal draw must use its location and scale inputs"
        )
    origin = request.origin
    site = origin.static_site
    if (
        origin.dynamic_path
        or origin.resumption_path
        or origin.relation != "preserve"
        or origin.parents
    ):
        raise JvpUnsupported(
            "piecewise Normal pathwise needs one original draw address"
        )
    if (
        len(policies) != 1
        or policies[0].site != site
        or policies[0].estimator != "reparam"
    ):
        raise JvpUnsupported(
            "piecewise Normal pathwise needs reparam at the actual draw site"
        )
    condition = branch.condition
    if (
        not isinstance(condition, PrimitiveApplication)
        or condition.primitive != PRIMITIVES["gt_real"].id
        or condition.arguments[0] != Var(local=body.binder)
        or not isinstance(literal := condition.arguments[1], LiteralValue)
        or literal.type != REAL
        or not isinstance(literal.value, (int, float))
        or isinstance(literal.value, bool)
        or (isinstance(literal.value, float) and not isfinite(literal.value))
    ):
        raise JvpUnsupported(
            "piecewise Normal test must compare its draw to a Real literal"
        )
    threshold = Fraction(literal.value)
    _bound(threshold)
    (lower_intercept, lower_slope), (upper_intercept, upper_slope) = _affine_arms(
        module, owner, body.binder, branch.otherwise, branch.then, max_work
    )
    lower_value = lower_intercept + lower_slope * threshold
    upper_value = upper_intercept + upper_slope * threshold
    if lower_value != upper_value:
        raise JvpUnsupported(
            f"Normal payoff arms disagree at the boundary: {lower_value} != {upper_value}"
        )
    offset = location - threshold
    argument = offset / scale
    change = upper_slope - lower_slope
    mean = NormalTailMoment(
        argument, lower_value + lower_slope * offset, change * offset, change * scale
    )
    tangent = NormalTailMoment(
        argument, lower_slope * dlocation, change * dlocation, change * dscale
    )
    _bound(
        lower_value,
        argument,
        mean.constant,
        mean.cdf_coefficient,
        mean.density_coefficient,
        tangent.constant,
        tangent.cdf_coefficient,
        tangent.density_coefficient,
    )
    return NormalPiecewisePathwisePlan(
        owner.id,
        NormalVisit(site, origin.dynamic_key(), scale, dscale),
        location,
        dlocation,
        threshold,
        lower_value,
        lower_slope,
        upper_slope,
        mean,
        tangent,
    )

Scalar Normal score derivatives

plan_normal_score checks one reached scalar Normal draw and a continuation that is polynomial in the draw on a neighborhood of the parameter point. The scale stays positive on that neighborhood. The plan holds the physical draw fixed in the direct derivative and adds the return times the directional derivative of the draw's log density. At fixed standard-normal noise at_noise returns the value and one score estimate. The exact result integrates both over the Normal law.

The plan records local domination by a polynomial times Gaussian tails. The native claim applies to the checked fragment and does not establish support in any particular target.

normal_score

Locally dominated score derivatives for one scalar Normal draw.

NormalScorePlan dataclass

NormalScorePlan(computation: ComputationId, exact: ExactJvp, visit: NormalVisit, primal: _Terms, tangent: _Terms, source_steps: int, polynomial_work: int)

The exact and pointwise actions of a checked single-draw score estimator.

PARAMETER DESCRIPTION
computation

The named source entry.

TYPE: ComputationId

exact

The exact expected return and its directional derivative.

TYPE: ExactJvp

visit

The checked Normal occurrence, including its address and positive scale.

TYPE: NormalVisit

primal

The return and score estimator as sparse polynomials of standard-normal noise. The tangent includes the direct derivative of the continuation.

TYPE: _Terms

tangent

The return and score estimator as sparse polynomials of standard-normal noise. The tangent includes the direct derivative of the continuation.

TYPE: _Terms

source_steps

The reference source steps and sparse arithmetic work used by the plan.

TYPE: int

polynomial_work

The reference source steps and sparse arithmetic work used by the plan.

TYPE: int

domination property

domination: Condition

Record the established local Gaussian domination condition.

RETURNS DESCRIPTION
Condition

The full-support and integrable derivative bound used by the score action.

derivative_semantics property

derivative_semantics: DerivativeSemantics

Record the unbiased native action at the addressed score site.

RETURNS DESCRIPTION
DerivativeSemantics

The checked score estimator for the site's nominal identity.

at_noise

at_noise(noise: int | Fraction) -> ExactJvp

Evaluate the return and score estimator at one fixed noise draw.

PARAMETER DESCRIPTION
noise

A scalar coordinate in the standard-normal base space.

TYPE: int or Fraction

RETURNS DESCRIPTION
ExactJvp

The return and one score estimate at that coordinate. The exact field integrates these actions against the standard normal law.

RAISES DESCRIPTION
ValueError

If the coordinate is invalid.

JvpLimit

If the coefficient bound is exceeded.

Source code in src/quivers/qiec/normal_score.py
def at_noise(self, noise: int | Fraction) -> ExactJvp:
    """Evaluate the return and score estimator at one fixed noise draw.

    Parameters
    ----------
    noise : int or Fraction
        A scalar coordinate in the standard-normal base space.

    Returns
    -------
    ExactJvp
        The return and one score estimate at that coordinate. The `exact`
        field integrates these actions against the standard normal law.

    Raises
    ------
    ValueError
        If the coordinate is invalid.
    JvpLimit
        If the coefficient bound is exceeded.
    """
    coordinate = _fraction(noise)
    _bound(coordinate)
    return ExactJvp(
        _evaluate_terms(self.primal, (coordinate,)),
        _evaluate_terms(self.tangent, (coordinate,)),
    )

plan_normal_score

plan_normal_score(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_work: int = 65536, fuel: int = 65536) -> NormalScorePlan

License a scalar Normal score estimator at an exact input point.

The single reached, unplated Normal draw has full real support at every positive scale. Comparisons must be locally stable and independent of the draw. The return and its fixed-draw derivative are polynomials of the drawn value whose coefficients are smooth in a neighborhood of the input. The location, scale and their derivatives are bounded on a smaller closed neighborhood where the scale is bounded away from zero. The payoff times the density and its parameter derivative thus admit polynomial times Gaussian envelopes with integrable tails on that neighborhood.

PARAMETER DESCRIPTION
module

The checked source module and its nominal requests.

TYPE: QiecModule

computation

The scalar real entry with one Random instance.

TYPE: ComputationId

arguments

The exact parameter point and directional tangent in source order.

TYPE: tuple[int or Fraction, ...]

direction

The exact parameter point and directional tangent in source order.

TYPE: tuple[int or Fraction, ...]

policies

One explicit score policy for the reached static site.

TYPE: tuple[SiteEstimator, ...]

max_work

Maximum sparse arithmetic and moment work.

TYPE: int DEFAULT: 65536

fuel

Maximum reference steps for the source replay.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
NormalScorePlan

The exact expected JVP and the pointwise likelihood-ratio action.

RAISES DESCRIPTION
ValueError

If the entry, input vectors or resource bounds are invalid.

JvpUnsupported

If the source fails the score licence checks.

JvpBoundaryError

If a decision is at an input-dependent equality boundary.

JvpLimit

If the source needs a second coordinate or exceeds an execution bound.

Source code in src/quivers/qiec/normal_score.py
def plan_normal_score(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> NormalScorePlan:
    """License a scalar Normal score estimator at an exact input point.

    The single reached, unplated Normal draw has full real support at every
    positive scale. Comparisons must be locally stable and independent of the
    draw. The return and its fixed-draw derivative are polynomials of the drawn
    value whose coefficients are smooth in a neighborhood of the input. The
    location, scale and their derivatives are bounded on a smaller closed
    neighborhood where the scale is bounded away from zero. The payoff times
    the density and its parameter derivative thus admit polynomial times
    Gaussian envelopes with integrable tails on that neighborhood.

    Parameters
    ----------
    module : QiecModule
        The checked source module and its nominal requests.
    computation : ComputationId
        The scalar real entry with one Random instance.
    arguments, direction : tuple[int or Fraction, ...]
        The exact parameter point and directional tangent in source order.
    policies : tuple[SiteEstimator, ...]
        One explicit score policy for the reached static site.
    max_work : int
        Maximum sparse arithmetic and moment work.
    fuel : int
        Maximum reference steps for the source replay.

    Returns
    -------
    NormalScorePlan
        The exact expected JVP and the pointwise likelihood-ratio action.

    Raises
    ------
    ValueError
        If the entry, input vectors or resource bounds are invalid.
    JvpUnsupported
        If the source fails the score licence checks.
    JvpBoundaryError
        If a decision is at an input-dependent equality boundary.
    JvpLimit
        If the source needs a second coordinate or exceeds an execution bound.
    """
    _validate_limit("max_work", max_work)
    _validate_limit("fuel", fuel)
    registry, owner = _random_computation(module, computation, "Normal score")
    if not len(arguments) == len(direction) == len(owner.parameters):
        raise ValueError("arguments and direction must match the computation's arity")
    if len(policies) != 1 or policies[0].estimator != "score":
        raise JvpUnsupported(
            "Normal score estimation needs exactly one explicit score policy"
        )
    _check_first_order_graph(
        module, owner, "Normal score", _check_request, require_acyclic=True
    )
    ring = _PolynomialRing(1, max_work)
    evaluator = _NormalScoreEvaluator(module, fuel, ring, frozenset({policies[0].site}))
    environment = {
        parameter: evaluator.input(_fraction(value), _fraction(tangent), parameter=True)
        for parameter, value, tangent in zip(
            owner.parameters, arguments, direction, strict=True
        )
    }
    try:
        result = evaluator.evaluate_validated(owner.body, registry, environment)
        assert isinstance(result, _NoiseDual)
        if evaluator.log_density_tangent is None:
            raise JvpUnsupported("Normal score estimation needs one reached draw")
        tangent = ring.add(
            result.tangent, ring.multiply(result.primal, evaluator.log_density_tangent)
        )
        exact = ExactJvp(
            _gaussian_expectation(result.primal, ring),
            _gaussian_expectation(tangent, ring),
        )
    except FuelExhaustedError as error:
        raise JvpLimit(
            f"Normal score run exceeded its step budget of {fuel}"
        ) from error
    except PolynomialLawLimit as error:
        raise JvpLimit(f"Normal score expansion: {error}") from error
    return NormalScorePlan(
        computation,
        exact,
        evaluator.visits[0],
        tuple(sorted(result.primal.items())),
        tuple(sorted(tangent.items())),
        evaluator._steps,
        max_work - ring.remaining,
    )

Mixed Bernoulli and Normal estimators

plan_mixed_site_gradient checks both kinds of request in the same scalar source computation. A Bernoulli site's probability may depend on earlier Boolean draws and on the inputs. It must stay strictly between zero and one and be independent of Normal noise. A Normal site uses reparam or score. A scored location and every scale must be independent of earlier continuous draws on each complete finite history.

The source may handle local non-Random scalar control. The handler must be total, authored and monomorphic. Its clauses have grade zero, affine or one and introduce no effects of their own. The reference machine executes the clauses. A clause that returns without resuming retains its own value and derivative. Its abandoned continuation adds no draw, score term or noise coordinate. Earlier draws retain their probability and score, and reached Random requests keep their original addresses. Noise-dependent comparisons and reached parameter-dependent equalities still fail the derivative check.

The finite estimator combines the conditional returns and derivatives linearly, including negative returns. A Bernoulli action accounts for its own changing probability exactly once. A reparameterized Normal action differentiates at fixed base noise. A scored Normal action holds the draw fixed and adds its log-density derivative weighted by the return. The plan uses finite enumeration to check all local hypotheses and compute the exact expectation and derivative. Calling sample estimates these quantities by the selected finite estimator with the Normal moments integrated at the leaves.

at_noise instead fixes all Normal coordinates before applying the finite estimators. Coordinates follow normal_visits. Each occurrence is keyed by its canonical address and the finite choices made before it. Branches share the coordinates from their common history and use separate coordinates after they diverge.

An effect_law for block names the computation that owns its estimator assignments. Each estimator row binds a policy name to a literal sample label and a method. The label must identify one direct Random request in the named computation's body. The compiler binds the assignment to the request's original static site ID. Use enumerate, score, or measure for a checked Bernoulli request and reparam or score for a checked Normal request. All occurrences of that site use the same policy when the caller passes it to a planner, with each occurrence keeping its own address. The planner checks its reached sites, support, and arithmetic at the requested point.

from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import plan_mixed_site_gradient

source = """
instance random : Random

define signed_reward(p : Real, s : Real) : Real !{random} =
    let x <- perform random.sample[Real](site("x"), Normal(loc=0.0, scale=s))
    let positive <- perform random.sample[Bool](site("positive"), Bernoulli(probs=p))
    if positive then
        return x * x
    else
        return -x * x

effect_law for signed_reward
    estimator normal_pathwise at "x" = reparam
    estimator finite_score at "positive" = score
"""
compiler = Compiler(parse(source), module_name="mixed-estimator")
module = compiler.qiec_module
assert module is not None
owner = next(item for item in module.computations if item.name == "signed_reward")
plan = plan_mixed_site_gradient(
    module, owner.id, (Fraction(3, 4), 2), (1, 1),
    compiler.authored_site_estimators("signed_reward"),
)
assert (plan.exact.value, plan.exact.tangent) == (2, 10)
assert len(plan.normal_visits) == 1
assert plan.at_noise((2,)).exact.tangent == 40
assert len(plan.sample(seed=42).draws) == 1

In this example, the affine clause resumes only when the earlier draw is true. Declining the resumption returns \(2-c\) directly. The mean is \((1-p)(2-c) + p((2+c)^2+1)\).

from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import plan_mixed_site_gradient

source = '''
effect Adjust
    shift : Bool -> Real

instance adjust : Adjust
instance random : Random

handler add_bias for Adjust : Real -> Real with (bias : Real) [coverage=total, forwards=none, implementation=authored]
    return value =>
        return value
    shift(keep : Bool) resumes aff =>
        if keep then
            resume(2.0 + bias)
        else
            return 2.0 - bias

define reward(p : Real, c : Real) : Real !{random} =
    let choose <- perform random.sample[Bool](site("choose"), Bernoulli(probs=p))
    handle adjust with add_bias(c) in
        let loc <- perform adjust.shift(choose)
        let x <- perform random.sample[Real](site("noise"), Normal(loc=loc, scale=1.0))
        return x * x

effect_law for reward
    estimator coin at "choose" = score
    estimator normal at "noise" = reparam
'''
compiler = Compiler(parse(source), module_name="branch-local-reward")
module = compiler.qiec_module
assert module is not None
(owner,) = module.computations
plan = plan_mixed_site_gradient(
    module, owner.id, (Fraction(1, 4), 0), (1, 1),
    compiler.authored_site_estimators("reward"),
)
assert (plan.exact.value, plan.exact.tangent) == (Fraction(11, 4), Fraction(13, 4))
assert [path.coordinates for path in plan.normal_paths] == [(), (0,)]
assert plan.at_noise((1,)).exact.tangent == Fraction(31, 4)

mixed_site_gradients

Compose finite Bernoulli estimators with checked Normal actions.

MixedNormalVisit dataclass

MixedNormalVisit(prefix: tuple[bool, ...], visit: NormalVisit, estimator: Literal['reparam', 'score'] = 'reparam')

One Normal coordinate for a source occurrence at a finite history.

PARAMETER DESCRIPTION
prefix

The Bernoulli choices already made when this request is reached.

TYPE: tuple[bool, ...]

visit

The canonical source occurrence and its checked scale.

TYPE: NormalVisit

estimator

The Normal rule chosen for the original site.

TYPE: ('reparam', 'score') DEFAULT: "reparam"

MixedNormalScoreAction dataclass

MixedNormalScoreAction(computation: ComputationId, exact: ExactJvp, visits: tuple[NormalVisit, ...], primal: _Terms, tangent: _Terms, source_steps: int, polynomial_work: int)

Bases: _NormalNoisePlan

The conditional Normal estimator for a history with a scored draw.

MixedNormalPath dataclass

MixedNormalPath(prefix: tuple[bool, ...], coordinates: tuple[int, ...], normal: NormalPathwisePlan | MixedNormalScoreAction)

The conditional Normal action for one complete finite branch.

PARAMETER DESCRIPTION
prefix

The complete Bernoulli choices for that branch.

TYPE: tuple[bool, ...]

coordinates

Indices into the mixed plan's full Normal-coordinate table, in order of the branch's Normal draws.

TYPE: tuple[int, ...]

normal

The checked exact and pointwise action of the actual branch.

TYPE: NormalPathwisePlan or MixedNormalScoreAction

MixedSiteGradientPlan dataclass

MixedSiteGradientPlan(finite: BernoulliGradientPlan, normal_visits: tuple[MixedNormalVisit, ...], normal_paths: tuple[MixedNormalPath, ...], polynomial_work: int)

A finite estimator tree whose leaves use checked Normal rules.

PARAMETER DESCRIPTION
finite

The finite estimator actions with the Normal noise integrated out.

TYPE: BernoulliGradientPlan

normal_visits

A fresh coordinate per source occurrence and preceding finite history. Histories share a coordinate when they reach exactly the same Normal request before they diverge.

TYPE: tuple[MixedNormalVisit, ...]

normal_paths

The complete finite histories and their conditional Normal actions.

TYPE: tuple[MixedNormalPath, ...]

polynomial_work

The total polynomial and moment work used by all reference replays.

TYPE: int

derivative_semantics property

derivative_semantics: DerivativeSemantics

Report the unbiased action and its checked finite and Normal policies.

RETURNS DESCRIPTION
DerivativeSemantics

The policies, with one entry per static site.

normal_score_domination property

normal_score_domination: Condition | None

Record domination for the checked histories with score sites.

RETURNS DESCRIPTION
Condition or None

The local Gaussian domination bound whenever a score site is reached.

exact property

exact: ExactJvp

Give the expected source return and its directional derivative.

RETURNS DESCRIPTION
ExactJvp

The expectation over both Bernoulli and Normal variables.

sample

sample(*, seed: int | None = None) -> BernoulliGradientSample

Run the admitted finite estimators with Normal noise integrated.

PARAMETER DESCRIPTION
seed

An optional seed for independent finite estimator draws.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
BernoulliGradientSample

An unbiased estimate of the signed expected return and its directional derivative in the checked local fragment.

Source code in src/quivers/qiec/mixed_site_gradients.py
def sample(self, *, seed: int | None = None) -> BernoulliGradientSample:
    """Run the admitted finite estimators with Normal noise integrated.

    Parameters
    ----------
    seed : int or None
        An optional seed for independent finite estimator draws.

    Returns
    -------
    BernoulliGradientSample
        An unbiased estimate of the signed expected return and its
        directional derivative in the checked local fragment.
    """
    return self.finite.sample(seed=seed)

at_noise

at_noise(noise: tuple[int | Fraction, ...]) -> BernoulliGradientPlan

Fix every Normal coordinate before applying the finite estimators.

PARAMETER DESCRIPTION
noise

The fixed coordinates in normal_visits order.

TYPE: tuple[int or Fraction, ...]

RETURNS DESCRIPTION
BernoulliGradientPlan

The finite estimator and its exact conditional mean at these coordinates. These inputs are supplied by the caller.

RAISES DESCRIPTION
ValueError

If the noise vector has the wrong size or invalid entries.

JvpLimit

If conditional values exceed the exact arithmetic bounds.

Source code in src/quivers/qiec/mixed_site_gradients.py
def at_noise(self, noise: tuple[int | Fraction, ...]) -> BernoulliGradientPlan:
    """Fix every Normal coordinate before applying the finite estimators.

    Parameters
    ----------
    noise : tuple[int or Fraction, ...]
        The fixed coordinates in normal_visits order.

    Returns
    -------
    BernoulliGradientPlan
        The finite estimator and its exact conditional mean at these
        coordinates. These inputs are supplied by the caller.

    Raises
    ------
    ValueError
        If the noise vector has the wrong size or invalid entries.
    JvpLimit
        If conditional values exceed the exact arithmetic bounds.
    """
    if len(noise) != len(self.normal_visits):
        raise ValueError("noise coordinates must match the mixed Normal visits")
    records: dict[tuple[bool, ...], ExactJvp | BernoulliVisit] = {
        visit.prefix: visit for visit in self.finite.visits
    }
    for path in self.normal_paths:
        records[path.prefix] = path.normal.at_noise(
            tuple(noise[index] for index in path.coordinates)
        )
    tree, exact = _assemble_finite_tree(records)
    return replace(self.finite, exact=exact, tree=tree)

plan_mixed_site_gradient

plan_mixed_site_gradient(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_paths: int = 4096, max_sites: int = 64, max_work: int = 250000, fuel: int = 50000) -> MixedSiteGradientPlan

Check a bounded nominal Bernoulli/Normal estimator program.

Bernoulli probabilities may use shared inputs and earlier Boolean outcomes. Each must be noise-independent and in the open interval from zero to one. Every Normal scale must be positive and noise-independent, and the same independence applies to scored Normal locations. On each finite history the return is a polynomial of the physical scored draws and the reparameterized base noises, with locally smooth coefficients. The joint Gaussian density in these coordinates and its directional derivative admit integrable polynomial times Gaussian envelopes. A total authored monomorphic scalar handler may handle local non-Random control with zero, affine or grade-one clauses that introduce no effects. The reference machine executes those clauses. Skipping a resumption skips every Random request it would have reached in the abandoned continuation. The finite estimator consumes the reached conditional values and their derivatives linearly.

PARAMETER DESCRIPTION
module

The checked source module.

TYPE: QiecModule

computation

The named scalar-returning entry on one nominal Random row.

TYPE: ComputationId

arguments

The exact parameter point and direction in source parameter order.

TYPE: tuple[int or Fraction, ...]

direction

The exact parameter point and direction in source parameter order.

TYPE: tuple[int or Fraction, ...]

policies

One explicit policy for each reached static site.

TYPE: tuple[SiteEstimator, ...]

max_paths

Maximum number of complete finite traces.

TYPE: int DEFAULT: 4096

max_sites

Maximum number of distinct Normal coordinates per finite trace.

TYPE: int DEFAULT: 64

max_work

Total polynomial and moment work over the checked reference runs.

TYPE: int DEFAULT: 250000

fuel

Maximum source steps in each reference run.

TYPE: int DEFAULT: 50000

RETURNS DESCRIPTION
MixedSiteGradientPlan

The integrated result and conditional estimator actions.

RAISES DESCRIPTION
ValueError

If the arguments, source name, declaration or a bound is malformed.

JvpUnsupported

If the actual source leaves the checked fragment.

JvpLimit

If a trace, occurrence, arithmetic or source step limit is exceeded.

Source code in src/quivers/qiec/mixed_site_gradients.py
def plan_mixed_site_gradient(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    max_paths: int = 4096,
    max_sites: int = 64,
    max_work: int = 250_000,
    fuel: int = 50_000,
) -> MixedSiteGradientPlan:
    """Check a bounded nominal Bernoulli/Normal estimator program.

    Bernoulli probabilities may use shared inputs and earlier Boolean
    outcomes. Each must be noise-independent and in the open interval
    from zero to one. Every Normal scale must be positive and
    noise-independent, and the same independence applies to scored Normal
    locations. On each finite history the return is a polynomial of the
    physical scored draws and the reparameterized base noises, with locally
    smooth coefficients. The joint Gaussian density in these coordinates
    and its directional derivative admit integrable polynomial times
    Gaussian envelopes. A total authored monomorphic scalar
    handler may handle local non-Random control with zero, affine or
    grade-one clauses that introduce no effects. The reference machine
    executes those clauses. Skipping a resumption skips every Random
    request it would have reached in the abandoned continuation. The
    finite estimator consumes the reached conditional values and their
    derivatives linearly.

    Parameters
    ----------
    module : QiecModule
        The checked source module.
    computation : ComputationId
        The named scalar-returning entry on one nominal Random row.
    arguments, direction : tuple[int or Fraction, ...]
        The exact parameter point and direction in source parameter order.
    policies : tuple[SiteEstimator, ...]
        One explicit policy for each reached static site.
    max_paths : int
        Maximum number of complete finite traces.
    max_sites : int
        Maximum number of distinct Normal coordinates per finite trace.
    max_work : int
        Total polynomial and moment work over the checked reference runs.
    fuel : int
        Maximum source steps in each reference run.

    Returns
    -------
    MixedSiteGradientPlan
        The integrated result and conditional estimator actions.

    Raises
    ------
    ValueError
        If the arguments, source name, declaration or a bound is malformed.
    JvpUnsupported
        If the actual source leaves the checked fragment.
    JvpLimit
        If a trace, occurrence, arithmetic or source step limit is exceeded.
    """
    for name, limit in (
        ("max_paths", max_paths),
        ("max_sites", max_sites),
        ("max_work", max_work),
        ("fuel", fuel),
    ):
        _validate_limit(name, limit)
    registry, owner = _random_computation(module, computation, "mixed site")
    if not len(arguments) == len(direction) == len(owner.parameters):
        raise ValueError("arguments and direction must match the computation's arity")
    declared = {policy.site: policy.estimator for policy in policies}
    if len(declared) != len(policies):
        raise ValueError("duplicate estimator for one mixed site")
    is_bernoulli: dict[SiteId, bool] = {}

    def record_family(request: EffectRequest, instance: EffectInstanceId) -> None:
        """Check the law at a static site and record its observed family.

        Parameters
        ----------
        request
            The original typed draw request.
        instance
            The Random instance expected by the enclosing computation.

        Raises
        ------
        JvpUnsupported
            If the request falls outside the admitted families or the same site has competing families.
        """
        _check_request(request, instance)
        site = request.origin.static_site
        finite = request.result_type == BOOL
        if is_bernoulli.setdefault(site, finite) != finite:
            raise JvpUnsupported(f"conflicting distribution families for site {site}")

    _check_first_order_graph(
        module,
        owner,
        "mixed site",
        record_family,
        allow_authored_control=True,
        require_at_most_one_resume=True,
    )
    bernoulli: dict[SiteId, _Estimator] = {}
    reparam: set[SiteId] = set()
    scored: set[SiteId] = set()
    for site, method in declared.items():
        if method == "score" and is_bernoulli.get(site) is False:
            scored.add(site)
        elif method in ("enumerate", "score", "measure"):
            bernoulli[site] = method
        elif method == "reparam":
            reparam.add(site)
        else:
            raise JvpUnsupported(f"unsupported mixed site estimator {method!r}")
    point = tuple(
        (parameter, _fraction(value), _fraction(tangent))
        for parameter, value, tangent in zip(
            owner.parameters, arguments, direction, strict=True
        )
    )
    normal_sites, normal_scores = frozenset(reparam | scored), frozenset(scored)
    width = min(max_sites, max_work, fuel)
    remaining = max_work
    pending: list[tuple[bool, ...]] = [()]
    records: dict[tuple[bool, ...], ExactJvp | BernoulliVisit] = {}
    visits: list[BernoulliVisit] = []
    normal_visits: list[MixedNormalVisit] = []
    coordinates: dict[tuple[tuple[bool, ...], _Address], int] = {}
    paths: list[MixedNormalPath] = []
    path_count, steps = 1, 0
    while pending:
        prefix = pending.pop()
        ring = _PolynomialRing(width, remaining)
        evaluator = _MixedEvaluator(
            module, fuel, ring, normal_sites, normal_scores, bernoulli, prefix
        )
        environment = {
            parameter: evaluator.input(value, tangent, parameter=True)
            for parameter, value, tangent in point
        }
        try:
            result = evaluator.evaluate_validated(owner.body, registry, environment)
            assert isinstance(result, _NoiseDual) and len(evaluator.choices) == len(
                prefix
            )
            if evaluator.reached_score:
                result = replace(
                    result,
                    tangent=ring.add(
                        result.tangent,
                        ring.multiply(result.primal, evaluator.log_density_tangent),
                    ),
                )
                leaf = _normal_path(
                    computation, evaluator, result, remaining, MixedNormalScoreAction
                )
            else:
                leaf = _normal_path(
                    computation, evaluator, result, remaining, NormalPathwisePlan
                )
        except _NeedChoice as choice:
            records[prefix] = choice.visit
            visits.append(choice.visit)
            path_count += 1
            if path_count > max_paths:
                raise JvpLimit(
                    f"mixed enumeration exceeds {max_paths} complete paths"
                ) from None
            pending.extend(((*prefix, True), (*prefix, False)))
        except FuelExhaustedError as error:
            raise JvpLimit(
                f"mixed replay exceeded its step budget of {fuel} at {prefix!r}"
            ) from error
        except PolynomialLawLimit as error:
            raise JvpLimit(f"mixed Normal expansion: {error}") from error
        else:
            records[prefix] = leaf.exact
            indices: list[int] = []
            for history, visit in zip(
                evaluator.normal_prefixes, leaf.visits, strict=True
            ):
                coord = coordinates.setdefault(
                    (history, visit.address), len(normal_visits)
                )
                if coord == len(normal_visits):
                    normal_visits.append(
                        MixedNormalVisit(
                            history,
                            visit,
                            "score" if visit.site in normal_scores else "reparam",
                        )
                    )
                indices.append(coord)
            paths.append(MixedNormalPath(prefix, tuple(indices), leaf))
        finally:
            steps += evaluator._steps
            remaining = ring.remaining
    reached = {visit.site for visit in visits} | {
        item.visit.site for item in normal_visits
    }
    unused = sorted(str(site) for site in declared.keys() - reached)
    if unused:
        raise JvpUnsupported(
            f"estimator policies name unreached sites: {', '.join(unused)}"
        )
    tree, exact = _assemble_finite_tree(records)
    ordered = tuple(
        sorted(
            (policy for policy in policies if policy.site in bernoulli),
            key=lambda p: str(p.site),
        )
    )
    finite = BernoulliGradientPlan(
        computation, exact, ordered, tuple(visits), path_count, steps, tree
    )
    return MixedSiteGradientPlan(
        finite, tuple(normal_visits), tuple(paths), max_work - remaining
    )

A Bernoulli choice with a continuous Normal payoff

plan_mixed_piecewise_pathwise checks one direct Bernoulli guard. One arm returns a scalar and the other makes a terminal call to a one-draw piecewise-affine Normal payoff. The called payoff must be continuous at its literal threshold. These conditions allow the location and scale derivatives at fixed noise to be integrated over the Normal draw.

For active-branch probability \(a\), inactive return \(b\) and conditional Normal mean \(M\), the integrated mean is \((1-a)b+aM\). Its directional derivative includes \(D a(M-b)\) as well as the two conditional derivatives. The integrated fields retain exact coefficients of the standard Normal CDF and density. They can be evaluated in binary64 with NormalTailMoment.evaluate. The original Normal address includes the actual call scope.

at_noise gives the ordinary exact finite estimator for one base-noise coordinate. A tape exactly at the threshold fails the pointwise derivative check. Gaussian polynomial variance analysis has its own entry point and continues to require polynomial returns.

from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import NormalTailMoment, plan_mixed_piecewise_pathwise

source = """
instance random : Random

define positive(location : Real, scale : Real) : Real !{random} =
    let x <- perform random.sample[Real](site("x"), Normal(loc=location, scale=scale))
    if x > 0.0 then
        return x
    else
        return 0.0

define response(p : Real, m : Real, s : Real) : Real !{random} =
    let choose <- perform random.sample[Bool](site("choose"), Bernoulli(probs=p))
    if choose then
        positive(m, s)
    else
        return 1.0

effect_law for response
    estimator coin at "choose" = score
effect_law for positive
    estimator noise at "x" = reparam
"""
compiler = Compiler(parse(source))
module = compiler.qiec_module
assert module is not None
owner = next(item for item in module.computations if item.name == "response")
policies = (
    *compiler.authored_site_estimators("response"),
    *compiler.authored_site_estimators("positive"),
)
plan = plan_mixed_piecewise_pathwise(module, owner.id, (Fraction(1, 4), 0, 2), (1, 1, 0), policies)
assert plan.expected_value == NormalTailMoment(0, Fraction(3, 4), 0, Fraction(1, 2))
assert plan.expected_tangent == NormalTailMoment(0, -1, Fraction(1, 4), 2)
assert plan.at_noise((1,)).exact.tangent == Fraction(5, 4)

mixed_piecewise_pathwise

A finite Bernoulli choice between a scalar return and a continuous Normal payoff.

MixedPiecewisePathwisePlan dataclass

MixedPiecewisePathwisePlan(computation: ComputationId, choice: BernoulliVisit, active_when: bool, inactive: ExactJvp, normal: NormalPiecewisePathwisePlan, expected_value: NormalTailMoment, expected_tangent: NormalTailMoment, source_steps: int)

A checked Bernoulli mixture with one continuous Normal payoff.

PARAMETER DESCRIPTION
computation

The actual mixed source entry.

TYPE: ComputationId

choice

Its single original addressed Bernoulli request and probability.

TYPE: BernoulliVisit

active_when

The choice that invokes the Normal payoff.

TYPE: bool

inactive

The other branch's scalar return and directional derivative.

TYPE: ExactJvp

normal

The certified called payoff with the Normal request's full address in this mixture.

TYPE: NormalPiecewisePathwisePlan

expected_value

The integrated mixture mean and derivative in exact symbolic form.

TYPE: NormalTailMoment

expected_tangent

The integrated mixture mean and derivative in exact symbolic form.

TYPE: NormalTailMoment

source_steps

Reference steps for the finite replay up through the original Normal request and the inactive return. The separate affine proof uses its own work budget.

TYPE: int

at_noise

at_noise(noise: tuple[int | Fraction, ...]) -> BernoulliGradientPlan

Apply the ordinary finite estimator at a fixed Normal coordinate.

PARAMETER DESCRIPTION
noise

The one fixed standard Normal coordinate.

TYPE: tuple of int or Fraction

RETURNS DESCRIPTION
BernoulliGradientPlan

The exact rational conditional expectation and finite estimator.

RAISES DESCRIPTION
ValueError

If the input lacks one exact Normal coordinate.

JvpBoundaryError

If the fixed noise reaches the Normal payoff boundary.

JvpLimit

If a coefficient exceeds its exact bound.

Source code in src/quivers/qiec/mixed_piecewise_pathwise.py
def at_noise(self, noise: tuple[int | Fraction, ...]) -> BernoulliGradientPlan:
    """Apply the ordinary finite estimator at a fixed Normal coordinate.

    Parameters
    ----------
    noise : tuple of int or Fraction
        The one fixed standard Normal coordinate.

    Returns
    -------
    BernoulliGradientPlan
        The exact rational conditional expectation and finite estimator.

    Raises
    ------
    ValueError
        If the input lacks one exact Normal coordinate.
    JvpBoundaryError
        If the fixed noise reaches the Normal payoff boundary.
    JvpLimit
        If a coefficient exceeds its exact bound.
    """
    records = {
        (): self.choice,
        (self.active_when,): self.normal.at_noise(noise),
        (not self.active_when,): self.inactive,
    }
    tree, exact = _assemble_finite_tree(records)
    _bound(exact.value, exact.tangent)
    return BernoulliGradientPlan(
        self.computation,
        exact,
        (SiteEstimator(site=self.choice.site, estimator=self.choice.estimator),),
        (self.choice,),
        2,
        self.source_steps,
        tree,
    )

plan_mixed_piecewise_pathwise

plan_mixed_piecewise_pathwise(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_work: int = 65536, max_payoff_work: int = 65536, fuel: int = 65536) -> MixedPiecewisePathwisePlan

License an addressed Bernoulli mixture of a continuous Normal payoff.

A direct Bernoulli guard in the entry selects one terminal call to the checked one-draw piecewise-affine Normal fragment and one pure scalar return. The finite probability must be interior. The called payoff must agree on its two sides at the literal threshold. Its actual call operands determine the Normal location, positive scale, and their directional actions. The finite policies apply on fixed-noise tapes. The integrated result retains its analytic CDF and density terms.

PARAMETER DESCRIPTION
module

The checked source containing the branch and the actual named payoff.

TYPE: QiecModule

computation

The selected scalar mixed entry with one nominal Random row.

TYPE: ComputationId

arguments

Exact parameter values and a direction in the entry's parameter order.

TYPE: tuple of int or Fraction

direction

Exact parameter values and a direction in the entry's parameter order.

TYPE: tuple of int or Fraction

policies

One finite policy for the original Bernoulli and one reparam policy for the original Normal.

TYPE: tuple of SiteEstimator

max_work

The exact polynomial work budget for the finite prefix replay.

TYPE: int DEFAULT: 65536

max_payoff_work

The separate polynomial certification budget for the payoff arms.

TYPE: int DEFAULT: 65536

fuel

Maximum source steps in each finite prefix replay.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
MixedPiecewisePathwisePlan

The integrated symbolic result and exact finite fixed-tape action.

RAISES DESCRIPTION
ValueError

If the selected entry, input vectors, or limits are malformed.

JvpUnsupported

If the source, distribution, policy or continuity leaves the fragment.

JvpLimit

If replay, proof work, or exact coefficients exceed a bound.

Source code in src/quivers/qiec/mixed_piecewise_pathwise.py
def plan_mixed_piecewise_pathwise(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    max_work: int = 65_536,
    max_payoff_work: int = 65_536,
    fuel: int = 65_536,
) -> MixedPiecewisePathwisePlan:
    """License an addressed Bernoulli mixture of a continuous Normal payoff.

    A direct Bernoulli guard in the entry selects one terminal call to
    the checked one-draw piecewise-affine Normal fragment and one pure
    scalar return. The finite probability must be interior. The called
    payoff must agree on its two sides at the literal threshold. Its
    actual call operands determine the Normal location, positive scale,
    and their directional actions. The finite policies apply on
    fixed-noise tapes. The integrated result retains its analytic CDF
    and density terms.

    Parameters
    ----------
    module : QiecModule
        The checked source containing the branch and the actual named payoff.
    computation : ComputationId
        The selected scalar mixed entry with one nominal Random row.
    arguments, direction : tuple of int or Fraction
        Exact parameter values and a direction in the entry's parameter order.
    policies : tuple of SiteEstimator
        One finite policy for the original Bernoulli and one reparam policy
        for the original Normal.
    max_work : int
        The exact polynomial work budget for the finite prefix replay.
    max_payoff_work : int
        The separate polynomial certification budget for the payoff arms.
    fuel : int
        Maximum source steps in each finite prefix replay.

    Returns
    -------
    MixedPiecewisePathwisePlan
        The integrated symbolic result and exact finite fixed-tape action.

    Raises
    ------
    ValueError
        If the selected entry, input vectors, or limits are malformed.
    JvpUnsupported
        If the source, distribution, policy or continuity leaves the fragment.
    JvpLimit
        If replay, proof work, or exact coefficients exceed a bound.
    """
    _validate_limit("max_payoff_work", max_payoff_work)
    _, owner = _random_computation(module, computation, "mixed piecewise pathwise")
    active_when, callee, draw = _normal_branch(module, owner)
    # Stop analysis at the original draw to read the actual call's location,
    # scale and address. Certification below uses the original payoff arms.
    prefix_callee = callee.with_(
        body=draw.with_(then=Return(value=Var(local=draw.binder)))
    )
    prefix = module.with_(
        computations=tuple(
            prefix_callee if item.id == callee.id else item
            for item in module.computations
        )
    )
    probe = plan_mixed_site_gradient(
        prefix,
        computation,
        arguments,
        direction,
        policies,
        max_paths=2,
        max_sites=1,
        max_work=max_work,
        fuel=fuel,
    )
    (choice,) = probe.finite.visits
    (normal_visit,) = probe.normal_visits
    paths = {path.prefix[0]: path.normal for path in probe.normal_paths}
    live, inactive = paths[active_when], paths[not active_when].exact
    visit = normal_visit.visit
    assert normal_visit.prefix == (active_when,) and live.visits == (visit,)
    zero = Fraction()
    normal = plan_normal_piecewise_pathwise(
        module,
        callee.id,
        (dict(live.primal).get((0,), zero), visit.scale),
        (dict(live.tangent).get((0,), zero), visit.scale_tangent),
        tuple(policy for policy in policies if policy.site == visit.site),
        max_work=max_payoff_work,
    )
    assert normal.visit.site == visit.site
    normal = replace(normal, visit=visit)
    mean, tangent = normal.expected_value, normal.expected_tangent
    p = choice.probability if active_when else 1 - choice.probability
    dp = choice.tangent if active_when else -choice.tangent
    b, db = inactive.value, inactive.tangent
    expected = NormalTailMoment(
        mean.argument,
        (1 - p) * b + p * mean.constant,
        p * mean.cdf_coefficient,
        p * mean.density_coefficient,
    )
    derivative = NormalTailMoment(
        mean.argument,
        (1 - p) * db + p * tangent.constant + dp * (mean.constant - b),
        p * tangent.cdf_coefficient + dp * mean.cdf_coefficient,
        p * tangent.density_coefficient + dp * mean.density_coefficient,
    )
    _bound(
        expected.constant,
        expected.cdf_coefficient,
        expected.density_coefficient,
        derivative.constant,
        derivative.cdf_coefficient,
        derivative.density_coefficient,
    )
    return MixedPiecewisePathwisePlan(
        computation,
        choice,
        active_when,
        inactive,
        normal,
        expected,
        derivative,
        probe.finite.source_steps,
    )

Gaussian moments of the mixed estimator

audit_mixed_site_gradient_moments computes the population variances and signed covariance of the estimator run with at_noise, when its canonical coordinates are independent standard Normals. A draw before a branch shares its coordinate across continuations. Draws after divergence use separate coordinates in each virtual branch. The audit collects the actual finite scripts, replays their arithmetic on the coefficients of each Gaussian monomial, and integrates the centered products. Its finite atom estimates are conditional means over the Normal coordinates. The plan's integrated sample method therefore has the variability of those conditional means alone.

The product degree receives its own bound, at twice the largest leaf degree. The moment work meter covers finite and coefficient replay, tree construction and Gaussian products. The checked source keeps its separate path and arithmetic limits.

from fractions import Fraction

from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, audit_mixed_site_gradient_moments

module = Compiler(parse("""
instance random : Random

define reward(p : Real, s : Real) : Real !{random} =
    let x <- perform random.sample[Real](site("x"), Normal(loc=0.0, scale=s))
    let b <- perform random.sample[Bool](site("b"), Bernoulli(probs=p))
    if b then
        return x
    else
        return -x
"""), module_name="mixed-gradient-moments").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "reward")
assert isinstance(entry.body, Bind) and isinstance(entry.body.then, Bind)
normal, finite = entry.body.first, entry.body.then.first
assert isinstance(normal, Perform) and isinstance(finite, Perform)
policies = (
    SiteEstimator(site=normal.request.origin.static_site, estimator="reparam"),
    SiteEstimator(site=finite.request.origin.static_site, estimator="score"),
)
audit = audit_mixed_site_gradient_moments(
    module, entry.id, (Fraction(1, 2), 2), (1, 1), policies,
)
assert (audit.mean.value, audit.mean.tangent) == (0, 0)
assert (audit.value_variance, audit.tangent_variance, audit.covariance) == (4, 17, 2)
assert all(outcome.estimate.tangent == 0 for outcome in audit.outcomes)

mixed_estimator_moments

Exact moments of a finite script with its independent Gaussian inputs.

MixedSiteGradientMoments dataclass

MixedSiteGradientMoments(module: QiecModule, source: MixedSiteGradientPlan, point: tuple[Fraction, ...], direction: tuple[Fraction, ...], policies: tuple[SiteEstimator, ...], mean: ExactJvp, value_variance: Fraction, tangent_variance: Fraction, covariance: Fraction, outcomes: tuple[BernoulliEstimatorOutcome, ...], degree_bound: int, moment_work: int, estimator_replays: int, coefficient_replays: int)

Joint moments of the at-noise estimator under independent Normals.

PARAMETER DESCRIPTION
module

The checked source.

TYPE: QiecModule

source

Its checked finite tree and canonical table of independent standard Normal coordinates. A common source prefix has one shared coordinate for each Normal request in it.

TYPE: MixedSiteGradientPlan

point

The supplied parameter point and direction in source order.

TYPE: tuple[Fraction, ...]

direction

The supplied parameter point and direction in source order.

TYPE: tuple[Fraction, ...]

policies

The source's explicit finite and Normal policies.

TYPE: tuple[SiteEstimator, ...]

mean

The expected value and derivative over both kinds of randomness.

TYPE: ExactJvp

value_variance

The population variances of the primal and directional estimates.

TYPE: Fraction

tangent_variance

The population variances of the primal and directional estimates.

TYPE: Fraction

covariance

Their signed covariance.

TYPE: Fraction

outcomes

The ordered finite scripts and their exact probabilities. The estimate at each script is its conditional mean over the Normal coordinates.

TYPE: tuple[BernoulliEstimatorOutcome, ...]

degree_bound

Twice the largest degree in either leaf polynomial, bounding every formed moment product.

TYPE: int

moment_work

Charged tree, rebasing, product and Gaussian integration work. Source polynomial work has a separate budget and meter.

TYPE: int

estimator_replays

The finite interpreter runs used to enumerate actual scripts, including suspensions at unresolved choices.

TYPE: int

coefficient_replays

The additional scalar interpreter runs used to lift the complete scripts to polynomials.

TYPE: int

audit_mixed_site_gradient_moments

audit_mixed_site_gradient_moments(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_paths: int = 4096, max_sites: int = 64, max_source_work: int = 250000, fuel: int = 50000, max_outcomes: int = 4096, max_coordinates: int = 128, max_degree: int = 64, max_moment_work: int = 250000) -> MixedSiteGradientMoments

Audit the finite and Gaussian randomness of a checked mixed estimator.

The calculation concerns the estimator obtained by fixing the canonical Normal inputs with at_noise and running the declared finite policies, then averaging under independent standard Normals. It includes Gaussian variability at fixed finite choices. The integrated convenience sampler has already averaged out that noise.

Each finite action is rational-linear in its leaf pairs since the checked probabilities and their tangents are noise-independent. Replaying the actual scalar interpreter on every monomial coefficient thus recovers the full polynomial action for each checked script. Gaussian moments give its conditional and joint moments exactly.

PARAMETER DESCRIPTION
module

The checked source module.

TYPE: QiecModule

computation

The named entry on one nominal Random row.

TYPE: ComputationId

arguments

Exact parameter point and tangent in parameter order.

TYPE: tuple[int or Fraction, ...]

direction

Exact parameter point and tangent in parameter order.

TYPE: tuple[int or Fraction, ...]

policies

One explicit estimator policy per reached static site.

TYPE: tuple[SiteEstimator, ...]

max_paths

The source planner's path, per-path Normal, polynomial work and per-replay step limits.

TYPE: int DEFAULT: 4096

max_sites

The source planner's path, per-path Normal, polynomial work and per-replay step limits.

TYPE: int DEFAULT: 4096

max_source_work

The source planner's path, per-path Normal, polynomial work and per-replay step limits.

TYPE: int DEFAULT: 4096

fuel

The source planner's path, per-path Normal, polynomial work and per-replay step limits.

TYPE: int DEFAULT: 4096

max_outcomes

The maximum number of complete finite estimator scripts.

TYPE: int DEFAULT: 4096

max_coordinates

The maximum total Normal coordinate width.

TYPE: int DEFAULT: 128

max_degree

The maximum bound on a moment product's total degree. At most half this value is allowed in any individual leaf term.

TYPE: int DEFAULT: 64

max_moment_work

Independent limit covering both finite and coefficient replays, tree construction, coordinate rebasing and Gaussian products. Each tree replay is conservatively charged its full node count.

TYPE: int DEFAULT: 250000

RETURNS DESCRIPTION
MixedSiteGradientMoments

The joint population moments with the checked law and work counts.

RAISES DESCRIPTION
ValueError

If a bound or exact input is malformed.

JvpUnsupported

If the checked source or policies leave the mixed fragment.

JvpBoundaryError

If a reached comparison hits an active equality boundary.

JvpLimit

If a source, estimator, degree, work or coefficient bound is exceeded.

RuntimeError

If symbolic replay disagrees with the checked source.

Source code in src/quivers/qiec/mixed_estimator_moments.py
def audit_mixed_site_gradient_moments(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    max_paths: int = 4096,
    max_sites: int = 64,
    max_source_work: int = 250_000,
    fuel: int = 50_000,
    max_outcomes: int = 4096,
    max_coordinates: int = 128,
    max_degree: int = 64,
    max_moment_work: int = 250_000,
) -> MixedSiteGradientMoments:
    """Audit the finite and Gaussian randomness of a checked mixed estimator.

    The calculation concerns the estimator obtained by fixing the
    canonical Normal inputs with `at_noise` and running the declared
    finite policies, then averaging under independent standard Normals.
    It includes Gaussian variability at fixed finite choices. The
    integrated convenience sampler has already averaged out that noise.

    Each finite action is rational-linear in its leaf pairs since the
    checked probabilities and their tangents are noise-independent.
    Replaying the actual scalar interpreter on every monomial coefficient
    thus recovers the full polynomial action for each checked script.
    Gaussian moments give its conditional and joint moments exactly.

    Parameters
    ----------
    module : QiecModule
        The checked source module.
    computation : ComputationId
        The named entry on one nominal Random row.
    arguments, direction : tuple[int or Fraction, ...]
        Exact parameter point and tangent in parameter order.
    policies : tuple[SiteEstimator, ...]
        One explicit estimator policy per reached static site.
    max_paths, max_sites, max_source_work, fuel : int
        The source planner's path, per-path Normal, polynomial work and
        per-replay step limits.
    max_outcomes : int
        The maximum number of complete finite estimator scripts.
    max_coordinates : int
        The maximum total Normal coordinate width.
    max_degree : int
        The maximum bound on a moment product's total degree. At most
        half this value is allowed in any individual leaf term.
    max_moment_work : int
        Independent limit covering both finite and coefficient replays,
        tree construction, coordinate rebasing and Gaussian products.
        Each tree replay is conservatively charged its full node count.

    Returns
    -------
    MixedSiteGradientMoments
        The joint population moments with the checked law and work counts.

    Raises
    ------
    ValueError
        If a bound or exact input is malformed.
    JvpUnsupported
        If the checked source or policies leave the mixed fragment.
    JvpBoundaryError
        If a reached comparison hits an active equality boundary.
    JvpLimit
        If a source, estimator, degree, work or coefficient bound is exceeded.
    RuntimeError
        If symbolic replay disagrees with the checked source.
    """
    for name, limit in (
        ("max_outcomes", max_outcomes),
        ("max_coordinates", max_coordinates),
        ("max_degree", max_degree),
        ("max_moment_work", max_moment_work),
    ):
        _validate_limit(name, limit)
    if max_degree > _MAX_DEGREE:
        raise ValueError(f"mixed moment degree limit cannot exceed {_MAX_DEGREE}")
    point = tuple(map(_fraction, arguments))
    tangent = tuple(map(_fraction, direction))
    policies = tuple(policies)
    source = plan_mixed_site_gradient(
        module,
        computation,
        point,
        tangent,
        policies,
        max_paths=max_paths,
        max_sites=max_sites,
        max_work=max_source_work,
        fuel=fuel,
    )
    width = len(source.normal_visits)
    if width > max_coordinates:
        raise JvpLimit(f"mixed moments exceed {max_coordinates} Normal coordinates")
    if width > max_moment_work:
        raise JvpLimit("mixed moment work cannot cover its Normal coordinate width")
    ring = _PolynomialRing(width, max_moment_work)
    nodes = source.finite.replays

    def charge_replay() -> None:
        """Charge the maximum node visits of another finite replay."""
        ring.spend(nodes)

    try:
        coefficients, degree = _coordinate_coefficients(source, ring, max_degree)
        outcomes, replays, mean = _estimator_outcomes(
            source.finite,
            max_outcomes,
            audit="mixed moment audit",
            charge_replay=charge_replay,
        )
        by_script: list[tuple[_Polynomial, _Polynomial]] = [({}, {}) for _ in outcomes]
        branches = {visit.prefix: visit for visit in source.finite.visits}
        leaves = tuple(path.prefix for path in source.normal_paths)
        for powers, values in coefficients.items():
            ring.spend(nodes)
            records: dict[tuple[bool, ...], ExactJvp | BernoulliVisit] = {
                **branches,
                **{prefix: values.get(prefix, _ZERO) for prefix in leaves},
            }
            tree, _ = _assemble_finite_tree(records)
            for atom, (v, d) in zip(outcomes, by_script, strict=True):
                charge_replay()
                pair = _replay_coefficients(tree, atom)
                ring.accumulate(v, powers, pair.value)
                ring.accumulate(d, powers, pair.tangent)

        var_v = var_d = cov = Fraction(0)
        for atom, (v, d) in zip(outcomes, by_script, strict=True):
            conditional = ExactJvp(
                _gaussian_expectation(v, ring), _gaussian_expectation(d, ring)
            )
            if conditional != atom.estimate:
                raise RuntimeError(
                    "mixed moment conditional mean disagrees with the checked estimator"
                )
            v = ring.add(v, {ring.zero: mean.value}, sign=-1)
            d = ring.add(d, {ring.zero: mean.tangent}, sign=-1)
            p = atom.probability
            var_v += p * _gaussian_product(v, v, ring)
            var_d += p * _gaussian_product(d, d, ring)
            cov += p * _gaussian_product(v, d, ring)
            _bound(var_v, var_d, cov)
    except PolynomialLawLimit as error:
        raise JvpLimit(f"mixed moment expansion: {error}") from error

    return MixedSiteGradientMoments(
        module,
        source,
        point,
        tangent,
        policies,
        mean,
        var_v,
        var_d,
        cov,
        outcomes,
        degree,
        max_moment_work - ring.remaining,
        replays,
        len(outcomes) * len(coefficients),
    )

Exact finite marginalization

marginalize_bernoulli_unit takes a scalar source computation whose return is an observation factor. It enumerates the latent Bernoulli histories and differentiates each prior probability and observation factor. Each site needs an explicit enumerate policy. The factor on every complete history must be strictly positive. This ensures the complete-data log scores exist on the checked local support.

For history \(h\), write \(w_h\) for the joint weight and \(Z = \sum_h w_h\) for the marginal observation weight. The result records \(Z\) and its directional derivative, the posterior weights \(w_h / Z\) and their derivatives, and the complete-data log scores \(w_h' / w_h\). The posterior mean of these scores equals \(Z' / Z\) by the finite Fisher identity. The reference computation checks this equality in rational arithmetic.

from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, marginalize_bernoulli_unit

source = """
instance random : Random

define observed_unit(p : Real) : Real !{random} =
    let group <- perform random.sample[Bool](site("group"), Bernoulli(probs=p))
    if group then
        return 3.0
    else
        return 1.0
"""
module = Compiler(parse(source), module_name="finite-marginalization").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "observed_unit")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="enumerate")
fit = marginalize_bernoulli_unit(module, entry.id, (Fraction(1, 4),), (1,), (policy,))
assert (fit.normalizer.value, fit.normalizer.tangent) == (Fraction(3, 2), 2)
assert fit.marginal_score == Fraction(4, 3)
assert [outcome.posterior.value for outcome in fit.outcomes] == [Fraction(1, 2)] * 2

finite_marginalization

Exact finite marginalization and checked complete-data scores.

FisherOutcome dataclass

FisherOutcome(prefix: tuple[bool, ...], prior: ExactJvp, observation: ExactJvp, joint: ExactJvp, posterior: ExactJvp, complete_score: Fraction)

One complete finite history with its prior and posterior actions.

PARAMETER DESCRIPTION
prefix

The chronological Bernoulli outcomes for this complete history.

TYPE: tuple[bool, ...]

prior

The prior path probability and its directional derivative.

TYPE: ExactJvp

observation

The positive observation factor returned by this source path.

TYPE: ExactJvp

joint

The joint weight, given by the prior times the observation factor.

TYPE: ExactJvp

posterior

The normalized probability of this path and its derivative.

TYPE: ExactJvp

complete_score

The directional derivative of the log joint weight.

TYPE: Fraction

FisherMarginalization dataclass

FisherMarginalization(computation: ComputationId, normalizer: ExactJvp, marginal_score: Fraction, outcomes: tuple[FisherOutcome, ...], source_steps: int, replays: int)

The exact marginalized unit and its Fisher score.

PARAMETER DESCRIPTION
computation

The checked source declaring the finite latent model.

TYPE: ComputationId

normalizer

The marginal observation weight and its derivative.

TYPE: ExactJvp

marginal_score

The directional derivative of the log normalizer, equal to the posterior expectation of the complete-data score.

TYPE: Fraction

outcomes

The full finite histories and their exact posterior actions.

TYPE: tuple[FisherOutcome, ...]

source_steps

The measured source work over all checked reference replays.

TYPE: int

replays

The number of complete and choice-suspended source runs.

TYPE: int

marginalize_bernoulli_unit

marginalize_bernoulli_unit(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_paths: int = 4096, fuel: int = 50000) -> FisherMarginalization

Marginalize a source unit over its finite Bernoulli alternatives.

The selected scalar computation returns the observation factor for each complete history. Every factor must be strictly positive at the given point. The checked Bernoulli and scalar rules ensure stable branches, open support and locally differentiable probabilities and factors. Positivity and the path bound give a valid finite posterior and log normalizer on a neighborhood of that point.

The marginalized score is exact without evaluating a logarithm. The function compares the posterior-weighted complete-data scores with the ordinary marginal derivative divided by the marginal weight.

PARAMETER DESCRIPTION
module

The source declaring the latent choices and observation factors.

TYPE: QiecModule

computation

The checked scalar entry on one nominal Random row.

TYPE: ComputationId

arguments

The exact parameter point and direction in parameter order.

TYPE: tuple[int or Fraction, ...]

direction

The exact parameter point and direction in parameter order.

TYPE: tuple[int or Fraction, ...]

policies

An explicit enumeration declaration for each reached static site.

TYPE: tuple[SiteEstimator, ...]

max_paths

Maximum number of complete latent histories.

TYPE: int DEFAULT: 4096

fuel

Maximum reference steps for each source run.

TYPE: int DEFAULT: 50000

RETURNS DESCRIPTION
FisherMarginalization

The evidence, posterior branch probabilities and directional scores.

RAISES DESCRIPTION
JvpUnsupported

If a policy excludes enumeration, a factor is nonpositive, or the checked probabilistic source leaves the finite scalar fragment.

JvpBoundaryError

If a parameter-dependent decision meets an equality boundary.

JvpLimit

If an arithmetic, path or replay bound is exceeded.

ValueError

If a bound, computation identity or input vector is malformed.

Source code in src/quivers/qiec/finite_marginalization.py
def marginalize_bernoulli_unit(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    max_paths: int = 4096,
    fuel: int = 50_000,
) -> FisherMarginalization:
    """Marginalize a source unit over its finite Bernoulli alternatives.

    The selected scalar computation returns the observation factor for
    each complete history. Every factor must be strictly positive at the
    given point. The checked Bernoulli and scalar rules ensure stable
    branches, open support and locally differentiable probabilities and
    factors. Positivity and the path bound give a valid finite posterior
    and log normalizer on a neighborhood of that point.

    The marginalized score is exact without evaluating a logarithm. The
    function compares the posterior-weighted complete-data scores with
    the ordinary marginal derivative divided by the marginal weight.

    Parameters
    ----------
    module : QiecModule
        The source declaring the latent choices and observation factors.
    computation : ComputationId
        The checked scalar entry on one nominal Random row.
    arguments, direction : tuple[int or Fraction, ...]
        The exact parameter point and direction in parameter order.
    policies : tuple[SiteEstimator, ...]
        An explicit enumeration declaration for each reached static site.
    max_paths : int
        Maximum number of complete latent histories.
    fuel : int
        Maximum reference steps for each source run.

    Returns
    -------
    FisherMarginalization
        The evidence, posterior branch probabilities and directional scores.

    Raises
    ------
    JvpUnsupported
        If a policy excludes enumeration, a factor is nonpositive, or the
        checked probabilistic source leaves the finite scalar fragment.
    JvpBoundaryError
        If a parameter-dependent decision meets an equality boundary.
    JvpLimit
        If an arithmetic, path or replay bound is exceeded.
    ValueError
        If a bound, computation identity or input vector is malformed.
    """
    finite = _checked_finite_unit(
        module, computation, arguments, direction, policies, max_paths, fuel
    )
    normalizer = finite.exact
    positive: list[tuple[tuple[bool, ...], ExactJvp, ExactJvp, ExactJvp]] = []
    for history, prior, node in _prior_histories(finite.tree):
        prefix = tuple(choice for _, choice in history)
        positive.append((prefix, prior, node, _positive_joint(prior, node, prefix)))

    assert normalizer.value > 0
    marginal_score = normalizer.tangent / normalizer.value
    _bound(marginal_score)
    outcomes: list[FisherOutcome] = []
    posterior_score = Fraction(0)
    for prefix, prior, observation, joint in positive:
        complete_score = joint.tangent / joint.value
        mass = joint.value / normalizer.value
        posterior = ExactJvp(mass, mass * (complete_score - marginal_score))
        _bound(complete_score, posterior.value, posterior.tangent)
        posterior_score += posterior.value * complete_score
        _bound(posterior_score)
        outcomes.append(
            FisherOutcome(prefix, prior, observation, joint, posterior, complete_score)
        )
    assert posterior_score == marginal_score
    return FisherMarginalization(
        computation,
        normalizer,
        marginal_score,
        tuple(outcomes),
        finite.source_steps,
        finite.replays,
    )

Finite importance sampling

plan_bernoulli_importance checks a target and a proposal at two separately supplied points for the same scalar source. The target supplies the prior probability times the positive observation factor. The proposal uses only its prior probabilities. These probabilities are held fixed in the target direction. Both evaluations use explicit enumerate policies to check every complete history.

The coverage check compares the ordered addresses and Boolean outcomes in each history. Distinct addresses can give distinct histories even when the Boolean outcomes are identical. A missing history raises ImportanceCoverageError with that original history and its positive target weight.

If \(w_h\) is the joint target weight and \(q_h\) is the proposal probability, a proposal draw returns \(w_h / q_h\) and \(w_h' / q_h\). Their means are the raw evidence and its directional derivative. Use the separate finite marginalization result for normalized posterior weights and the marginal log score.

from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, plan_bernoulli_importance

source = """
instance random : Random

define observed_unit(p : Real) : Real !{random} =
    let group <- perform random.sample[Bool](site("group"), Bernoulli(probs=p))
    if group then
        return 3.0
    else
        return 1.0
"""
module = Compiler(parse(source), module_name="finite-importance").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "observed_unit")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="enumerate")
plan = plan_bernoulli_importance(
    module, entry.id, (Fraction(1, 4),), (1,), (policy,),
    proposal_arguments=(Fraction(1, 2),), proposal_policies=(policy,),
)
assert (plan.exact.value, plan.exact.tangent) == (Fraction(3, 2), 2)
assert [outcome.estimate.tangent for outcome in plan.outcomes] == [-2, 6]
assert plan.sample(seed=12).estimate.value == Fraction(3, 2)

finite_importance

Exact importance estimates over checked finite addressed source histories.

ImportanceCoverageError

ImportanceCoverageError(history: _History, target_weight: Fraction)

Bases: JvpUnsupported

A positive target history has no proposal probability.

PARAMETER DESCRIPTION
history

The original chronological addresses and Boolean outcomes.

TYPE: tuple

target_weight

The positive target joint weight of this history.

TYPE: Fraction

Source code in src/quivers/qiec/finite_importance.py
def __init__(self, history: _History, target_weight: Fraction) -> None:
    super().__init__(
        f"finite proposal does not cover positive target history {history!r}"
    )
    self.history = history
    self.target_weight = target_weight

ImportanceCoverage dataclass

ImportanceCoverage(computation: ComputationId, target_point: tuple[Fraction, ...], proposal_point: tuple[Fraction, ...], histories: tuple[_History, ...])

Evidence that the checked proposal covers the target's addressed support.

PARAMETER DESCRIPTION
computation

The same nominal source computation used at both points.

TYPE: ComputationId

target_point

The exact parameter points whose supports were compared.

TYPE: tuple[Fraction, ...]

proposal_point

The exact parameter points whose supports were compared.

TYPE: tuple[Fraction, ...]

histories

Every positive target history, all matched by the proposal. Histories retain both the original addresses and the Boolean outcomes.

TYPE: tuple

ImportanceOutcome dataclass

ImportanceOutcome(history: _History, proposal: Fraction, target: ExactJvp, estimate: ExactJvp)

One proposal outcome and its exact held-fixed importance action.

PARAMETER DESCRIPTION
history

The original chronological addresses and Boolean outcomes.

TYPE: tuple

proposal

The ordinary prior probability at the distinct proposal point.

TYPE: Fraction

target

The target joint weight and its directional derivative.

TYPE: ExactJvp

estimate

The joint weight and derivative each divided by the same held-fixed proposal probability.

TYPE: ExactJvp

FiniteImportancePlan dataclass

FiniteImportancePlan(coverage: ImportanceCoverage, exact: ExactJvp, outcomes: tuple[ImportanceOutcome, ...], target_steps: int, proposal_steps: int, proposal_tree: ExactJvp | BernoulliBranch)

Exact coverage, expectation and proposal actions on the finite source.

PARAMETER DESCRIPTION
coverage

The support certified against the original addressed histories.

TYPE: ImportanceCoverage

exact

The unnormalized evidence and its directional derivative.

TYPE: ExactJvp

outcomes

The exact proposal law and estimator for each complete history.

TYPE: tuple[ImportanceOutcome, ...]

target_steps

The separately measured reference work at the two points.

TYPE: int

proposal_steps

The separately measured reference work at the two points.

TYPE: int

proposal_tree

The checked proposal source tree used to make the finite choices.

TYPE: ExactJvp or BernoulliBranch

sample

sample(*, seed: int | None = None) -> ImportanceOutcome

Draw one history from the original proposal probabilities.

PARAMETER DESCRIPTION
seed

An optional seed for the proposal's independent integer draws.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
ImportanceOutcome

The chosen history and one exact unnormalized importance estimate.

Source code in src/quivers/qiec/finite_importance.py
def sample(self, *, seed: int | None = None) -> ImportanceOutcome:
    """Draw one history from the original proposal probabilities.

    Parameters
    ----------
    seed : int or None
        An optional seed for the proposal's independent integer draws.

    Returns
    -------
    ImportanceOutcome
        The chosen history and one exact unnormalized importance estimate.
    """
    random = Random(seed)
    node = self.proposal_tree
    history: list[tuple[_Address, bool]] = []
    while isinstance(node, BernoulliBranch):
        p = node.visit.probability
        choice = random.randrange(p.denominator) < p.numerator
        history.append((node.visit.address, choice))
        node = node.yes if choice else node.no
    chosen = tuple(history)
    prefix = tuple(choice for _, choice in chosen)
    # Prior-tree traversal orders the complete, prefix-free Boolean histories.
    index = bisect_left(
        self.outcomes,
        prefix,
        key=lambda outcome: tuple(choice for _, choice in outcome.history),
    )
    outcome = self.outcomes[index]
    assert outcome.history == chosen
    return outcome

plan_bernoulli_importance

plan_bernoulli_importance(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, proposal_arguments: tuple[int | Fraction, ...], proposal_policies: tuple[SiteEstimator, ...], max_paths: int = 4096, fuel: int = 50000) -> FiniteImportancePlan

Check an exact finite proposal for a target observation unit.

The target point supplies the joint observation weights and their directional derivatives. The separately supplied proposal point supplies the prior branch probabilities, held fixed in that direction. Proposal return values do not tilt those probabilities. The check compares complete canonical address-outcome histories. In this full-support Bernoulli fragment, coverage entails matching the support of both finite trees.

An estimate divides both the target weight and its derivative by the same proposal probability. Its exact mean is the raw evidence and derivative supplied by ordinary target enumeration.

PARAMETER DESCRIPTION
module

The actual source used at both points.

TYPE: QiecModule

computation

Its scalar observation computation with one nominal Random row.

TYPE: ComputationId

arguments

The target point and directional perturbation.

TYPE: tuple[int or Fraction, ...]

direction

The target point and directional perturbation.

TYPE: tuple[int or Fraction, ...]

policies

An explicit enumerate policy for each reached target site.

TYPE: tuple[SiteEstimator, ...]

proposal_arguments

The held-fixed proposal point for the same source parameters.

TYPE: tuple[int or Fraction, ...]

proposal_policies

An explicit enumerate policy for each reached proposal site.

TYPE: tuple[SiteEstimator, ...]

max_paths

Bounds on complete histories at either point and steps per replay.

TYPE: int DEFAULT: 4096

fuel

Bounds on complete histories at either point and steps per replay.

TYPE: int DEFAULT: 4096

RETURNS DESCRIPTION
FiniteImportancePlan

Exact coverage and a checked estimator for the unnormalized unit.

RAISES DESCRIPTION
ImportanceCoverageError

If the proposal misses a positive addressed target history.

JvpUnsupported

If a factor is nonpositive or a source or policy leaves the finite scalar fragment.

JvpBoundaryError

If a parameter-dependent decision is at an equality boundary.

JvpLimit

If an arithmetic, path or replay bound is exceeded.

ValueError

If a bound, computation identity or input vector is malformed.

Source code in src/quivers/qiec/finite_importance.py
def plan_bernoulli_importance(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    proposal_arguments: tuple[int | Fraction, ...],
    proposal_policies: tuple[SiteEstimator, ...],
    max_paths: int = 4096,
    fuel: int = 50_000,
) -> FiniteImportancePlan:
    """Check an exact finite proposal for a target observation unit.

    The target point supplies the joint observation weights and their
    directional derivatives. The separately supplied proposal point
    supplies the prior branch probabilities, held fixed in that direction.
    Proposal return values do not tilt those probabilities. The check
    compares complete canonical address-outcome histories. In this
    full-support Bernoulli fragment, coverage entails matching the
    support of both finite trees.

    An estimate divides both the target weight and its derivative by the
    same proposal probability. Its exact mean is the raw evidence and
    derivative supplied by ordinary target enumeration.

    Parameters
    ----------
    module : QiecModule
        The actual source used at both points.
    computation : ComputationId
        Its scalar observation computation with one nominal Random row.
    arguments, direction : tuple[int or Fraction, ...]
        The target point and directional perturbation.
    policies : tuple[SiteEstimator, ...]
        An explicit enumerate policy for each reached target site.
    proposal_arguments : tuple[int or Fraction, ...]
        The held-fixed proposal point for the same source parameters.
    proposal_policies : tuple[SiteEstimator, ...]
        An explicit enumerate policy for each reached proposal site.
    max_paths, fuel : int
        Bounds on complete histories at either point and steps per replay.

    Returns
    -------
    FiniteImportancePlan
        Exact coverage and a checked estimator for the unnormalized unit.

    Raises
    ------
    ImportanceCoverageError
        If the proposal misses a positive addressed target history.
    JvpUnsupported
        If a factor is nonpositive or a source or policy leaves the finite
        scalar fragment.
    JvpBoundaryError
        If a parameter-dependent decision is at an equality boundary.
    JvpLimit
        If an arithmetic, path or replay bound is exceeded.
    ValueError
        If a bound, computation identity or input vector is malformed.
    """
    target = _checked_finite_unit(
        module, computation, arguments, direction, policies, max_paths, fuel
    )
    target_atoms = {
        history: _positive_joint(prior, factor, tuple(choice for _, choice in history))
        for history, prior, factor in _prior_histories(target.tree)
    }
    proposal = _checked_finite_unit(
        module,
        computation,
        proposal_arguments,
        (0,) * len(proposal_arguments),
        proposal_policies,
        max_paths,
        fuel,
    )
    proposal_atoms = {
        history: prior.value for history, prior, _ in _prior_histories(proposal.tree)
    }
    for history, atom in target_atoms.items():
        if proposal_atoms.get(history, 0) <= 0:
            raise ImportanceCoverageError(history, atom.value)
    assert target_atoms.keys() == proposal_atoms.keys()

    outcomes: list[ImportanceOutcome] = []
    expected_value = expected_tangent = Fraction(0)
    for history, q in proposal_atoms.items():
        atom = target_atoms[history]
        action = ExactJvp(atom.value / q, atom.tangent / q)
        _bound(action.value, action.tangent)
        expected_value += q * action.value
        expected_tangent += q * action.tangent
        _bound(expected_value, expected_tangent)
        outcomes.append(ImportanceOutcome(history, q, atom, action))
    assert (expected_value, expected_tangent) == (
        target.exact.value,
        target.exact.tangent,
    )
    return FiniteImportancePlan(
        ImportanceCoverage(
            computation,
            tuple(map(_fraction, arguments)),
            tuple(map(_fraction, proposal_arguments)),
            tuple(target_atoms),
        ),
        target.exact,
        tuple(outcomes),
        target.source_steps,
        proposal.source_steps,
        proposal.tree,
    )

Finite observation and intervention

compare_bernoulli_do_and_condition compares the effect of observing one addressed Boolean draw and fixing that draw to the same value. Both queries use a checked finite source model in which each draw is a separate probabilistic mechanism. The treatment and response addresses must occur on every complete history. The source returns a positive observation factor on each history.

Conditioning on the treatment retains its probability in the source weights. The intervention replaces that kernel by a point mass at the chosen value. The returned interventional weights omit the original probability of the treated draw and its derivative. The other kernels use their source probabilities at each history. Both queries include the source's observation factor and normalize with their own evidence.

from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import (
    AddressedBernoulliEvent,
    Bind,
    Perform,
    SiteEstimator,
    compare_bernoulli_do_and_condition,
)

source = """
instance random : Random

define propensity(c : Bool, p : Real) : Real !{} =
    if c then
        return 0.75
    else
        return p

define model(p : Real) : Real !{random} =
    let c <- perform random.sample[Bool](site("confounder"), Bernoulli(probs=0.5))
    let q <- propensity(c, p)
    let t <- perform random.sample[Bool](site("treatment"), Bernoulli(probs=q))
    return 1.0
"""
module = Compiler(parse(source), module_name="finite-intervention").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "model")
policies = []
term = entry.body
while isinstance(term, Bind):
    if isinstance(term.first, Perform):
        site = term.first.request.origin.static_site
        policies.append(SiteEstimator(site=site, estimator="enumerate"))
    term = term.then
confounder, treatment = policies
comparison = compare_bernoulli_do_and_condition(
    module, entry.id, (Fraction(1, 4),), (1,), tuple(policies),
    treatment=AddressedBernoulliEvent((str(treatment.site), (), ()), True),
    outcome=AddressedBernoulliEvent((str(confounder.site), (), ()), True),
)
assert (comparison.conditioned.value, comparison.conditioned.tangent) == (
    Fraction(3, 4), Fraction(-3, 4),
)
assert (comparison.intervened.value, comparison.intervened.tangent) == (
    Fraction(1, 2), 0,
)

finite_intervention

Compare observation and atomic intervention at one addressed Bernoulli draw.

AddressedBernoulliEvent dataclass

AddressedBernoulliEvent(address: _Address, value: bool)

A fixed Boolean outcome at an original canonical sample address.

PARAMETER DESCRIPTION
address

The full canonical source request address, including scope frames.

TYPE: tuple

value

The Boolean outcome at that address.

TYPE: bool

__post_init__

__post_init__() -> None

Require a Boolean outcome.

RAISES DESCRIPTION
ValueError

If the supplied outcome is not a Boolean.

Source code in src/quivers/qiec/finite_intervention.py
def __post_init__(self) -> None:
    """Require a Boolean outcome.

    Raises
    ------
    ValueError
        If the supplied outcome is not a Boolean.
    """
    if type(self.value) is not bool:
        raise ValueError("an addressed Bernoulli outcome must be Boolean")

CausalBernoulliHistory dataclass

CausalBernoulliHistory(history: _History, matches_outcome: bool, observational_weight: ExactJvp, interventional_weight: ExactJvp)

One history compatible with the selected treatment value.

PARAMETER DESCRIPTION
history

The chronological canonical addresses and Boolean outcomes.

TYPE: tuple

matches_outcome

Whether this history also has the requested response value.

TYPE: bool

observational_weight

The unnormalized weights with the source observation factor. The interventional weight omits only the treated kernel.

TYPE: ExactJvp

interventional_weight

The unnormalized weights with the source observation factor. The interventional weight omits only the treated kernel.

TYPE: ExactJvp

CausalBernoulliComparison dataclass

CausalBernoulliComparison(computation: ComputationId, treatment: AddressedBernoulliEvent, outcome: AddressedBernoulliEvent, conditioned: ExactJvp, intervened: ExactJvp, observational_evidence: ExactJvp, interventional_evidence: ExactJvp, histories: tuple[CausalBernoulliHistory, ...], source_steps: int)

Exact conditional and interventional responses on bounded source.

PARAMETER DESCRIPTION
computation

The named observational source and its autonomous ordered kernels.

TYPE: ComputationId

treatment

The selected treatment and response events.

TYPE: AddressedBernoulliEvent

outcome

The selected treatment and response events.

TYPE: AddressedBernoulliEvent

conditioned

The normalized response probability and derivative when observing or replacing the treated draw, respectively.

TYPE: ExactJvp

intervened

The normalized response probability and derivative when observing or replacing the treated draw, respectively.

TYPE: ExactJvp

observational_evidence

Each unnormalized denominator and its derivative.

TYPE: ExactJvp

interventional_evidence

Each unnormalized denominator and its derivative.

TYPE: ExactJvp

histories

The matched source histories and their weights before normalization.

TYPE: tuple[CausalBernoulliHistory, ...]

source_steps

The measured source work across the original finite enumeration.

TYPE: int

compare_bernoulli_do_and_condition

compare_bernoulli_do_and_condition(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, treatment: AddressedBernoulliEvent, outcome: AddressedBernoulliEvent, max_paths: int = 4096, fuel: int = 50000) -> CausalBernoulliComparison

Compare observing and fixing the same source Bernoulli outcome.

The checked scalar source specifies the joint process and returns one positive observation factor per history. Both queried addresses must occur in every history. The comparison treats the individual source kernels as autonomous mechanisms of this specified model.

Observational conditioning retains the probability of the chosen treatment in the original joint distribution. The intervention replaces that one conditional kernel by the chosen constant. Both sides retain the source observation factors, and normalize with their own evidence and quotient rule. Earlier and later kernels retain their original probabilities at their actual histories.

PARAMETER DESCRIPTION
module

The source supplying the actual Bernoulli kernels.

TYPE: QiecModule

computation

The scalar entry on one nominal Random instance.

TYPE: ComputationId

arguments

The parameter point and exact directional perturbation.

TYPE: tuple[int or Fraction, ...]

direction

The parameter point and exact directional perturbation.

TYPE: tuple[int or Fraction, ...]

policies

An explicit enumerate policy for each reached site.

TYPE: tuple[SiteEstimator, ...]

treatment

The fixed treatment and the queried response value.

TYPE: AddressedBernoulliEvent

outcome

The fixed treatment and the queried response value.

TYPE: AddressedBernoulliEvent

max_paths

Bounds on complete histories and steps per reference replay.

TYPE: int DEFAULT: 4096

fuel

Bounds on complete histories and steps per reference replay.

TYPE: int DEFAULT: 4096

RETURNS DESCRIPTION
CausalBernoulliComparison

Exact responses, evidence, and the contributing addressed histories.

RAISES DESCRIPTION
JvpUnsupported

If an address is missing on a history, an observation factor is nonpositive, or the source leaves the finite Bernoulli fragment.

JvpBoundaryError

If a parameter-dependent decision meets a comparison boundary.

JvpLimit

If the arithmetic or reference exploration exceeds a bound.

ValueError

If the entry, arguments or limits are malformed.

Source code in src/quivers/qiec/finite_intervention.py
def compare_bernoulli_do_and_condition(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    treatment: AddressedBernoulliEvent,
    outcome: AddressedBernoulliEvent,
    max_paths: int = 4096,
    fuel: int = 50_000,
) -> CausalBernoulliComparison:
    """Compare observing and fixing the same source Bernoulli outcome.

    The checked scalar source specifies the joint process and returns one
    positive observation factor per history. Both queried addresses must
    occur in every history. The comparison treats the individual source
    kernels as autonomous mechanisms of this specified model.

    Observational conditioning retains the probability of the chosen
    treatment in the original joint distribution. The intervention
    replaces that one conditional kernel by the chosen constant. Both
    sides retain the source observation factors, and normalize with their
    own evidence and quotient rule. Earlier and later kernels retain
    their original probabilities at their actual histories.

    Parameters
    ----------
    module : QiecModule
        The source supplying the actual Bernoulli kernels.
    computation : ComputationId
        The scalar entry on one nominal Random instance.
    arguments, direction : tuple[int or Fraction, ...]
        The parameter point and exact directional perturbation.
    policies : tuple[SiteEstimator, ...]
        An explicit enumerate policy for each reached site.
    treatment, outcome : AddressedBernoulliEvent
        The fixed treatment and the queried response value.
    max_paths, fuel : int
        Bounds on complete histories and steps per reference replay.

    Returns
    -------
    CausalBernoulliComparison
        Exact responses, evidence, and the contributing addressed histories.

    Raises
    ------
    JvpUnsupported
        If an address is missing on a history, an observation factor is
        nonpositive, or the source leaves the finite Bernoulli fragment.
    JvpBoundaryError
        If a parameter-dependent decision meets a comparison boundary.
    JvpLimit
        If the arithmetic or reference exploration exceeds a bound.
    ValueError
        If the entry, arguments or limits are malformed.
    """
    finite = _checked_finite_unit(
        module, computation, arguments, direction, policies, max_paths, fuel
    )
    visits = {visit.prefix: visit for visit in finite.visits}
    histories: list[CausalBernoulliHistory] = []
    action_priors: list[ExactJvp] = []
    for history, prior, factor in _prior_histories(finite.tree):
        prefix = tuple(choice for _, choice in history)
        addressed = {address: index for index, (address, _) in enumerate(history)}
        target_index = addressed.get(treatment.address)
        response_index = addressed.get(outcome.address)
        if target_index is None or response_index is None:
            missing = "treatment" if target_index is None else "outcome"
            raise JvpUnsupported(
                f"the {missing} address must occur on every source history, missing at {prefix!r}"
            )
        observed = _positive_joint(prior, factor, prefix)
        if prefix[target_index] != treatment.value:
            continue
        visit = visits[prefix[:target_index]]
        assert visit.address == treatment.address
        kernel = (
            ExactJvp(visit.probability, visit.tangent)
            if treatment.value
            else ExactJvp(1 - visit.probability, -visit.tangent)
        )
        action_priors.append(_quotient(prior, kernel))
        histories.append(
            CausalBernoulliHistory(
                history,
                prefix[response_index] == outcome.value,
                observed,
                _quotient(observed, kernel),
            )
        )
    assert _sum_weights(action_priors) == ExactJvp(Fraction(1), Fraction(0))
    obs_evidence = _sum_weights(atom.observational_weight for atom in histories)
    do_evidence = _sum_weights(atom.interventional_weight for atom in histories)
    selected = tuple(atom for atom in histories if atom.matches_outcome)
    obs_response = _sum_weights(atom.observational_weight for atom in selected)
    do_response = _sum_weights(atom.interventional_weight for atom in selected)
    return CausalBernoulliComparison(
        computation,
        treatment,
        outcome,
        _quotient(obs_response, obs_evidence),
        _quotient(do_response, do_evidence),
        obs_evidence,
        do_evidence,
        tuple(histories),
        finite.source_steps,
    )

Finite multinomial resampling

plan_multinomial_resampling checks one stage with an ordered input table of particle values and positive weights. Each value and weight has a directional derivative. Each offspring slot independently chooses an original position according to its normalized weight. Equal particle values remain distinct positions.

The native scalar objective receives the selected values in slot order, followed by its direct arguments. The default score estimate adds the objective times the sum of the selected log probability derivatives to the objective's derivative at fixed ancestry. Repeated positions contribute a score for each selecting slot. The plan enumerates all ordered assignments up to its bound and reports the exact expectation and derivative for this finite-step objective.

plan.audit_estimator(policy="detached") selects the fixed-ancestry derivative. It keeps derivatives through the selected particle values and the direct arguments. The audit averages these derivatives under the original ordered ancestry law. Its signed bias is the mean estimate minus the exact derivative at the checked inputs and direction. audit.sample uses the same sampler and retains each ancestry's positions, probability, and score. The detached audit visits each stored outcome once. This is a host policy for the finite plan.

The expectation depends on the declared objective. For instance, an unnormalized estimate of 1 or 3 with equal probability has mean 2. Its expected logarithm is \(\log\sqrt{3}\), which is below \(\log 2\).

from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import (
    Bind,
    Perform,
    ResamplingParticle,
    SiteEstimator,
    marginalize_bernoulli_unit,
    plan_multinomial_resampling,
)

source = """
instance random : Random

define observed(p : Real) : Real !{random} =
    let chosen <- perform random.sample[Bool](site("chosen"), Bernoulli(probs=p))
    if chosen then
        return 3.0
    else
        return 1.0

define objective(first : Real, second : Real) : Real !{} =
    return first + 2.0 * second
"""
module = Compiler(parse(source), module_name="multinomial-resampling").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "observed")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="enumerate")
fit = marginalize_bernoulli_unit(module, entry.id, (Fraction(1, 4),), (1,), (policy,))
particles = tuple(ResamplingParticle(x.observation, x.joint) for x in fit.outcomes)
plan = plan_multinomial_resampling(module, "objective", particles)
assert len(plan.outcomes) == 4
assert (plan.exact.value, plan.exact.tangent) == (6, 8)
detached = plan.audit_estimator(policy="detached")
assert (detached.mean.value, detached.mean.tangent) == (6, 0)
assert detached.signed_bias == -8
assert detached.sample(seed=13).positions == plan.sample(seed=13).positions

finite_resampling

Exact ordered multinomial ancestry for a checked, finite-step objective.

ResamplingParticle dataclass

ResamplingParticle(value: ExactJvp, weight: ExactJvp)

The exact represented value and weight at one particle position.

PARAMETER DESCRIPTION
value

Its scalar value and directional derivative.

TYPE: ExactJvp

weight

Its positive unnormalized weight and directional derivative.

TYPE: ExactJvp

ResamplingAncestor dataclass

ResamplingAncestor(position: int, value: ExactJvp, probability: ExactJvp, score: Fraction)

One position with its categorical probability and score.

PARAMETER DESCRIPTION
position

The original zero-based position in the ordered particle table.

TYPE: int

value

The scalar and directional derivative at this position.

TYPE: ExactJvp

probability

The normalized probability of choosing this position and its derivative.

TYPE: ExactJvp

score

The exact directional derivative of its log probability.

TYPE: Fraction

ResamplingOutcome dataclass

ResamplingOutcome(positions: tuple[int, ...], probability: ExactJvp, objective: ExactJvp, ancestry_score: Fraction, estimate: ExactJvp)

The native finite objective and its estimate for one ordered ancestry.

PARAMETER DESCRIPTION
positions

The original ancestor position selected for each offspring slot.

TYPE: tuple[int, ...]

probability

The mass and derivative of this whole ordered ancestry.

TYPE: ExactJvp

objective

The checked objective and its directional derivative for these fixed positions.

TYPE: ExactJvp

ancestry_score

The sum of the selected log probability derivatives across slots.

TYPE: Fraction

estimate

The sampled objective and its derivative estimate under the chosen policy.

TYPE: ExactJvp

MultinomialResamplingPlan dataclass

MultinomialResamplingPlan(objective: ComputationId, draws: int, total_weight: ExactJvp, exact: ExactJvp, ancestors: tuple[ResamplingAncestor, ...], outcomes: tuple[ResamplingOutcome, ...], source_steps: int, selector_probabilities: tuple[Fraction, ...])

A complete exact finite multinomial stage for the declared objective.

PARAMETER DESCRIPTION
objective

The actual checked scalar source computation.

TYPE: ComputationId

draws

The number of independent ordered offspring slots.

TYPE: int

total_weight

The original particle weight sum and its derivative.

TYPE: ExactJvp

exact

The expected finite-step objective and its directional derivative.

TYPE: ExactJvp

ancestors

The normalized table of original particle positions.

TYPE: tuple[ResamplingAncestor, ...]

outcomes

Every ordered assignment with its exact probability and estimate.

TYPE: tuple[ResamplingOutcome, ...]

source_steps

The total measured reference work over the checked objective runs.

TYPE: int

selector_probabilities

The exact sequential conditional probabilities for one categorical draw. The last position is the complement of all earlier choices.

TYPE: tuple[Fraction, ...]

sample

sample(*, seed: int | None = None) -> ResamplingOutcome

Choose one complete ancestry from the exact multinomial law.

PARAMETER DESCRIPTION
seed

An optional seed for independent exact integer choices.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
ResamplingOutcome

The sampled ordered positions and their score-corrected estimate.

Source code in src/quivers/qiec/finite_resampling.py
def sample(self, *, seed: int | None = None) -> ResamplingOutcome:
    """Choose one complete ancestry from the exact multinomial law.

    Parameters
    ----------
    seed : int or None
        An optional seed for independent exact integer choices.

    Returns
    -------
    ResamplingOutcome
        The sampled ordered positions and their score-corrected estimate.
    """
    random = Random(seed)
    count = len(self.ancestors)
    index = 0
    for _ in range(self.draws):
        position = _choose_position(self.selector_probabilities, random)
        index = index * count + position
    return self.outcomes[index]

audit_estimator

audit_estimator(*, policy: Literal['score', 'detached'] = 'score') -> ResamplingEstimatorAudit

Compute the selected estimator's finite mean and signed bias.

PARAMETER DESCRIPTION
policy

Include the ancestry score or retain only the checked objective's derivative at fixed ancestry.

TYPE: ('score', 'detached') DEFAULT: "score"

RETURNS DESCRIPTION
ResamplingEstimatorAudit

The exact pointwise mean and bias over this plan's ordered law.

RAISES DESCRIPTION
ValueError

If the policy is unknown.

JvpLimit

If exact arithmetic exceeds the coefficient bound.

Source code in src/quivers/qiec/finite_resampling.py
def audit_estimator(
    self, *, policy: Literal["score", "detached"] = "score"
) -> ResamplingEstimatorAudit:
    """Compute the selected estimator's finite mean and signed bias.

    Parameters
    ----------
    policy : {"score", "detached"}
        Include the ancestry score or retain only the checked objective's
        derivative at fixed ancestry.

    Returns
    -------
    ResamplingEstimatorAudit
        The exact pointwise mean and bias over this plan's ordered law.

    Raises
    ------
    ValueError
        If the policy is unknown.
    JvpLimit
        If exact arithmetic exceeds the coefficient bound.
    """
    if type(policy) is not str or policy not in ("score", "detached"):
        raise ValueError("resampling policy must be 'score' or 'detached'")
    tangent = self.exact.tangent
    if policy == "detached":
        tangent = Fraction(0)
        for outcome in self.outcomes:
            tangent += outcome.probability.value * outcome.objective.tangent
            _bound(tangent)
    bias = tangent - self.exact.tangent
    _bound(bias)
    return ResamplingEstimatorAudit(
        self, policy, ExactJvp(self.exact.value, tangent), bias
    )

ResamplingEstimatorAudit dataclass

ResamplingEstimatorAudit(source: MultinomialResamplingPlan, policy: Literal['score', 'detached'], mean: ExactJvp, signed_bias: Fraction)

A policy and its exact bias for one checked finite resampling plan.

PARAMETER DESCRIPTION
source

The checked objective, directed inputs and ordered ancestry law.

TYPE: MultinomialResamplingPlan

policy

The derivative contribution to use for each sampled ancestry.

TYPE: ('score', 'detached') DEFAULT: "score"

mean

The expectation of the sampled value and derivative estimate.

TYPE: ExactJvp

signed_bias

The mean derivative estimate minus the exact objective derivative at the plan's parameter point and direction.

TYPE: Fraction

sample

sample(*, seed: int | None = None) -> ResamplingOutcome

Sample the original ancestry law with the audited policy.

PARAMETER DESCRIPTION
seed

An optional seed for the original exact integer choices.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
ResamplingOutcome

The original positions, mass and score, with the audited estimate.

Source code in src/quivers/qiec/finite_resampling.py
def sample(self, *, seed: int | None = None) -> ResamplingOutcome:
    """Sample the original ancestry law with the audited policy.

    Parameters
    ----------
    seed : int or None
        An optional seed for the original exact integer choices.

    Returns
    -------
    ResamplingOutcome
        The original positions, mass and score, with the audited estimate.
    """
    outcome = self.source.sample(seed=seed)
    if self.policy == "detached":
        return replace(outcome, estimate=outcome.objective)
    return outcome

plan_multinomial_resampling

plan_multinomial_resampling(module: QiecModule, objective: str, particles: tuple[ResamplingParticle, ...], *, arguments: tuple[int | Fraction, ...] = (), direction: tuple[int | Fraction, ...] = (), max_outcomes: int = 4096, fuel: int = 65536) -> MultinomialResamplingPlan

Check one finite, ordered multinomial resampling stage.

The closed scalar objective takes one selected value per offspring slot, followed by any direct arguments. The particle jets and direct argument directions supply its fixed-ancestry directional action. Strict positivity preserves the normalized support locally. Every possible ordered ancestry must pass the exact scalar source checks.

The derivative estimate adds the objective times the sum of the ancestor scores to that directional action. The sum counts each offspring slot, including repeated choices of the same position. The exact result integrates the declared finite-step objective.

PARAMETER DESCRIPTION
module

The source of the declared scalar objective.

TYPE: QiecModule

objective

The name of the closed scalar objective with at least one slot.

TYPE: str

particles

The ordered, nonempty input table of value and weight jets.

TYPE: tuple[ResamplingParticle, ...]

arguments

The exact direct arguments and directions after the offspring slots in the objective's positional parameters.

TYPE: tuple[int or Fraction, ...] DEFAULT: ()

direction

The exact direct arguments and directions after the offspring slots in the objective's positional parameters.

TYPE: tuple[int or Fraction, ...] DEFAULT: ()

max_outcomes

The maximum number of complete ordered assignments.

TYPE: int DEFAULT: 4096

fuel

The reference step bound for each objective evaluation.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
MultinomialResamplingPlan

The checked ancestry law, exact objective and sampled estimator.

RAISES DESCRIPTION
ValueError

If inputs, objective arity or a bound is malformed.

JvpUnsupported

If weights are nonpositive or a reached source action is unsupported.

JvpBoundaryError

If an admitted objective branch meets an input-dependent equality.

JvpLimit

If assignment count, arithmetic or reference steps exceed a bound.

Source code in src/quivers/qiec/finite_resampling.py
def plan_multinomial_resampling(
    module: QiecModule,
    objective: str,
    particles: tuple[ResamplingParticle, ...],
    *,
    arguments: tuple[int | Fraction, ...] = (),
    direction: tuple[int | Fraction, ...] = (),
    max_outcomes: int = 4096,
    fuel: int = 65_536,
) -> MultinomialResamplingPlan:
    """Check one finite, ordered multinomial resampling stage.

    The closed scalar objective takes one selected value per offspring
    slot, followed by any direct arguments. The particle jets and direct
    argument directions supply its fixed-ancestry directional action.
    Strict positivity preserves the normalized support locally. Every
    possible ordered ancestry must pass the exact scalar source checks.

    The derivative estimate adds the objective times the sum of the
    ancestor scores to that directional action. The sum counts each
    offspring slot, including repeated choices of the same position.
    The exact result integrates the declared finite-step objective.

    Parameters
    ----------
    module : QiecModule
        The source of the declared scalar objective.
    objective : str
        The name of the closed scalar objective with at least one slot.
    particles : tuple[ResamplingParticle, ...]
        The ordered, nonempty input table of value and weight jets.
    arguments, direction : tuple[int or Fraction, ...]
        The exact direct arguments and directions after the offspring
        slots in the objective's positional parameters.
    max_outcomes : int
        The maximum number of complete ordered assignments.
    fuel : int
        The reference step bound for each objective evaluation.

    Returns
    -------
    MultinomialResamplingPlan
        The checked ancestry law, exact objective and sampled estimator.

    Raises
    ------
    ValueError
        If inputs, objective arity or a bound is malformed.
    JvpUnsupported
        If weights are nonpositive or a reached source action is unsupported.
    JvpBoundaryError
        If an admitted objective branch meets an input-dependent equality.
    JvpLimit
        If assignment count, arithmetic or reference steps exceed a bound.
    """
    _validate_limit("max_outcomes", max_outcomes)
    if not particles:
        raise ValueError(
            "finite multinomial resampling needs a nonempty particle table"
        )
    if len(arguments) != len(direction):
        raise ValueError("direct arguments and direction must have equal arity")
    registry, declaration = _prepare_scalar(module, objective, fuel)
    draws = len(declaration.parameters) - len(arguments)
    if draws < 1:
        raise ValueError("the resampling objective needs at least one offspring slot")
    count = 1
    for _ in range(draws):
        count *= len(particles)
        if count > max_outcomes:
            raise JvpLimit(
                f"multinomial resampling exceeds {max_outcomes} ordered assignments"
            )
    ancestors, total_weight, selectors = _ancestor_table(particles)
    direct = tuple(
        _dual(_fraction(value), _fraction(tangent), True)
        for value, tangent in zip(arguments, direction, strict=True)
    )
    seeds = tuple(
        _dual(ancestor.value.value, ancestor.value.tangent, True)
        for ancestor in ancestors
    )
    outcomes: list[ResamplingOutcome] = []
    mean = derivative = expected_estimator = Fraction(0)
    mass_total = mass_tangent = Fraction(0)
    source_steps = 0
    for positions in product(range(len(ancestors)), repeat=draws):
        evaluator = _ScalarDerivativeEvaluator(module=module, fuel=fuel)
        positional = tuple(seeds[position] for position in positions)
        environment = dict(
            zip(declaration.parameters, (*positional, *direct), strict=True)
        )
        source = _run_derivative(evaluator, declaration, registry, environment)
        assert isinstance(source, _Dual)
        source_steps += evaluator._steps
        mass, slope, score = Fraction(1), Fraction(0), Fraction(0)
        for position in positions:
            ancestor = ancestors[position]
            p = ancestor.probability
            slope = slope * p.value + mass * p.tangent
            mass *= p.value
            score += ancestor.score
            _bound(mass, slope, score)
        assert slope == mass * score
        cost = ExactJvp(source.value, source.tangent)
        estimate = ExactJvp(cost.value, cost.tangent + cost.value * score)
        _bound(estimate.value, estimate.tangent)
        mean += mass * cost.value
        derivative += slope * cost.value + mass * cost.tangent
        expected_estimator += mass * estimate.tangent
        mass_total += mass
        mass_tangent += slope
        _bound(mean, derivative, expected_estimator, mass_total, mass_tangent)
        outcomes.append(
            ResamplingOutcome(positions, ExactJvp(mass, slope), cost, score, estimate)
        )
    assert derivative == expected_estimator and mass_total == 1 and mass_tangent == 0
    return MultinomialResamplingPlan(
        declaration.id,
        draws,
        total_weight,
        ExactJvp(mean, derivative),
        ancestors,
        tuple(outcomes),
        source_steps,
        selectors,
    )

Finite unit subsampling

plan_unit_subsampling checks a fixed design for an additive finite population total. The design lists complete subsets of whole unit positions and their exact probabilities. Every unit needs positive inclusion probability. The estimator divides each selected unit's value and directional derivative by that unit's inclusion probability, then sums the selected contributions. Its expectation gives the full total and its derivative.

Use UnitSubset.from_plate_rows for the existing plate index format when each row is a whole unit. Uniform samples of a fixed size recover the existing size-over-sample-size coefficient. A design with unequal inclusion probabilities uses a separate coefficient for each unit.

The log likelihood of positive observation factors \(L_i\) has an additive directional score \(\sum_i L_i' / L_i\). Applying the inclusion weights to those scores estimates that separate sum. The log of a sampled raw total instead depends on the distribution of that whole estimate.

from fractions import Fraction
import torch
from quivers.dsl import Compiler, parse
from quivers.qiec import UnitSubset, exact_jvp, plan_unit_subsampling

source = """
define unit(x : Real, theta : Real) : Real !{} =
    return x * theta
"""
module = Compiler(parse(source), module_name="unit-subsampling").qiec_module
assert module is not None
units = tuple(exact_jvp(module, "unit", (x, 2), (0, 1)) for x in (1, 3))
design = tuple(
    UnitSubset.from_plate_rows("Units", torch.tensor([i]), Fraction(1, 2))
    for i in range(2)
)
plan = plan_unit_subsampling(units, design)
assert plan.inclusion_probabilities == (Fraction(1, 2), Fraction(1, 2))
assert (plan.exact.value, plan.exact.tangent) == (8, 4)
assert [action.estimate.value for action in plan.outcomes] == [4, 12]

finite_subsampling

Exact first-order inclusion weights for fixed finite unit subsampling.

UnitSubset dataclass

UnitSubset(positions: tuple[int, ...], probability: Fraction)

One sample of whole unit positions with its ordinary design probability.

PARAMETER DESCRIPTION
positions

The strictly increasing zero-based positions of the units kept.

TYPE: tuple[int, ...]

probability

The fixed probability of drawing this complete subset.

TYPE: Fraction

from_plate_rows classmethod

from_plate_rows(plate: str, rows: Tensor, probability: int | Fraction) -> UnitSubset

Read the existing plate row format for an axis of whole units.

PARAMETER DESCRIPTION
plate

The axis name used by the plate subsampling handler.

TYPE: str

rows

Its ordinary subsample index. Positions must identify whole units.

TYPE: Tensor

probability

The fixed probability of this complete subset.

TYPE: int or Fraction

RETURNS DESCRIPTION
UnitSubset

The validated positions and exact design probability.

RAISES DESCRIPTION
ValueError

If the row format or probability is malformed.

Source code in src/quivers/qiec/finite_subsampling.py
@classmethod
def from_plate_rows(
    cls, plate: str, rows: Tensor, probability: int | Fraction
) -> UnitSubset:
    """Read the existing plate row format for an axis of whole units.

    Parameters
    ----------
    plate : str
        The axis name used by the plate subsampling handler.
    rows : Tensor
        Its ordinary subsample index. Positions must identify whole units.
    probability : int or Fraction
        The fixed probability of this complete subset.

    Returns
    -------
    UnitSubset
        The validated positions and exact design probability.

    Raises
    ------
    ValueError
        If the row format or probability is malformed.
    """
    from quivers.effects.subsample import SubsampleHandler

    selection = SubsampleHandler(plate, rows).index
    return cls(tuple(selection.tolist()), _fraction(probability))

UnitSubsampleEstimate dataclass

UnitSubsampleEstimate(subset: UnitSubset, estimate: ExactJvp)

The raw total estimate and derivative on one finite whole-unit subset.

PARAMETER DESCRIPTION
subset

The actual positions and probability used by the design.

TYPE: UnitSubset

estimate

The inverse-inclusion weighted sum of selected unit jets.

TYPE: ExactJvp

FiniteUnitSubsamplingPlan dataclass

FiniteUnitSubsamplingPlan(exact: ExactJvp, inclusion_probabilities: tuple[Fraction, ...], outcomes: tuple[UnitSubsampleEstimate, ...], work: int, selector_probabilities: tuple[Fraction, ...])

A finite design verified for a raw additive unit objective.

PARAMETER DESCRIPTION
exact

The full population total and its directional derivative.

TYPE: ExactJvp

inclusion_probabilities

Probability of including each original unit position.

TYPE: tuple[Fraction, ...]

outcomes

Every declared subset and its exact weighted action.

TYPE: tuple[UnitSubsampleEstimate, ...]

work

Total unit positions and subset memberships checked.

TYPE: int

selector_probabilities

The exact sequential conditional probabilities used to draw a subset.

TYPE: tuple[Fraction, ...]

sample

sample(*, seed: int | None = None) -> UnitSubsampleEstimate

Draw one subset from the declared exact design.

PARAMETER DESCRIPTION
seed

An optional seed for independent uniform integer draws.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
UnitSubsampleEstimate

The selected whole units and their raw weighted estimate.

Source code in src/quivers/qiec/finite_subsampling.py
def sample(self, *, seed: int | None = None) -> UnitSubsampleEstimate:
    """Draw one subset from the declared exact design.

    Parameters
    ----------
    seed : int or None
        An optional seed for independent uniform integer draws.

    Returns
    -------
    UnitSubsampleEstimate
        The selected whole units and their raw weighted estimate.
    """
    selected = _choose_position(self.selector_probabilities, Random(seed))
    return self.outcomes[selected]

plan_unit_subsampling

plan_unit_subsampling(units: tuple[ExactJvp, ...], design: tuple[UnitSubset, ...], *, max_outcomes: int = 4096, max_work: int = 250000) -> FiniteUnitSubsamplingPlan

Check exact subsampling of a fixed finite sum of whole unit returns.

Each input is an exact scalar contribution and its directional derivative, such as an exact source JVP or a finite marginalized unit's raw normalizer. The design is fixed in that direction. The probability of including a unit is the sum of probabilities of the declared subsets containing its position. Every unit needs positive inclusion probability.

Dividing each selected value and derivative by that probability makes the two expected sums equal their full-population totals. This is an additive objective. A log likelihood score for a unit can enter as a separately defined additive contribution.

PARAMETER DESCRIPTION
units

A nonempty ordered table containing one exact jet per whole unit.

TYPE: tuple[ExactJvp, ...]

design

The full, fixed probability law of nonempty sorted subsets.

TYPE: tuple[UnitSubset, ...]

max_outcomes

The maximum number of distinct declared subsets.

TYPE: int DEFAULT: 4096

max_work

The maximum total of unit positions and subset memberships.

TYPE: int DEFAULT: 250000

RETURNS DESCRIPTION
FiniteUnitSubsamplingPlan

The checked inclusion probabilities and raw total estimator.

RAISES DESCRIPTION
ValueError

If the whole unit table, subset law or a limit is malformed.

JvpUnsupported

If a unit is absent from the positive-probability design.

JvpLimit

If the checked subset count, memberships or arithmetic exceed a bound.

Source code in src/quivers/qiec/finite_subsampling.py
def plan_unit_subsampling(
    units: tuple[ExactJvp, ...],
    design: tuple[UnitSubset, ...],
    *,
    max_outcomes: int = 4096,
    max_work: int = 250_000,
) -> FiniteUnitSubsamplingPlan:
    """Check exact subsampling of a fixed finite sum of whole unit returns.

    Each input is an exact scalar contribution and its directional
    derivative, such as an exact source JVP or a finite marginalized
    unit's raw normalizer. The design is fixed in that direction. The
    probability of including a unit is the sum of probabilities of the
    declared subsets containing its position. Every unit needs positive
    inclusion probability.

    Dividing each selected value and derivative by that probability
    makes the two expected sums equal their full-population totals.
    This is an additive objective. A log likelihood score for a unit can
    enter as a separately defined additive contribution.

    Parameters
    ----------
    units : tuple[ExactJvp, ...]
        A nonempty ordered table containing one exact jet per whole unit.
    design : tuple[UnitSubset, ...]
        The full, fixed probability law of nonempty sorted subsets.
    max_outcomes : int
        The maximum number of distinct declared subsets.
    max_work : int
        The maximum total of unit positions and subset memberships.

    Returns
    -------
    FiniteUnitSubsamplingPlan
        The checked inclusion probabilities and raw total estimator.

    Raises
    ------
    ValueError
        If the whole unit table, subset law or a limit is malformed.
    JvpUnsupported
        If a unit is absent from the positive-probability design.
    JvpLimit
        If the checked subset count, memberships or arithmetic exceed a bound.
    """
    _validate_limit("max_outcomes", max_outcomes)
    _validate_limit("max_work", max_work)
    if not units or not design:
        raise ValueError("unit subsampling needs nonempty units and subset design")
    if len(design) > max_outcomes:
        raise JvpLimit(f"unit subsampling exceeds {max_outcomes} distinct subsets")
    work = len(units) + sum(len(item.positions) for item in design)
    if work > max_work:
        raise JvpLimit(
            f"unit subsampling exceeds {max_work} unit positions and memberships"
        )

    atoms: list[UnitSubset] = []
    inclusion = [Fraction(0)] * len(units)
    seen: set[tuple[int, ...]] = set()
    probability_total = Fraction(0)
    for subset in design:
        positions = subset.positions
        if (
            not isinstance(positions, tuple)
            or not positions
            or any(
                type(index) is not int or not 0 <= index < len(units)
                for index in positions
            )
            or any(left >= right for left, right in zip(positions, positions[1:]))
        ):
            raise ValueError(
                "a unit subset needs distinct positions in increasing order within the population"
            )
        if positions in seen:
            raise ValueError("the unit design declares the same subset twice")
        seen.add(positions)
        probability = _fraction(subset.probability)
        if not 0 < probability <= 1:
            raise ValueError(
                "unit subset probabilities must be strictly positive and at most one"
            )
        _bound(probability)
        probability_total += probability
        _bound(probability_total)
        for index in positions:
            inclusion[index] += probability
            _bound(inclusion[index])
        atoms.append(UnitSubset(positions, probability))
    if probability_total != 1:
        raise ValueError("unit subset probabilities must sum to one")
    missing = next(
        (index for index, probability in enumerate(inclusion) if not probability), None
    )
    if missing is not None:
        raise JvpUnsupported(
            f"whole unit position {missing} has zero inclusion probability"
        )

    expected = expected_tangent = total = tangent_total = Fraction(0)
    actions: list[ExactJvp] = []
    for unit, probability in zip(units, inclusion, strict=True):
        value, tangent = _fraction(unit.value), _fraction(unit.tangent)
        _bound(value, tangent)
        total += value
        tangent_total += tangent
        action = ExactJvp(value / probability, tangent / probability)
        _bound(total, tangent_total, action.value, action.tangent)
        actions.append(action)
    outputs: list[UnitSubsampleEstimate] = []
    for subset in atoms:
        value = tangent = Fraction(0)
        for index in subset.positions:
            value += actions[index].value
            tangent += actions[index].tangent
            _bound(value, tangent)
        expected += subset.probability * value
        expected_tangent += subset.probability * tangent
        _bound(expected, expected_tangent)
        outputs.append(UnitSubsampleEstimate(subset, ExactJvp(value, tangent)))
    assert (expected, expected_tangent) == (total, tangent_total)
    return FiniteUnitSubsamplingPlan(
        ExactJvp(total, tangent_total),
        tuple(inclusion),
        tuple(outputs),
        work,
        _selector_probabilities(tuple(subset.probability for subset in atoms)),
    )

Finite-step Metropolis derivatives

finite_metropolis_jvp takes an initial law, positive target weights, and a proposal kernel on the same finite state space. Its inputs are values and tangents of differentiable curves. The initial law and each proposal row are normalized, with zero total tangent. The Metropolis transition from \(i\) to \(j\ne i\) has mass \(P_{ij}=\min(q_{ij},\,w_jq_{ji}/w_i)\). The diagonal collects the remaining mass, including rejected proposals. Hastings (1970, §2.2)

At a strict minimum the active expression gives the tangent. At an equality, the two expressions must have the same directional slope for this comparison to be admitted. If the initial row is \(u_0\), the recurrence propagates

\[ u_{k+1}=u_kP, \qquad \dot u_{k+1}=\dot u_k P+u_k\dot P. \]

The result is the law after the requested number of steps, with separate contributions from the initial law and the transition law. For \(n\) states and \(k\) positive steps, the recurrence uses \(O((1+k)n^2)\) rational arithmetic operations. Rational coefficient bit lengths contribute separately to runtime.

audit_finite_metropolis_acceptance compares two directional actions on this same finite law. For an off-diagonal move with positive proposal probability, the detached action keeps \((P_{ij}/q_{ij})Dq_{ij}\). The probability of proposing a move and the initial law keep their derivatives. The derivative of the accept or reject probability is omitted in the detached action. An admitted zero proposal contributes zero. Each diagonal tangent is the negative sum of its row's off-diagonal tangents. The audit reports the detached tangent minus the exact tangent in the original state order. Both actions require the same acceptance tie checks.

For positive \(k\), the audit adds \((1+k)n^2\) work positions to the ordinary preflight, one per state pair for the tangent difference table and one per state pair at each step. At zero steps, the audit returns the initial law with zero bias.

from fractions import Fraction

from quivers.dsl import loads
from quivers.qiec import (
    ExactJvp,
    audit_finite_metropolis_acceptance,
    exact_jvp,
    finite_metropolis_jvp,
)

module = loads("""
define target_weight(t : Real) : Real !{} =
    return t
""").qiec
assert module is not None

def constant(value):
    return ExactJvp(Fraction(value), Fraction(0))

second_weight = exact_jvp(module, "target_weight", (Fraction(1, 4),), (1,))
proposal = (
    (constant(Fraction(3, 4)), constant(Fraction(1, 4))),
    (constant(Fraction(1, 2)), constant(Fraction(1, 2))),
)
law = finite_metropolis_jvp(
    (constant(1), constant(0)), (constant(1), second_weight), proposal, steps=2
)
assert law[1] == ExactJvp(Fraction(11, 64), Fraction(5, 8))
audit = audit_finite_metropolis_acceptance(
    (constant(1), constant(0)), (constant(1), second_weight), proposal, steps=2
)
assert audit.exact == law
assert audit.detached[1] == constant(Fraction(11, 64))
assert audit.signed_bias[1] == -Fraction(5, 8)

finite_metropolis

Exact directional derivatives of finite-step Metropolis--Hastings laws.

MetropolisAcceptanceAudit dataclass

MetropolisAcceptanceAudit(steps: int, exact: tuple[ExactJvp, ...], detached: tuple[ExactJvp, ...], signed_bias: tuple[Fraction, ...])

The effects of detaching acceptance at one checked point and direction.

PARAMETER DESCRIPTION
steps

The exact number of transitions.

TYPE: int

exact

The finite law and exact tangent in the original state order.

TYPE: tuple of ExactJvp

detached

The same law with only the initial and proposal derivatives.

TYPE: tuple of ExactJvp

signed_bias

The detached tangent minus the exact tangent for each state.

TYPE: tuple of Fraction

finite_metropolis_jvp

finite_metropolis_jvp(initial: tuple[ExactJvp, ...], target: tuple[ExactJvp, ...], proposal: tuple[tuple[ExactJvp, ...], ...], *, steps: int, max_work: int = 65536) -> tuple[ExactJvp, ...]

Return the exact law and directional derivative after a fixed number of steps.

Inputs give values and directional derivatives of differentiable curves through the point. The initial and proposal curves are normalized and nonnegative in a neighborhood. The target curve is positive and may be unnormalized. Equal acceptance values have a directional derivative when their directional slopes agree. The recurrence propagates both rejection and acceptance derivatives.

PARAMETER DESCRIPTION
initial

The initial law and its tangent in finite-state order.

TYPE: tuple[ExactJvp, ...]

target

The positive target masses and their tangents in the same order.

TYPE: tuple[ExactJvp, ...]

proposal

For each source state, its normalized proposal row and tangent.

TYPE: tuple[tuple[ExactJvp, ...], ...]

steps

The exact number of transitions after initialization.

TYPE: int

max_work

The maximum number of table positions for validation, transition construction and recurrence steps, measured as an arithmetic work bound independent of coefficient bit length.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
tuple[ExactJvp, ...]

One mass and tangent per state in the finite-step law.

RAISES DESCRIPTION
ValueError

If the dimensions, limits, or pointwise measure conditions fail.

JvpBoundaryError

If an acceptance tie has unequal slopes along the supplied direction.

JvpLimit

If the arithmetic work bound would be exceeded.

Source code in src/quivers/qiec/finite_metropolis.py
def finite_metropolis_jvp(
    initial: tuple[ExactJvp, ...],
    target: tuple[ExactJvp, ...],
    proposal: tuple[tuple[ExactJvp, ...], ...],
    *,
    steps: int,
    max_work: int = 65_536,
) -> tuple[ExactJvp, ...]:
    """Return the exact law and directional derivative after a fixed number of steps.

    Inputs give values and directional derivatives of differentiable
    curves through the point. The initial and proposal curves are
    normalized and nonnegative in a neighborhood. The target curve is
    positive and may be unnormalized. Equal acceptance values have a
    directional derivative when their directional slopes agree. The
    recurrence propagates both rejection and acceptance derivatives.

    Parameters
    ----------
    initial : tuple[ExactJvp, ...]
        The initial law and its tangent in finite-state order.
    target : tuple[ExactJvp, ...]
        The positive target masses and their tangents in the same order.
    proposal : tuple[tuple[ExactJvp, ...], ...]
        For each source state, its normalized proposal row and tangent.
    steps : int
        The exact number of transitions after initialization.
    max_work : int
        The maximum number of table positions for validation, transition
        construction and recurrence steps, measured as an arithmetic
        work bound independent of coefficient bit length.

    Returns
    -------
    tuple[ExactJvp, ...]
        One mass and tangent per state in the finite-step law.

    Raises
    ------
    ValueError
        If the dimensions, limits, or pointwise measure conditions fail.
    JvpBoundaryError
        If an acceptance tie has unequal slopes along the supplied direction.
    JvpLimit
        If the arithmetic work bound would be exceeded.
    """
    exact, _ = _finite_metropolis_law(
        initial, target, proposal, steps=steps, max_work=max_work, audit=False
    )
    return exact

audit_finite_metropolis_acceptance

audit_finite_metropolis_acceptance(initial: tuple[ExactJvp, ...], target: tuple[ExactJvp, ...], proposal: tuple[tuple[ExactJvp, ...], ...], *, steps: int, max_work: int = 65536) -> MetropolisAcceptanceAudit

Audit ignoring acceptance-coin tangents along a finite Metropolis law.

The calculation retains the primal acceptance and rejection probabilities. It omits their tangents in the detached lane and retains the initial and direct proposal derivatives. It reports the resulting pointwise bias after the requested number of transitions.

PARAMETER DESCRIPTION
initial

The ordered exact mass and tangent inputs of finite_metropolis_jvp.

TYPE: tuple

target

The ordered exact mass and tangent inputs of finite_metropolis_jvp.

TYPE: tuple

proposal

The ordered exact mass and tangent inputs of finite_metropolis_jvp.

TYPE: tuple

steps

The number of transitions after initialization.

TYPE: int

max_work

Bound on table positions. At positive steps, the audit charges one extra state-pair table and one extra pass per step. This counts rational arithmetic positions independently of coefficient bit length.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
MetropolisAcceptanceAudit

The exact and detached lanes and their signed tangent difference.

RAISES DESCRIPTION
ValueError

If the inputs fail the finite measure or bound checks.

JvpBoundaryError

If an acceptance tie has unequal slopes.

JvpLimit

If the audit table position bound is insufficient.

Source code in src/quivers/qiec/finite_metropolis.py
def audit_finite_metropolis_acceptance(
    initial: tuple[ExactJvp, ...],
    target: tuple[ExactJvp, ...],
    proposal: tuple[tuple[ExactJvp, ...], ...],
    *,
    steps: int,
    max_work: int = 65_536,
) -> MetropolisAcceptanceAudit:
    """Audit ignoring acceptance-coin tangents along a finite Metropolis law.

    The calculation retains the primal acceptance and rejection probabilities.
    It omits their tangents in the detached lane and retains the initial and
    direct proposal derivatives. It reports the resulting pointwise bias
    after the requested number of transitions.

    Parameters
    ----------
    initial, target, proposal : tuple
        The ordered exact mass and tangent inputs of `finite_metropolis_jvp`.
    steps : int
        The number of transitions after initialization.
    max_work : int
        Bound on table positions. At positive `steps`, the audit charges
        one extra state-pair table and one extra pass per step. This counts
        rational arithmetic positions independently of coefficient bit length.

    Returns
    -------
    MetropolisAcceptanceAudit
        The exact and detached lanes and their signed tangent difference.

    Raises
    ------
    ValueError
        If the inputs fail the finite measure or bound checks.
    JvpBoundaryError
        If an acceptance tie has unequal slopes.
    JvpLimit
        If the audit table position bound is insufficient.
    """
    exact, bias = _finite_metropolis_law(
        initial, target, proposal, steps=steps, max_work=max_work, audit=True
    )
    detached = tuple(
        ExactJvp(mass.value, mass.tangent + difference)
        for mass, difference in zip(exact, bias, strict=True)
    )
    return MetropolisAcceptanceAudit(steps, exact, detached, bias)

Moments of a finite gradient estimator

audit_bernoulli_gradient_moments checks an authored scalar entry and enumerates the actual randomness of its enumerate, score and measure policies. Each atom records the source addresses and history prefixes of the requested draws and selectors, their choices in execution order, and the product of their conditional probabilities. A weak derivative visits both virtual branches. Each branch receives its own random inputs even when the same lexical site occurs in both branches.

The audit verifies that the atom probabilities sum to one and that their mean agrees with the exhaustive source expectation and its directional derivative. It computes both population variances and the signed covariance at the supplied point and direction. The estimator replay count includes runs suspended at a new choice. The source replay count belongs to construction of the separate source tree.

from fractions import Fraction

from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, audit_bernoulli_gradient_moments

module = Compiler(parse("""
instance random : Random

define reward(p : Real) : Real !{random} =
    let chosen <- perform random.sample[Bool](site("chosen"), Bernoulli(probs=p))
    if chosen then
        return 1.0
    else
        return 0.0
"""), module_name="gradient-moments").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "reward")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="score")
audit = audit_bernoulli_gradient_moments(
    module, entry.id, (Fraction(1, 4),), (1,), (policy,),
)
assert audit.mean.tangent == 1
assert audit.value_variance == Fraction(3, 16)
assert audit.tangent_variance == 3
assert audit.covariance == Fraction(3, 4)

Pass omit_independent_cost=True to the plan or the moment audit to exclude a checked additive cost from one Bernoulli score product. The entry binds a pure Real cost before its original score draw and returns the nominal Real sum of that binding and a pure Real continuation result. The audit keeps the full primal and all direct derivatives. It reads the cost from the source scope before the request and uses only its primal in the score product. The visit records this cost and its direct tangent.

For a draw with probability \(p\) and directional derivative \(\dot p\), the conditional score has mean \((1-p)(-\dot p/(1-p)) + p(\dot p/p)=0\). A cost known before the draw thus contributes zero in expectation to that score product. Its direct derivative still contributes to the derivative of the return. The comparison of tangent variances depends on the cost and the chosen point. Omitting a cost can increase the variance.

Conditional moments of an addressed estimator

audit_conditioned_bernoulli_gradient keeps any distinct set of stochastic estimator choices from the complete audited law. A BernoulliChoiceKey identifies the request address and its original source prefix. Two virtual arms may visit the same address under different prefixes. An absent occurrence has its own observed value distinct from either Boolean.

For an observation with positive probability, the estimator averages the original values and directional estimates over its compatible scripts using their exact conditional probabilities. The sampler draws from the exact marginal law of the retained observations. The two means agree with the original audit. The difference of the original and projected covariance matrices is the mean within-observation covariance. Thus every linear contrast has variance at most its original variance. Differentiating the conditional primal would also require the derivative of its conditional law. The conditional estimator here concerns the original objective at the checked point and direction.

The bounded projection runs after constructing the complete script audit, which it keeps in its report. Empty retention returns the deterministic mean. Reached sites with deterministic enumeration are outside the stochastic projection.

finite_estimator_moments

Exact moments of the randomness used by a checked Bernoulli estimator.

BernoulliEstimatorOutcome dataclass

BernoulliEstimatorOutcome(decisions: tuple[BernoulliScoreDraw | BernoulliWeakSelector, ...], probability: Fraction, estimate: ExactJvp)

One atom of the stochastic estimator's finite execution law.

PARAMETER DESCRIPTION
decisions

The actual choices in interpreter order, with their original source addresses and source prefixes. An enumerated site makes no choice of its own.

TYPE: tuple[BernoulliScoreDraw or BernoulliWeakSelector, ...]

probability

The product of conditional masses along this complete script.

TYPE: Fraction

estimate

The returned primal and directional estimates on this script.

TYPE: ExactJvp

FiniteBernoulliEstimatorMoments dataclass

FiniteBernoulliEstimatorMoments(module: QiecModule, source: BernoulliGradientPlan, point: tuple[Fraction, ...], direction: tuple[Fraction, ...], mean: ExactJvp, value_variance: Fraction, tangent_variance: Fraction, covariance: Fraction, outcomes: tuple[BernoulliEstimatorOutcome, ...], estimator_replays: int)

The exact joint moments of a checked estimator at a supplied point.

PARAMETER DESCRIPTION
module

The source used to build and check the estimator.

TYPE: QiecModule

source

The addressed source tree and explicit policies. Its replay count concerns the construction of that tree.

TYPE: BernoulliGradientPlan

point

The exact parameter point and direction in source order.

TYPE: tuple[Fraction, ...]

direction

The exact parameter point and direction in source order.

TYPE: tuple[Fraction, ...]

mean

The two means of the enumerated estimator law, equal to the checked source expectation and its derivative.

TYPE: ExactJvp

value_variance

The population variances of the primal and directional estimates.

TYPE: Fraction

tangent_variance

The population variances of the primal and directional estimates.

TYPE: Fraction

covariance

The signed covariance of those two estimates.

TYPE: Fraction

outcomes

All complete estimator scripts and their positive exact weights.

TYPE: tuple[BernoulliEstimatorOutcome, ...]

estimator_replays

The number of interpreter runs, including those that reached an unresolved choice. These runs use the already checked source tree.

TYPE: int

BernoulliChoiceKey dataclass

BernoulliChoiceKey(address: _Address, prefix: tuple[bool, ...])

Identify one stochastic estimator choice in the original source tree.

PARAMETER DESCRIPTION
address

The complete canonical request address.

TYPE: tuple

prefix

The preceding source choices at this visit. Two virtual arms may use the same request address at different source prefixes.

TYPE: tuple of bool

__post_init__

__post_init__() -> None

Check the exact address and source-prefix carriers.

RAISES DESCRIPTION
ValueError

If an address or source-prefix token has an invalid type.

Source code in src/quivers/qiec/finite_estimator_moments.py
def __post_init__(self) -> None:
    """Check the exact address and source-prefix carriers.

    Raises
    ------
    ValueError
        If an address or source-prefix token has an invalid type.
    """
    address = self.address
    if type(address) is not tuple or len(address) != 3:
        raise ValueError("a Bernoulli choice needs a canonical request address")
    site, frames, shots = address
    if (
        type(site) is not str
        or not site
        or type(frames) is not tuple
        or any(
            type(frame) is not tuple
            or len(frame) != 2
            or type(frame[0]) is not str
            or type(frame[1]) not in (str, int)
            for frame in frames
        )
        or type(shots) is not tuple
        or any(type(shot) is not int or shot < 0 for shot in shots)
    ):
        raise ValueError("a Bernoulli choice needs a canonical request address")
    if type(self.prefix) is not tuple or any(
        type(bit) is not bool for bit in self.prefix
    ):
        raise ValueError(
            "a Bernoulli choice source prefix must contain Boolean outcomes"
        )

ConditionalBernoulliEstimatorOutcome dataclass

ConditionalBernoulliEstimatorOutcome(choices: tuple[bool | None, ...], probability: Fraction, estimate: ExactJvp)

One observation of the retained choices and its conditional action.

PARAMETER DESCRIPTION
choices

The choices in the requested order. None records that the original script did not reach this stochastic occurrence.

TYPE: tuple of bool or None

probability

The total probability of complete scripts with this observation.

TYPE: Fraction

estimate

The exact conditional means of the original value and action.

TYPE: ExactJvp

FiniteConditionalBernoulliEstimator dataclass

FiniteConditionalBernoulliEstimator(source: FiniteBernoulliEstimatorMoments, retained: tuple[BernoulliChoiceKey, ...], outcomes: tuple[ConditionalBernoulliEstimatorOutcome, ...], value_variance: Fraction, tangent_variance: Fraction, covariance: Fraction, projection_work: int, selector_probabilities: tuple[Fraction, ...])

An exact conditional estimator law over checked addressed scripts.

PARAMETER DESCRIPTION
source

The original checked point, direction, policies and complete law.

TYPE: FiniteBernoulliEstimatorMoments

retained

The ordering of the observed choice coordinates.

TYPE: tuple of BernoulliChoiceKey

outcomes

The complete marginal law of retained observations.

TYPE: tuple of ConditionalBernoulliEstimatorOutcome

value_variance

The population variances of the two conditional estimates.

TYPE: Fraction

tangent_variance

The population variances of the two conditional estimates.

TYPE: Fraction

covariance

The signed covariance of those estimates.

TYPE: Fraction

projection_work

Retention positions, script choices, observation cells and normalization, moment and sampling rows charged after source auditing.

TYPE: int

selector_probabilities

The internal exact categorical sampler's sequential probabilities.

TYPE: tuple of Fraction

mean property

mean: ExactJvp

Read the preserved joint mean at the checked point.

RETURNS DESCRIPTION
ExactJvp

The original expected value and directional derivative.

semantics property

Report the original site policies and exact zero pointwise bias.

RETURNS DESCRIPTION
DerivativeSemantics

An unbiased estimate of the original objective's derivative at this point and direction.

sample

sample(*, seed: int | None = None) -> ConditionalBernoulliEstimatorOutcome

Draw a retained observation from its exact marginal law.

PARAMETER DESCRIPTION
seed

An optional seed for the exact categorical sampler.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
ConditionalBernoulliEstimatorOutcome

The observation, marginal probability and conditional action.

Source code in src/quivers/qiec/finite_estimator_moments.py
def sample(
    self, *, seed: int | None = None
) -> ConditionalBernoulliEstimatorOutcome:
    """Draw a retained observation from its exact marginal law.

    Parameters
    ----------
    seed : int or None
        An optional seed for the exact categorical sampler.

    Returns
    -------
    ConditionalBernoulliEstimatorOutcome
        The observation, marginal probability and conditional action.
    """
    return self.outcomes[
        _choose_position(self.selector_probabilities, Random(seed))
    ]

audit_bernoulli_gradient_moments

audit_bernoulli_gradient_moments(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_outcomes: int = 4096, max_paths: int = 4096, fuel: int = 50000, omit_independent_cost: bool = False) -> FiniteBernoulliEstimatorMoments

Audit the joint moments of a checked finite Bernoulli estimator.

The source checker requires strictly interior Bernoulli probabilities, regular scalar arithmetic and explicit policies for all reached sites. The audit enumerates the score draws and weak selectors the sampler actually requests. Each request is a new conditional Bernoulli choice, including visits in virtual weak branches with the same static site. The report gives pointwise moments of this estimator law with finite exact arithmetic.

PARAMETER DESCRIPTION
module

The checked source of the scalar finite estimator.

TYPE: QiecModule

computation

The named entry whose expected value is differentiated.

TYPE: ComputationId

arguments

The exact parameter point and direction in source order.

TYPE: tuple[int or Fraction, ...]

direction

The exact parameter point and direction in source order.

TYPE: tuple[int or Fraction, ...]

policies

One policy for each static site reached anywhere in the source tree.

TYPE: tuple[SiteEstimator, ...]

max_outcomes

The maximum number of complete estimator scripts.

TYPE: int DEFAULT: 4096

max_paths

The independent source path bound and source replay step limit.

TYPE: int DEFAULT: 4096

fuel

The independent source path bound and source replay step limit.

TYPE: int DEFAULT: 4096

omit_independent_cost

Request the checked single-site score omission in :func:plan_bernoulli_gradient. The moments then describe the estimator with that omission.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
FiniteBernoulliEstimatorMoments

The complete estimator law, its checked means and its moments.

RAISES DESCRIPTION
ValueError

If the point, direction, policies or budget have malformed values.

JvpUnsupported

If the source or policies leave the finite checked fragment.

JvpBoundaryError

If a reached comparison hits an active equality boundary.

JvpLimit

If a source, arithmetic or script bound is exceeded.

RuntimeError

If the enumerated law disagrees with the source or interpreter.

Source code in src/quivers/qiec/finite_estimator_moments.py
def audit_bernoulli_gradient_moments(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    max_outcomes: int = 4096,
    max_paths: int = 4096,
    fuel: int = 50_000,
    omit_independent_cost: bool = False,
) -> FiniteBernoulliEstimatorMoments:
    """Audit the joint moments of a checked finite Bernoulli estimator.

    The source checker requires strictly interior Bernoulli probabilities,
    regular scalar arithmetic and explicit policies for all reached sites.
    The audit enumerates the score draws and weak selectors the sampler
    actually requests. Each request is a new conditional Bernoulli
    choice, including visits in virtual weak branches with the same
    static site. The report gives pointwise moments of this estimator
    law with finite exact arithmetic.

    Parameters
    ----------
    module : QiecModule
        The checked source of the scalar finite estimator.
    computation : ComputationId
        The named entry whose expected value is differentiated.
    arguments, direction : tuple[int or Fraction, ...]
        The exact parameter point and direction in source order.
    policies : tuple[SiteEstimator, ...]
        One policy for each static site reached anywhere in the source tree.
    max_outcomes : int
        The maximum number of complete estimator scripts.
    max_paths, fuel : int
        The independent source path bound and source replay step limit.
    omit_independent_cost : bool
        Request the checked single-site score omission in
        :func:`plan_bernoulli_gradient`. The moments then describe the
        estimator with that omission.

    Returns
    -------
    FiniteBernoulliEstimatorMoments
        The complete estimator law, its checked means and its moments.

    Raises
    ------
    ValueError
        If the point, direction, policies or budget have malformed values.
    JvpUnsupported
        If the source or policies leave the finite checked fragment.
    JvpBoundaryError
        If a reached comparison hits an active equality boundary.
    JvpLimit
        If a source, arithmetic or script bound is exceeded.
    RuntimeError
        If the enumerated law disagrees with the source or interpreter.
    """
    _validate_limit("max_outcomes", max_outcomes)
    point = tuple(map(_fraction, arguments))
    tangent = tuple(map(_fraction, direction))
    source = plan_bernoulli_gradient(
        module,
        computation,
        point,
        tangent,
        policies,
        max_paths=max_paths,
        fuel=fuel,
        omit_independent_cost=omit_independent_cost,
    )
    outcomes, replays, mean = _estimator_outcomes(
        source, max_outcomes, audit="Bernoulli moment audit"
    )
    variance_value, variance_tangent, covariance = _moments(outcomes, mean)
    return FiniteBernoulliEstimatorMoments(
        module,
        source,
        point,
        tangent,
        mean,
        variance_value,
        variance_tangent,
        covariance,
        outcomes,
        replays,
    )

audit_conditioned_bernoulli_gradient

audit_conditioned_bernoulli_gradient(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, retain: tuple[BernoulliChoiceKey, ...], max_projection_work: int = 250000, max_outcomes: int = 4096, max_paths: int = 4096, fuel: int = 50000, omit_independent_cost: bool = False) -> FiniteConditionalBernoulliEstimator

Condition a checked finite estimator on selected source choices.

The original source and the mixed estimator are audited exactly. Two complete scripts have the same observation when each retained addressed choice has the same outcome or is absent in both. The new law gives each observation its total script probability and averages the original value and directional estimate within that observation.

Both means are unchanged. The covariance reduction is positive semidefinite by the finite conditional variance identity, so the variance of every linear combination of the two estimates can only decrease. Conditional actions average the actual original gradient estimates. Differentiating a conditional value would in general require derivatives of its conditional law and answers a separate question.

PARAMETER DESCRIPTION
module

The checked source module.

TYPE: QiecModule

computation

The ordinary scalar entry being differentiated.

TYPE: ComputationId

arguments

The exact parameter point and directional inputs in source order.

TYPE: tuple of int or Fraction

direction

The exact parameter point and directional inputs in source order.

TYPE: tuple of int or Fraction

policies

The checked policies for all reached source sites.

TYPE: tuple of SiteEstimator

retain

Distinct original stochastic choices to keep, in observation order. Empty retention gives the deterministic unconditional mean.

TYPE: tuple of BernoulliChoiceKey

max_projection_work

The bound on post-audit projection cells and row operations. This counts positions and rows, excluding exact rational bit work, address size and dictionary collision costs.

TYPE: int DEFAULT: 250000

max_outcomes

Bounds of the existing complete-script and checked-source audit.

TYPE: int DEFAULT: 4096

max_paths

Bounds of the existing complete-script and checked-source audit.

TYPE: int DEFAULT: 4096

fuel

Bounds of the existing complete-script and checked-source audit.

TYPE: int DEFAULT: 4096

omit_independent_cost

Use the original audit's checked single-site score omission.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
FiniteConditionalBernoulliEstimator

The exact projected law and its preserved mean and covariance.

RAISES DESCRIPTION
ValueError

If retained keys, inputs or bounds are malformed.

JvpUnsupported

If retention names a choice outside the stochastic estimator law or the source leaves the checked fragment.

JvpBoundaryError

If the original source reaches a comparison boundary.

JvpLimit

If a source, script, arithmetic or projection limit is exceeded.

RuntimeError

If the checked scripts or derived law violate their invariants.

Source code in src/quivers/qiec/finite_estimator_moments.py
def audit_conditioned_bernoulli_gradient(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    retain: tuple[BernoulliChoiceKey, ...],
    max_projection_work: int = 250_000,
    max_outcomes: int = 4096,
    max_paths: int = 4096,
    fuel: int = 50_000,
    omit_independent_cost: bool = False,
) -> FiniteConditionalBernoulliEstimator:
    """Condition a checked finite estimator on selected source choices.

    The original source and the mixed estimator are audited exactly. Two
    complete scripts have the same observation when each retained
    addressed choice has the same outcome or is absent in both. The new
    law gives each observation its total script probability and averages
    the original value and directional estimate within that observation.

    Both means are unchanged. The covariance reduction is positive
    semidefinite by the finite conditional variance identity, so the
    variance of every linear combination of the two estimates can only
    decrease. Conditional actions average the actual original gradient
    estimates. Differentiating a conditional value would in general
    require derivatives of its conditional law and answers a separate
    question.

    Parameters
    ----------
    module : QiecModule
        The checked source module.
    computation : ComputationId
        The ordinary scalar entry being differentiated.
    arguments, direction : tuple of int or Fraction
        The exact parameter point and directional inputs in source order.
    policies : tuple of SiteEstimator
        The checked policies for all reached source sites.
    retain : tuple of BernoulliChoiceKey
        Distinct original stochastic choices to keep, in observation order.
        Empty retention gives the deterministic unconditional mean.
    max_projection_work : int
        The bound on post-audit projection cells and row operations.
        This counts positions and rows, excluding exact rational bit
        work, address size and dictionary collision costs.
    max_outcomes, max_paths, fuel : int
        Bounds of the existing complete-script and checked-source audit.
    omit_independent_cost : bool
        Use the original audit's checked single-site score omission.

    Returns
    -------
    FiniteConditionalBernoulliEstimator
        The exact projected law and its preserved mean and covariance.

    Raises
    ------
    ValueError
        If retained keys, inputs or bounds are malformed.
    JvpUnsupported
        If retention names a choice outside the stochastic estimator law
        or the source leaves the checked fragment.
    JvpBoundaryError
        If the original source reaches a comparison boundary.
    JvpLimit
        If a source, script, arithmetic or projection limit is exceeded.
    RuntimeError
        If the checked scripts or derived law violate their invariants.
    """
    _validate_limit("max_projection_work", max_projection_work)
    if type(retain) is not tuple:
        raise ValueError("retention requires a tuple of checked Bernoulli choice keys")
    work = len(retain)
    if work > max_projection_work:
        raise JvpLimit("conditional Bernoulli projection work limit exhausted")
    if any(type(key) is not BernoulliChoiceKey for key in retain):
        raise ValueError("retention requires a tuple of checked Bernoulli choice keys")
    positions = {(key.address, key.prefix): index for index, key in enumerate(retain)}
    if len(positions) != len(retain):
        raise ValueError("retained Bernoulli choice keys must be distinct")

    source = audit_bernoulli_gradient_moments(
        module,
        computation,
        arguments,
        direction,
        policies,
        max_outcomes=max_outcomes,
        max_paths=max_paths,
        fuel=fuel,
        omit_independent_cost=omit_independent_cost,
    )
    seen: set[int] = set()
    masses: dict[tuple[bool | None, ...], tuple[Fraction, Fraction, Fraction]] = {}
    for outcome in source.outcomes:
        work += len(outcome.decisions) + len(retain) + 1
        if work > max_projection_work:
            raise JvpLimit("conditional Bernoulli projection work limit exhausted")
        observed: list[bool | None] = [None] * len(retain)
        for decision in outcome.decisions:
            index = positions.get((decision.visit.address, decision.visit.prefix))
            if index is None:
                continue
            if observed[index] is not None:
                raise RuntimeError(
                    "a retained choice occurs twice in one checked script"
                )
            observed[index] = decision.choice
            seen.add(index)
        key = tuple(observed)
        mass, value, action = masses.get(key, (Fraction(), Fraction(), Fraction()))
        p = outcome.probability
        total = (
            mass + p,
            value + p * outcome.estimate.value,
            action + p * outcome.estimate.tangent,
        )
        _bound(*total)
        masses[key] = total
    if len(seen) != len(retain):
        missing = next(key for i, key in enumerate(retain) if i not in seen)
        raise JvpUnsupported(
            f"retained choice is absent from the stochastic estimator law: {missing!r}"
        )

    work += 3 * len(masses)
    if work > max_projection_work:
        raise JvpLimit("conditional Bernoulli projection work limit exhausted")
    outcomes = []
    mass = value = action = Fraction()
    for key, (p, weighted_value, weighted_action) in masses.items():
        estimate = ExactJvp(weighted_value / p, weighted_action / p)
        mass += p
        value += p * estimate.value
        action += p * estimate.tangent
        _bound(mass, value, action, estimate.value, estimate.tangent)
        outcomes.append(ConditionalBernoulliEstimatorOutcome(key, p, estimate))
    if mass != 1 or ExactJvp(value, action) != source.mean:
        raise RuntimeError(
            "conditional Bernoulli projection did not preserve the checked mean"
        )
    rows = tuple(outcomes)
    vv, vt, cov = _moments(rows, source.mean)
    difference_vv, difference_vt, difference_cov = (
        source.value_variance - vv,
        source.tangent_variance - vt,
        source.covariance - cov,
    )
    _bound(difference_vv, difference_vt, difference_cov)
    if (
        min(difference_vv, difference_vt) < 0
        or difference_vv * difference_vt < difference_cov**2
    ):
        raise RuntimeError(
            "conditional Bernoulli covariance reduction is not positive semidefinite"
        )

    return FiniteConditionalBernoulliEstimator(
        source,
        retain,
        rows,
        vv,
        vt,
        cov,
        work,
        _selector_probabilities(tuple(row.probability for row in rows)),
    )

Bias of finite gradient clipping

audit_clipped_bernoulli_gradient checks a finite Bernoulli source with explicit estimator policies, then caps each realized final directional estimate at the supplied magnitude. It enumerates the estimator's own score choices and weak selectors, including choices made in both branches of a weak estimator. Each outcome retains its source addresses, selector choices, and exact probability.

The signed bias is the mean clipped tangent minus the exact source tangent. The report belongs to the checked source, parameter point, direction, policies, and clipping limit. A different point or direction requires its own calculation.

from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, audit_clipped_bernoulli_gradient

source = """
instance random : Random

define reward(p : Real) : Real !{random} =
    let chosen <- perform random.sample[Bool](site("chosen"), Bernoulli(probs=p))
    if chosen then
        return 1.0
    else
        return 0.0
"""
module = Compiler(parse(source), module_name="clipped-gradient").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "reward")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="score")
audit = audit_clipped_bernoulli_gradient(
    module, entry.id, (Fraction(1, 4),), (1,), (policy,), clip_limit=2,
)
assert audit.source.exact.tangent == 1
assert audit.mean.tangent == Fraction(1, 2)
assert audit.signed_bias == Fraction(-1, 2)

finite_clipping

Exact pointwise bias of clipping a finite checked gradient estimator.

ClippedEstimatorDecision dataclass

ClippedEstimatorDecision(visit: BernoulliVisit, choice: bool)

One actual random choice during the finite estimator evaluation.

PARAMETER DESCRIPTION
visit

The original source occurrence, policy and probability used.

TYPE: BernoulliVisit

choice

The score draw or weak selector at this occurrence.

TYPE: bool

ClippedEstimatorOutcome dataclass

ClippedEstimatorOutcome(decisions: tuple[ClippedEstimatorDecision, ...], probability: Fraction, raw: ExactJvp, clipped: ExactJvp)

The raw and clipped actions for one complete estimator script.

PARAMETER DESCRIPTION
decisions

The actual stochastic choices in evaluation order.

TYPE: tuple[ClippedEstimatorDecision, ...]

probability

The probability of this entire estimator script.

TYPE: Fraction

raw

The original estimate and the estimate with its tangent clipped.

TYPE: ExactJvp

clipped

The original estimate and the estimate with its tangent clipped.

TYPE: ExactJvp

FiniteClippedEstimatorAudit dataclass

FiniteClippedEstimatorAudit(module: QiecModule, source: BernoulliGradientPlan, point: tuple[Fraction, ...], direction: tuple[Fraction, ...], clip_limit: Fraction, mean: ExactJvp, signed_bias: Fraction, outcomes: tuple[ClippedEstimatorOutcome, ...])

A pointwise clipping audit bound to one checked estimator execution.

PARAMETER DESCRIPTION
module

The actual source used to construct the checked estimator.

TYPE: QiecModule

source

The checked objective, occurrence identities and policy tree.

TYPE: BernoulliGradientPlan

point

The supplied parameter point and direction in source order.

TYPE: tuple[Fraction, ...]

direction

The supplied parameter point and direction in source order.

TYPE: tuple[Fraction, ...]

clip_limit

The symmetric cap applied to each realized directional estimate.

TYPE: Fraction

mean

The exact mean of the clipped estimator at this point and direction.

TYPE: ExactJvp

signed_bias

The mean clipped derivative minus the exact target derivative.

TYPE: Fraction

outcomes

The complete finite law of the estimator's own random scripts.

TYPE: tuple[ClippedEstimatorOutcome, ...]

sample

sample(*, seed: int | None = None) -> BernoulliGradientSample

Draw a clipped action with the original estimator's choices.

PARAMETER DESCRIPTION
seed

An optional seed for the original exact finite estimator.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
BernoulliGradientSample

The sample and its unchanged trace of choices, with its final tangent capped at the audit limit.

Source code in src/quivers/qiec/finite_clipping.py
def sample(self, *, seed: int | None = None) -> BernoulliGradientSample:
    """Draw a clipped action with the original estimator's choices.

    Parameters
    ----------
    seed : int or None
        An optional seed for the original exact finite estimator.

    Returns
    -------
    BernoulliGradientSample
        The sample and its unchanged trace of choices, with its final
        tangent capped at the audit limit.
    """
    estimate = self.source.sample(seed=seed)
    return replace(estimate, tangent=_clip(estimate.tangent, self.clip_limit))

audit_clipped_bernoulli_gradient

audit_clipped_bernoulli_gradient(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, clip_limit: int | Fraction, max_outcomes: int = 4096, max_paths: int = 4096, fuel: int = 50000) -> FiniteClippedEstimatorAudit

Compute the signed bias of clipping the final finite directional action.

The base estimator uses the source's explicit enumerate, score and measure policies. This audit drives the same interpreter with a complete enumeration of its own score draws and weak selectors. It takes the mean after clipping each realized tangent. The exact unclipped expectation agrees with the source objective.

The result attests to the supplied source, point, direction, policies and clipping operation. It describes a finite numerical calculation at that point.

PARAMETER DESCRIPTION
module

The actual checked source of the finite Bernoulli estimator.

TYPE: QiecModule

computation

The named scalar entry on one nominal Random instance.

TYPE: ComputationId

arguments

The exact parameter point and directional seed.

TYPE: tuple[int or Fraction, ...]

direction

The exact parameter point and directional seed.

TYPE: tuple[int or Fraction, ...]

policies

The explicit source estimator at each reached static site.

TYPE: tuple[SiteEstimator, ...]

clip_limit

The nonnegative symmetric cap on the final sampled tangent.

TYPE: int or Fraction

max_outcomes

Maximum number of complete stochastic estimator scripts.

TYPE: int DEFAULT: 4096

max_paths

The independent source path limit and per-replay step limit.

TYPE: int DEFAULT: 4096

fuel

The independent source path limit and per-replay step limit.

TYPE: int DEFAULT: 4096

RETURNS DESCRIPTION
FiniteClippedEstimatorAudit

The checked source estimator, signed clipping bias and exact law.

RAISES DESCRIPTION
ValueError

If the clipping limit, bounds or exact inputs are malformed.

JvpUnsupported

If the checked source or its policies leave the finite fragment.

JvpBoundaryError

If an active input comparison hits an equality boundary.

JvpLimit

If the source, exact arithmetic or script enumeration is exhausted.

Source code in src/quivers/qiec/finite_clipping.py
def audit_clipped_bernoulli_gradient(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policies: tuple[SiteEstimator, ...],
    *,
    clip_limit: int | Fraction,
    max_outcomes: int = 4096,
    max_paths: int = 4096,
    fuel: int = 50_000,
) -> FiniteClippedEstimatorAudit:
    """Compute the signed bias of clipping the final finite directional action.

    The base estimator uses the source's explicit enumerate, score and
    measure policies. This audit drives the same interpreter with a
    complete enumeration of its own score draws and weak selectors.
    It takes the mean after clipping each realized tangent. The exact
    unclipped expectation agrees with the source objective.

    The result attests to the supplied source, point, direction, policies
    and clipping operation. It describes a finite numerical calculation
    at that point.

    Parameters
    ----------
    module : QiecModule
        The actual checked source of the finite Bernoulli estimator.
    computation : ComputationId
        The named scalar entry on one nominal Random instance.
    arguments, direction : tuple[int or Fraction, ...]
        The exact parameter point and directional seed.
    policies : tuple[SiteEstimator, ...]
        The explicit source estimator at each reached static site.
    clip_limit : int or Fraction
        The nonnegative symmetric cap on the final sampled tangent.
    max_outcomes : int
        Maximum number of complete stochastic estimator scripts.
    max_paths, fuel : int
        The independent source path limit and per-replay step limit.

    Returns
    -------
    FiniteClippedEstimatorAudit
        The checked source estimator, signed clipping bias and exact law.

    Raises
    ------
    ValueError
        If the clipping limit, bounds or exact inputs are malformed.
    JvpUnsupported
        If the checked source or its policies leave the finite fragment.
    JvpBoundaryError
        If an active input comparison hits an equality boundary.
    JvpLimit
        If the source, exact arithmetic or script enumeration is exhausted.
    """
    _validate_limit("max_outcomes", max_outcomes)
    cap = _fraction(clip_limit)
    if cap < 0:
        raise ValueError("the finite clipping limit must be nonnegative")
    _bound(cap)
    point = tuple(map(_fraction, arguments))
    tangent = tuple(map(_fraction, direction))
    source = plan_bernoulli_gradient(
        module,
        computation,
        point,
        tangent,
        policies,
        max_paths=max_paths,
        fuel=fuel,
    )
    rows, _, mean = _estimator_outcomes(source, max_outcomes, audit="clipping audit")
    outcomes: list[ClippedEstimatorOutcome] = []
    clipped_tangent = Fraction(0)
    for row in rows:
        decisions = tuple(
            ClippedEstimatorDecision(choice.visit, choice.choice)
            for choice in row.decisions
        )
        raw = row.estimate
        capped = ExactJvp(raw.value, _clip(raw.tangent, cap))
        outcomes.append(
            ClippedEstimatorOutcome(decisions, row.probability, raw, capped)
        )
        clipped_tangent += row.probability * capped.tangent
        _bound(clipped_tangent)
    bias = clipped_tangent - mean.tangent
    _bound(bias)
    return FiniteClippedEstimatorAudit(
        module,
        source,
        point,
        tangent,
        cap,
        ExactJvp(mean.value, clipped_tangent),
        bias,
        tuple(outcomes),
    )

Straight-through Bernoulli derivatives

audit_straight_through_bernoulli_gradient checks a source with one Bernoulli draw and one explicit straight-through site policy. It also checks a closed scalar real extension with the hard outcome as its first argument and the source arguments after it. At each of zero and one, the extension must reproduce the source branch's value and directional derivative at fixed choice. The estimator samples the original hard draw and passes the probability tangent to the first input of that extension.

The audit enumerates the two choices made by this sampler. Its reported signed bias is the mean straight-through tangent minus the exact source tangent. Its derivative semantics carry the original site and the absolute bias at that point and direction. The extension is checked on both hard outcomes, with two exact scalar evaluations per outcome.

from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, audit_straight_through_bernoulli_gradient

source = """
instance random : Random

define payoff(x : Real, p : Real, t : Real) : Real !{} =
    return x * x * x + t * x

define reward(p : Real, t : Real) : Real !{random} =
    let bit <- perform random.sample[Bool](site("reward"), Bernoulli(probs=p))
    payoff(real(bit), p, t)
"""
module = Compiler(parse(source), module_name="straight-through-example").qiec_module
assert module is not None
owner = next(item for item in module.computations if item.name == "reward")
assert isinstance(owner.body, Bind) and isinstance(owner.body.first, Perform)
policy = SiteEstimator(site=owner.body.first.request.origin.static_site, estimator="straight-through")
audit = audit_straight_through_bernoulli_gradient(
    module, owner.id, (Fraction(1, 4), Fraction(1, 2)), (1, 2), policy, extension="payoff",
)
assert audit.mean.value == Fraction(3, 8)
assert audit.source.exact.tangent == 2
assert audit.mean.tangent == Fraction(7, 4)
assert audit.signed_bias == Fraction(-1, 4)

finite_straight_through

Exact pointwise bias of one checked straight-through Bernoulli site.

FiniteStraightThroughBernoulliAudit dataclass

FiniteStraightThroughBernoulliAudit(module: QiecModule, source: BernoulliGradientPlan, policy: SiteEstimator, extension: str, point: tuple[Fraction, ...], direction: tuple[Fraction, ...], mean: ExactJvp, signed_bias: Fraction, outcomes: tuple[BernoulliEstimatorOutcome, ...])

The hard draw law and the pointwise bias of its declared surrogate.

PARAMETER DESCRIPTION
module

The checked module containing the source and the real extension.

TYPE: QiecModule

source

The exact addressed source and its original hard draw sampler.

TYPE: BernoulliGradientPlan

policy

The explicit straight-through policy for the source's draw.

TYPE: SiteEstimator

extension

The closed scalar computation extending the Boolean branches.

TYPE: str

point

The checked source point and direction in parameter order.

TYPE: tuple of Fraction

direction

The checked source point and direction in parameter order.

TYPE: tuple of Fraction

mean

The exact mean value and mean straight-through derivative.

TYPE: ExactJvp

signed_bias

The mean estimated tangent minus the exact source tangent.

TYPE: Fraction

outcomes

The complete finite law of hard choices and surrogate tangents.

TYPE: tuple of BernoulliEstimatorOutcome

semantics property

Report the derivative semantics for this point and direction.

RETURNS DESCRIPTION
DerivativeSemantics

The declared site policy and the exact absolute bias bound.

sample

sample(*, seed: int | None = None) -> BernoulliEstimatorOutcome

Draw from the original addressed law and return its audited atom.

PARAMETER DESCRIPTION
seed

An optional seed for the existing exact integer sampler.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
BernoulliEstimatorOutcome

The hard choice, its original occurrence and the surrogate action.

Source code in src/quivers/qiec/finite_straight_through.py
def sample(self, *, seed: int | None = None) -> BernoulliEstimatorOutcome:
    """Draw from the original addressed law and return its audited atom.

    Parameters
    ----------
    seed : int or None
        An optional seed for the existing exact integer sampler.

    Returns
    -------
    BernoulliEstimatorOutcome
        The hard choice, its original occurrence and the surrogate action.
    """
    decisions = self.source.sample(seed=seed).draws
    return next(row for row in self.outcomes if row.decisions == decisions)

audit_straight_through_bernoulli_gradient

audit_straight_through_bernoulli_gradient(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policy: SiteEstimator, *, extension: str, fuel: int = 50000) -> FiniteStraightThroughBernoulliAudit

Audit one hard Bernoulli draw with a declared real extension.

At each hard outcome, the extension receives that outcome as zero or one followed by the original source arguments. Its value and tangent at fixed choice must match the corresponding source leaf. The policy then passes the probability tangent to the extension's first input. The original source sampler still selects the hard outcome.

PARAMETER DESCRIPTION
module

The module owning both checked computations.

TYPE: QiecModule

computation

The scalar source with one reached Bernoulli draw.

TYPE: ComputationId

arguments

The point and directional seed of the source's parameters.

TYPE: tuple of int or Fraction

direction

The point and directional seed of the source's parameters.

TYPE: tuple of int or Fraction

policy

The explicit straight-through policy naming the one source site.

TYPE: SiteEstimator

extension

The closed real computation taking the extra first coordinate.

TYPE: str

fuel

The ordinary reference step bound per source replay or extension evaluation. The audit enumerates two hard scripts and checks the extension twice for each outcome.

TYPE: int DEFAULT: 50000

RETURNS DESCRIPTION
FiniteStraightThroughBernoulliAudit

The original law, biased mean and exact signed pointwise bias.

RAISES DESCRIPTION
ValueError

If the policy or other inputs are malformed.

JvpUnsupported

If the source or extension leaves the checked scalar fragment, or the extension changes the fixed-choice value or tangent.

JvpBoundaryError

If a reached input-dependent comparison lies on its boundary.

JvpLimit

If source paths, fuel or the exact coefficient bound is exceeded.

Source code in src/quivers/qiec/finite_straight_through.py
def audit_straight_through_bernoulli_gradient(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    policy: SiteEstimator,
    *,
    extension: str,
    fuel: int = 50_000,
) -> FiniteStraightThroughBernoulliAudit:
    """Audit one hard Bernoulli draw with a declared real extension.

    At each hard outcome, the extension receives that outcome as zero or
    one followed by the original source arguments. Its value and tangent
    at fixed choice must match the corresponding source leaf. The policy
    then passes the probability tangent to the extension's first input.
    The original source sampler still selects the hard outcome.

    Parameters
    ----------
    module : QiecModule
        The module owning both checked computations.
    computation : ComputationId
        The scalar source with one reached Bernoulli draw.
    arguments, direction : tuple of int or Fraction
        The point and directional seed of the source's parameters.
    policy : SiteEstimator
        The explicit straight-through policy naming the one source site.
    extension : str
        The closed real computation taking the extra first coordinate.
    fuel : int
        The ordinary reference step bound per source replay or extension
        evaluation. The audit enumerates two hard scripts and checks the
        extension twice for each outcome.

    Returns
    -------
    FiniteStraightThroughBernoulliAudit
        The original law, biased mean and exact signed pointwise bias.

    Raises
    ------
    ValueError
        If the policy or other inputs are malformed.
    JvpUnsupported
        If the source or extension leaves the checked scalar fragment,
        or the extension changes the fixed-choice value or tangent.
    JvpBoundaryError
        If a reached input-dependent comparison lies on its boundary.
    JvpLimit
        If source paths, fuel or the exact coefficient bound is exceeded.
    """
    if not isinstance(policy, SiteEstimator) or policy.estimator != "straight-through":
        raise ValueError("the audit requires an explicit straight-through site policy")
    point, seed = tuple(map(_fraction, arguments)), tuple(map(_fraction, direction))
    source = plan_bernoulli_gradient(
        module,
        computation,
        point,
        seed,
        (SiteEstimator(site=policy.site, estimator="score"),),
        max_paths=2,
        fuel=fuel,
    )
    tree = source.tree
    if (
        not isinstance(tree, BernoulliBranch)
        or not isinstance(tree.no, ExactJvp)
        or not isinstance(tree.yes, ExactJvp)
    ):
        raise JvpUnsupported("straight-through requires one reached Bernoulli draw")
    scripts, _, _ = _estimator_outcomes(source, 2, audit="straight-through audit")
    outcomes: list[BernoulliEstimatorOutcome] = []
    mean_tangent = Fraction(0)
    for script in scripts:
        (draw,) = script.decisions
        branch = tree.yes if draw.choice else tree.no
        extended_point = (int(draw.choice), *point)
        fixed = exact_jvp(module, extension, extended_point, (0, *seed), fuel=fuel)
        if fixed != branch:
            raise JvpUnsupported(
                "straight-through extension changes a fixed-choice value or tangent"
            )
        estimated = exact_jvp(
            module, extension, extended_point, (tree.visit.tangent, *seed), fuel=fuel
        )
        outcomes.append(
            replace(script, estimate=ExactJvp(branch.value, estimated.tangent))
        )
        mean_tangent += script.probability * estimated.tangent
        _bound(mean_tangent)
    bias = mean_tangent - source.exact.tangent
    _bound(bias)
    return FiniteStraightThroughBernoulliAudit(
        module,
        source,
        policy,
        extension,
        point,
        seed,
        ExactJvp(source.exact.value, mean_tangent),
        bias,
        tuple(outcomes),
    )

Binary Concrete relaxation bias

audit_binary_concrete_bias compares two checked source computations that use the same closed unary polynomial loss with no named callees. One passes a scalar RelaxedBernoulli draw to the loss. The other calls the loss with one or zero according to a scalar Bernoulli draw. Each uses its original nominal Random site and takes the probability directly from its sole argument. The audit accepts literal temperature one, probability one half, and an explicit relaxation policy at the relaxed site.

For the cubic loss and unit probability direction, the relaxed objective has expected value \(1/4\) and derivative \(3/5\). The hard objective has expected value \(1/2\) and derivative \(1\). The signed derivative bias is thus \(-2/5\). The report records the exact probability and direction alongside both objectives. Its bias bound concerns the ideal laws at this point and direction. A finite-precision sampler can be compared to the pointwise pathwise formula using fixed interior uniform noise.

binary_concrete_bias

Exact probability-coordinate bias of a checked scalar binary relaxation.

BinaryConcreteBiasAudit dataclass

BinaryConcreteBiasAudit(module: QiecModule, relaxed_computation: ComputationId, hard_computation: ComputationId, loss: ComputationId, policy: SiteEstimator, hard_site: SiteId, probability: Fraction, direction: Fraction, relaxed: ExactJvp, hard: ExactJvp)

The exact local bias of a relaxed draw against its checked hard law.

PARAMETER DESCRIPTION
module

The checked module containing both draws and the shared loss.

TYPE: QiecModule

relaxed_computation

The nominal identities of the paired owners and shared loss.

TYPE: ComputationId

hard_computation

The nominal identities of the paired owners and shared loss.

TYPE: ComputationId

loss

The nominal identities of the paired owners and shared loss.

TYPE: ComputationId

policy

The explicit relaxation policy at the original relaxed site.

TYPE: SiteEstimator

hard_site

The original hard site checked by exact enumeration.

TYPE: SiteId

probability

The exact source probability and its directional seed.

TYPE: Fraction

direction

The exact source probability and its directional seed.

TYPE: Fraction

relaxed

The two ideal expected returns and their directional derivatives.

TYPE: ExactJvp

hard

The two ideal expected returns and their directional derivatives.

TYPE: ExactJvp

signed_bias property

signed_bias: Fraction

Return the signed difference for this point and direction.

RETURNS DESCRIPTION
Fraction

The relaxed expected tangent minus the hard law's tangent.

semantics property

Report the existing bias contract for this audit's point and direction.

RETURNS DESCRIPTION
DerivativeSemantics

The relaxation policy and the exact local absolute bias. Zero here uses the canonical unbiased record for this direction.

audit_binary_concrete_bias

audit_binary_concrete_bias(module: QiecModule, relaxed: ComputationId, hard: ComputationId, probability: int | Fraction, direction: int | Fraction, policy: SiteEstimator, *, max_work: int = 65536, fuel: int = 50000) -> BinaryConcreteBiasAudit

Check a binary relaxation against the same loss on hard endpoints.

The relaxed source passes the result of one unplated RelaxedBernoulli with literal temperature one and direct probability input to a closed unary polynomial with no named callees. The hard source uses the same probability coordinate and the same nominal loss at one for true and zero for false. Both requests are original scalar sites on the same declared Random instance.

At probability one half, the ideal relaxed draw equals its uniform noise u and its probability derivative is 4u(1-u). Exact polynomial integration gives the relaxed expectation and tangent. The hard tangent is checked by the existing Bernoulli enumerator. The reported bias concerns this probability, direction and pair of checked objectives.

PARAMETER DESCRIPTION
module

The checked module containing the two owners and shared loss.

TYPE: QiecModule

relaxed

The selected original scalar computations.

TYPE: ComputationId

hard

The selected original scalar computations.

TYPE: ComputationId

probability

The probability point and its directional seed.

TYPE: int or Fraction

direction

The probability point and its directional seed.

TYPE: int or Fraction

policy

An explicit relaxation policy at the relaxed draw's actual site.

TYPE: SiteEstimator

max_work

The work limit passed to exact polynomial normalization.

TYPE: int DEFAULT: 65536

fuel

The reference step limit per hard enumeration replay.

TYPE: int DEFAULT: 50000

RETURNS DESCRIPTION
BinaryConcreteBiasAudit

The ideal paired expectations and their signed directional bias.

RAISES DESCRIPTION
ValueError

If an input, policy or budget is malformed.

JvpUnsupported

If the sources, point or site leave the stated fragment.

JvpLimit

If a work, step or exact coefficient limit is exceeded.

Source code in src/quivers/qiec/binary_concrete_bias.py
def audit_binary_concrete_bias(
    module: QiecModule,
    relaxed: ComputationId,
    hard: ComputationId,
    probability: int | Fraction,
    direction: int | Fraction,
    policy: SiteEstimator,
    *,
    max_work: int = 65_536,
    fuel: int = 50_000,
) -> BinaryConcreteBiasAudit:
    """Check a binary relaxation against the same loss on hard endpoints.

    The relaxed source passes the result of one unplated RelaxedBernoulli
    with literal temperature one and direct probability input to a closed
    unary polynomial with no named callees. The hard source uses the same
    probability coordinate
    and the same nominal loss at one for true and zero for false. Both
    requests are original scalar sites on the same declared Random instance.

    At probability one half, the ideal relaxed draw equals its uniform noise
    u and its probability derivative is 4u(1-u). Exact polynomial integration
    gives the relaxed expectation and tangent. The hard tangent is checked
    by the existing Bernoulli enumerator. The reported bias concerns this
    probability, direction and pair of checked objectives.

    Parameters
    ----------
    module : QiecModule
        The checked module containing the two owners and shared loss.
    relaxed, hard : ComputationId
        The selected original scalar computations.
    probability, direction : int or Fraction
        The probability point and its directional seed.
    policy : SiteEstimator
        An explicit `relaxation` policy at the relaxed draw's actual site.
    max_work : int
        The work limit passed to exact polynomial normalization.
    fuel : int
        The reference step limit per hard enumeration replay.

    Returns
    -------
    BinaryConcreteBiasAudit
        The ideal paired expectations and their signed directional bias.

    Raises
    ------
    ValueError
        If an input, policy or budget is malformed.
    JvpUnsupported
        If the sources, point or site leave the stated fragment.
    JvpLimit
        If a work, step or exact coefficient limit is exceeded.
    """
    _validate_limit("max_work", max_work)
    _validate_limit("fuel", fuel)
    point, seed = _fraction(probability), _fraction(direction)
    _bound(point, seed)
    if point != Fraction(1, 2):
        raise JvpUnsupported("binary relaxation bias requires probability 1/2")
    if not isinstance(policy, SiteEstimator) or policy.estimator != "relaxation":
        raise ValueError(
            "binary relaxation bias requires an explicit relaxation site policy"
        )

    soft_owner, soft, soft_dist, soft_site = _source_draw(
        module, relaxed, "RelaxedBernoulli", REAL
    )
    hard_owner, discrete, hard_dist, hard_site = _source_draw(
        module, hard, "Bernoulli", BOOL
    )
    if (
        soft_owner.type.effects != hard_owner.type.effects
        or soft_site == hard_site
        or policy.site != soft_site
    ):
        raise JvpUnsupported(
            "binary relaxation bias requires the paired original sites on the same Random instance"
        )
    if tuple(name for name, _ in soft_dist.arguments) != ("temperature", "probs"):
        raise JvpUnsupported(
            "RelaxedBernoulli must use literal temperature one and direct probs"
        )
    (_, temperature), (_, soft_probability) = soft_dist.arguments
    if not _real_literal(temperature, 1):
        raise JvpUnsupported("RelaxedBernoulli temperature must be literal Real one")
    if soft_probability != Var(
        local=soft_owner.parameters[0]
    ) or hard_dist.arguments != (("probs", Var(local=hard_owner.parameters[0])),):
        raise JvpUnsupported(
            "both Bernoulli draws must use their probability input directly as probs"
        )

    loss_call = soft.then
    if not isinstance(loss_call, Call) or loss_call.arguments != (
        Var(local=soft.binder),
    ):
        raise JvpUnsupported(
            "relaxed draw must be passed directly to the shared polynomial loss"
        )
    branch = discrete.then
    if (
        not isinstance(branch, If)
        or branch.condition != Var(local=discrete.binder)
        or not isinstance(branch.then, Call)
        or not isinstance(branch.otherwise, Call)
        or any(
            call.callee != loss_call.callee
            or len(call.arguments) != 1
            or not _real_literal(call.arguments[0], endpoint)
            for call, endpoint in ((branch.then, 1), (branch.otherwise, 0))
        )
    ):
        raise JvpUnsupported(
            "hard outcomes must call the same nominal loss at one and zero"
        )
    loss = next(item for item in module.computations if item.id == loss_call.callee)
    closed_loss = QiecModule(
        module=module.module,
        source_protocol=module.source_protocol,
        computations=(loss,),
    )
    try:
        normalized = check_polynomial_law(
            closed_loss, loss.name, loss.name, max_work=max_work
        )
    except PolynomialLawLimit as error:
        raise JvpLimit(f"binary relaxation loss proof: {error}") from error
    except (KernelError, PolynomialLawUnsupported) as error:
        raise JvpUnsupported(
            "shared binary relaxation loss must be a closed unary Real polynomial"
        ) from error

    primal = slope = Fraction()
    for (power,), coefficient in normalized.left:
        primal += coefficient / (power + 1)
        slope += Fraction(4 * power, (power + 1) * (power + 2)) * coefficient
        _bound(primal, slope)
    estimate = ExactJvp(primal, slope * seed)
    target = plan_bernoulli_gradient(
        module,
        hard,
        (point,),
        (seed,),
        (SiteEstimator(site=hard_site, estimator="enumerate"),),
        max_paths=2,
        fuel=fuel,
    ).exact
    _bound(estimate.tangent, estimate.tangent - target.tangent)
    return BinaryConcreteBiasAudit(
        module=module,
        relaxed_computation=relaxed,
        hard_computation=hard,
        loss=loss.id,
        policy=policy,
        hard_site=hard_site,
        probability=point,
        direction=seed,
        relaxed=estimate,
        hard=target,
    )

Finite continuation selection

finite_selection_jvp binds two operations on an authored entry's nominal effect instance. A choice request takes a Boolean direction. True maximizes the continuation loss and false minimizes it. A writer request adds an exact real loss independently of the returned value. When a continuation contains a later choice, the interpreter applies that choice before exposing the candidate loss to the earlier request. This is the bounded Boolean, whole-entry case of choice continuations. Plotkin and Xie (2025, §§2.3 and 4.3)

Each explored path uses its own writer. The result records the selected return, the selected loss, and the original request addresses for the decisions that selected the path. Strictly ordered losses give an exact tangent where the source's other comparisons are also stable. The default refuses ties. Setting choose_first_at_ties=True gives the false alternative at a tie and reports the tangent of the chosen path.

from quivers.dsl import loads
from quivers.qiec import finite_selection_jvp

module = loads("""
effect Selection
    choose : Bool -> Bool
    loss : Real -> Unit

instance selection : Selection

define tradeoff(x : Real) : Real !{selection} =
    let take_first <- perform selection.choose(false)
    if take_first then
        let recorded <- perform selection.loss(x * x)
        return 3.0 * x
    else
        let recorded <- perform selection.loss(5.0 * x)
        return 7.0 * x
""").qiec
assert module is not None
operations = {operation.name: operation.id for operation in module.effects[0].operations}
result = finite_selection_jvp(
    module, module.computations[0].id, (2,), (1,),
    choose=operations["choose"], loss=operations["loss"],
)
assert (result.value.value, result.value.tangent) == (6, 3)
assert (result.loss.value, result.loss.tangent) == (4, 4)
assert result.decisions[0].losses == (10, 4)

finite_selection

Interpret bounded binary choice over the exact loss of a QIEC continuation.

FiniteSelectionDecision dataclass

FiniteSelectionDecision(address: _Address, maximize: bool, losses: tuple[Fraction, Fraction], choice: bool)

The alternatives and the chosen answer at one realized occurrence.

PARAMETER DESCRIPTION
address

The original checked request's dynamic address.

TYPE: tuple

maximize

Whether the choice operation asks to maximize loss.

TYPE: bool

losses

Total source losses for the two policies' optimal continuations, in false, true order. Loss before the choice is common to both.

TYPE: tuple[Fraction, Fraction]

choice

The reply issued to the selected continuation.

TYPE: bool

FiniteSelectionResult dataclass

FiniteSelectionResult(value: ExactJvp, loss: ExactJvp, decisions: tuple[FiniteSelectionDecision, ...], ties: int, paths: int, source_steps: int)

Return, loss, and derivative observations for a checked finite choice.

PARAMETER DESCRIPTION
value

The returned value and tangent of the selected source path.

TYPE: ExactJvp

loss

The sum of the selected path's loss writes and its tangent.

TYPE: ExactJvp

decisions

Decisions in the selected trace, in execution order.

TYPE: tuple[FiniteSelectionDecision, ...]

ties

Equal comparisons across the explored tree. When this is positive, the tangents are of the selected path at the point.

TYPE: int

paths

The number of completed alternatives.

TYPE: int

source_steps

Actual reference machine steps, including speculative replays.

TYPE: int

finite_selection_jvp

finite_selection_jvp(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], *, choose: OperationId, loss: OperationId, choose_first_at_ties: bool = False, max_paths: int = 1024, fuel: int = 65536) -> FiniteSelectionResult

Handle authored binary selection over the loss of the remaining entry.

The selected entry has one closed nominal effect instance. Its bound choice, of type Bool -> Bool, takes a direction (true maximizes). Its bound writer, of type Real -> Unit, accumulates exact loss. Traversal interprets later decisions before comparing the losses offered to an earlier decision. Candidate evaluations have private writer state. The returned loss counts the selected writes once. Local control may use total authored monomorphic scalar handlers outside the selected effect, with grade zero, affine or one and no introduced effects. An early return skips the enclosed choices and writes in its abandoned continuation. Writes after the handler remain in scope. The scalar derivative is exact wherever all explored source comparisons and choices are locally fixed.

PARAMETER DESCRIPTION
module

The module supplying checked source and its effect interface.

TYPE: QiecModule

computation

The scalar real entry whose remaining computation defines the loss scope for all requests in it.

TYPE: ComputationId

arguments

Exact input coordinates in source position order.

TYPE: tuple[int or Fraction, ...]

direction

Exact tangent coordinates in the same order.

TYPE: tuple[int or Fraction, ...]

choose

The nominal Bool -> Bool operation of the entry's interface.

TYPE: OperationId

loss

The nominal Real -> Unit operation of the same interface.

TYPE: OperationId

choose_first_at_ties

Allow a pointwise branch tangent by choosing false at equal losses. By default equality refuses a derivative claim.

TYPE: bool DEFAULT: False

max_paths

Maximum number of complete alternatives.

TYPE: int DEFAULT: 1024

fuel

Reference machine steps allowed for each replay.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
FiniteSelectionResult

The exact selected source value, writer loss, and decisions.

RAISES DESCRIPTION
JvpUnsupported

If the source or either operation is outside the checked fragment.

JvpBoundaryError

If the source comparison is unstable or a selection ties.

JvpLimit

If the path, reference machine, or exact arithmetic bounds are hit.

ValueError

If an argument or resource limit is malformed.

Source code in src/quivers/qiec/finite_selection.py
def finite_selection_jvp(
    module: QiecModule,
    computation: ComputationId,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    *,
    choose: OperationId,
    loss: OperationId,
    choose_first_at_ties: bool = False,
    max_paths: int = 1_024,
    fuel: int = 65_536,
) -> FiniteSelectionResult:
    """Handle authored binary selection over the loss of the remaining entry.

    The selected entry has one closed nominal effect instance. Its
    bound choice, of type `Bool -> Bool`, takes a direction (true
    maximizes). Its bound writer, of type `Real -> Unit`, accumulates
    exact loss. Traversal interprets later decisions before comparing the
    losses offered to an earlier decision. Candidate evaluations have
    private writer state. The returned loss counts the selected writes
    once. Local control may use total authored monomorphic scalar
    handlers outside the selected effect, with grade zero, affine or
    one and no introduced effects. An early return skips the enclosed
    choices and writes in its abandoned continuation. Writes after the
    handler remain in scope. The scalar derivative is exact wherever
    all explored source comparisons and choices are locally fixed.

    Parameters
    ----------
    module : QiecModule
        The module supplying checked source and its effect interface.
    computation : ComputationId
        The scalar real entry whose remaining computation defines the
        loss scope for all requests in it.
    arguments : tuple[int or Fraction, ...]
        Exact input coordinates in source position order.
    direction : tuple[int or Fraction, ...]
        Exact tangent coordinates in the same order.
    choose : OperationId
        The nominal `Bool -> Bool` operation of the entry's interface.
    loss : OperationId
        The nominal `Real -> Unit` operation of the same interface.
    choose_first_at_ties : bool
        Allow a pointwise branch tangent by choosing false at equal
        losses. By default equality refuses a derivative claim.
    max_paths : int
        Maximum number of complete alternatives.
    fuel : int
        Reference machine steps allowed for each replay.

    Returns
    -------
    FiniteSelectionResult
        The exact selected source value, writer loss, and decisions.

    Raises
    ------
    JvpUnsupported
        If the source or either operation is outside the checked fragment.
    JvpBoundaryError
        If the source comparison is unstable or a selection ties.
    JvpLimit
        If the path, reference machine, or exact arithmetic bounds are hit.
    ValueError
        If an argument or resource limit is malformed.
    """
    for name, limit in (("max_paths", max_paths), ("fuel", fuel)):
        if type(limit) is not int or limit < 1:
            raise ValueError(f"{name} must be a positive integer")
    if type(choose_first_at_ties) is not bool:
        raise ValueError("choose_first_at_ties must be Boolean")
    registry = validate_module(module)
    owner = next((item for item in module.computations if item.id == computation), None)
    if owner is None:
        raise JvpUnsupported(f"unknown computation for finite selection {computation}")
    row = owner.type.effects
    if (
        owner.telescope
        or owner.type.result != REAL
        or any(parameter.type != REAL for parameter in owner.parameters)
        or row.tail is not None
        or len(row.entries) != 1
    ):
        raise JvpUnsupported(
            "finite selection needs a scalar real entry with one nominal effect instance"
        )
    if not len(arguments) == len(direction) == len(owner.parameters):
        raise ValueError("arguments and direction must match the computation's arity")
    effect = row.entries[0].effect
    declaration = next((item for item in module.effects if item.ref == effect), None)
    operations = (
        {} if declaration is None else {op.id: op for op in declaration.operations}
    )
    for identity, arg, result in ((choose, BOOL, BOOL), (loss, REAL, UNIT)):
        operation = operations.get(identity)
        if (
            operation is None
            or operation.telescope
            or tuple(parameter.type for parameter in operation.arguments) != (arg,)
            or operation.result_type != result
        ):
            raise JvpUnsupported(
                "finite selection operation does not match its nominal interface and signature"
            )

    def check_request(request: EffectRequest, instance: EffectInstanceId) -> None:
        """Restrict all reachable requests to the two checked operations.

        Parameters
        ----------
        request : EffectRequest
            A request found in the checked source graph.
        instance : EffectInstanceId
            The unique instance selected by the entry.

        Raises
        ------
        JvpUnsupported
            If the source requests another instance or operation.
        """
        if request.instance != instance or request.operation not in (choose, loss):
            raise JvpUnsupported("request is outside the finite selection interface")

    _check_first_order_graph(
        module,
        owner,
        "finite selection",
        check_request,
        allow_authored_control=True,
        require_at_most_one_resume=True,
    )
    instance = row.entries[0].instance
    environment = {
        parameter: _dual(_fraction(value), _fraction(tangent), True)
        for parameter, value, tangent in zip(
            owner.parameters, arguments, direction, strict=True
        )
    }
    records: dict[tuple[bool, ...], _Choice | _Completed] = {}
    pending: list[tuple[bool, ...]] = [()]
    paths = 1
    source_steps = 0
    while pending:
        prefix = pending.pop()
        evaluator = _SelectionEvaluator(module, fuel, instance, choose, prefix)
        try:
            value = _run_derivative(evaluator, owner, registry, environment)
        except _Choice as event:
            records[prefix] = event
            paths += 1
            if paths > max_paths:
                raise JvpLimit(
                    f"finite selection exceeds {max_paths} complete paths"
                ) from None
            pending.extend(((*prefix, True), (*prefix, False)))
        else:
            assert isinstance(value, _Dual) and evaluator.position == len(prefix)
            records[prefix] = _Completed(
                ExactJvp(value.value, value.tangent), evaluator.loss
            )
        finally:
            source_steps += evaluator._steps
    return _resolve(records, choose_first_at_ties, paths, source_steps)

Finite independent Bernoulli batches

plan_bernoulli_batch checks an ordered batch of a scalar source with direct Bernoulli draws. Each row gets the shared deterministic input prefix and its own local inputs. The source must have an acyclic call graph, and every complete history must have the same ordered sequence of draw addresses in every row.

Rows may select different constructors in an admitted scalar case. If both branches call the same sampler under the same checked address, the branches can use different probabilities and return different values. Any change to the ordered address sequence, including an extra draw or a different call activation, prevents a fixed-shape batch. This check uses scalar replay. The tensor planner below admits a narrower case shape.

The joint history law is the product of the row laws at the supplied shared values. Each observed address contains the axis label, row ordinal, and original source address. The row laws can agree while the joint coupling changes. For instance, two independent fair Booleans disagree with probability one half. Reusing one draw makes them agree on every run. The sampler draws each row's history from its checked finite support in row order.

expected gives the exact row expectations and their derivatives. replay gives the results and derivatives with the named choices held fixed, together with the probability of those choices in the independent source law. In each case the Jacobian acts on shared and row-local tangents. Its transpose sums adjoints to the shared prefix and returns local adjoints in row order. The plan checks this fragment by scalar reference runs in basis directions.

For a selected entry, Compiler.effect_plan(name).check_bernoulli_batch requests the finite-bernoulli-batch stage on the checked discharged module. The report identifies both executable graphs and retains the batch and the exact row expectation JVPs for the explicitly requested shared and local directions. The expectation derivative includes changes in history mass. The existing batch limits apply to scalar replay work. Ordinary discharge and digest construction have separate costs. The method selects this native stage only for the explicit request. Physical tensor replay and portable target reporting retain their own entry points.

from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, plan_bernoulli_batch

source = """
instance random : Random

define unit(s : Real, p : Real, x : Real) : Real !{random} =
    let yes <- perform random.sample[Bool](site("yes"), Bernoulli(probs=p))
    if yes then
        return s * x
    else
        return x
"""
module = Compiler(parse(source), module_name="finite-batch").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "unit")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="enumerate")
batch = plan_bernoulli_batch(
    module, entry.id, "Items", (2,), ((Fraction(1, 2), 3), (Fraction(1, 4), 4)), (policy,),
)
assert batch.expected.values == (Fraction(9, 2), 5)
assert batch.expected.jvp((1,), ((0, 0), (0, 0))) == (Fraction(3, 2), 1)
assert batch.expected.vjp((2, -1)).shared == (2,)
replay = batch.replay((batch.paths[0][0].tape, batch.paths[1][1].tape))
assert replay.probability == Fraction(1, 8)
assert replay.linearization.values == (3, 8)
assert replay.linearization.jvp((1,), ((0, 0), (0, 0))) == (0, 4)

finite_bernoulli_batch

Exact independent row axes for finite Bernoulli source computations.

BernoulliBatchCotangent dataclass

BernoulliBatchCotangent(shared: tuple[Fraction, ...], rows: tuple[tuple[Fraction, ...], ...])

Adjoints for the shared prefix and the row-local input vectors.

PARAMETER DESCRIPTION
shared

The sum of all rows' adjoints for the same shared inputs.

TYPE: tuple[Fraction, ...]

rows

The independent row-local adjoints in axis order.

TYPE: tuple[tuple[Fraction, ...], ...]

BernoulliBatchLinearization dataclass

BernoulliBatchLinearization(shared_arity: int, rows: tuple[ExactGradient, ...])

The exact ordered row outputs and their source-parameter gradients.

PARAMETER DESCRIPTION
shared_arity

The length of the deterministic parameter prefix shared by all rows.

TYPE: int

rows

The row values and gradients in original source parameter order.

TYPE: tuple[ExactGradient, ...]

values property

values: tuple[Fraction, ...]

Give the row values in axis order.

RETURNS DESCRIPTION
tuple[Fraction, ...]

The output vector.

jvp

jvp(shared: tuple[int | Fraction, ...], rows: tuple[tuple[int | Fraction, ...], ...]) -> tuple[Fraction, ...]

Apply the exact batch Jacobian to shared and row-local tangents.

PARAMETER DESCRIPTION
shared

The one common tangent for the shared source inputs.

TYPE: tuple[int or Fraction, ...]

rows

A local tangent for each row in axis order.

TYPE: tuple[tuple[int or Fraction, ...], ...]

RETURNS DESCRIPTION
tuple[Fraction, ...]

The output tangent for each row.

RAISES DESCRIPTION
ValueError

If any of the input tangent axes have the wrong extent.

Source code in src/quivers/qiec/finite_bernoulli_batch.py
def jvp(
    self,
    shared: tuple[int | Fraction, ...],
    rows: tuple[tuple[int | Fraction, ...], ...],
) -> tuple[Fraction, ...]:
    """Apply the exact batch Jacobian to shared and row-local tangents.

    Parameters
    ----------
    shared : tuple[int or Fraction, ...]
        The one common tangent for the shared source inputs.
    rows : tuple[tuple[int or Fraction, ...], ...]
        A local tangent for each row in axis order.

    Returns
    -------
    tuple[Fraction, ...]
        The output tangent for each row.

    Raises
    ------
    ValueError
        If any of the input tangent axes have the wrong extent.
    """
    if len(shared) != self.shared_arity or len(rows) != len(self.rows):
        raise ValueError(
            "batch tangents must match the shared prefix and row count"
        )
    shared_seed = tuple(map(_fraction, shared))
    results: list[Fraction] = []
    for row, local in zip(self.rows, rows, strict=True):
        if len(local) != len(row.gradient) - self.shared_arity:
            raise ValueError("each local tangent must match its row's input arity")
        seed = (*shared_seed, *map(_fraction, local))
        _bound(*seed)
        result = sum(
            (
                slope * value
                for slope, value in zip(row.gradient, seed, strict=True)
            ),
            Fraction(0),
        )
        _bound(result)
        results.append(result)
    return tuple(results)

vjp

vjp(cotangents: tuple[int | Fraction, ...]) -> BernoulliBatchCotangent

Apply the transpose Jacobian in row order.

PARAMETER DESCRIPTION
cotangents

One output cotangent for each row.

TYPE: tuple[int or Fraction, ...]

RETURNS DESCRIPTION
BernoulliBatchCotangent

The shared summed adjoints and the separate row-local adjoints.

RAISES DESCRIPTION
ValueError

If the output cotangent has the wrong row extent.

Source code in src/quivers/qiec/finite_bernoulli_batch.py
def vjp(self, cotangents: tuple[int | Fraction, ...]) -> BernoulliBatchCotangent:
    """Apply the transpose Jacobian in row order.

    Parameters
    ----------
    cotangents : tuple[int or Fraction, ...]
        One output cotangent for each row.

    Returns
    -------
    BernoulliBatchCotangent
        The shared summed adjoints and the separate row-local adjoints.

    Raises
    ------
    ValueError
        If the output cotangent has the wrong row extent.
    """
    if len(cotangents) != len(self.rows):
        raise ValueError("the batch cotangent must match the row count")
    shared = [Fraction(0)] * self.shared_arity
    locals_: list[tuple[Fraction, ...]] = []
    for row, cotangent in zip(self.rows, cotangents, strict=True):
        seed = _fraction(cotangent)
        _bound(seed)
        projected = tuple(seed * slope for slope in row.gradient)
        _bound(*projected)
        for position, contribution in enumerate(projected[: self.shared_arity]):
            shared[position] += contribution
            _bound(shared[position])
        locals_.append(projected[self.shared_arity :])
    return BernoulliBatchCotangent(tuple(shared), tuple(locals_))

BernoulliRowReplay dataclass

BernoulliRowReplay(axis: str, ordinal: int, choices: _History)

A replay tape for one original row and its canonical sample scopes.

PARAMETER DESCRIPTION
axis

The finite batch axis label.

TYPE: str

ordinal

The original row ordinal.

TYPE: int

choices

The canonical local addresses and replayed Boolean outcomes in order.

TYPE: tuple

addresses property

addresses: tuple[_AxisAddress, ...]

Give the original request addresses with their row coordinates.

RETURNS DESCRIPTION
tuple

An axis label, row ordinal and original address per occurrence.

BernoulliBatchPath dataclass

BernoulliBatchPath(tape: BernoulliRowReplay, probability: Fraction, action: ExactGradient)

One checked conditional path in an independent row.

PARAMETER DESCRIPTION
tape

The complete addressed replay choices.

TYPE: BernoulliRowReplay

probability

The source probability of those choices in their original scope.

TYPE: Fraction

action

The source result and derivatives with the replay choices fixed.

TYPE: ExactGradient

BernoulliBatchReplay dataclass

BernoulliBatchReplay(tapes: tuple[BernoulliRowReplay, ...], probability: Fraction, linearization: BernoulliBatchLinearization)

One complete jointly addressed replay in the independent product law.

PARAMETER DESCRIPTION
tapes

The original tapes in row order.

TYPE: tuple[BernoulliRowReplay, ...]

probability

Their joint probability in the independent source law.

TYPE: Fraction

linearization

The row outputs and derivatives with these choices fixed.

TYPE: BernoulliBatchLinearization

BernoulliBatchPlan dataclass

BernoulliBatchPlan(axis: str, computation: ComputationId, shared_point: tuple[Fraction, ...], row_points: tuple[tuple[Fraction, ...], ...], shape: tuple[_Address, ...], expected: BernoulliBatchLinearization, paths: tuple[tuple[BernoulliBatchPath, ...], ...], source_steps: int, selectors: tuple[tuple[Fraction, ...], ...])

A checked independent finite row axis over the same scalar program.

PARAMETER DESCRIPTION
axis

The axis label for the row namespaces.

TYPE: str

computation

The named scalar source run independently in every row.

TYPE: ComputationId

shared_point

The exact deterministic shared parameters and row-local parameters.

TYPE: tuple

row_points

The exact deterministic shared parameters and row-local parameters.

TYPE: tuple

shape

The same ordered sequence of local addresses on every history.

TYPE: tuple

expected

The exact expected row values and their derivatives, including the parameter dependence of each row's probability.

TYPE: BernoulliBatchLinearization

paths

Each row's original independent support, in ordinal order.

TYPE: tuple[tuple[BernoulliBatchPath, ...], ...]

source_steps

The total measured scalar reference work over the row and basis runs.

TYPE: int

selectors

The exact categorical sampler for each independent row support.

TYPE: tuple[tuple[Fraction, ...], ...]

replay

replay(tapes: tuple[BernoulliRowReplay, ...]) -> BernoulliBatchReplay

Replay complete row-local choices at their original addresses.

PARAMETER DESCRIPTION
tapes

One tape per row in axis order, with each choice fixed.

TYPE: tuple[BernoulliRowReplay, ...]

RETURNS DESCRIPTION
BernoulliBatchReplay

The exact fixed-replay value map and its derivative.

RAISES DESCRIPTION
ValueError

If any axis, ordinal, address, Boolean choice or tape count differs from the checked row shape.

Source code in src/quivers/qiec/finite_bernoulli_batch.py
def replay(self, tapes: tuple[BernoulliRowReplay, ...]) -> BernoulliBatchReplay:
    """Replay complete row-local choices at their original addresses.

    Parameters
    ----------
    tapes : tuple[BernoulliRowReplay, ...]
        One tape per row in axis order, with each choice fixed.

    Returns
    -------
    BernoulliBatchReplay
        The exact fixed-replay value map and its derivative.

    Raises
    ------
    ValueError
        If any axis, ordinal, address, Boolean choice or tape count differs
        from the checked row shape.
    """
    if len(tapes) != len(self.paths):
        raise ValueError("a batch replay needs one addressed tape per row")
    paths: list[BernoulliBatchPath] = []
    for ordinal, (tape, support) in enumerate(zip(tapes, self.paths, strict=True)):
        if (
            tape.axis != self.axis
            or type(tape.ordinal) is not int
            or tape.ordinal != ordinal
        ):
            raise ValueError("batch replay tapes must match the axis and row order")
        if tuple(address for address, _ in tape.choices) != self.shape or any(
            type(choice) is not bool for _, choice in tape.choices
        ):
            raise ValueError(
                "batch replay choices must match the checked original addresses"
            )
        path = next(item for item in support if item.tape == tape)
        paths.append(path)
    return self._replayed(tuple(paths))

sample

sample(*, seed: int | None = None) -> BernoulliBatchReplay

Draw separately from each row's complete source law.

PARAMETER DESCRIPTION
seed

An optional seed for exact integer draws in row order.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
BernoulliBatchReplay

One joint ordered trace and its fixed-replay linearization.

Source code in src/quivers/qiec/finite_bernoulli_batch.py
def sample(self, *, seed: int | None = None) -> BernoulliBatchReplay:
    """Draw separately from each row's complete source law.

    Parameters
    ----------
    seed : int or None
        An optional seed for exact integer draws in row order.

    Returns
    -------
    BernoulliBatchReplay
        One joint ordered trace and its fixed-replay linearization.
    """
    random = Random(seed)
    selected = tuple(
        support[_choose_position(selectors, random)]
        for support, selectors in zip(self.paths, self.selectors, strict=True)
    )
    return self._replayed(selected)

plan_bernoulli_batch

plan_bernoulli_batch(module: QiecModule, computation: ComputationId, axis: str, shared: tuple[int | Fraction, ...], rows: tuple[tuple[int | Fraction, ...], ...], policies: tuple[SiteEstimator, ...], *, max_rows: int = 256, max_paths: int = 256, max_work: int = 1000000, fuel: int = 50000) -> BernoulliBatchPlan

Validate a finite independent row axis and its exact linearizations.

Source inputs start with the shared deterministic parameters, followed by that row's local inputs. All reached requests must be direct Bernoulli draws on one nominal Random row. The call graph is acyclic. Closed scalar constructor cases and linear call-address scopes may remain in the discharged graph. Every complete trace of every row must have the same ordered local addresses. Row random choices are separate even when all row inputs and local address sequences coincide.

Each scalar basis direction gives the fixed-path derivatives and the derivative of the row expectation. The replay maps hold choices fixed. The expectation maps include their changing probabilities.

PARAMETER DESCRIPTION
module

The actual checked source.

TYPE: QiecModule

computation

The scalar entry to run on each row.

TYPE: ComputationId

axis

The nonempty axis label used to namespace requests.

TYPE: str

shared

The exact shared deterministic input prefix.

TYPE: tuple[int or Fraction, ...]

rows

The exact local inputs in ordinal row order.

TYPE: tuple[tuple[int or Fraction, ...], ...]

policies

The explicit enumeration policies for the common static sites.

TYPE: tuple[SiteEstimator, ...]

max_rows

Bounds on row count, complete paths per scalar run, aggregate reference steps, and steps per replay prefix.

TYPE: int DEFAULT: 256

max_paths

Bounds on row count, complete paths per scalar run, aggregate reference steps, and steps per replay prefix.

TYPE: int DEFAULT: 256

max_work

Bounds on row count, complete paths per scalar run, aggregate reference steps, and steps per replay prefix.

TYPE: int DEFAULT: 256

fuel

Bounds on row count, complete paths per scalar run, aggregate reference steps, and steps per replay prefix.

TYPE: int DEFAULT: 256

RETURNS DESCRIPTION
BernoulliBatchPlan

The checked row support, replay values and exact batch derivatives.

RAISES DESCRIPTION
ValueError

If an axis, input table, policy, or bound is malformed.

JvpUnsupported

If the row graph, operation, probability or trace shape is outside the admitted finite independent fragment.

JvpBoundaryError

If an active source decision is at an input equality boundary.

JvpLimit

If a row, path, arithmetic or reference-work limit is exceeded.

Source code in src/quivers/qiec/finite_bernoulli_batch.py
def plan_bernoulli_batch(
    module: QiecModule,
    computation: ComputationId,
    axis: str,
    shared: tuple[int | Fraction, ...],
    rows: tuple[tuple[int | Fraction, ...], ...],
    policies: tuple[SiteEstimator, ...],
    *,
    max_rows: int = 256,
    max_paths: int = 256,
    max_work: int = 1_000_000,
    fuel: int = 50_000,
) -> BernoulliBatchPlan:
    """Validate a finite independent row axis and its exact linearizations.

    Source inputs start with the shared deterministic parameters, followed
    by that row's local inputs. All reached requests must be direct
    Bernoulli draws on one nominal Random row. The call graph is acyclic.
    Closed scalar constructor cases and linear call-address scopes may
    remain in the discharged graph.
    Every complete trace of every row must have the same ordered local
    addresses. Row random choices are separate even when all row inputs
    and local address sequences coincide.

    Each scalar basis direction gives the fixed-path derivatives and
    the derivative of the row expectation. The replay maps hold choices
    fixed. The expectation maps include their changing probabilities.

    Parameters
    ----------
    module : QiecModule
        The actual checked source.
    computation : ComputationId
        The scalar entry to run on each row.
    axis : str
        The nonempty axis label used to namespace requests.
    shared : tuple[int or Fraction, ...]
        The exact shared deterministic input prefix.
    rows : tuple[tuple[int or Fraction, ...], ...]
        The exact local inputs in ordinal row order.
    policies : tuple[SiteEstimator, ...]
        The explicit enumeration policies for the common static sites.
    max_rows, max_paths, max_work, fuel : int
        Bounds on row count, complete paths per scalar run, aggregate
        reference steps, and steps per replay prefix.

    Returns
    -------
    BernoulliBatchPlan
        The checked row support, replay values and exact batch derivatives.

    Raises
    ------
    ValueError
        If an axis, input table, policy, or bound is malformed.
    JvpUnsupported
        If the row graph, operation, probability or trace shape is outside
        the admitted finite independent fragment.
    JvpBoundaryError
        If an active source decision is at an input equality boundary.
    JvpLimit
        If a row, path, arithmetic or reference-work limit is exceeded.
    """
    for name, value in (
        ("max_rows", max_rows),
        ("max_paths", max_paths),
        ("max_work", max_work),
        ("fuel", fuel),
    ):
        _validate_limit(name, value)
    if not isinstance(axis, str) or not axis.strip() or not rows:
        raise ValueError("a Bernoulli batch needs an axis label and at least one row")
    if len(rows) > max_rows:
        raise JvpLimit(f"Bernoulli batch exceeds {max_rows} rows")
    _, owner = _random_computation(module, computation, "Bernoulli batch")
    _check_first_order_graph(
        module,
        owner,
        "Bernoulli batch",
        _check_request,
        require_acyclic=True,
        allow_closed_cases=True,
        allow_shot_scopes=True,
    )
    arity = len(owner.parameters)
    if len(shared) > arity or any(len(shared) + len(row) != arity for row in rows):
        raise ValueError("shared and row-local inputs must match the source arity")
    shared_point = tuple(map(_fraction, shared))
    row_points = tuple(tuple(map(_fraction, row)) for row in rows)
    shape: tuple[_Address, ...] | None = None
    batches: list[tuple[BernoulliBatchPath, ...]] = []
    expectations: list[ExactGradient] = []
    selectors: list[tuple[Fraction, ...]] = []
    work = _BernoulliWork(max_work, "Bernoulli batch")
    for ordinal, row in enumerate(row_points):
        point = (*shared_point, *row)
        results: list[ExactJvp] = []
        supports: list[tuple[tuple[_History, ExactJvp, ExactJvp], ...]] = []
        for index in range(max(1, arity)):
            seed = tuple(int(position == index) for position in range(arity))
            finite = _checked_finite_unit(
                module, computation, point, seed, policies, max_paths, fuel, work=work
            )
            results.append(finite.exact)
            support = tuple(_prior_histories(finite.tree))
            for history, _, _ in support:
                addresses = tuple(address for address, _ in history)
                if shape is None:
                    shape = addresses
                if addresses != shape:
                    raise JvpUnsupported(
                        "Bernoulli batch needs the same ordered draw addresses on every history"
                    )
            supports.append(support)
        expected = ExactGradient(
            results[0].value, tuple(result.tangent for result in results[:arity])
        )
        expectations.append(expected)
        paths: list[BernoulliBatchPath] = []
        for across_bases in zip(*supports, strict=True):
            history, prior, value = across_bases[0]
            gradient = tuple(result.tangent for _, _, result in across_bases[:arity])
            assert all(
                bits == history
                and mass.value == prior.value
                and pair.value == value.value
                for bits, mass, pair in across_bases
            )
            paths.append(
                BernoulliBatchPath(
                    BernoulliRowReplay(axis, ordinal, history),
                    prior.value,
                    ExactGradient(value.value, gradient),
                )
            )
        batches.append(tuple(paths))
        selectors.append(
            _selector_probabilities(tuple(path.probability for path in paths))
        )
    assert shape is not None
    return BernoulliBatchPlan(
        axis,
        computation,
        shared_point,
        row_points,
        shape,
        BernoulliBatchLinearization(len(shared_point), tuple(expectations)),
        tuple(batches),
        work.spent,
        tuple(selectors),
    )

Tensor replay and sampling

EffectPlan.check_bernoulli_tensor_replay applies a JVP to one actual physical replay on the independently checked discharge with the default common-address tensor axis. Provide one complete addressed tape per row and directions in the same floating domain as the shared and local inputs. The report records the original and discharged identities, detached copies of that point and direction, the actual tapes, and the physical evaluator passes, steps and lane steps. Those counts describe source execution. It returns the values and per-request log scores with their working-precision fixed-tape JVPs. A nonfinite observation refuses. The numerical observation concerns this native execution at the recorded point and direction. The scalar batch check reports expectation JVPs.

BernoulliTensorAxis runs the literal-branch fragment through one QIEC evaluator pass using Torch tensors. Shared inputs stay scalar until an operation needs the row axis. Each Bernoulli request produces a separate choice and log probability for each row, even when every row has the same probability. The tensor pass retains the original request address and adds the row ordinal on each tape. The output reports passes, aggregate source steps, and lane steps, which weight each pass by its active row count.

For a straight-line discharged handler, the checked tensor pass can also restore fixed call and resumption scopes. Each draw retains its original local address, including the shot ordinal, inside the row's tape. A replay must provide all of these entries in source order. This fragment requires the same sequence of local addresses on every admitted row and every replay choice.

The active source uses addition, subtraction, multiplication, negation, and conversion of a Boolean to a Real. The evaluator runs only the selected arm and checks that every reached probability is strictly between zero and one in the run's floating dtype.

The tensor planner also accepts a closed two-constructor case when a pure initial call chooses its constructor with a single strict comparison of a Real input to a literal. Each arm must call the same direct Bernoulli helper once. Sampling and default replay require one complete source draw address across reached arms. Replay runs each nonempty group of rows that shares a constructor and a replayed bit. Sampling uses up to two additional passes to collect the active probabilities at the common address before drawing one vector in original row order. Replay needs at most four passes and sampling needs at most six, regardless of row count. Fuel bounds their combined source steps. Only selected rows reach partial operations such as division. Crossing the selector threshold changes the branch being differentiated, and the axis refuses equality at the threshold. The native Bernoulli law scores probabilities directly, including values closer to zero or one than machine epsilon. The case planner checks that the reciprocal of the scored mass fits in the working dtype. Replay checks the recorded outcome. Sampling checks both possible masses before drawing.

Pass allow_disjoint_replay=True to construct a replay-only axis whose selected constructors can reach different source addresses. The checked case may use one direct draw per arm or the common sampling helper. Each row tape must give exactly one Boolean choice at its selected full address. The executor checks the address against the reached request and gathers values and scores back into row order. The one score column represents the selected occurrence in each row, and each row's tape identifies its site. The replay index uses one address index and bit per row and at most two distinct addresses. It retains the four-pass bound. A replay-only axis refuses sampling before using a generator. Supply one BernoulliRowReplay per row, using that row's checked scalar address and its fixed bit. The exact batch planner retains its common-history contract.

replay accepts the same addressed tapes as the exact scalar plan when the source satisfies both fragments. The output has one value per row and a log score per row and request. A PyTorch JVP or VJP through replay differentiates the value and log score with those choices fixed. A derivative of an expectation must also account for the dependence of the choice probabilities on the parameters. See the finite Bernoulli estimator rules for that calculation.

import torch
from quivers.dsl import Compiler, parse
from quivers.qiec import BernoulliTensorAxis

source = """
instance random : Random

define unit(s : Real, p : Real, x : Real) : Real !{random} =
    let yes <- perform random.sample[Bool](site("yes"), Bernoulli(probs=p))
    return x + s * real(yes)
"""
module = Compiler(parse(source), module_name="tensor-batch").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "unit")
axis = BernoulliTensorAxis(module, entry.id, "Items", shared_arity=1)
shared = torch.tensor([2.0], dtype=torch.float64)
rows = torch.tensor([[0.25, 3.0], [0.75, 4.0]], dtype=torch.float64)
sample = axis.sample(shared, rows, generator=torch.Generator().manual_seed(7))
assert sample.source_passes == 1
assert sample.log_scores.shape == (2, 1)
assert [tape.ordinal for tape in sample.tapes] == [0, 1]

def fixed(s):
    return axis.replay(s, rows, sample.tapes).values

values, tangents = torch.func.jvp(fixed, (shared,), (torch.ones_like(shared),))
torch.testing.assert_close(values, sample.values)
assert tangents.tolist() == [float(tape.choices[0][1]) for tape in sample.tapes]
import torch
from quivers.dsl import Compiler, parse
from quivers.qiec import BernoulliTensorAxis

source = """
instance random : Random

family Route : Type
    constructor Upper : Real -> Route
    constructor Lower : Real -> Route

define route(x : Real) : Route !{} =
    if x > 0.0 then
        return (Upper(x) : Route)
    else
        return (Lower(x) : Route)

define toss(p : Real) : Bool !{random} =
    perform random.sample[Bool](site("toss"), Bernoulli(probs=p))

define unit(x : Real, p : Real, q : Real) : Real !{random} =
    let selected <- route(x)
    case selected motive => Real
        Upper(offset) =>
            let bit <- toss(p)
            return offset + real(bit)
        Lower(offset) =>
            let bit <- toss(q)
            return offset + 2.0 * real(bit)
"""
module = Compiler(parse(source), module_name="tensor-case").qiec_module
entry = next(item for item in module.computations if item.name == "unit")
axis = BernoulliTensorAxis(module, entry.id, "Items", shared_arity=0)
rows = torch.tensor([[0.5, 0.25, 0.75], [-0.5, 0.25, 0.75]], dtype=torch.float64)
shared = rows.new_empty((0,))
sample = axis.sample(shared, rows, generator=torch.Generator().manual_seed(7))
bits = rows.new_tensor([int(tape.choices[0][1]) for tape in sample.tapes])
torch.testing.assert_close(sample.values, rows[:, 0] + bits * rows.new_tensor([1.0, 2.0]))
assert [tape.choices[0][0][1] for tape in sample.tapes] == [(('call', 'toss#2'),)] * 2
assert sample.source_passes == 4
assert axis.replay(shared, rows, sample.tapes).source_passes == 2

bernoulli_tensor_axis

One-pass tensor execution for a checked independent Bernoulli row axis.

BernoulliTensorResult dataclass

BernoulliTensorResult(values: Tensor, log_scores: Tensor, tapes: tuple[BernoulliRowReplay, ...], source_passes: int, source_steps: int, lane_steps: int = 0)

Values and addressed log scores from one tensor-axis invocation.

PARAMETER DESCRIPTION
values

The source results in row order.

TYPE: Tensor

log_scores

The fixed-outcome log probability of each request, laid out as rows by request occurrence. Differentiation of these scores holds the Boolean outcomes fixed. With disjoint replay, the same column may refer to different source addresses across rows. The tapes give each row's actual address.

TYPE: Tensor

tapes

The original source addresses and choices lifted to the row axis.

TYPE: tuple[BernoulliRowReplay, ...]

source_passes

The number of checked evaluator invocations.

TYPE: int

source_steps

The sum of machine steps across the executed passes.

TYPE: int

lane_steps

The sum of each pass's machine steps times its active row count.

TYPE: int DEFAULT: 0

BernoulliTensorAxis

BernoulliTensorAxis(module: QiecModule, computation: ComputationId, axis: str, shared_arity: int, *, max_rows: int = 256, fuel: int = 50000, allow_disjoint_replay: bool = False)

Check source for native tensor execution over independent rows.

Only scalar Real entries with one nominal Random row, acyclic calls, direct unplated Boolean Bernoulli draws and an elementwise polynomial fragment are admitted. Literal Boolean decisions use one pass. A two-constructor case with one strict scalar selector and a common direct Bernoulli helper may use bounded passes over the reached row subsets. Explicit disjoint replay permits one addressed draw per constructor and keeps each row's supplied outcome and original request address. A straight-line discharged handler may use fixed resumption scopes. Its shot labels remain part of each row's local address. Shared inputs are scalars and local inputs are tensor columns. Draws and log scores keep the row axis even when a probability is shared.

PARAMETER DESCRIPTION
module

The actual source module to validate and execute.

TYPE: QiecModule

computation

The nominal scalar source entry.

TYPE: ComputationId

axis

The label used with the ordinal in each row's addresses.

TYPE: str

shared_arity

How many initial source parameters are shared across rows.

TYPE: int

max_rows

The maximum number of rows and source steps in one invocation.

TYPE: int DEFAULT: 256

fuel

The maximum number of rows and source steps in one invocation.

TYPE: int DEFAULT: 256

allow_disjoint_replay

Use only replay on the checked two-constructor case. Each selected constructor can use its own complete source request address.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ValueError

If the entry, axis label, arity or a bound is malformed.

JvpUnsupported

If the checked source leaves the tensor fragment.

Source code in src/quivers/qiec/bernoulli_tensor_axis.py
def __init__(
    self,
    module: QiecModule,
    computation: ComputationId,
    axis: str,
    shared_arity: int,
    *,
    max_rows: int = 256,
    fuel: int = 50_000,
    allow_disjoint_replay: bool = False,
) -> None:
    _validate_limit("max_rows", max_rows)
    _validate_limit("fuel", fuel)
    if type(allow_disjoint_replay) is not bool:
        raise ValueError("allow_disjoint_replay must be a Boolean")
    if not isinstance(axis, str) or not axis.strip():
        raise ValueError("a Bernoulli tensor axis needs a nonempty label")
    fragment = "Bernoulli tensor axis"
    self._registry, self._owner = _random_computation(module, computation, fragment)
    if type(shared_arity) is not int or not 0 <= shared_arity <= len(
        self._owner.parameters
    ):
        raise ValueError("shared arity must be within the source entry arity")
    self._case = None
    try:
        _check_first_order_graph(
            module,
            self._owner,
            fragment,
            _check_request,
            require_acyclic=True,
            allow_shot_scopes=True,
        )
        _check_tensor_terms(module, self._owner)
    except JvpUnsupported:
        self._case = _case_axis(
            module, self._owner, allow_disjoint_replay=allow_disjoint_replay
        )
        if self._case is None:
            raise
        _check_first_order_graph(
            module,
            self._owner,
            fragment,
            _check_request,
            require_acyclic=True,
            allow_closed_cases=True,
        )
        _check_tensor_terms(module, self._owner, self._case)
    if allow_disjoint_replay and self._case is None:
        raise JvpUnsupported(
            "disjoint Bernoulli replay needs a two-constructor case"
        )
    self._module = module
    self._axis = axis
    self._allow_disjoint_replay = allow_disjoint_replay
    self._shared_arity = shared_arity
    self._max_rows = max_rows
    self._fuel = fuel

replay

replay(shared: Tensor, rows: Tensor, tapes: tuple[BernoulliRowReplay, ...]) -> BernoulliTensorResult

Run all rows on fixed addressed tapes, keeping scores and derivatives.

PARAMETER DESCRIPTION
shared

The shared input prefix, with one axis of source parameters.

TYPE: Tensor

rows

The local inputs, laid out as rows by local source parameters.

TYPE: Tensor

tapes

One complete tape per row in ordinal order.

TYPE: tuple[BernoulliRowReplay, ...]

RETURNS DESCRIPTION
BernoulliTensorResult

Finite tensor values and per-request log scores. PyTorch JVPs and VJPs differentiate both with the supplied choices fixed.

RAISES DESCRIPTION
ValueError

If the input tensors, probabilities or replay addresses fail a check.

JvpLimit

If the row or machine step limit is exceeded.

Source code in src/quivers/qiec/bernoulli_tensor_axis.py
def replay(
    self,
    shared: torch.Tensor,
    rows: torch.Tensor,
    tapes: tuple[BernoulliRowReplay, ...],
) -> BernoulliTensorResult:
    """Run all rows on fixed addressed tapes, keeping scores and derivatives.

    Parameters
    ----------
    shared : torch.Tensor
        The shared input prefix, with one axis of source parameters.
    rows : torch.Tensor
        The local inputs, laid out as rows by local source parameters.
    tapes : tuple[BernoulliRowReplay, ...]
        One complete tape per row in ordinal order.

    Returns
    -------
    BernoulliTensorResult
        Finite tensor values and per-request log scores. PyTorch JVPs
        and VJPs differentiate both with the supplied choices fixed.

    Raises
    ------
    ValueError
        If the input tensors, probabilities or replay addresses fail a check.
    JvpLimit
        If the row or machine step limit is exceeded.
    """
    return self._run(shared, rows, tapes, None)

sample

sample(shared: Tensor, rows: Tensor, *, generator: Generator | None = None) -> BernoulliTensorResult

Sample one independent Boolean vector at each source request.

PARAMETER DESCRIPTION
shared

The shared input prefix.

TYPE: Tensor

rows

The rows by local-parameters table.

TYPE: Tensor

generator

Optional torch generator on the input device. Requests are visited in source order and each draw fills all row ordinals.

TYPE: Generator or None DEFAULT: None

RETURNS DESCRIPTION
BernoulliTensorResult

The sampled values, log scores and addressed replay tapes. Derivatives through selection require a separate estimator.

RAISES DESCRIPTION
ValueError

If the input tensors or probabilities fail a check.

JvpLimit

If the row or machine step limit is exceeded.

JvpUnsupported

If this axis was checked for disjoint replay only.

Source code in src/quivers/qiec/bernoulli_tensor_axis.py
def sample(
    self,
    shared: torch.Tensor,
    rows: torch.Tensor,
    *,
    generator: torch.Generator | None = None,
) -> BernoulliTensorResult:
    """Sample one independent Boolean vector at each source request.

    Parameters
    ----------
    shared : torch.Tensor
        The shared input prefix.
    rows : torch.Tensor
        The rows by local-parameters table.
    generator : torch.Generator or None
        Optional torch generator on the input device. Requests are
        visited in source order and each draw fills all row ordinals.

    Returns
    -------
    BernoulliTensorResult
        The sampled values, log scores and addressed replay tapes.
        Derivatives through selection require a separate estimator.

    Raises
    ------
    ValueError
        If the input tensors or probabilities fail a check.
    JvpLimit
        If the row or machine step limit is exceeded.
    JvpUnsupported
        If this axis was checked for disjoint replay only.
    """
    if self._allow_disjoint_replay:
        raise JvpUnsupported(
            "a disjoint Bernoulli tensor axis supports replay only"
        )
    return self._run(shared, rows, None, generator)

Scored Bernoulli replay

check_scored_bernoulli_tensor_replay checks a straight-line discharge with one original Random instance and one original Score instance against independent fixed-tape scalar executions. Each row provides all of its original Bernoulli addresses and outcomes. The checked observation retains the ordered sequence of outward draws and scores, the separate log-probability and additive-factor columns, and their directional derivatives. The joint unnormalized mass of a replayed outcome is the exponential of the sum of both columns for that row.

scored_bernoulli_tensor_evidence records digests of the source, request, selected graph, and measured observation, including its work counts. verify_scored_bernoulli_tensor_evidence repeats the comparison using the verifier’s own binary64 inputs, directions, and tapes. The physical comparison uses eight times binary64 epsilon as relative tolerance and zero absolute tolerance. Receipt verification requires equality of the observation digest.

In this example, the two Bernoulli outcomes have probabilities \(1/4\) and \(3/4\) at \(p=1/4\). In the direction \(dp=1\), their log-probability derivatives are \(4\) and \(-4/3\). The extra log factor is \(p\) in both rows, with derivative \(1\).

import torch

from quivers.dsl import Compiler, parse
from quivers.qiec import (
    BernoulliRowReplay,
    Bind,
    Perform,
    ScoredBernoulliTensorEvidenceRequest,
    check_scored_bernoulli_tensor_replay,
    scored_bernoulli_tensor_evidence,
    verify_scored_bernoulli_tensor_evidence,
)

source = """
instance random : Random
instance score : Score

define subject(p : Real) : Real !{random, score} =
    let b <- perform random.sample[Bool](site("choice"), Bernoulli(probs=p))
    perform score.add(weight(p))
    return real(b)
"""
plan = Compiler(parse(source), module_name="docs.scored_replay").effect_plan("subject")
module = plan.bundle.module
entry = next(c for c in module.computations if c.id == plan.computation)
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
site = str(entry.body.first.request.origin.static_site)
tapes = tuple(
    BernoulliRowReplay("Rows", row, (((site, (), ()), answer),))
    for row, answer in enumerate((True, False))
)
shared = torch.empty(0, dtype=torch.float64)
points = torch.full((2, 1), 0.25, dtype=torch.float64)
directions = torch.ones_like(points)
observed = check_scored_bernoulli_tensor_replay(
    module, plan.computation, "Rows", shared, points, tapes,
    shared_direction=shared, row_directions=directions,
)
assert observed.replay.values.tolist() == [1.0, 0.0]
assert observed.factor_scores.tolist() == [[0.25], [0.25]]
assert observed.factor_score_jvp.tolist() == [[1.0], [1.0]]
torch.testing.assert_close(
    observed.log_score_jvp,
    torch.tensor([[4.0], [-4.0 / 3.0]], dtype=torch.float64),
)
request = ScoredBernoulliTensorEvidenceRequest(
    plan.computation, "Rows", shared, points, tapes, shared, directions,
)
evidence = scored_bernoulli_tensor_evidence(module, request)
assert verify_scored_bernoulli_tensor_evidence(module, evidence, request=request) == evidence

scored_bernoulli_tensor_evidence

scored_bernoulli_tensor_evidence(source: QiecModule, request: ScoredBernoulliTensorEvidenceRequest) -> EffectScoredBernoulliTensorEvidence

Record a checked scored row comparison and its exact measured bytes.

PARAMETER DESCRIPTION
source

The original checked program containing the entry.

TYPE: QiecModule

request

The exact tensors, original tapes and checked resource limits.

TYPE: ScoredBernoulliTensorEvidenceRequest

RETURNS DESCRIPTION
EffectScoredBernoulliTensorEvidence

The source-bound receipt of the completed comparison.

RAISES DESCRIPTION
ValueError

If a requested coordinate or checked observation fails.

TypeError

If the request, tensor or tape uses an unsupported host type.

JvpUnsupported

If the source leaves the scored row fragment.

JvpLimit

If the selected replay reaches a work limit.

Source code in src/quivers/qiec/scored_bernoulli_tensor_evidence.py
def scored_bernoulli_tensor_evidence(
    source: QiecModule, request: ScoredBernoulliTensorEvidenceRequest
) -> EffectScoredBernoulliTensorEvidence:
    """Record a checked scored row comparison and its exact measured bytes.

    Parameters
    ----------
    source : QiecModule
        The original checked program containing the entry.
    request : ScoredBernoulliTensorEvidenceRequest
        The exact tensors, original tapes and checked resource limits.

    Returns
    -------
    EffectScoredBernoulliTensorEvidence
        The source-bound receipt of the completed comparison.

    Raises
    ------
    ValueError
        If a requested coordinate or checked observation fails.
    TypeError
        If the request, tensor or tape uses an unsupported host type.
    JvpUnsupported
        If the source leaves the scored row fragment.
    JvpLimit
        If the selected replay reaches a work limit.
    """
    frozen = _snapshot(request)
    return _measure(source, frozen, _request_digest(frozen))

Declared row-parallel operations

A RowParallelOperation names an outward instance, its operation, and a closed QIEC computation with the same scalar Real signature. The replay checks that the computation uses elementwise primitives and allocates no addresses. For each reached operation, it compares the answer and its directional derivative against independent scalar execution of the original source. The schedule records the nominal instance and operation together with the full original address. Each row adds its own axis label and ordinal.

The operation table may include several declarations for one interface or distinct instances. Their deterministic interpretations compose with addressed Bernoulli draws and additive scores. An empty Bernoulli tape specifies a deterministic row with no draws. The replay refuses an undeclared reached operation or an installation that would intercept a declared outward request. The portable receipt names the ordered operation table and axis, binds the original and discharged graphs, and verifies all channels against independently supplied replay inputs.

Here the operation computes \(x^2\) and the entry returns \(x^2+x\). In the two rows, the inputs are \(2\) and \(3\) with directions \(1\) and \(-1\).

import torch

from quivers.dsl import Compiler, parse
from quivers.qiec import (
    BernoulliRowReplay,
    RowParallelOperation,
    RowParallelTensorEvidenceRequest,
    check_row_parallel_tensor_replay,
    loads,
    dumps,
    row_parallel_tensor_evidence,
    verify_row_parallel_tensor_evidence,
)

source = """
effect Step
    adjust : Real -> Real

instance lane : Step

define square(x : Real) : Real !{} =
    return x * x

define subject(x : Real) : Real !{lane} =
    let y <- perform lane.adjust(x)
    return y + x
"""
plan = Compiler(parse(source)).effect_plan("subject")
module = plan.bundle.module
instance = next(item.entry for item in module.instances if item.name == "lane")
effect = next(item for item in module.effects if item.ref == instance.effect)
operation = next(item.id for item in effect.operations if item.name == "adjust")
square = next(item.id for item in module.computations if item.name == "square")
bindings = (RowParallelOperation(instance.instance, operation, square),)
tapes = tuple(BernoulliRowReplay("Rows", row, ()) for row in range(2))
shared = torch.empty(0, dtype=torch.float64)
points = torch.tensor([[2.0], [3.0]], dtype=torch.float64)
directions = torch.tensor([[1.0], [-1.0]], dtype=torch.float64)
result = check_row_parallel_tensor_replay(
    module, plan.computation, bindings, "Rows", shared, points, tapes,
    shared_direction=shared, row_directions=directions,
)
assert result.replay.values.tolist() == [6.0, 12.0]
assert result.value_jvp.tolist() == [5.0, -7.0]
assert result.operation_jvp.tolist() == [[4.0], [-6.0]]
request = RowParallelTensorEvidenceRequest(
    plan.computation, bindings, "Rows", shared, points, tapes, shared, directions,
)
receipt = loads(dumps(row_parallel_tensor_evidence(module, request)))
assert verify_row_parallel_tensor_evidence(module, receipt, request=request) == receipt

row_parallel_tensor_evidence

row_parallel_tensor_evidence(source: QiecModule, request: RowParallelTensorEvidenceRequest) -> EffectRowParallelTensorEvidence

Record the completed source check and native measured bytes.

PARAMETER DESCRIPTION
source

The original checked source.

TYPE: QiecModule

request

The independent typed declaration set, tensors and original tapes.

TYPE: RowParallelTensorEvidenceRequest

RETURNS DESCRIPTION
EffectRowParallelTensorEvidence

The detached stage receipt.

RAISES DESCRIPTION
TypeError

If a request or tensor uses an unsupported host type.

ValueError

If a requested coordinate or observed result is invalid.

JvpUnsupported

If the declaration or graph leaves the checked row fragment.

JvpLimit

If the physical or reference replay reaches its work limit.

Source code in src/quivers/qiec/row_parallel_tensor_evidence.py
def row_parallel_tensor_evidence(
    source: QiecModule, request: RowParallelTensorEvidenceRequest
) -> EffectRowParallelTensorEvidence:
    """Record the completed source check and native measured bytes.

    Parameters
    ----------
    source : QiecModule
        The original checked source.
    request : RowParallelTensorEvidenceRequest
        The independent typed declaration set, tensors and original tapes.

    Returns
    -------
    EffectRowParallelTensorEvidence
        The detached stage receipt.

    Raises
    ------
    TypeError
        If a request or tensor uses an unsupported host type.
    ValueError
        If a requested coordinate or observed result is invalid.
    JvpUnsupported
        If the declaration or graph leaves the checked row fragment.
    JvpLimit
        If the physical or reference replay reaches its work limit.
    """
    frozen, _, digest = _bound_request(request)
    return _measure(source, frozen, digest)

Polynomial laws

The polynomial checker compares scalar real computations after discharging their authored handlers. It interprets the admitted arithmetic over rational coefficients. A real literal contributes the exact rational value it represents, and a quotient of two constants can supply an exact coefficient such as 1.0 / 3.0.

The checker supports addition, subtraction, multiplication, division by a closed nonzero constant, and nonnegative integral constant powers. It checks divisors in the source before using the discharged result, including divisors in bindings whose results are unused. A runtime branch condition leaves the polynomial fragment.

Each normal form lists monomial exponents in parameter order and their coefficients. Equal forms certify equality on the scalar polynomial domain. When the forms differ, the checker gives integer arguments and the two exact rational results.

polynomial_laws

Exact polynomial laws for the scalar real fragment of QIEC.

The checker interprets the supported scalar operations in the polynomial ring over the rationals. A QIEC real literal contributes its represented rational value. For instance, 1.0 / 3.0 gives the exact coefficient one third. Named continuations can expose their answers as shared scalar parameters after their handlers have discharged.

PolynomialLawUnsupported

Bases: ValueError

The law is outside the exact polynomial fragment.

PolynomialLawLimit

Bases: ValueError

Normalization or witness construction exceeded a resource limit.

PolynomialLawCounterexample dataclass

PolynomialLawCounterexample(arguments: tuple[int, ...], left: Fraction, right: Fraction)

An exact input at which the two polynomials differ.

PARAMETER DESCRIPTION
arguments

The integer arguments, in parameter order.

TYPE: tuple[int, ...]

left

The exact rational value on the left.

TYPE: Fraction

right

The exact rational value on the right.

TYPE: Fraction

PolynomialLawDecision dataclass

PolynomialLawDecision(parameters: tuple[str, ...], left: _Terms, right: _Terms, counterexample: PolynomialLawCounterexample | None = None)

Normalized polynomial terms and a witness if they differ.

PARAMETER DESCRIPTION
parameters

The left computation's parameter names, in position order.

TYPE: tuple[str, ...]

left

The left monomials with exact coefficients, sorted by exponents.

TYPE: tuple[tuple[tuple[int, ...], Fraction], ...]

right

The corresponding terms on the right.

TYPE: tuple[tuple[tuple[int, ...], Fraction], ...]

counterexample

A separating input, or no witness when the normal forms agree.

TYPE: PolynomialLawCounterexample or None DEFAULT: None

check_polynomial_law

check_polynomial_law(module: QiecModule, left: str, right: str, *, max_work: int = 65536) -> PolynomialLawDecision

Check a scalar polynomial identity between two QIEC computations.

PARAMETER DESCRIPTION
module

The module with the checked computations.

TYPE: QiecModule

left

The left computation's name.

TYPE: str

right

The right computation's name. Both sides must have equally many scalar real arguments, a scalar real result, and empty residual effect rows.

TYPE: str

max_work

The budget for visiting terms, expanding monomials, and finding a separating assignment.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
PolynomialLawDecision

Exact rational normal forms and a witness if they differ.

RAISES DESCRIPTION
PolynomialLawUnsupported

If either side leaves the scalar polynomial fragment.

PolynomialLawLimit

If normalization or witness construction exhausts a limit.

ValueError

If the work limit is not a positive integer.

Source code in src/quivers/qiec/polynomial_laws.py
def check_polynomial_law(
    module: QiecModule,
    left: str,
    right: str,
    *,
    max_work: int = 65_536,
) -> PolynomialLawDecision:
    """Check a scalar polynomial identity between two QIEC computations.

    Parameters
    ----------
    module : QiecModule
        The module with the checked computations.
    left : str
        The left computation's name.
    right : str
        The right computation's name. Both sides must have equally many
        scalar real arguments, a scalar real result, and empty residual
        effect rows.
    max_work : int
        The budget for visiting terms, expanding monomials, and finding
        a separating assignment.

    Returns
    -------
    PolynomialLawDecision
        Exact rational normal forms and a witness if they differ.

    Raises
    ------
    PolynomialLawUnsupported
        If either side leaves the scalar polynomial fragment.
    PolynomialLawLimit
        If normalization or witness construction exhausts a limit.
    ValueError
        If the work limit is not a positive integer.
    """
    _validate_limit("max_work", max_work)
    validate_module(module)
    discharged = discharge_module(module)
    named = {item.name: item for item in discharged.module.computations}
    if left not in named or right not in named:
        missing = left if left not in named else right
        raise PolynomialLawUnsupported(
            f"unknown polynomial law computation `{missing}`"
        )
    lhs, rhs = named[left], named[right]
    _scalar(lhs)
    _scalar(rhs)
    width = len(lhs.parameters)
    if width != len(rhs.parameters):
        raise PolynomialLawUnsupported(
            "a polynomial law requires matching positional signatures"
        )
    interpreter = _Normalizer(discharged, width, max_work)
    interpreter.spend(width * width)
    arguments = tuple(
        {tuple(int(i == j) for i in range(width)): Fraction(1)} for j in range(width)
    )
    try:
        interpreter.check_source(module, left, right)
        first = interpreter.call(lhs, arguments, frozenset())
        second = interpreter.call(rhs, arguments, frozenset())
        witness = interpreter.counterexample(first, second)
    except RecursionError as error:
        raise PolynomialLawLimit("polynomial law nesting limit exhausted") from error
    return PolynomialLawDecision(
        tuple(parameter.name for parameter in lhs.parameters),
        tuple(sorted(first.items())),
        tuple(sorted(second.items())),
        witness,
    )

Rational laws

The rational checker runs the original, checked computation with exact symbolic scalar arithmetic. A divisor contributes a nonzero condition whenever it is evaluated, including in an unused binding. Both sides of an equation must have the same nonzero domain polynomial after multiplying their distinct monic guards. When the checker cannot establish this domain agreement, it reports an unsupported law.

On a shared domain the checker compares exact numerators over a common denominator. If they differ, it returns integer arguments where both computations are defined and gives their exact rational values. The checker supports authored handlers whose branch choices can be resolved during the symbolic run, including branches selected by resumed Booleans.

rational_laws

Exact identities of partial scalar rational functions computed by QIEC.

RationalLawUnsupported

Bases: ValueError

The checker cannot decide a law in the supported rational fragment.

RationalLawLimit

Bases: ValueError

Exact rational evaluation exhausted a resource limit.

RationalLawDecision dataclass

RationalLawDecision(parameters: tuple[str, ...], domain_polynomial: _Terms, difference_numerator: _Terms, counterexample: PolynomialLawCounterexample | None)

A comparison on an exactly identified common rational domain.

PARAMETER DESCRIPTION
parameters

The left computation's inputs, in position order.

TYPE: tuple[str, ...]

domain_polynomial

The domain consists of inputs at which this polynomial is nonzero.

TYPE: tuple[tuple[tuple[int, ...], Fraction], ...]

difference_numerator

The numerator after writing the difference over a common denominator. The empty tuple is the zero polynomial.

TYPE: tuple[tuple[tuple[int, ...], Fraction], ...]

counterexample

A separating integer input in the common domain with exact values, or no witness if both sides agree throughout the domain.

TYPE: PolynomialLawCounterexample or None

check_rational_law

check_rational_law(module: QiecModule, left: str, right: str, *, max_work: int = 65536, fuel: int = 65536) -> RationalLawDecision

Compare two checked scalar computations on a common rational domain.

The checked reference evaluator preserves the order and strictness of calls, authored clauses and resumptions. Each side accumulates exact divisor guards even for unused intermediate results. A decision requires equal normalized products of monic nonzero guards.

PARAMETER DESCRIPTION
module

The module declaring both computations.

TYPE: QiecModule

left

The first computation's name.

TYPE: str

right

The second computation's name. The computations have matching scalar real signatures and empty residual rows.

TYPE: str

max_work

The budget for exact arithmetic and finding a witness.

TYPE: int DEFAULT: 65536

fuel

The reference step budget per side.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
RationalLawDecision

The shared domain and the difference numerator, with an exact witness in the domain if the values can differ.

RAISES DESCRIPTION
RationalLawUnsupported

If a computation or domain is outside the admitted exact fragment.

RationalLawLimit

If arithmetic or the reference evaluator exhausts a limit.

ValueError

If a limit is not a positive integer.

Source code in src/quivers/qiec/rational_laws.py
def check_rational_law(
    module: QiecModule,
    left: str,
    right: str,
    *,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> RationalLawDecision:
    """Compare two checked scalar computations on a common rational domain.

    The checked reference evaluator preserves the order and strictness of
    calls, authored clauses and resumptions. Each side accumulates exact
    divisor guards even for unused intermediate results. A decision
    requires equal normalized products of monic nonzero guards.

    Parameters
    ----------
    module : QiecModule
        The module declaring both computations.
    left : str
        The first computation's name.
    right : str
        The second computation's name. The computations have matching
        scalar real signatures and empty residual rows.
    max_work : int
        The budget for exact arithmetic and finding a witness.
    fuel : int
        The reference step budget per side.

    Returns
    -------
    RationalLawDecision
        The shared domain and the difference numerator, with an exact
        witness in the domain if the values can differ.

    Raises
    ------
    RationalLawUnsupported
        If a computation or domain is outside the admitted exact fragment.
    RationalLawLimit
        If arithmetic or the reference evaluator exhausts a limit.
    ValueError
        If a limit is not a positive integer.
    """
    _validate_limit("max_work", max_work)
    _validate_limit("fuel", fuel)
    registry = validate_module(module)
    named = {item.name: item for item in module.computations}
    if left not in named or right not in named:
        unknown = left if left not in named else right
        raise RationalLawUnsupported(f"unknown rational law computation `{unknown}`")
    lhs, rhs = named[left], named[right]
    width = len(lhs.parameters)
    ring = _PolynomialRing(width, max_work)
    evaluator = _RationalEvaluator(module, ring, fuel)
    try:
        _scalar(lhs)
        _scalar(rhs)
        if width != len(rhs.parameters):
            raise RationalLawUnsupported(
                "a rational law requires matching positional signatures"
            )
        ring.spend(width * width)
        symbolic = tuple(
            evaluator.fraction(
                {tuple(int(i == j) for i in range(width)): Fraction(1)}, evaluator.one
            )
            for j in range(width)
        )
        first = evaluator.evaluate_validated(
            lhs.body, registry, dict(zip(lhs.parameters, symbolic, strict=True))
        )
        domain = evaluator.domain()
        second = evaluator.evaluate_validated(
            rhs.body, registry, dict(zip(rhs.parameters, symbolic, strict=True))
        )
        if domain != evaluator.domain():
            raise RationalLawUnsupported(
                "could not establish equal rational law domains"
            )
        assert isinstance(first, _Fraction) and isinstance(second, _Fraction)
        difference = ring.add(
            ring.multiply(dict(first.numerator), dict(second.denominator)),
            ring.multiply(dict(second.numerator), dict(first.denominator)),
            -1,
        )
        witness = ring.counterexample(ring.multiply(difference, domain), {})
        if witness is not None:
            arguments = witness.arguments
            witness = PolynomialLawCounterexample(
                arguments,
                _value_at(ring, first, arguments),
                _value_at(ring, second, arguments),
            )
    except (FuelExhaustedError, PolynomialLawLimit) as error:
        raise RationalLawLimit(str(error)) from error
    except RecursionError as error:
        raise RationalLawLimit("rational law nesting limit exhausted") from error
    except (EvaluationError, PolynomialLawUnsupported) as error:
        raise RationalLawUnsupported(str(error)) from error
    return RationalLawDecision(
        tuple(parameter.name for parameter in lhs.parameters),
        tuple(sorted(domain.items())),
        tuple(sorted(difference.items())),
        witness,
    )

Rational derivative rules

An authored scalar derivative rule is a checked computation. A forward rule takes the primal arguments followed by their tangents. Each reverse component takes the primal arguments and one output cotangent. Reverse components follow the order of the primal parameters.

The checker differentiates the primal's symbolic rational form, then compares each supplied rule with the resulting derivative action for all seeds. This establishes linearity in the seeds and, when both rules are supplied, transposition. A false identity has an exact separating input.

Every evaluated divisor also supplies a nonzero guard. The checker must establish that all candidate rules are defined everywhere the primal is defined, including at zero seeds. A rule may divide by the square of a divisor already checked by the primal. When the checker cannot establish domain coverage, it raises RationalLawUnsupported.

An effect_law declaration with a primal names derivative actions in QVR. Give a jvp, a positional vjp list, or both. Each name refers to an authored computation. For a closed wrapper around a handled operation, the rule concerns that wrapper's denotation with its chosen handler. Reverse actions may repeat when coordinates have identical derivatives. A nullary primal takes an empty reverse list.

from quivers.dsl import Compiler, parse
from quivers.qiec import EffectDerivativeRequest, Rational, check_rational_derivative_rule

source = """
define ratio(x : Real, y : Real) : Real !{} =
    return x / y

define push(x : Real, y : Real, dx : Real, dy : Real) : Real !{} =
    return (dx * y - x * dy) / (y * y)

define pull_x(x : Real, y : Real, seed : Real) : Real !{} =
    return seed / y

define pull_y(x : Real, y : Real, seed : Real) : Real !{} =
    return (0.0 - seed * x) / (y * y)

effect_law ratio_rule [primal=ratio, jvp=push, vjp=[pull_x, pull_y]]
"""
compiler = Compiler(parse(source), module_name="checked-ratio-rule")
module = compiler.qiec_module
assert module is not None
rule = compiler.authored_derivative_rule("ratio_rule")
decision = check_rational_derivative_rule(module, rule)
assert decision.certified
assert decision.domain_polynomial == (((0, 1), 1),)
receipt = compiler.effect_plan("ratio").target_derivative_evidence(
    EffectDerivativeRequest(target="stan", rule=rule)
)
assert receipt.rule_status == "checked"
assert receipt.rule_domain == (((0, 1), Rational.of(1)),)
assert not receipt.emission.refusals

A RationalDerivativeDeclaration identifies its primal, forward action, and reverse components by computation ID. It can be serialized independently of the executable module. Passing it to exact_jvp or exact_gradient checks the identities against the supplied module before executing the named action. The checker returns the primal guard and any separating input. Each application keeps the primal evaluation's ordinary domain and resource limits.

from fractions import Fraction

from quivers.dsl import loads
from quivers.qiec import (
    RationalDerivativeDeclaration,
    check_rational_derivative_rule,
    dumps,
    exact_jvp,
)
from quivers.qiec import loads as read_qiec

module = loads("""
define mean_term(x : Real) : Real !{} =
    return 1.0 / x

define mean_direction(x : Real, step : Real) : Real !{} =
    return -step / (x * x)
""").qiec
assert module is not None
ids = {computation.name: computation.id for computation in module.computations}
rule = RationalDerivativeDeclaration(primal=ids["mean_term"], jvp=ids["mean_direction"])
decoded = read_qiec(dumps(rule))
assert isinstance(decoded, RationalDerivativeDeclaration)
assert check_rational_derivative_rule(module, decoded).certified
result = exact_jvp(module, "mean_term", (2,), (3,), rule=decoded)
assert (result.value, result.tangent) == (Fraction(1, 2), Fraction(-3, 4))

RationalDerivativeDeclaration didactic-model

RationalDerivativeDeclaration(*, primal: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), jvp: ComputationId | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), vjp: tuple[ComputationId, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Name the authored directional actions of a checked scalar computation.

PARAMETER DESCRIPTION
primal

The computation whose derivative is declared.

TYPE: ComputationId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

jvp

A forward computation taking the primal coordinates and their tangents.

TYPE: ComputationId or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

vjp

A scalar reverse action for each primal coordinate, in input order. They each take the primal coordinates followed by the output seed.

TYPE: tuple[ComputationId, ...] or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

derivative_rules

Check authored scalar derivative rules by exact rational identities.

RationalDerivativeComponent dataclass

RationalDerivativeComponent(computation: str, difference_numerator: _Terms, counterexample: PolynomialLawCounterexample | None)

A checked equality for an authored derivative computation.

PARAMETER DESCRIPTION
computation

The authored computation's name.

TYPE: str

difference_numerator

The numerator of the authored result minus the formal derivative action. Monomial exponents are in the authored parameter order.

TYPE: tuple[tuple[tuple[int, ...], Fraction], ...]

counterexample

An exact argument vector in the primal domain at which the authored value (left) and formal derivative action (right) differ.

TYPE: PolynomialLawCounterexample or None

RationalDerivativeDecision dataclass

RationalDerivativeDecision(primal: str, parameters: tuple[str, ...], domain_polynomial: _Terms, jvp: RationalDerivativeComponent | None, vjp: tuple[RationalDerivativeComponent, ...] | None)

Derivative rule checks on one strictly evaluated primal domain.

PARAMETER DESCRIPTION
primal

The primal computation's name.

TYPE: str

parameters

Its input parameters in positional order.

TYPE: tuple[str, ...]

domain_polynomial

The primal inputs where this polynomial is nonzero are the domain of the symbolic reference execution.

TYPE: tuple[tuple[tuple[int, ...], Fraction], ...]

jvp

The result for the supplied forward rule, if present.

TYPE: RationalDerivativeComponent or None

vjp

The supplied reverse component results in primal parameter order.

TYPE: tuple[RationalDerivativeComponent, ...] or None

certified property

certified: bool

Whether all supplied components implement the exact derivatives.

RETURNS DESCRIPTION
bool

Whether every checked difference is identically zero.

check_rational_derivative_rule

check_rational_derivative_rule(module: QiecModule, primal: str | RationalDerivativeDeclaration, *, jvp: str | None = None, vjp: tuple[str, ...] | None = None, max_work: int = 65536, fuel: int = 65536) -> RationalDerivativeDecision

Certify authored derivative actions of a checked scalar computation.

A JVP takes the n primal coordinates followed by their n tangents. A VJP has one scalar computation per primal coordinate. Each takes the primal coordinates followed by an output cotangent. A certificate establishes agreement with the formal derivative for every such seed on the primal's domain. Thus each action is linear in its seed and both actions, if supplied, are transposes at each primal point.

PARAMETER DESCRIPTION
module

The module declaring the primal and the supplied rules.

TYPE: QiecModule

primal

A named computation with scalar real inputs and result and an empty residual effect row. A declaration supplies the primal and actions by their nominal IDs in this module.

TYPE: str or RationalDerivativeDeclaration

jvp

A named scalar computation implementing the forward rule.

TYPE: str or None DEFAULT: None

vjp

Named scalar computations implementing the reverse action in primal parameter order.

TYPE: tuple[str, ...] or None DEFAULT: None

max_work

The exact arithmetic and counterexample-search budget.

TYPE: int DEFAULT: 65536

fuel

The reference machine step budget per computation.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
RationalDerivativeDecision

The verified primal domain and component checks. A false identity carries an exact separating input in the domain.

RAISES DESCRIPTION
RationalLawUnsupported

If a computation is outside the rational fragment, or a rule's domain cannot be shown to cover the primal domain for every seed.

RationalLawLimit

If arithmetic or reference evaluation exhausts a limit.

ValueError

If no rule was specified, a declaration was combined with separately named actions, or a limit is invalid.

Source code in src/quivers/qiec/derivative_rules.py
def check_rational_derivative_rule(
    module: QiecModule,
    primal: str | RationalDerivativeDeclaration,
    *,
    jvp: str | None = None,
    vjp: tuple[str, ...] | None = None,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> RationalDerivativeDecision:
    """Certify authored derivative actions of a checked scalar computation.

    A JVP takes the n primal coordinates followed by their n tangents.
    A VJP has one scalar computation per primal coordinate. Each takes
    the primal coordinates followed by an output cotangent. A certificate
    establishes agreement with the formal derivative for every such seed
    on the primal's domain. Thus each action is linear in its seed and
    both actions, if supplied, are transposes at each primal point.

    Parameters
    ----------
    module : QiecModule
        The module declaring the primal and the supplied rules.
    primal : str or RationalDerivativeDeclaration
        A named computation with scalar real inputs and result and an
        empty residual effect row. A declaration supplies the primal
        and actions by their nominal IDs in this module.
    jvp : str or None
        A named scalar computation implementing the forward rule.
    vjp : tuple[str, ...] or None
        Named scalar computations implementing the reverse action in
        primal parameter order.
    max_work : int
        The exact arithmetic and counterexample-search budget.
    fuel : int
        The reference machine step budget per computation.

    Returns
    -------
    RationalDerivativeDecision
        The verified primal domain and component checks. A false identity
        carries an exact separating input in the domain.

    Raises
    ------
    RationalLawUnsupported
        If a computation is outside the rational fragment, or a rule's
        domain cannot be shown to cover the primal domain for every seed.
    RationalLawLimit
        If arithmetic or reference evaluation exhausts a limit.
    ValueError
        If no rule was specified, a declaration was combined with
        separately named actions, or a limit is invalid.
    """
    _validate_limit("max_work", max_work)
    _validate_limit("fuel", fuel)
    if isinstance(primal, RationalDerivativeDeclaration):
        if jvp is not None or vjp is not None:
            raise ValueError("a derivative declaration already specifies its actions")
        names = {item.id: item.name for item in module.computations}
        try:
            jvp = None if primal.jvp is None else names[primal.jvp]
            vjp = (
                None
                if primal.vjp is None
                else tuple(names[rule] for rule in primal.vjp)
            )
            primal = names[primal.primal]
        except KeyError as error:
            raise RationalLawUnsupported(
                "a rational derivative declaration names an unknown computation"
            ) from error
    if jvp is None and vjp is None:
        raise ValueError("at least one derivative rule is required")
    declarations = {item.name: item for item in module.computations}
    owner = declarations.get(primal)
    if owner is None:
        raise RationalLawUnsupported(f"unknown primal computation `{primal}`")
    arity = len(owner.parameters)
    try:
        _scalar(owner)
        forward = None if jvp is None else _rule(declarations, jvp, 2 * arity)
        reverse = None
        if vjp is not None:
            if len(vjp) != arity:
                raise RationalLawUnsupported(
                    "a VJP requires one rule per primal parameter"
                )
            reverse = tuple(_rule(declarations, name, arity + 1) for name in vjp)
        checker = _RuleChecker(module, arity, max_work, fuel)
        value, domain = checker.evaluate(owner)
        checked_jvp, checked_vjp = checker.expected(
            value, arity, forward, reverse, domain
        )
    except (FuelExhaustedError, PolynomialLawLimit) as error:
        raise RationalLawLimit(str(error)) from error
    except RecursionError as error:
        raise RationalLawLimit(
            "rational derivative rule nesting limit exhausted"
        ) from error
    except (EvaluationError, PolynomialLawUnsupported) as error:
        raise RationalLawUnsupported(str(error)) from error
    return RationalDerivativeDecision(
        primal,
        tuple(parameter.name for parameter in owner.parameters),
        tuple(sorted((powers[:arity], value) for powers, value in domain.items())),
        checked_jvp,
        checked_vjp,
    )

Tunneling

A request that reaches generic code only through an open row tunnels past the handlers that code installs for its instance (reference). Elaboration inserts the Mask terms, and the kernel rejects a body in which a handler could intercept such a request.

tunneling

Lexically scoped instances: requests from an open row tunnel past handlers.

A computation that is polymorphic in an effect row, such as one taking a function f : A -> B !{| rho}, is not given the instances rho stands for. If it installs a handler for an instance i around an application of f, a caller that instantiates rho with i must still see its own requests answered by its own handler: the generic code cannot intercept an instance it was not given [@biernacki2020binders]. QIEC enforces this by tunneling [@zhang2019abstraction]. Elaboration wraps every call or application whose row reaches i only through an open tail in a Mask of i, once per handler of i the enclosing body installs around it, so the request skips exactly those handlers. The kernel guard (check_tunneling) rejects a body in which such a call or application is left unmasked, and a call that is given i explicitly while it may also reach i through a tail that does not lack i: there the two requests cannot be told apart, and the signature has to state rho lacks i.

A tail is checked against the lacks constraints the declaration states for its row variables, in its own row and in its parameters' function types, never against constraints a body's row operations add, since those are not promises the caller keeps.

declared_lacks

declared_lacks(type_: ComputationType, parameters: tuple[Local, ...]) -> _Declared

The lacks constraints a declaration states for its row variables.

PARAMETER DESCRIPTION
type_

The declared calling type.

TYPE: ComputationType

parameters

The declared value parameters.

TYPE: tuple[Local, ...]

RETURNS DESCRIPTION
Mapping[RowVariableId, frozenset[EffectInstanceId]]

For each row variable the declaration mentions, the instances it is stated to lack.

Source code in src/quivers/qiec/tunneling.py
def declared_lacks(type_: ComputationType, parameters: tuple[Local, ...]) -> _Declared:
    """The ``lacks`` constraints a declaration states for its row variables.

    Parameters
    ----------
    type_ : ComputationType
        The declared calling type.
    parameters : tuple[Local, ...]
        The declared value parameters.

    Returns
    -------
    Mapping[RowVariableId, frozenset[EffectInstanceId]]
        For each row variable the declaration mentions, the instances it
        is stated to lack.
    """
    found: dict[RowVariableId, frozenset[EffectInstanceId]] = {}
    rows = [type_.effects, *_rows(type_.result)]
    for parameter in parameters:
        rows.extend(_rows(parameter.type))
    for row in rows:
        if row.tail is not None:
            found[row.tail.identity] = found.get(
                row.tail.identity, frozenset()
            ) | frozenset(row.tail.lacks)
    return found

tunnel_body

tunnel_body(type_: ComputationType, parameters: tuple[Local, ...], body: Computation) -> Computation

Insert the masks a declaration's body needs.

PARAMETER DESCRIPTION
type_

The declared calling type.

TYPE: ComputationType

parameters

The declared value parameters.

TYPE: tuple[Local, ...]

body

The body, without masks.

TYPE: Computation

RETURNS DESCRIPTION
Computation

The body with one mask per handler of an instance around each call or application that reaches that instance only through an open tail not stated to lack it.

RAISES DESCRIPTION
KernelError

If a call or application is given an instance explicitly and may also reach it through such a tail.

Source code in src/quivers/qiec/tunneling.py
def tunnel_body(
    type_: ComputationType, parameters: tuple[Local, ...], body: Computation
) -> Computation:
    """Insert the masks a declaration's body needs.

    Parameters
    ----------
    type_ : ComputationType
        The declared calling type.
    parameters : tuple[Local, ...]
        The declared value parameters.
    body : Computation
        The body, without masks.

    Returns
    -------
    Computation
        The body with one mask per handler of an instance around each call
        or application that reaches that instance only through an open
        tail not stated to lack it.

    Raises
    ------
    KernelError
        If a call or application is given an instance explicitly and may
        also reach it through such a tail.
    """
    return _Tunnel(declared_lacks(type_, parameters)).term(body, ())

check_tunneling

check_tunneling(type_: ComputationType, parameters: tuple[Local, ...], body: Computation, *, subject: str) -> None

Reject a body in which generic code could intercept a request.

PARAMETER DESCRIPTION
type_

The declared calling type.

TYPE: ComputationType

parameters

The declared value parameters.

TYPE: tuple[Local, ...]

body

The body.

TYPE: Computation

subject

The declaration, named in a diagnostic.

TYPE: str

RAISES DESCRIPTION
KernelError

If a handler the body installs could answer a request that a call or application reaches through an open tail not stated to lack its instance, without a mask routing the request past it; or if such a call is also given the instance explicitly.

Source code in src/quivers/qiec/tunneling.py
def check_tunneling(
    type_: ComputationType,
    parameters: tuple[Local, ...],
    body: Computation,
    *,
    subject: str,
) -> None:
    """Reject a body in which generic code could intercept a request.

    Parameters
    ----------
    type_ : ComputationType
        The declared calling type.
    parameters : tuple[Local, ...]
        The declared value parameters.
    body : Computation
        The body.
    subject : str
        The declaration, named in a diagnostic.

    Raises
    ------
    KernelError
        If a handler the body installs could answer a request that a call
        or application reaches through an open tail not stated to lack its
        instance, without a mask routing the request past it; or if such
        a call is also given the instance explicitly.
    """
    declared = declared_lacks(type_, parameters)
    for node, around in _scopes(body, ()):
        instances = {instance for _, instance in around}
        for instance in instances:
            if not _abstract(node.effects, instance, declared):
                continue
            skipped = 0
            exposed = False
            for kind, scoped in reversed(around):
                if scoped != instance:
                    continue
                if kind == "mask":
                    skipped += 1
                elif skipped:
                    skipped -= 1
                else:
                    exposed = True
                    break
            if not exposed:
                continue
            what = (
                f"the call of `{node.name}`"
                if isinstance(node, Call)
                else "a function application"
            )
            if node.effects.contains(instance):
                raise _ambiguous(f"{subject}: {what}", instance)
            raise KernelError(
                f"{subject}: a handler of instance {instance} installed around "
                f"{what} could answer requests that reach it through an open row "
                f"it was not given; mask the instance there",
                "qiec-tunnel",
            )

Control-flow linearity

linearity

Control-flow linearity: one-shot resumptions under multi-shot handlers.

A clause of grade 1 or aff holds a one-shot resumption token from the moment its request arrives until it resumes. If, while the token is unspent, the clause makes a request that a multi-shot handler answers (a clause of grade omega, or an interval whose upper bound is at least two), that handler may resume the rest of the clause more than once, and every copy of the rest holds the same token. The reference machine then refuses the second invocation at run time. Following the control-flow linearity of Tang, Hillerström, Lindley, and Morris [@tang2024soundly], control_flow_violations finds every installation of a multi-shot handler whose shots can each reach the resumption of one one-shot clause, and the kernel (quivers.qiec.module.require_control_flow_linearity) refuses a module that has one.

The analysis is sound and incomplete, so it is a report and an opt-in requirement rather than a rule of the kernel. A request counts as reaching the multi-shot handler when the one-shot handler is installed anywhere in the multi-shot handler's extent, lexically or through calls; an intervening handler of the same instance could answer it first. And a copy that aborts before it resumes spends nothing, so a module whose copies all abort but one runs on the reference machine although the analysis reports it.

LinearityViolation didactic-model

LinearityViolation(*, computation: str, multi_shot: str, instance: EffectInstanceId = field(opaque=True, extras=OPAQUE_BY_VALUE), operations: tuple[str, ...], one_shot: str, clause: str)

Bases: QiecModel

A one-shot clause whose unspent resumption a multi-shot handler copies.

PARAMETER DESCRIPTION
computation

The computation that installs the multi-shot handler.

TYPE: str

multi_shot

The multi-shot handler's name.

TYPE: str

instance

The instance it handles.

TYPE: EffectInstanceId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

operations

The operations whose clauses may resume more than once.

TYPE: tuple[str, ...]

one_shot

The handler whose one-shot clause makes the request.

TYPE: str

clause

The name of that clause's operation.

TYPE: str

message

message() -> str

The diagnostic.

RETURNS DESCRIPTION
str

Which clause, which request, and which handler copies it.

Source code in src/quivers/qiec/linearity.py
def message(self) -> str:
    """The diagnostic.

    Returns
    -------
    str
        Which clause, which request, and which handler copies it.
    """
    return (
        f"computation {self.computation!r} installs {self.multi_shot!r}, which "
        f"may resume `{', '.join(self.operations)}` more than once, around the "
        f"handler {self.one_shot!r}, whose one-shot clause `{self.clause}` "
        f"makes such a request before it resumes; each copy of the rest of "
        f"that clause would hold the same one-shot resumption"
    )

is_multi_shot

is_multi_shot(grade: ResumptionGrade | ResumptionInterval) -> bool

Whether a clause grade lets a clause resume more than once.

PARAMETER DESCRIPTION
grade

The declared grade.

TYPE: ResumptionGrade | ResumptionInterval

RETURNS DESCRIPTION
bool

True for omega and for an interval whose upper bound is at least two.

Source code in src/quivers/qiec/linearity.py
def is_multi_shot(grade: ResumptionGrade | ResumptionInterval) -> bool:
    """Whether a clause grade lets a clause resume more than once.

    Parameters
    ----------
    grade : ResumptionGrade | ResumptionInterval
        The declared grade.

    Returns
    -------
    bool
        True for ``omega`` and for an interval whose upper bound is at
        least two.
    """
    if isinstance(grade, ResumptionInterval):
        return grade.maximum >= 2
    return grade is ResumptionGrade.UNRESTRICTED

is_one_shot

is_one_shot(grade: ResumptionGrade | ResumptionInterval) -> bool

Whether a clause holds a one-shot resumption token.

PARAMETER DESCRIPTION
grade

The declared grade.

TYPE: ResumptionGrade | ResumptionInterval

RETURNS DESCRIPTION
bool

True for grades 1 and aff.

Source code in src/quivers/qiec/linearity.py
def is_one_shot(grade: ResumptionGrade | ResumptionInterval) -> bool:
    """Whether a clause holds a one-shot resumption token.

    Parameters
    ----------
    grade : ResumptionGrade | ResumptionInterval
        The declared grade.

    Returns
    -------
    bool
        True for grades ``1`` and ``aff``.
    """
    return grade in (ResumptionGrade.LINEAR, ResumptionGrade.AFFINE)

unspent_requests

unspent_requests(body: Computation) -> frozenset[_Request]

The requests a clause can make while its resumption is unspent.

A request sequenced after a binding whose computation resumes on every path is made with the token spent. Everything else, including a request in a branch that has not yet resumed, counts.

PARAMETER DESCRIPTION
body

The clause body.

TYPE: Computation

RETURNS DESCRIPTION
frozenset[tuple[EffectInstanceId, OperationId | None]]

The requests, None standing for any operation of an instance a call's row names.

Source code in src/quivers/qiec/linearity.py
def unspent_requests(body: Computation) -> frozenset[_Request]:
    """The requests a clause can make while its resumption is unspent.

    A request sequenced after a binding whose computation resumes on
    every path is made with the token spent. Everything else, including
    a request in a branch that has not yet resumed, counts.

    Parameters
    ----------
    body : Computation
        The clause body.

    Returns
    -------
    frozenset[tuple[EffectInstanceId, OperationId | None]]
        The requests, ``None`` standing for any operation of an instance
        a call's row names.
    """
    found: set[_Request] = set()
    pending: list[Computation] = [body]
    while pending:
        term = pending.pop()
        if isinstance(term, Bind):
            pending.append(term.first)
            if not _resumes(term.first):
                pending.append(term.then)
            continue
        if isinstance(term, Resume):
            continue
        if isinstance(term, Perform):
            found.add((term.request.instance, term.request.operation))
            continue
        if isinstance(term, Call | Apply):
            found.update(_row_requests(term.effects))
            continue
        for child in _children(term):
            if isinstance(child, Computation.__value__):
                pending.append(cast(Computation, child))
            else:
                found.update(_requests(child))
    return frozenset(found)

control_flow_violations

control_flow_violations(computations: Mapping[ComputationId, tuple[str, Computation]], handlers: Mapping[HandlerId, HandlerDef], operations: Mapping[OperationId, str]) -> tuple[LinearityViolation, ...]

Every multi-shot installation whose shots can each resume one token.

For each installation of a handler with a multi-shot clause, and each one-shot clause installed in its extent (lexically or in a computation it calls), the analysis follows the one-shot clause from each request to the multi-shot instance it makes before resuming, once per value the multi-shot clause resumes with on one of its paths. A shot that takes a branch decided by a known value away from the resumption, or that makes a request answered by a clause of grade 0 before it, does not count. Two shots on one path that can both reach the resumption are a violation.

PARAMETER DESCRIPTION
computations

Each computation's name and body.

TYPE: Mapping[ComputationId, tuple[str, Computation]]

handlers

The module's handlers.

TYPE: Mapping[HandlerId, HandlerDef]

operations

Each operation's name, for diagnostics.

TYPE: Mapping[OperationId, str]

RETURNS DESCRIPTION
tuple[LinearityViolation, ...]

One record per pair of a multi-shot installation and a one-shot clause whose resumption two of its shots can reach.

Source code in src/quivers/qiec/linearity.py
def control_flow_violations(
    computations: Mapping[ComputationId, tuple[str, Computation]],
    handlers: Mapping[HandlerId, HandlerDef],
    operations: Mapping[OperationId, str],
) -> tuple[LinearityViolation, ...]:
    """Every multi-shot installation whose shots can each resume one token.

    For each installation of a handler with a multi-shot clause, and each
    one-shot clause installed in its extent (lexically or in a computation
    it calls), the analysis follows the one-shot clause from each request
    to the multi-shot instance it makes before resuming, once per value
    the multi-shot clause resumes with on one of its paths. A shot that
    takes a branch decided by a known value away from the resumption, or
    that makes a request answered by a clause of grade ``0`` before it, does
    not count. Two shots on one path that can both reach the resumption
    are a violation.

    Parameters
    ----------
    computations : Mapping[ComputationId, tuple[str, Computation]]
        Each computation's name and body.
    handlers : Mapping[HandlerId, HandlerDef]
        The module's handlers.
    operations : Mapping[OperationId, str]
        Each operation's name, for diagnostics.

    Returns
    -------
    tuple[LinearityViolation, ...]
        One record per pair of a multi-shot installation and a one-shot
        clause whose resumption two of its shots can reach.
    """
    violations: list[LinearityViolation] = []
    for name, body in computations.values():
        for installation, around in _sites(body, (), handlers):
            multi_handler = handlers[installation.handler]
            multi = {
                clause.operation: clause
                for clause in multi_handler.clauses
                if is_multi_shot(clause.grade)
            }
            if not multi:
                continue
            sites = _reached_sites(
                installation.computation,
                (*around, (installation.instance, multi_handler)),
                computations,
                handlers,
            )
            reported: set[tuple[HandlerId, OperationId]] = set()
            for handler, stack in sites:
                for clause in handler.clauses:
                    if clause.body is None or not is_one_shot(clause.grade):
                        continue
                    if (handler.id, clause.operation) in reported:
                        continue
                    hit = _copies(clause.body, stack, installation.instance, multi)
                    if not hit:
                        continue
                    reported.add((handler.id, clause.operation))
                    violations.append(
                        LinearityViolation(
                            computation=name,
                            multi_shot=multi_handler.name,
                            instance=installation.instance,
                            operations=tuple(
                                operations.get(item, str(item)) for item in hit
                            ),
                            one_shot=handler.name,
                            clause=operations.get(
                                clause.operation, str(clause.operation)
                            ),
                        )
                    )
    return tuple(violations)

Hefty elaboration

hefty

Hefty elaboration of higher-order operations into algebraic ones.

A higher-order operation takes computations as arguments: catch takes the computation to try and the one to recover with, and local takes a function that changes the environment and the computation to run under the changed environment. In QVR such an operation is an ordinary operation whose arguments are function values. Handled algebraically, its clause would run those functions where the handler is installed, outside every handler between the request and the handler, which is the wrong scope for them. Following Bach Poulsen and van der Rest [@poulsen2023hefty], a higher-order operation is instead elaborated before anything is handled: each request is replaced by its elaboration, code written with algebraic operations and handlers, which runs the function arguments at the request, under the handlers in scope there.

An elaboration is an authored handler declared as the elaborator of an instance (scoped_operation name [instance=i, elaborator=e], without body_effects). Each of its clauses is the elaboration of one operation: it computes the operation's result from the arguments, may perform the effects it introduces and apply the function arguments, and ends by resuming once with the result. Elaborations are modular: each instance is elaborated by its own elaborator, independently of the others, and an elaboration may itself request another elaborated instance. The elaborated module requests no elaborated instance; in every row, an elaborated instance is replaced by the effects its elaborator introduces.

HigherOrderElaboration didactic-model

HigherOrderElaboration(*, instance: EffectInstanceId = field(opaque=True, extras=OPAQUE_BY_VALUE), handler: HandlerId = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The elaborator of one instance's higher-order operations.

PARAMETER DESCRIPTION
instance

The instance whose requests are elaborated.

TYPE: EffectInstanceId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

handler

The authored handler whose clauses are the elaborations.

TYPE: HandlerId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

elaborator_obstacle

elaborator_obstacle(handler: HandlerDef) -> str | None

Why a handler cannot elaborate an instance's operations.

PARAMETER DESCRIPTION
handler

A checked handler declaration.

TYPE: HandlerDef

RETURNS DESCRIPTION
str or None

None when the handler is authored, total, takes no parameters, answers its computation unchanged, and every clause has grade 1 and ends every path in one tail resumption; otherwise the first property that fails, naming the handler. An elaboration is a computation from the arguments to the result, so it resumes exactly once, with the result, after whatever it does.

Source code in src/quivers/qiec/hefty.py
def elaborator_obstacle(handler: HandlerDef) -> str | None:
    """Why a handler cannot elaborate an instance's operations.

    Parameters
    ----------
    handler : HandlerDef
        A checked handler declaration.

    Returns
    -------
    str or None
        ``None`` when the handler is authored, total, takes no parameters,
        answers its computation unchanged, and every clause has grade 1 and
        ends every path in one tail resumption; otherwise the first
        property that fails, naming the handler. An elaboration is a
        computation from the arguments to the result, so it resumes exactly
        once, with the result, after whatever it does.
    """
    if handler.implementation != "authored":
        return f"elaborator `{handler.name}` is foreign"
    if not handler.total:
        return f"elaborator `{handler.name}` does not cover every operation"
    if handler.parameters:
        return (
            f"elaborator `{handler.name}` takes parameters, which no installation gives"
        )
    clause = handler.return_clause
    if handler.input_type != handler.output_type or (
        clause is not None and clause.body != Return(value=Var(local=clause.binder))
    ):
        return f"elaborator `{handler.name}` changes the answer of the computation"
    for operation in handler.clauses:
        if operation.grade is not ResumptionGrade.LINEAR or (
            operation.body is None or _tail_reply(operation.body, ()) is None
        ):
            return (
                f"a clause of elaborator `{handler.name}` does not end every path "
                f"in one tail resumption"
            )
    return None

elaborate_higher_order

elaborate_higher_order(module: QiecModule, elaborations: tuple[HigherOrderElaboration, ...]) -> QiecModule

Elaborate every request to the given instances throughout a module.

PARAMETER DESCRIPTION
module

The checked module, in which the elaborated instances' operations may take function values.

TYPE: QiecModule

elaborations

The elaborator of each elaborated instance.

TYPE: tuple[HigherOrderElaboration, ...]

RETURNS DESCRIPTION
QiecModule

The module with every such request replaced by its elaboration at the request, and every row rewritten. The module itself when there is nothing to elaborate.

RAISES DESCRIPTION
KernelError

If an elaborator does not qualify (elaborator_obstacle), an instance has two elaborators, an elaborated instance is handled, or elaborations request each other without end.

Source code in src/quivers/qiec/hefty.py
def elaborate_higher_order(
    module: QiecModule, elaborations: tuple[HigherOrderElaboration, ...]
) -> QiecModule:
    """Elaborate every request to the given instances throughout a module.

    Parameters
    ----------
    module : QiecModule
        The checked module, in which the elaborated instances' operations
        may take function values.
    elaborations : tuple[HigherOrderElaboration, ...]
        The elaborator of each elaborated instance.

    Returns
    -------
    QiecModule
        The module with every such request replaced by its elaboration at
        the request, and every row rewritten. The module itself when there
        is nothing to elaborate.

    Raises
    ------
    KernelError
        If an elaborator does not qualify (`elaborator_obstacle`), an
        instance has two elaborators, an elaborated instance is handled, or
        elaborations request each other without end.
    """
    if not elaborations:
        return module
    handlers = {item.id: item for item in module.handlers}
    selected: dict[EffectInstanceId, HandlerDef] = {}
    for elaboration in elaborations:
        handler = handlers[elaboration.handler]
        reason = elaborator_obstacle(handler)
        if reason is not None:
            raise KernelError(reason, "qiec-elaboration")
        if elaboration.instance in selected:
            raise KernelError(
                f"instance {elaboration.instance} has two elaborators",
                "qiec-elaboration",
            )
        selected[elaboration.instance] = handler
    elaborator = _Elaborator(module, selected)
    computations: list[NamedComputation] = []
    for computation in module.computations:
        fresh = _LocalNames(computation, prefix="__hefty")
        computations.append(elaborator.node(computation, fresh, 0))
    # Other handlers' clauses may request an elaborated instance too; the
    # elaborators themselves are elaborated where they are inlined.
    rewritten: list[HandlerDef] = []
    for handler in module.handlers:
        if handler.id in {item.id for item in selected.values()}:
            rewritten.append(handler)
            continue
        fresh = _LocalNames(handler, prefix="__hefty")
        rewritten.append(elaborator.node(handler, fresh, 0))
    elaborated = module.with_(
        computations=tuple(computations), handlers=tuple(rewritten)
    )
    # The declared row of a computation that requested an elaborated
    # instance becomes what the elaborator introduces; a handler the body
    # installs may answer some of that, so the body keeps the exact row it
    # has, beneath the declared calling type, as discharge does.
    registry = declaration_registry(elaborated)
    weakened: list[NamedComputation] = []
    for computation in elaborated.computations:
        declared = computation.type.effects
        if declared.tail is None and declared.entries:
            actual = _infer_named_body(computation, registry)
            if actual.result == computation.type.result and _strict_closed_subrow(
                actual.effects, declared
            ):
                computation = _WeakenedComputation(
                    id=computation.id,
                    name=computation.name,
                    telescope=computation.telescope,
                    parameters=computation.parameters,
                    body=computation.body,
                    type=computation.type,
                    origin=computation.origin,
                    predicates=computation.predicates,
                    body_effects=actual.effects,
                )
        weakened.append(computation)
    return elaborated.with_(computations=tuple(weakened))

Local effect theories

effect_theories

Laws as local effect theories: every installed handler is checked.

An effect equation states what code using an instance relies on, for example that reading a world model twice reads the same fact. Declared without a list of handlers, the equation is a local effect theory of the instance [@luksic2020local]: it holds of every handler installed for the instance anywhere in the module, including handlers that other modules supply when they link to the code that states it. Each installed handler is checked, by the finite, polynomial, or rational method the equation names. A decided counterexample refutes the handler. An equation outside the decidable fragment, or one whose check exhausts its budget, is recorded as assumed for that handler, never as checked: handler correctness is undecidable in general [@plotkin2013handling].

TheoryDecision didactic-model

TheoryDecision(*, equation: EffectEquation = field(opaque=True, extras=OPAQUE_BY_VALUE), handler: HandlerId = field(opaque=True, extras=OPAQUE_BY_VALUE), handler_name: str, status: Literal['checked', 'refuted', 'assumed'], reason: str = '')

Bases: QiecModel

What checking one installed handler against one equation decided.

PARAMETER DESCRIPTION
equation

The equation.

TYPE: EffectEquation DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

handler

The installed handler.

TYPE: HandlerId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

handler_name

Its name, for reports.

TYPE: str

status

"checked" when the method decided that the equation holds, "refuted" when it found a counterexample, and "assumed" when it could not decide.

TYPE: Literal['checked', 'refuted', 'assumed']

reason

The counterexample for a refutation, or why the equation is assumed; empty when checked.

TYPE: str DEFAULT: ''

installed_handlers_of

installed_handlers_of(module: QiecModule, instance: EffectInstanceId) -> tuple[HandlerId, ...]

Every handler a module installs for one instance, in source order.

PARAMETER DESCRIPTION
module

The checked module.

TYPE: QiecModule

instance

The instance.

TYPE: EffectInstanceId

RETURNS DESCRIPTION
tuple[HandlerId, ...]

Each handler installed for the instance by some computation, once.

Source code in src/quivers/qiec/effect_theories.py
def installed_handlers_of(
    module: QiecModule, instance: EffectInstanceId
) -> tuple[HandlerId, ...]:
    """Every handler a module installs for one instance, in source order.

    Parameters
    ----------
    module : QiecModule
        The checked module.
    instance : EffectInstanceId
        The instance.

    Returns
    -------
    tuple[HandlerId, ...]
        Each handler installed for the instance by some computation,
        once.
    """
    found: dict[HandlerId, None] = {}
    for computation in module.computations:
        pending: list[QiecModel] = [computation.body]
        ordered: list[HandlerId] = []
        while pending:
            node = pending.pop()
            if isinstance(node, Handle) and node.instance == instance:
                ordered.append(node.handler)
            queue = list(_children(node))
            while queue:
                item = queue.pop()
                if isinstance(item, QiecModel):
                    pending.append(item)
                elif isinstance(item, tuple):
                    queue.extend(item)
        for handler in sorted(ordered, key=str):
            found.setdefault(handler, None)
    return tuple(found)

decide_local_theory

decide_local_theory(module: QiecModule, obligation: EffectLawObligation) -> TheoryDecision

Check one handler against one equation, recording undecided as assumed.

PARAMETER DESCRIPTION
module

The checked module holding the equation's sides and the handler.

TYPE: QiecModule

obligation

The equation, the handler, and the method.

TYPE: EffectLawObligation

RETURNS DESCRIPTION
TheoryDecision

The decision.

Source code in src/quivers/qiec/effect_theories.py
def decide_local_theory(
    module: QiecModule, obligation: EffectLawObligation
) -> TheoryDecision:
    """Check one handler against one equation, recording undecided as assumed.

    Parameters
    ----------
    module : QiecModule
        The checked module holding the equation's sides and the handler.
    obligation : EffectLawObligation
        The equation, the handler, and the method.

    Returns
    -------
    TheoryDecision
        The decision.
    """
    handler = next(item for item in module.handlers if item.id == obligation.handler)
    module, obligation = _at_side_type(module, obligation, handler)
    try:
        if obligation.method == "finite":
            finite = check_finite_effect_law(
                module, obligation.equation, obligation.handler
            )
            counterexample = finite.result.counterexample
        else:
            scalar = check_scalar_effect_law(
                module,
                obligation.equation,
                obligation.handler,
                method=obligation.method,
            )
            counterexample = scalar.result.counterexample
    except _UNDECIDED as error:
        return TheoryDecision(
            equation=obligation.equation,
            handler=obligation.handler,
            handler_name=handler.name,
            status="assumed",
            reason=str(error),
        )
    if counterexample is None:
        return TheoryDecision(
            equation=obligation.equation,
            handler=obligation.handler,
            handler_name=handler.name,
            status="checked",
        )
    return TheoryDecision(
        equation=obligation.equation,
        handler=obligation.handler,
        handler_name=handler.name,
        status="refuted",
        reason=str(counterexample),
    )

Cited sources

Gordon Plotkin and Matija Pretnar. Handlers of Algebraic Effects. In Programming Languages and Systems, volume 5502 of Lecture Notes in Computer Science, 80–94. Springer, 2009. URL: https://link.springer.com/chapter/10.1007/978-3-642-00590-9_7, doi:10.1007/978-3-642-00590-9_7.

Andrej Bauer and Matija Pretnar. Programming with Algebraic Effects and Handlers. Journal of Logical and Algebraic Methods in Programming, 84(1):108–123, 2015. URL: https://www.sciencedirect.com/science/article/pii/S2352220814000194, doi:10.1016/j.jlamp.2014.02.001.

Daan Leijen. Koka: Programming with Row Polymorphic Effect Types. In Proceedings of the 5th Workshop on Mathematically Structured Functional Programming (MSFP), volume 153 of Electronic Proceedings in Theoretical Computer Science, 100–126. 2014. doi:10.4204/EPTCS.153.8.