# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-call-lineage-and-token-accounting-from-silently-diverging-under-opentelemetry-genai-span-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-call-lineage-and-token-accounting-from-silently-diverging-under-opentelemetry-genai-span-conventions.warrant.json
# Markdown SHA-256:   9c996c056572da12a1b48cc6512b33c3581838bbdd878b6a469970f5c6cf107e
# Code AST SHA-256:   9ec6071eb5a78853d23db5fdd991ac9fa9cfd4f23b45ad070b3f35d1c96a4b78
# Verified Classes:   LineageLedgerDivergence, CheckpointLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class LineageLedgerDivergence(RuntimeError):
    """Raised when a resumed agent's span emission would violate
    tool-call-ID uniqueness or token-usage attribution invariants."""
    pass


@dataclass
class CheckpointLedger:
    """Authoritative record persisted with the agent checkpoint.
    The trace is a derived projection; this is the source of truth."""
    emitted_call_ids: Set[str] = field(default_factory=set)
    usage_by_turn: Dict[int, Dict[str, int]] = field(default_factory=dict)


def emit_resumed_turn(
    ledger: CheckpointLedger,
    turn_index: int,
    tool_call_ids: list[str],
    reported_input_tokens: int,
    reported_output_tokens: int,
    replayed: bool,
) -> Dict[str, int]:
    """Project one resumed turn onto gen_ai.* span attributes, enforcing
    the uniqueness and attribution invariants before emission."""
    # Invariant 1: call-ID uniqueness within the trace.
    duplicates = ledger.emitted_call_ids.intersection(tool_call_ids)
    if duplicates:
        raise LineageLedgerDivergence(
            f"turn {turn_index} re-emits tool_call_ids already present in "
            f"trace ledger: {sorted(duplicates)}; resume must suppress replayed "
            f"tool spans, not duplicate them"
        )

    # Invariant 2: replayed turns must not re-count fresh input tokens.
    if replayed and reported_input_tokens > 0:
        raise LineageLedgerDivergence(
            f"turn {turn_index} is marked replayed but reports "
            f"{reported_input_tokens} fresh input tokens; cache/replay must "
            f"emit zero fresh usage to keep the token ledger additive"
        )

    # Invariant 3: attribution is per-turn, not per-emission.
    if turn_index in ledger.usage_by_turn:
        raise LineageLedgerDivergence(
            f"turn {turn_index} already has usage attributed "
            f"({ledger.usage_by_turn[turn_index]}); checkpoint atomicity broken"
        )

    ledger.emitted_call_ids.update(tool_call_ids)
    usage = {
        "gen_ai.usage.input_tokens": reported_input_tokens,
        "gen_ai.usage.output_tokens": reported_output_tokens,
    }
    ledger.usage_by_turn[turn_index] = usage
    return usage
