# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-otel-genai-span-accounting-divergence-that-occurs-when-a-tool-call-span-reopens-after-a-speculative-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-otel-genai-span-accounting-divergence-that-occurs-when-a-tool-call-span-reopens-after-a-speculative-retry.warrant.json
# Markdown SHA-256:   0c5c32ebbef7121b66ef14666aaad2a2677cd23db55825b78940215fafcc30ea
# Code AST SHA-256:   66d7f222307c447a4db270eff7a5a1650a0af5f84c13d8ed8be187491c1f255f
# Verified Classes:   SpanAccountingDivergence, ToolSpan, TraceLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpanAccountingDivergence(RuntimeError):
    """Raised when a logical tool call is represented by more than one emitted span."""
    pass


@dataclass
class ToolSpan:
    span_id: str
    tool_name: str
    arguments_hash: str
    parent_span_id: str
    status: str
    attempt: int = 1
    superseded: bool = False


@dataclass
class TraceLedger:
    spans: list = field(default_factory=list)

    def emit(self, span: ToolSpan) -> None:
        # Enforce the one-to-one invariant: a logical tool call (tool_name + args_hash
        # under the same logical parent) may appear at most once as a *live* span.
        for existing in self.spans:
            same_logical = (
                existing.tool_name == span.tool_name
                and existing.arguments_hash == span.arguments_hash
                and existing.parent_span_id == span.parent_span_id
            )
            if same_logical and not existing.superseded:
                if span.attempt <= existing.attempt:
                    raise SpanAccountingDivergence(
                        f"duplicate live span for logical tool call "
                        f"{span.tool_name}/{span.arguments_hash[:8]} "
                        f"(existing attempt={existing.attempt}, new attempt={span.attempt}); "
                        f"retries must be folded into a single span with attempt_count"
                    )
                existing.superseded = True
        self.spans.append(span)

    def per_tool_token_attribution(self, tool_name: str) -> int:
        live = [
            s for s in self.spans
            if s.tool_name == tool_name and not s.superseded
        ]
        if len(live) > 1:
            raise SpanAccountingDivergence(
                f"join fan-out: {len(live)} live spans for tool {tool_name}; "
                f"aggregator would double-count parent LLM input tokens"
            )
        return sum(1 for _ in live)


def record_retry(ledger: TraceLedger, original: ToolSpan, retry: ToolSpan) -> None:
    if original.tool_name != retry.tool_name or original.arguments_hash != retry.arguments_hash:
        raise SpanAccountingDivergence(
            "retry does not match original logical call; not a speculative retry"
        )
    retry.attempt = original.attempt + 1
    ledger.emit(retry)
