aeat.application.aggregation._source_mesh module¶
Canonical application-layer source resolution contracts.
The source mesh is the calculation-facing envelope for values derived from
bucket-local ledgers, invoices, prior filings, profile facts, borrador data,
relation prefill, and other registry-declared sources. A
CalculationSourceContext binds the active bucket, modelo,
Period, and selected ModeloRevision; each
ModeloSourceResolver claims one or more BindingSourceKind
members and returns a CalculationSourceResolution.
CalculationSourceResolution is the single resolved-source carrier consumed
by modelo calculation. It carries decimal, enum, date, row-indexed binding,
relation, bound-casilla, detail-row, transaction-id, diagnostic, and provenance
channels. Exclusive merges use merge_source_resolutions(); precedence overlays use
merge_source_resolutions_by_precedence(); and
collect_unhandled_source_diagnostics() is the no-silent-blank safety net
for declared binding sources without an enrolled resolver.
- exception SourceMeshError(message_key)[source]¶
Bases:
CoreValidationErrorRaised when a
CalculationSourceMeshfield validator rejects an invariant.Replaces bare
ValueErrorat theowned_sourcesuniqueness / blank guards and thesource_transaction_idsuniqueness / blank guards so callers receive a typed, registry-bound, localized error. Inherits fromCoreValidationError(which inherits fromValueError) so pydantic field validators surface it throughValidationErrorwithout special handling.- Parameters:
message_key (str)
- Return type:
None
- code: ClassVar[ErrorCode]¶
- class DeferredSourceTarget(owning_adr, trigger, promotion_depends_on=None)[source]¶
Bases:
NamedTupleThe governed promotion target of a deferred binding source kind.
A deferred kind has no live mesh resolver yet, so it produces a standing calculate-path advisory rather than a silent blank. Re-ratification per the deferrals ADR replaces the former free-prose deferral comments with this structured annotation so the deferral set is governed, not merely enumerated: every deferred kind names the decision that owns it and the condition that promotes it, and a kind whose trigger has fired but which remains deferred is a mechanically-detectable finding at the swarm-audit cadence.
- Members:
- owning_adr: The decision-record stem that ratifies this deferral and its
promotion target.
- trigger: The condition under which the kind should be promoted to a live
mesh binding (a dependency for the IVA kinds; a per-modelo review for the informativa detail-row kinds, which carry no promotion date).
- promotion_depends_on: For a kind gated on another source kind landing,
the source kind it waits on.
Nonefor kinds whose trigger is a human review rather than a mechanical source-kind dependency. When a named dependency has itself been promoted out of the deferred set, this kind’s trigger has fired.
- Parameters:
owning_adr (str)
trigger (str)
promotion_depends_on (BindingSourceKind | None)
-
promotion_depends_on:
BindingSourceKind|None¶ Alias for field number 2
- class CallerOverrideDisposition(*values)[source]¶
Bases:
StrEnumWhether the calculate path permits a caller override of a source’s value.
The override disposition axis of the caller-override precedence ladder (aggregation-taxonomy ADR ruling D2).
- Members:
- LOCK: Deterministic bucket-owned resolvers (the ledger aggregations and
the invoice families). A caller override is REJECTED so the persisted revision faithfully reflects the sources it aggregates.
- CARRY: Carry-style sources (previous_filing, relation_prefill, the
IVA-compensation annual partition, and prorrata regularizacion). A caller override of an automatically-carried prior value is legitimate and must reach the engine, so these are EXCLUDED from the post-merge caller-override guard.
- LOCK¶
- CARRY¶
- class CallerOverridePrecedenceTier(name, source_kinds, disposition)[source]¶
Bases:
NamedTupleOne ordered tier of the calculate-path caller-override precedence ladder.
Carries the tier name, the source kinds it owns, and the override disposition the guard applies to them. The ordered ladder is the single declaration the caller-override guard sets are derived from —
CALLER_OVERRIDE_PRECEDENCE_LADDERreplaces the hand-listed lock / carry frozensets, and a conformance test binds the policy’s derived sets to it so the two cannot silently diverge.- Parameters:
name (str)
source_kinds (frozenset[BindingSourceKind])
disposition (CallerOverrideDisposition)
-
source_kinds:
frozenset[BindingSourceKind]¶ Alias for field number 1
-
disposition:
CallerOverrideDisposition¶ Alias for field number 2
- CALLER_OVERRIDE_PRECEDENCE_LADDER: tuple[CallerOverridePrecedenceTier, ...]¶
The calculate-path caller-override precedence ladder as ordered tier data (aggregation-taxonomy ADR ruling D2), lowest-precedence tier first. The guard’s lock and carry source sets are the unions of the LOCK- and CARRY-disposition tiers (see
precedence_ladder_sources()). This encodes the override DISPOSITION axis only; the merge OVERLAY order (profile < mesh backend < borrador < caller, later tier wins) is enforced separately bymerge_source_resolutions().
- precedence_ladder_sources(disposition)[source]¶
Union of the source kinds carried by every ladder tier of
disposition.The single derivation the caller-override policy sets read, so a source kind’s lock-vs-carry disposition is declared once in
CALLER_OVERRIDE_PRECEDENCE_LADDERrather than hand-listed per set.- Return type:
- Returns:
The
BindingSourceKindmembers carried by every ladder tier whose disposition matches disposition.- Parameters:
disposition (CallerOverrideDisposition)
- class BindingSourceDisposition(*values)[source]¶
Bases:
StrEnumWhere a binding source kind resolves on the live calculate mesh.
The single closed answer to “where does source X resolve” for every
BindingSourceKindmember, replacing the four scattered enrollment structures (themerge_source_resolutionsresolver tuple, the pre-mesh-handled set,DEFERRED_SOURCE_KINDS, and the per-modelo service provider enum).- ENROLLED¶
- DEFERRED¶
- RESERVED¶
- build_binding_source_dispositions(enrolled_sources)[source]¶
Classify every
BindingSourceKindmember by its live meshBindingSourceDisposition.enrolled_sourcesis the LIVE enrolled set read at execution time – the union of every active resolver’sowned_sourcesplus the pre-mesh tiers andmanual_input– so no disposition is hard-coded; a newly-enrolled source (e.g. withholding, or profile / borrador now folded into the mesh) is reflected automatically.DEFERRED_SOURCE_KINDSandRESERVED_SOURCE_KINDSsupply the other two states. Raises if a member is in two states at once, or in none (an unaccounted source kind – the “neither set contains the other” defect).- Return type:
- Parameters:
enrolled_sources (frozenset[BindingSourceKind])
- class CalculationSourceContext(**data)[source]¶
Bases:
BaseModelContext supplied to a calculation source resolver.
The
periodfield is the typedPeriodvalue carrying both the filing year and the bare registry period code. Consumers that need the raw token for a downstreamstr-typed API should usecontext.period.registry_token; those that need only the year can usecontext.period.year(which mirrorscontext.filing_year).- Parameters:
- bucket_id: BucketId¶
- modelo: str¶
- filing_year: int¶
- period: Period¶
- revision: ModeloRevision¶
- calculated_at: datetime | None¶
- class CalculationSourceDiagnostic(**data)[source]¶
Bases:
BaseModelDiagnostic emitted while resolving source-backed calculation values.
- Parameters:
reason (Literal['duplicate_binding_owner', 'duplicate_bound_casilla_owner', 'duplicate_relation_owner', 'source_issue', 'unresolved_binding', 'storage_degraded', 'source_domain_not_ready', 'unhandled_binding_source', 'unrouted_observation', 'oss_no_live_source', 'missing_transaction_evidence', 'administrador_retencion_rate_mismatch', 'official_box_unpopulated', 'prior_payment_not_deducted', 'prior_payment_minoracion_not_captured', 'settlement_not_computed', 'prorrata_especial_obligatoria', 'prorrata_especial_check_unavailable', 'dt12_regime_window_closed', 'dt12_regime_window_unverified', 'dt12_parcial_rescate_guidance'])
source_kind (str)
binding_source (BindingSourceKind | None)
message (str)
resolver_id (str | None)
binding_id (BindingId | None)
relation_id (RelationId | None)
casilla_id (CasillaId | None)
out_of_window_count (int | None)
out_of_window_min_filing_date (date | None)
out_of_window_max_filing_date (date | None)
- reason: CalculationSourceDiagnosticReason¶
- source_kind: str¶
- binding_source: BindingSourceKind | None¶
Canonical binding source when
source_kindnames one;Nonefor advisory categories.
- message: str¶
- resolver_id: str | None¶
- binding_id: BindingId | None¶
- relation_id: RelationId | None¶
- casilla_id: CasillaId | None¶
- out_of_window_count: int | None¶
- out_of_window_min_filing_date: date | None¶
- out_of_window_max_filing_date: date | None¶
- out_of_window_summary_message(*, count, min_filing_date, max_filing_date)[source]¶
Return the standard source-diagnostic message for summarized period exclusions.
- out_of_window_summary_source_diagnostic(*, source_kind, resolver_id, count, min_filing_date, max_filing_date)[source]¶
Build one structured source diagnostic for summarized
OUTSIDE_PERIODrows.
- class CalculationSourceProvenance(**data)[source]¶
Bases:
BaseModelStable source object provenance produced by a resolver.
- Parameters:
source_kind (str)
binding_source (BindingSourceKind | None)
source_ref (str)
fingerprint (str | None)
relation_id (RelationId | None)
source_modelo (ModeloId | None)
source_filing_year (int | None)
source_casilla_ids (tuple[CasillaId, ...])
legal_refs (tuple[LegalRefId, ...])
source_refs (tuple[SourceRefId, ...])
- source_kind: str¶
- binding_source: BindingSourceKind | None¶
Canonical binding source when
source_kindnames one;Nonefor non-binding provenance.
- source_ref: str¶
- fingerprint: str | None¶
- relation_id: RelationId | None¶
- source_modelo: ModeloId | None¶
- source_filing_year: int | None¶
- source_periods: tuple[str, ...]¶
- source_casilla_ids: tuple[CasillaId, ...]¶
- legal_refs: tuple[LegalRefId, ...]¶
- source_refs: tuple[SourceRefId, ...]¶
- class BorradorSourceProvenance(**data)[source]¶
Bases:
BaseModelTyped borrador-snapshot provenance carried on a source resolution.
The AEAT borrador snapshot is the one source whose downstream consumer (
persist_calculation_revision) needs more than the genericCalculationSourceProvenancerow: it persists the originatingborrador_snapshot_idand the sortedbindings_sourced_from_borradortrace onto theCalculationRevision. Carrying that as ONE typed sub-model keeps the genericCalculationSourceResolutionenvelope from accreting per-source named fields while preserving the trace as typed data the call site reads directly – never by parsing theborrador:{id}:binding:{bid}provenancesource_refstrings.- snapshot_id: str¶
- bindings_sourced: tuple[BindingId, ...]¶
- class CalculationSourceResolution(**data)[source]¶
Bases:
BaseModelResolved values and provenance returned by one source resolver.
- Parameters:
resolver_id (str)
owned_sources (tuple[BindingSourceKind, ...])
row_binding_values (Mapping[tuple[BindingId, int], str | Decimal])
unresolved_relation_ids (tuple[RelationId, ...])
unresolved_binding_ids (tuple[BindingId, ...])
detail_rows (tuple[Modelo184MemberRow | Modelo232VinculadaRow | Modelo349OperadorRow | Modelo349RectificacionRow | Modelo347ContraparteRow, ...])
borrador_provenance (BorradorSourceProvenance | None)
diagnostics (tuple[CalculationSourceDiagnostic, ...])
provenance (tuple[CalculationSourceProvenance, ...])
- resolver_id: str¶
- owned_sources: tuple[BindingSourceKind, ...]¶
- binding_values: Mapping[BindingId, Decimal]¶
- enum_binding_values: Mapping[BindingId, str]¶
- date_binding_values: Mapping[BindingId, date]¶
- row_binding_values: Mapping[RowBindingKey, RowBindingValue]¶
- relation_values: Mapping[RelationId, Decimal]¶
- unresolved_relation_ids: tuple[RelationId, ...]¶
- unresolved_binding_ids: tuple[BindingId, ...]¶
- bound_inputs_by_casilla_id: Mapping[CasillaId, Decimal]¶
- detail_rows: tuple[ModeloDetailRow, ...]¶
- source_transaction_ids: Sequence[str]¶
- borrador_provenance: BorradorSourceProvenance | None¶
- diagnostics: tuple[CalculationSourceDiagnostic, ...]¶
- provenance: tuple[CalculationSourceProvenance, ...]¶
- class ModeloSourceResolver(*args, **kwargs)[source]¶
Bases:
ProtocolApplication port implemented by one calculation source adapter.
- property owned_sources: tuple[BindingSourceKind, ...]¶
Registry
BindingSourceKindthis resolver owns.
- resolve(context)[source]¶
Resolve source-backed calculation values for
context.Returns a
CalculationSourceResolutioncarrying resolved binding values, provenance, and any source diagnostics.- Return type:
- Parameters:
context (CalculationSourceContext)
- merge_source_resolutions(resolutions, *, resolver_id='source_mesh')[source]¶
Merge resolver outputs and reject ambiguous ownership.
Returns a
CalculationSourceResolution.- Return type:
- Parameters:
resolutions (Sequence[CalculationSourceResolution])
resolver_id (str)
- merge_source_resolutions_by_precedence(tiers, *, resolver_id='source_mesh_precedence')[source]¶
Overlay tiers into one
CalculationSourceResolution.Later tiers win on collision.
Unlike
merge_source_resolutions()(which is EXCLUSIVE: a binding claimed by two resolvers in one tier is a hardAggregationValidationError), this merge is a precedence OVERLAY: the binding / enum / date channels dict-merge in tier order so a higher-precedence tier silently overrides a lower one. It is the explicit form of the historical{**profile, **backend, **borrador, **caller}ladder: each tier is itself an intra-tier-exclusivemerge_source_resolutions()output, and the tiers are layered lowest -> highest.The non-channel fields (relations, bound-casilla inputs, source transaction ids, unresolved relations, diagnostics, provenance, owned_sources) accumulate across tiers;
borrador_provenanceis carried from whichever tier supplies it (exactly one does).- Return type:
- Parameters:
tiers (Sequence[CalculationSourceResolution])
resolver_id (str)
- collect_unhandled_source_diagnostics(revision, *, handled_sources, manual_sources=frozenset({'manual_input'}))[source]¶
Return
CalculationSourceDiagnosticentries for revision bindings with no enrolled resolver.- Parameters:
revision (
ModeloRevision) – TheModeloRevisionwhose bindings are inspected for missing resolvers.handled_sources (
frozenset[str]) – Source kind strings already claimed by enrolled resolvers.manual_sources (
frozenset[str]) – Source kind strings treated as intentionally unresolved.
- Return type:
- storage_degradation_resolution(*, resolver_id, owned_sources, source_kinds, error)[source]¶
Return an empty
CalculationSourceResolutioncarrying secure-storage degradation diagnostics.- Return type:
- Parameters:
resolver_id (str)
owned_sources (tuple[BindingSourceKind, ...])
error (BaseException)