cadrumo.domain.calculations.registry.formula_runtime module¶
Registry-backed formula runtime using typed operation graphs.
Evaluates
FormulaExpression trees declared on
a ModeloRevision against casilla
inputs and binding values drawn from a
RegistrySnapshot.
The calculation entry point calculate_registry_snapshot() is the
primary surface used by
ValidatedRegistryAuthority-backed
callers to produce
CasillaObservation rows with full
provenance.
See also
domain.calculations.registry.runtime_graphProduces formula evaluation order and dependency projections.
domain.calculations.registry.formula_runtime_opsArithmetic, rounding, and parameter lookup helpers called by this evaluator.
domain.calculations.registry.formula_initial_valuesBuilds the initial casilla value map and materialised observation envelope for this runtime.
- class RegistryCalculationEntry(**data)[source]¶
Bases:
BaseModelOne trace row emitted by the registry formula runtime.
Carries the per-formula provenance for a single formula-computed
CasillaId. Entries cover only casillas computed by a registry formula; input and bound casillas remain inCasillaObservationstorage and must be read throughRegistryCalculationResult.observations.- Parameters:
data (Any)
- formula_id: FormulaId¶
- target_casilla_id: CasillaId¶
- op: str¶
- operand_refs: tuple[str, ...]¶
- operand_casilla_refs: tuple[CasillaId, ...]¶
- operand_values: tuple[Decimal, ...]¶
- value: Decimal¶
- legal_refs: tuple[LegalRefId, ...]¶
- source_refs: tuple[SourceRefId, ...]¶
- class RegistryCalculationUnresolvedOutcome(**data)[source]¶
Bases:
BaseModelOne formula target that could not produce a Decimal value.
The outcome rides beside
RegistryCalculationResult.observationsso the engine’s value channels remain Decimal-only. Legal/source refs and formula lineage mirrorCasillaObservationfor the same target.- Parameters:
data (Any)
- casilla_id: CasillaId¶
- reason: RegistryUnresolvedOutcomeReason¶
- formula_id: FormulaId¶
- op: str¶
- operand_refs: tuple[str, ...]¶
- operand_casilla_refs: tuple[CasillaId, ...]¶
- operand_values: tuple[Decimal, ...]¶
- legal_refs: tuple[LegalRefId, ...]¶
- source_refs: tuple[SourceRefId, ...]¶
- context: Mapping[str, str]¶
- class RegistryCalculationResult(**data)[source]¶
Bases:
BaseModelCalculated outputs for one registry snapshot.
Canonical storage is
observations: a typed tuple ofCasillaObservationcovering every casilla on theRegistrySnapshotrevision (inputs, bound, and formula-computed). Each observation carries its final scalarvalueplus the legal / source provenance for that casilla pulled from the registry. Formula-computed observations additionally carryformula_id,op,operand_refs, andoperand_valuesso the full evaluation lineage survives the engine boundary.The
valuesandentriesviews are derived convenience properties for readers that need the flat{casilla_id: Decimal}map or the formula-onlyRegistryCalculationEntrytuple. The typed envelope is the contract; the flat views never grow new fields.Coverage asymmetry preserved by the derivation:
valuescovers every Decimal observation (inputs, bound, computed), keyed bycasilla_idtovalue. Text observations stay exclusively on the canonical typed envelope.entriescovers ONLY observations whereformula_idis set.len(entries) <= len(observations)always; equality holds only when every casilla is formula-computed (rare in practice).
Consumers that need provenance for non-computed casillas must iterate
observationsdirectly; the entries view drops them by design.- Parameters:
data (Any)
- modelo: str¶
- revision: str¶
- observations: tuple[CasillaObservation, ...]¶
- unresolved_outcomes: tuple[RegistryCalculationUnresolvedOutcome, ...]¶
- property values: Mapping[CasillaId, Decimal]¶
Read-only view from registry casilla id to final Decimal value.
Deliberately a plain
@property, not a pydanticcomputed_field: the typedobservationsenvelope is canonical storage; exposing this in JSON would round-trip self-incompatibly underextra='forbid'because the loader would refuse the duplicate field on the way back in.
- property entries: tuple[RegistryCalculationEntry, ...]¶
Read-only view of formula-computed
RegistryCalculationEntryrows.Preserves the formula-only entry view with
target_casilla_idandopfields for the application-layer indexers that build{target_casilla_id: entry}dictionaries. Insertion order fromobservationsis preserved; the engine emits in formula evaluation order, which matches the originalentriesshape.
- calculate_registry_snapshot(snapshot, *, inputs, date_context, binding_values=None, enum_binding_values=None, relation_values=None, unresolved_relation_ids=(), unresolved_binding_ids=(), date_binding_values=None, boolean_binding_values=None, text_inputs=None)[source]¶
Evaluate all computed formulas for a registry snapshot.
enum_binding_valuescarries string-valued bindings (typically profile-sourced enums likeCCAA) that thelookup_bracket_by_ccaaop routes against. They are kept in a separate mapping frombinding_valuesso the Decimal-only contract on numeric bindings stays intact.date_binding_valuescarries date-valued profile facts (e.g. birth_date) consumed by theage_at_year_endop. Date facts cannot flow through the Decimalbinding_valueschannel; keeping them in a dedicated channel preserves the Decimal-only invariant.boolean_binding_valuescarries the truth values of bindings whose registry value contract declares thebooleanchannel – an applicability flag, a regimen eligibility predicate. The channel exists so “no” and “zero euros” are not the same bytes in transport: the projection toZERO/ONEhappens where a predicate reads the operand, and a binding supplied on both this channel and the Decimal one is refused rather than silently preferred.The returned
RegistryCalculationResultstoresCasillaObservationrows for all materialised casillas. Input validation is delegated todomain.calculations.registry.formula_runtime_opsanddomain.calculations.registry.formula_text_inputs; initial casilla values and absent-by-design markers are delegated todomain.calculations.registry.formula_initial_values.- Parameters:
snapshot (
RegistrySnapshot) – TheRegistrySnapshotthat supplies the revision, casilla definitions, and formula graph to evaluate.inputs (
Mapping[TypeVar(InputKey),TypeVar(InputValue)]) – Operator-supplied input casilla values; rejected if any value is not adecimal.Decimal.date_context (
Mapping[str,date]) – Date-axis context (e.g.filing_period) consumed by date-aware ops;filing_perioddefaults to the snapshot’s typed calculation filing date when present, otherwise its year-end.binding_values (
Mapping[TypeAliasType,Decimal] |None) – Optional resolved numeric binding values keyed byBindingDefinitionid; Decimal-only.enum_binding_values (
Mapping[TypeAliasType,str] |None) – Optional string-valued bindings (e.g. profile CCAA) keyed by binding id; consumed by enum-routed ops.relation_values (
Mapping[TypeAliasType,Decimal] |None) – Optional resolved relation values keyed byrelation.id; Decimal-only.unresolved_relation_ids (
tuple[TypeAliasType,...]) – Relation ids that source resolution proved missing/incomplete but non-blocking. Formula targets depending on these ids are omitted instead of zero-contributed; relation ids not listed here remain hard validation errors when absent.unresolved_binding_ids (
tuple[TypeAliasType,...]) – Binding ids whose enrolled resolver ran for a present source but produced no value (expected-but-missing). Formula targets depending on these ids are omitted instead of raisingbinding_value_missing; binding ids not listed here remain hard validation errors when absent frombinding_values.date_binding_values (
Mapping[TypeAliasType,date] |None) – Optional date-valued profile bindings (e.g.birth_date) consumed by date-aware ops.boolean_binding_values (
Mapping[TypeAliasType,bool] |None) – Optional truth-valued bindings, keyed by binding id, for every binding whose registry value contract declares thebooleanchannel. A boolean operand is projected toONE/ZEROat the moment a predicate reads it, never in transport, so a yes/no fact and a zero-valued amount stay distinguishable up to the point of use.text_inputs (
Mapping[TypeVar(TextInputKey),TypeVar(TextInputValue)] |None) – Optional string-valued operator inputs keyed by casilla id; consumed by text-routed ops.
- Return type:
- evaluate_expression(expression, *, values, binding_values, parameters, date_context, relation_values, unresolved_relation_ids, unresolved_casilla_ids, operand_refs, operand_casilla_refs, operand_values, unresolved_binding_ids=frozenset({}), enum_binding_values=None, date_binding_values=None, boolean_binding_values=None, filing_year=0, text_values=None)[source]¶
Build the shared
EvalContextfor one formula tree and evaluate it.The entry point from loose arguments: it normalises the optional channels and constructs the context once. Recursive re-entry goes through
evaluate_with_context(), which carries that same context object forward instead of rebuilding it.- Return type:
- Returns:
The evaluated
Decimalvalue ofexpression.- Parameters:
expression (FormulaExpression)
parameters (Mapping[str, ParameterDefinition])
unresolved_relation_ids (frozenset[RelationId])
unresolved_binding_ids (frozenset[BindingId])
filing_year (int)
- class EvalContext(values, binding_values, parameters, date_context, relation_values, unresolved_relation_ids, unresolved_casilla_ids, operand_refs, operand_casilla_refs, operand_values, enum_binding_values, date_binding_values, filing_year, boolean_binding_values=<factory>, unresolved_binding_ids=frozenset({}), text_values=<factory>)[source]¶
Bases:
objectBundles the runtime sinks + maps threaded through every recursive call.
Frozen and slotted. Exactly one instance is built per formula tree, by
evaluate_expression(), and handed by reference to every per-op evaluator and every recursive re-entry throughevaluate_with_context(); the tree is walked without rebuilding it. The three list sinks (operand_refs, operand_casilla_refs, operand_values) ARE mutated in place — they accumulate evaluation provenance for the explainability surface, and passing the one context object by reference is what keeps every node of the tree appending to those same three lists.- Parameters:
-
parameters:
Mapping[str,ParameterDefinition]¶
- evaluate_with_context(expression, ctx)[source]¶
Evaluate one expression node against
ctx, recursing into its args.The dispatcher proper: leaf, specialised per-op evaluator, or generic arg-folding op.
ctxis passed through by reference rather than destructured and rebuilt, so the whole tree shares one context object and one set of provenance sinks.- Return type:
- Parameters:
expression (FormulaExpression)
ctx (EvalContext)