# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-when-tool-call-token-accounting-diverges-from-the-parent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-when-tool-call-token-accounting-diverges-from-the-parent-span.warrant.json
# Markdown SHA-256:   a195419e252a327c7d5a81c5296307d1b9ea4a4ed82126759b55a39b30a5addf
# Code AST SHA-256:   607392a4c81e8528830b818791371ae47c19a44c2c6ef5c9fa63fa3d27e870f6
# Verified Classes:   TokenAccountingDivergence, SpanRecord, AgentSpanGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class TokenAccountingDivergence(RuntimeError):
    """Raised when a parent agent span's output_tokens is less than the sum
    of its child spans' output_tokens beyond the declared tolerance."""
    pass


@dataclass
class SpanRecord:
    span_id: str
    parent_id: Optional[str]
    operation_name: str
    output_tokens: int
    provider: str
    ended: bool = False


@dataclass
class AgentSpanGate:
    tolerance: int = 0
    quarantine: list = field(default_factory=list)

    def _children_of(self, parent: SpanRecord, all_spans: list) -> list:
        return [
            s for s in all_spans
            if s.parent_id == parent.span_id
            and s.operation_name in ("llm", "chat", "tool_call")
            and s.provider == parent.provider
        ]

    def close_agent_span(self, parent: SpanRecord, all_spans: list) -> None:
        if parent.ended:
            raise TokenAccountingDivergence(
                f"span {parent.span_id} already ended; invariant cannot be enforced"
            )
        children = self._children_of(parent, all_spans)
        child_sum = sum(c.output_tokens for c in children)
        residual = parent.output_tokens - child_sum

        if residual < -self.tolerance:
            # Persist a durable sidecar BEFORE refusing, or the span is lost.
            self.quarantine.append({
                "trace_span": parent.span_id,
                "parent_output": parent.output_tokens,
                "child_sum": child_sum,
                "residual": residual,
                "provider": parent.provider,
                "ts": time.time(),
            })
            # Do NOT call parent.end(); route to reconciliation.
            raise TokenAccountingDivergence(
                f"span {parent.span_id}: parent output {parent.output_tokens} < "
                f"child sum {child_sum} (residual {residual}, tol {self.tolerance}); "
                f"refusing to close, quarantined for reconciliation"
            )

        # Within tolerance: close normally, record residual for audit.
        parent.ended = True
        # span.set_attribute("agent.token_accounting.residual", residual)
        # span.end()


def run_example() -> None:
    gate = AgentSpanGate(tolerance=0)
    parent = SpanRecord("p1", None, "agent", output_tokens=2041, provider="vendorA")
    children = [
        SpanRecord(f"c{i}", "p1", "llm", output_tokens=165, provider="vendorA")
        for i in range(14)
    ]  # sum = 2310 > 2041
    try:
        gate.close_agent_span(parent, [parent, *children])
    except TokenAccountingDivergence as e:
        assert not parent.ended
        assert len(gate.quarantine) == 1
        print(f"quarantined: {e}")


if __name__ == "__main__":
    run_example()
