# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-genai-agent-span-the-orphaned-tool-call-event-that-silently-corrupts-token-accounting.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-genai-agent-span-the-orphaned-tool-call-event-that-silently-corrupts-token-accounting.warrant.json
# Markdown SHA-256:   22f8097eb6006061938a5aa163157ece59f691ba3b3f7bd0acc4c3ff1ddeb20f
# Code AST SHA-256:   f6a11d661a440bc4f2eff54ee5cf12f294a6794cbe3dffc400e7b1952289ec8f
# Verified Classes:   OrphanedToolCallError, UnreconciledTokenAccountingError, AgentSpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanedToolCallError(RuntimeError):
    """Raised when an agent span is closed while a dispatched tool call is unresolved."""
    pass


class UnreconciledTokenAccountingError(RuntimeError):
    """Raised when a trace is consumed for token accounting without reconciliation."""
    pass


@dataclass
class AgentSpan:
    span_id: str
    conversation_id: str
    step_index: int
    input_hash: str
    output_tokens: int = 0
    reconciliation: str = "complete"          # "complete" | "incomplete"
    retry_of_span_id: Optional[str] = None
    in_flight_tool_calls: set = field(default_factory=set)
    closed: bool = False

    def dispatch_tool(self, call_id: str) -> None:
        if self.closed:
            raise OrphanedToolCallError(
                f"cannot dispatch tool {call_id} on closed span {self.span_id}"
            )
        self.in_flight_tool_calls.add(call_id)

    def resolve_tool(self, call_id: str) -> None:
        self.in_flight_tool_calls.discard(call_id)

    def close(self) -> None:
        if self.in_flight_tool_calls:
            # Boundary: parent cannot close cleanly with children in flight.
            # Either hold-and-wait, or close with explicit non-authoritative flag.
            self.reconciliation = "incomplete"
        self.closed = True


def consume_for_accounting(spans: list[AgentSpan]) -> int:
    """Sum output tokens across a conversation, rejecting unreconciled traces."""
    total = 0
    seen: dict[tuple, str] = {}
    for s in spans:
        if not s.closed:
            raise OrphanedToolCallError(f"span {s.span_id} still open at accounting time")
        if s.reconciliation != "complete" and s.retry_of_span_id is None:
            raise UnreconciledTokenAccountingError(
                f"span {s.span_id} closed with in-flight tools but no retry link; "
                "trace is non-authoritative for token accounting"
            )
        key = (s.conversation_id, s.step_index, s.input_hash)
        if key in seen:
            # deterministic identity: retry of the same model invocation
            raise UnreconciledTokenAccountingError(
                f"duplicate invocation {key}: {s.span_id} retries {seen[key]} "
                "without deduplication"
            )
        seen[key] = s.span_id
        total += s.output_tokens
    return total


def demo() -> None:
    parent = AgentSpan("sp-1", "conv-9", step_index=6, input_hash="h6", output_tokens=1180)
    parent.dispatch_tool("call_7f3a")
    parent.close()  # closes with tool in flight -> reconciliation = "incomplete"
    try:
        consume_for_accounting([parent])
    except UnreconciledTokenAccountingError as e:
        print("rejected:", e)
        raise OrphanedToolCallError(
            "runtime closed agent span with unresolved tool call and no tombstone; "
            "retry would double-count 1180 output tokens"
        ) from e


if __name__ == "__main__":
    demo()
