# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-attribute-observability-spend-to-the-wrong-agent-when-mcp-sessions-outlive-their-owning-agent-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-attribute-observability-spend-to-the-wrong-agent-when-mcp-sessions-outlive-their-owning-agent-identity.warrant.json
# Markdown SHA-256:   ff973c8e6ab7baa412aef8b5781f9224f4162fd09532beace950a3802314e78b
# Code AST SHA-256:   e3badbe300cea0ad4cc9701f41dfb5725fc5aa01e4c34573aa142a6de05b0d79
# Verified Classes:   AttributionInvariantError, Span, CostLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class AttributionInvariantError(RuntimeError):
    """Raised when a billable span cannot be attributed to its authorizing agent."""


@dataclass
class Span:
    session_id: str
    agent_id: str | None
    tokens: int


@dataclass
class CostLedger:
    # per-agent spend, keyed strictly on authorizing identity
    spend: dict[str, int] = field(default_factory=dict)
    ceilings: dict[str, int] = field(default_factory=dict)

    def record(self, span: Span) -> None:
        if not span.agent_id:
            # fail closed: never fall back to session owner
            raise AttributionInvariantError(
                f"span on session {span.session_id!r} has no agent_id; "
                "refusing to attribute to session owner"
            )
        self.spend[span.agent_id] = self.spend.get(span.agent_id, 0) + span.tokens

    def check_breaker(self, agent_id: str) -> None:
        ceiling = self.ceilings.get(agent_id)
        if ceiling is None:
            raise AttributionInvariantError(
                f"no ceiling registered for agent {agent_id!r}; breaker would be blind"
            )
        if self.spend.get(agent_id, 0) > ceiling:
            raise AttributionInvariantError(
                f"agent {agent_id!r} exceeded ceiling: "
                f"{self.spend[agent_id]} > {ceiling}"
            )


def reconcile(ledger: CostLedger, session_spend: dict[str, int]) -> None:
    """Assert per-agent sums equal session totals; mismatch means misattribution."""
    per_agent_total = sum(ledger.spend.values())
    session_total = sum(session_spend.values())
    if per_agent_total != session_total:
        raise AttributionInvariantError(
            f"attribution reconciliation failed: per-agent={per_agent_total} "
            f"session={session_total}; spans dropped or double-credited"
        )


def run_batch(ledger: CostLedger, spans: list[Span], session_spend: dict[str, int]) -> None:
    for span in spans:
        ledger.record(span)
        ledger.check_breaker(span.agent_id)  # type: ignore[arg-type]
    reconcile(ledger, session_spend)
