# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-genai-span-whose-gen-ai-usage-input-tokens-was-emitted-by-a-resumed-turn-and-how-does-the-resumed-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-genai-span-whose-gen-ai-usage-input-tokens-was-emitted-by-a-resumed-turn-and-how-does-the-resumed-turn.warrant.json
# Markdown SHA-256:   856a1e93219ae01c1e8ea868e5b213cd691a8698d1719cea09cb96584b7b8925
# Code AST SHA-256:   8e51795d28dbe1c5b650370e5da2be3515263e67f12098000e2deb025a0b6be6
# Verified Classes:   ReplayedSpanAccountingError, GenAISpanRegistry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ReplayedSpanAccountingError(RuntimeError):
    """Raised when a resumed GenAI span would double-count a model invocation."""
    pass


class GenAISpanRegistry:
    def __init__(self):
        self._response_ids = {}   # response.id -> span_id
        self._tool_call_ids = {}  # tool.call.id -> attempt count

    def admit_chat_span(self, span):
        rid = span.attributes.get("gen_ai.response.id")
        replay_of = span.attributes.get("agent.resume.replayed_span_id")

        if rid is None:
            raise ReplayedSpanAccountingError(
                f"span {span.span_id} missing gen_ai.response.id; "
                "cannot prove uniqueness"
            )

        if rid in self._response_ids:
            if replay_of is None:
                raise ReplayedSpanAccountingError(
                    f"span {span.span_id} reuses response.id={rid} "
                    f"(held by {self._response_ids[rid]}) with no replay marker; "
                    "downstream dedup would silently drop one completion"
                )
            if replay_of != self._response_ids[rid]:
                raise ReplayedSpanAccountingError(
                    f"span {span.span_id} claims replay of {replay_of} "
                    f"but response.id={rid} belongs to {self._response_ids[rid]}"
                )
            # Linked replay: usage must be measured, not copied.
            if span.attributes.get("gen_ai.usage.input_tokens") is None:
                raise ReplayedSpanAccountingError(
                    f"replay span {span.span_id} has no measured input_tokens; "
                    "checkpoint-copied counts are not admissible"
                )
            return "accepted_linked_replay"

        self._response_ids[rid] = span.span_id
        return "accepted_primary"

    def admit_tool_span(self, span):
        call_id = span.attributes.get("gen_ai.tool.call.id")
        if call_id is None:
            raise ReplayedSpanAccountingError(
                f"tool span {span.span_id} missing stable gen_ai.tool.call.id; "
                "retries will be indistinguishable from independent calls"
            )
        self._tool_call_ids[call_id] = self._tool_call_ids.get(call_id, 0) + 1
        return self._tool_call_ids[call_id]
