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: CoreValidationError

Raised when a CalculationSourceMesh field validator rejects an invariant.

Replaces bare ValueError at the owned_sources uniqueness / blank guards and the source_transaction_ids uniqueness / blank guards so callers receive a typed, registry-bound, localized error. Inherits from CoreValidationError (which inherits from ValueError) so pydantic field validators surface it through ValidationError without special handling.

Parameters:

message_key (str)

Return type:

None

code: ClassVar[ErrorCode]
class DeferredSourceTarget(owning_adr, trigger, promotion_depends_on=None)[source]

Bases: NamedTuple

The 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. None for 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

Alias for field number 0

trigger: str

Alias for field number 1

promotion_depends_on: BindingSourceKind | None

Alias for field number 2

class CallerOverrideDisposition(*values)[source]

Bases: StrEnum

Whether 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: NamedTuple

One 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_LADDER replaces 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

Alias for field number 0

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 by merge_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_LADDER rather than hand-listed per set.

Return type:

frozenset[BindingSourceKind]

Returns:

The BindingSourceKind members carried by every ladder tier whose disposition matches disposition.

Parameters:

disposition (CallerOverrideDisposition)

class BindingSourceDisposition(*values)[source]

Bases: StrEnum

Where a binding source kind resolves on the live calculate mesh.

The single closed answer to “where does source X resolve” for every BindingSourceKind member, replacing the four scattered enrollment structures (the merge_source_resolutions resolver 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 BindingSourceKind member by its live mesh BindingSourceDisposition.

enrolled_sources is the LIVE enrolled set read at execution time – the union of every active resolver’s owned_sources plus the pre-mesh tiers and manual_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_KINDS and RESERVED_SOURCE_KINDS supply 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:

Mapping[BindingSourceKind, BindingSourceDisposition]

Parameters:

enrolled_sources (frozenset[BindingSourceKind])

class CalculationSourceContext(**data)[source]

Bases: BaseModel

Context supplied to a calculation source resolver.

The period field is the typed Period value carrying both the filing year and the bare registry period code. Consumers that need the raw token for a downstream str-typed API should use context.period.registry_token; those that need only the year can use context.period.year (which mirrors context.filing_year).

Parameters:
  • bucket_id (Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=128, pattern=None, ascii_only=None)])

  • modelo (str)

  • filing_year (int)

  • period (Period)

  • revision (ModeloRevision)

  • calculated_at (datetime | None)

bucket_id: BucketId
modelo: str
filing_year: int
period: Period
revision: ModeloRevision
calculated_at: datetime | None
class CalculationSourceDiagnostic(**data)[source]

Bases: BaseModel

Diagnostic 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_kind names one; None for 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.

Return type:

str

Parameters:
  • count (int)

  • min_filing_date (date)

  • max_filing_date (date)

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_PERIOD rows.

Return type:

CalculationSourceDiagnostic

Parameters:
  • source_kind (str)

  • resolver_id (str)

  • count (int)

  • min_filing_date (date)

  • max_filing_date (date)

class CalculationSourceProvenance(**data)[source]

Bases: BaseModel

Stable 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_periods (tuple[str, ...])

  • 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_kind names one; None for 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: BaseModel

Typed 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 generic CalculationSourceProvenance row: it persists the originating borrador_snapshot_id and the sorted bindings_sourced_from_borrador trace onto the CalculationRevision. Carrying that as ONE typed sub-model keeps the generic CalculationSourceResolution envelope from accreting per-source named fields while preserving the trace as typed data the call site reads directly – never by parsing the borrador:{id}:binding:{bid} provenance source_ref strings.

Parameters:
  • snapshot_id (str)

  • bindings_sourced (tuple[BindingId, ...])

snapshot_id: str
bindings_sourced: tuple[BindingId, ...]
class CalculationSourceResolution(**data)[source]

Bases: BaseModel

Resolved values and provenance returned by one source resolver.

Parameters:
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: Protocol

Application port implemented by one calculation source adapter.

property resolver_id: str

Stable resolver identifier for diagnostics and provenance.

property owned_sources: tuple[BindingSourceKind, ...]

Registry BindingSourceKind this resolver owns.

resolve(context)[source]

Resolve source-backed calculation values for context.

Returns a CalculationSourceResolution carrying resolved binding values, provenance, and any source diagnostics.

Return type:

CalculationSourceResolution

Parameters:

context (CalculationSourceContext)

merge_source_resolutions(resolutions, *, resolver_id='source_mesh')[source]

Merge resolver outputs and reject ambiguous ownership.

Returns a CalculationSourceResolution.

Return type:

CalculationSourceResolution

Parameters:
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 hard AggregationValidationError), 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-exclusive merge_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_provenance is carried from whichever tier supplies it (exactly one does).

Return type:

CalculationSourceResolution

Parameters:
collect_unhandled_source_diagnostics(revision, *, handled_sources, manual_sources=frozenset({'manual_input'}))[source]

Return CalculationSourceDiagnostic entries for revision bindings with no enrolled resolver.

Parameters:
  • revision (ModeloRevision) – The ModeloRevision whose 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:

tuple[CalculationSourceDiagnostic, ...]

storage_degradation_resolution(*, resolver_id, owned_sources, source_kinds, error)[source]

Return an empty CalculationSourceResolution carrying secure-storage degradation diagnostics.

Return type:

CalculationSourceResolution

Parameters: