# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-genai-span-attribute-collapse-when-a-tool-call-lineage-re-enters-a-resumed-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-genai-span-attribute-collapse-when-a-tool-call-lineage-re-enters-a-resumed-invocation.warrant.json
# Markdown SHA-256:   edddd3f8df14909a7d89a1873a5e82a902ea466f7ad864c80792179cc84ab986
# Code AST SHA-256:   43695d8b58d4c4c63565f8f4c2c3510670710f8d441d21acc49d7ac49f4fe5f7
# Verified Classes:   GenAILineageInvariantError, ToolCall, InvocationSpan, TraceReconciler
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class GenAILineageInvariantError(RuntimeError):
    """Raised when a resumed invocation would violate tool-call lineage
    uniqueness or double-count token usage within a single trace_id."""
    pass


@dataclass
class ToolCall:
    call_id: str
    name: str
    arguments: str

    def arg_hash(self) -> str:
        return hashlib.sha256(self.arguments.encode()).hexdigest()


@dataclass
class InvocationSpan:
    span_id: str
    trace_id: str
    input_tokens: int
    output_tokens: int
    tool_calls: list[ToolCall] = field(default_factory=list)
    resumed_from_checkpoint: bool = False
    resume_link: str | None = None


class TraceReconciler:
    """Enforces the two GenAI aggregate invariants:
    (1) gen_ai.tool.call.id unique per trace_id;
    (2) token sums equal true billed total (no re-emission double-count).
    """

    def __init__(self) -> None:
        self._seen_call_ids: dict[str, set[str]] = {}
        self._seen_arg_hashes: dict[str, set[str]] = {}
        self._billed_tokens: dict[str, int] = {}

    def admit_invocation(self, span: InvocationSpan) -> None:
        trace = span.trace_id
        self._seen_call_ids.setdefault(trace, set())
        self._seen_arg_hashes.setdefault(trace, set())

        if span.resumed_from_checkpoint and not span.resume_link:
            raise GenAILineageInvariantError(
                f"resumed invocation {span.span_id} in trace {trace} "
                f"lacks gen_ai.resume.link; lineage would orphan"
            )

        for call in span.tool_calls:
            if call.call_id in self._seen_call_ids[trace]:
                raise GenAILineageInvariantError(
                    f"duplicate gen_ai.tool.call.id {call.call_id} in "
                    f"trace {trace}; re-emission would double-count"
                )
            if call.arg_hash() in self._seen_arg_hashes[trace]:
                raise GenAILineageInvariantError(
                    f"re-emitted tool call {call.name} (arg_hash "
                    f"{call.arg_hash()[:12]}) in trace {trace}; "
                    f"checkpoint distillation dropped call identity"
                )
            self._seen_call_ids[trace].add(call.call_id)
            self._seen_arg_hashes[trace].add(call.arg_hash())

        self._billed_tokens[trace] = (
            self._billed_tokens.get(trace, 0)
            + span.input_tokens
            + span.output_tokens
        )

    def assert_billed_total(self, trace_id: str, provider_total: int, epsilon: int = 0) -> None:
        observed = self._billed_tokens.get(trace_id, 0)
        if abs(observed - provider_total) > epsilon:
            raise GenAILineageInvariantError(
                f"trace {trace_id} token sum {observed} diverges from "
                f"provider billed {provider_total} by {observed - provider_total}; "
                f"suspected resume re-emission"
            )
