# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-when-a-tool-call-span-outlives-its-parent-agent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-when-a-tool-call-span-outlives-its-parent-agent-span.warrant.json
# Markdown SHA-256:   446ba41417594466c40d8062c21d6f6a2640aff7c5176bfcdb1a71b892f131a2
# Code AST SHA-256:   97984856af36f33b566635ae9b37736c9691fe7159d56cff155abda1f4327472
# Verified Classes:   TokenAccountingInvariantError, Span, TraceLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a usage-bearing span closes after its parent was finalized."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    name: str
    close_time: float
    usage_tokens: int = 0
    is_terminal: bool = False


@dataclass
class TraceLedger:
    spans: dict[str, Span] = field(default_factory=dict)
    finalized_parents: set[str] = field(default_factory=set)
    rolled_up_tokens: int = 0

    def record(self, span: Span) -> None:
        if span.parent_id in self.finalized_parents and span.usage_tokens > 0:
            raise TokenAccountingInvariantError(
                f"span {span.name}({span.span_id}) carries {span.usage_tokens} tokens "
                f"but parent {span.parent_id} was already finalized; "
                f"tree rollup would drop these tokens"
            )
        self.spans[span.span_id] = span
        if span.is_terminal:
            self._finalize_trace(span.parent_id)

    def _finalize_trace(self, root_id: str | None) -> None:
        if root_id is None:
            return
        total = sum(
            s.usage_tokens for s in self.spans.values()
            if s.parent_id == root_id or s.span_id == root_id
        )
        self.rolled_up_tokens += total
        for s in self.spans.values():
            if s.parent_id == root_id:
                self.finalized_parents.add(s.span_id)
        self.finalized_parents.add(root_id)


def emit_agent_turn(ledger: TraceLedger, tool_delay_s: float) -> None:
    t0 = time.monotonic()
    ledger.record(Span("agent-1", None, "invoke_agent", t0 + 0.1, usage_tokens=412))
    ledger.record(Span("chat-1", "agent-1", "chat", t0 + 0.2, usage_tokens=0))
    # Tool span closes AFTER the agent span — the ordering inversion.
    ledger.record(Span("tool-1", "agent-1", "execute_tool", t0 + tool_delay_s, usage_tokens=1880))
    # Terminal sentinel guarantees rollup sees the tool span first.
    ledger.record(Span("sentinel-1", "agent-1", "turn_complete", t0 + tool_delay_s + 0.01, is_terminal=True))


def run() -> None:
    ledger = TraceLedger()
    try:
        emit_agent_turn(ledger, tool_delay_s=8.0)
    except TokenAccountingInvariantError as e:
        raise TokenAccountingInvariantError(
            "trace accounting would silently undercount; require terminal sentinel span"
        ) from e
    assert ledger.rolled_up_tokens == 2292, ledger.rolled_up_tokens


if __name__ == "__main__":
    run()
