# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-tenant-token-attribution-drift-when-federated-agent-traces-are-joined-after-the-fact.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-tenant-token-attribution-drift-when-federated-agent-traces-are-joined-after-the-fact.warrant.json
# Markdown SHA-256:   6221407649d7e017ef8d1500bed3a75519d61e4a49bf80b64c110b95ae31cddc
# Code AST SHA-256:   827e7c0333cc46c97b576662498b02979114d7c622e7efa5af6dbe51b96eb04b
# Verified Classes:   AttributionConservationError, MeterSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class AttributionConservationError(RuntimeError):
    """Raised when federated token attribution fails to reconcile to the gateway meter."""


@dataclass(frozen=True)
class MeterSpan:
    trace_id: str
    logical_op_id: str | None
    upstream_trace_id: str | None
    retry_reason: str | None
    tokens: int
    billing_tenant: str | None  # None => unattributed


def reconcile(
    spans: list[MeterSpan],
    gateway_total_tokens: int,
    tolerance: int = 0,
) -> dict[str, int]:
    """
    Enforce: sum(attributed per tenant) + unattributed == gateway_total.

    A span is attributable only if it carries a stable logical_op_id AND a
    resolvable billing_tenant. Retries without a logical_op_id are routed to
    the unattributed bucket rather than guessed onto a tenant.
    """
    attributed: dict[str, int] = {}
    unattributed = 0

    for s in spans:
        if s.logical_op_id is None or s.billing_tenant is None:
            unattributed += s.tokens
            continue
        attributed[s.billing_tenant] = attributed.get(s.billing_tenant, 0) + s.tokens

    accounted = sum(attributed.values()) + unattributed
    delta = accounted - gateway_total_tokens
    if abs(delta) > tolerance:
        raise AttributionConservationError(
            f"attribution does not reconcile to gateway meter: "
            f"accounted={accounted} gateway_total={gateway_total_tokens} "
            f"delta={delta} unattributed={unattributed} "
            f"tenants={attributed}"
        )

    attributed["__unattributed__"] = unattributed
    return attributed


def attribute_retry(span: MeterSpan, requester: str, shared_pool: str) -> str:
    """Retry-class provenance decides the economic owner of a retried call."""
    if span.retry_reason == "rate_limited":
        return shared_pool
    if span.retry_reason in ("timeout", "client_retry"):
        return requester
    raise AttributionConservationError(
        f"unclassifiable retry_reason={span.retry_reason!r} on trace={span.trace_id}; "
        f"refusing to guess a billing entity"
    )
