# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-token-attribution-when-a-federated-mesh-s-span-tree-forks-across-re-entrant-agent-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-token-attribution-when-a-federated-mesh-s-span-tree-forks-across-re-entrant-agent-calls.warrant.json
# Markdown SHA-256:   2aa963584eb2f4931e92e60286cea181c9067e811411514b0950dc5fdea43f11
# Code AST SHA-256:   53518b77d8265393832b575e23897e0ec8d238122ecace234a5fbf24a3a99cef
# Verified Classes:   AttributionDivergenceError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class AttributionDivergenceError(RuntimeError):
    """Raised when span-tree token rollup and warrant-ledger debits disagree
    beyond the accounted residual for untagged re-entrant spans."""
    pass


def reconcile_mesh_tokens(
    span_rollup: dict[str, int],        # trace_id -> tokens, from tree traversal
    warrant_debits: dict[str, int],     # warrant_id -> tokens, from reservation ledger
    span_warrant_map: dict[str, str],   # trace_id -> warrant_id (post-join)
    untagged_reentrant_tokens: int,     # known residual: legacy instances, no warrant tag
    tolerance: int = 0,
) -> dict[str, int]:
    """Return per-warrant attributed tokens, or raise if the residual is unexplained.

    The invariant: after joining spans to warrants, the difference between
    tree-rollup totals and ledger debits must equal exactly the accounted
    untagged re-entrant residual. Any other gap means a re-entrant span was
    attributed to the trace root while funded by a different warrant.
    """
    tree_total = sum(span_rollup.values())
    ledger_total = sum(warrant_debits.values())
    residual = tree_total - ledger_total

    unexplained = abs(residual) - untagged_reentrant_tokens
    if unexplained > tolerance:
        raise AttributionDivergenceError(
            f"unexplained token residual {unexplained} "
            f"(tree={tree_total}, ledger={ledger_total}, "
            f"accounted_untagged={untagged_reentrant_tokens}); "
            f"likely a re-entrant span missing budget_warrant_id"
        )

    attributed: dict[str, int] = {}
    for trace_id, tokens in span_rollup.items():
        warrant = span_warrant_map.get(trace_id)
        if warrant is None:
            # Legacy untagged span: falls back to trace-root attribution and is
            # counted in untagged_reentrant_tokens, never silently absorbed.
            continue
        attributed[warrant] = attributed.get(warrant, 0) + tokens
    return attributed
