# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-token-accounting-divergence-across-opentelemetry-genai-agent-spans-when-tool-call-attribute-emission-and-multi-agent-t.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-token-accounting-divergence-across-opentelemetry-genai-agent-spans-when-tool-call-attribute-emission-and-multi-agent-t.warrant.json
# Markdown SHA-256:   a2b969cc170dbef3141e1d4ace3ebeb80541079b3369036d0b0241edc9e401f5
# Code AST SHA-256:   a970975611cbdaf5c7c515cae42ec1702df8a6cdf1f5a566a98df683046e4a7c
# Verified Classes:   TraceAccountingError, GenAISpan, TraceStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceAccountingError(RuntimeError):
    """Raised when a trace is reconciled before its completion barrier is asserted,
    or when a usage attribute was mutated after span end."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    trace_id: str
    operation_name: Optional[str] = None
    input_tokens: int = 0
    output_tokens: int = 0
    ended: bool = False
    usage_finalized_before_end: bool = True
    is_root: bool = False
    task_complete_marker: bool = False


@dataclass
class TraceStore:
    spans_by_trace: dict = field(default_factory=dict)

    def ingest(self, span: GenAISpan) -> None:
        if span.ended and not span.usage_finalized_before_end:
            # The span closed with a usage attribute that was patched afterward.
            # The SDK snapshot is unreliable; refuse to count it silently.
            raise TraceAccountingError(
                f"span {span.span_id} in trace {span.trace_id} mutated "
                f"gen_ai.usage.* after end(); snapshot is stale"
            )
        self.spans_by_trace.setdefault(span.trace_id, []).append(span)

    def reconcile_task_cost(self, trace_id: str) -> int:
        spans = self.spans_by_trace.get(trace_id, [])
        roots = [s for s in spans if s.is_root]
        if len(roots) != 1:
            raise TraceAccountingError(
                f"trace {trace_id} has {len(roots)} root spans; "
                f"cannot attribute cost to a single task"
            )
        root = roots[0]
        if not root.task_complete_marker:
            # Root ended before children reported; trace is known-incomplete.
            # Do NOT compute a partial sum and call it the task cost.
            raise TraceAccountingError(
                f"trace {trace_id} root {root.span_id} lacks "
                f"gen_ai.task.complete marker; reconciliation would "
                f"under-count by the usage of unarrived child spans"
            )
        total = 0
        for s in spans:
            if s.operation_name is None:
                continue
            if not s.usage_finalized_before_end:
                raise TraceAccountingError(
                    f"span {s.span_id} usage not finalized before end()"
                )
            total += s.input_tokens + s.output_tokens
        return total
