# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-opentelemetry-genai-span-emission-has-silently-desynchronized-from-its-own-reasoning-state-during-a-tool-call-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-opentelemetry-genai-span-emission-has-silently-desynchronized-from-its-own-reasoning-state-during-a-tool-call-loop.warrant.json
# Markdown SHA-256:   a4f764b92e775a27d70d2443889af68abb9ac78eceeaf7d9debdeccbbbc63642
# Code AST SHA-256:   b09a564a8190dcba9c96a10eadbe92598bfb2b8a345422b7c9d50dc652aa6684
# Verified Classes:   TelemetryDesyncError, ToolSpan, TurnRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TelemetryDesyncError(RuntimeError):
    """Raised when emitted GenAI spans disagree with the agent's message history."""
    pass


@dataclass
class ToolSpan:
    call_id: Optional[str]
    tool_name: str
    status: str  # "ok" | "error" | "pending"
    input_tokens: Optional[int] = None


@dataclass
class TurnRecord:
    turn_index: int
    history_tool_calls: list[str]          # call IDs the model's history holds
    emitted_spans: list[ToolSpan] = field(default_factory=list)
    span_input_tokens: Optional[int] = None
    history_input_estimate: Optional[int] = None


def assert_turn_consistent(turn: TurnRecord, prior_warnings: int) -> None:
    """
    Pre-dispatch guard. Must run before tool call N+1 is dispatched.
    Raises TelemetryDesyncError on any unrecoverable divergence.
    """
    span_ids = {s.call_id for s in turn.emitted_spans if s.call_id}
    hist_ids = set(turn.history_tool_calls)

    # Orphaned span: emitted a tool span with no call.id at all.
    orphans = [s for s in turn.emitted_spans if not s.call_id]
    if orphans:
        raise TelemetryDesyncError(
            f"turn {turn.turn_index}: {len(orphans)} tool span(s) emitted "
            f"without gen_ai.tool.call.id; correlation impossible"
        )

    # History entry dispatched with no matching span.
    missing = hist_ids - span_ids
    pending_ok = {
        s.call_id for s in turn.emitted_spans
        if s.status == "pending"
    }
    truly_missing = missing - pending_ok
    if truly_missing:
        raise TelemetryDesyncError(
            f"turn {turn.turn_index}: history holds call IDs "
            f"{sorted(truly_missing)} with no emitted span and no pending marker"
        )

    # Span present but not in history: speculative dispatch or retry.
    extra = span_ids - hist_ids
    if extra:
        raise TelemetryDesyncError(
            f"turn {turn.turn_index}: spans {sorted(extra)} have no history "
            f"entry; do not trust span-derived recovery state"
        )

    # Token cross-check: cached-prefix divergence detector.
    if (turn.span_input_tokens is not None
            and turn.history_input_estimate):
        drift = abs(turn.span_input_tokens - turn.history_input_estimate) \
            / turn.history_input_estimate
        if drift > 0.15:
            if prior_warnings >= 1:
                raise TelemetryDesyncError(
                    f"turn {turn.turn_index}: input_tokens drift {drift:.2f} "
                    f"across two consecutive turns; compact history now, "
                    f"do not use span token count for budget decisions"
                )
            # First warning: emit gen_ai.agent.desync event, continue.
            return
