# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-attribution-drift-from-silently-corrupting-per-agent-cost-accounting-in-multi-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-attribution-drift-from-silently-corrupting-per-agent-cost-accounting-in-multi-agent-traces.warrant.json
# Markdown SHA-256:   81b89b37584f051e00a57ea5b87f3ef1b9ac1375840b0030d13ad52f244ff1ec
# Code AST SHA-256:   e8b96ec7f2bededfaee9a4b87de6f75be34fde851e481889b3d45d1c068262ed
# Verified Classes:   TokenAttributionDriftError, ProviderResponse, Span, TraceLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List


class TokenAttributionDriftError(RuntimeError):
    """Raised when attributed tokens do not reconcile against provider response records."""
    pass


@dataclass(frozen=True)
class ProviderResponse:
    response_id: str
    model: str
    input_tokens: int
    output_tokens: int
    cache_read_tokens: int = 0

    @property
    def total_tokens(self) -> int:
        return self.input_tokens + self.output_tokens + self.cache_read_tokens


@dataclass
class Span:
    span_id: str
    agent_id: str
    contributing_response_ids: List[str] = field(default_factory=list)


class TraceLedger:
    """Source of truth is provider responses; span attribution is derived."""

    def __init__(self) -> None:
        self._responses: Dict[str, ProviderResponse] = {}
        self._spans: Dict[str, Span] = {}

    def record_response(self, resp: ProviderResponse) -> None:
        if resp.response_id in self._responses:
            raise TokenAttributionDriftError(
                f"Duplicate response_id {resp.response_id}: provider IDs must be unique"
            )
        self._responses[resp.response_id] = resp

    def register_span(self, span: Span) -> None:
        for rid in span.contributing_response_ids:
            if rid not in self._responses:
                raise TokenAttributionDriftError(
                    f"Span {span.span_id} references unknown response {rid}"
                )
        self._spans[span.span_id] = span

    def reconcile(self) -> None:
        """Enforce conservation: every response attributed exactly once, per leaf."""
        seen: Dict[str, str] = {}
        for span in self._spans.values():
            for rid in span.contributing_response_ids:
                if rid in seen:
                    raise TokenAttributionDriftError(
                        f"Response {rid} attributed to both {seen[rid]} and {span.span_id} "
                        f"(double-count)"
                    )
                seen[rid] = span.span_id

        orphaned = set(self._responses) - set(seen)
        if orphaned:
            raise TokenAttributionDriftError(
                f"Orphaned provider responses billed but never attributed: {sorted(orphaned)}"
            )

    def cost_by_agent(self) -> Dict[str, int]:
        self.reconcile()
        totals: Dict[str, int] = {}
        for span in self._spans.values():
            tokens = sum(
                self._responses[rid].total_tokens
                for rid in span.contributing_response_ids
            )
            totals[span.agent_id] = totals.get(span.agent_id, 0) + tokens
        return totals


def close_trace(ledger: TraceLedger) -> Dict[str, int]:
    try:
        return ledger.cost_by_agent()
    except TokenAttributionDriftError as exc:
        raise TokenAttributionDriftError(
            f"Trace close blocked: attribution invariant violated — {exc}"
        ) from exc
