# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-emit-a-genai-span-with-gen-ai-usage-input-tokens-that-disagrees-with-the-tool-call-children-it-spawned-and-what-invariant-does-th.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-emit-a-genai-span-with-gen-ai-usage-input-tokens-that-disagrees-with-the-tool-call-children-it-spawned-and-what-invariant-does-th.warrant.json
# Markdown SHA-256:   f88f42c4649b26778eb2e13267512e197408b84ca54ce9098fbe6b732e1da428
# Code AST SHA-256:   da41a23a0d7d56f8e9d492bbf23c145d1bc138b89fa1befb74a1d55ced8c12cf
# Verified Classes:   TokenConservationViolation, UsageAccumulator
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Tuple


class TokenConservationViolation(RuntimeError):
    """Raised when an agent span's reported usage under-reports its chat children."""


@dataclass
class UsageAccumulator:
    # key: (trace_id, parent_span_id) -> [input_tokens, output_tokens, round_trips]
    _acc: Dict[Tuple[str, str], list] = field(default_factory=dict)

    def record_chat(self, trace_id: str, parent_span_id: str,
                    input_tokens: int, output_tokens: int) -> None:
        key = (trace_id, parent_span_id)
        slot = self._acc.setdefault(key, [0, 0, 0])
        slot[0] += input_tokens
        slot[1] += output_tokens
        slot[2] += 1

    def reconcile_agent(self, trace_id: str, span_id: str,
                        reported_input: int, reported_output: int,
                        max_single_round_trip: int) -> Tuple[int, int]:
        slot = self._acc.pop((trace_id, span_id), None)
        if slot is None:
            # No chat children observed: agent may be tool-free or uninstrumented.
            return reported_input, reported_output

        summed_in, summed_out, n = slot
        deficit_in = summed_in - reported_input
        deficit_out = summed_out - reported_output

        # Deficit whose shape matches "last-turn-only capture" is the double-ownership bug.
        if deficit_in > max_single_round_trip or deficit_out > max_single_round_trip:
            raise TokenConservationViolation(
                f"agent span {span_id} under-reports usage: "
                f"reported=({reported_input},{reported_output}) "
                f"children_sum=({summed_in},{summed_out}) over {n} round-trips; "
                f"deficit=({deficit_in},{deficit_out}) exceeds max single round-trip "
                f"{max_single_round_trip} — likely last-turn-only attribute capture"
            )

        # Otherwise: small deficit is stream-cancellation loss; accumulator is authoritative.
        return summed_in, summed_out
