# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-call-lineage-corruption-when-opentelemetry-genai-span-attributes-are-emitted-across-a-retry-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-call-lineage-corruption-when-opentelemetry-genai-span-attributes-are-emitted-across-a-retry-boundary.warrant.json
# Markdown SHA-256:   ca7a562843d98e4815b73160379fbf73ba21077731a40dc11bf7d50e4f19f347
# Code AST SHA-256:   72cf5338abfa68f1c696bc0dc81be777ee6b3709039a1822a175b63b1c78ba29
# Verified Classes:   CallLineageInvariantError, CallCommitment
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class CallLineageInvariantError(RuntimeError):
    """Raised when a tool-call span violates the call-identity invariant."""
    pass


@dataclass(frozen=True)
class CallCommitment:
    call_id: str
    tool_name: str
    arguments_digest: str
    turn_index: int
    rollback_generation: int = 0


def commit_call(tool_name: str, arguments: dict, turn_index: int,
                rollback_generation: int = 0) -> CallCommitment:
    # Digest is computed at commitment time over canonical serialization and is
    # immutable thereafter. It must not be recomputed from mutated transport state.
    digest = hashlib.sha256(
        json.dumps(arguments, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()
    call_id = f"call_{digest[:12]}_{turn_index}_{rollback_generation}"
    return CallCommitment(call_id, tool_name, digest, turn_index, rollback_generation)


def emit_attempt_span(commitment: CallCommitment, attempt: int,
                      arguments_digest_at_emit: str,
                      status: str,
                      supersedes: Optional[str] = None) -> dict:
    if attempt < 0:
        raise CallLineageInvariantError(
            f"retry.attempt must be >= 0, got {attempt} for call {commitment.call_id}"
        )
    if supersedes is not None:
        # A re-plan must fork identity; it may not reuse the originating call_id.
        if supersedes == commitment.call_id:
            raise CallLineageInvariantError(
                f"call {commitment.call_id} cannot supersede itself; "
                "re-plan requires a fresh call_id with a supersedes edge"
            )
    if arguments_digest_at_emit != commitment.arguments_digest:
        # Arguments changed between commitment and emission: this is a re-plan,
        # not a retry. Emitting under the original call_id would corrupt lineage.
        raise CallLineageInvariantError(
            f"arguments digest drift on call {commitment.call_id}: "
            f"committed={commitment.arguments_digest} emitted={arguments_digest_at_emit}; "
            "fork a new call_id and set supersedes"
        )
    if attempt > 0 and supersedes is not None:
        raise CallLineageInvariantError(
            f"call {commitment.call_id} attempt {attempt} cannot both retry and supersede"
        )
    return {
        "gen_ai.tool.name": commitment.tool_name,
        "gen_ai.tool.call.id": commitment.call_id,
        "gen_ai.tool.arguments.digest": commitment.arguments_digest,
        "retry.attempt": attempt,
        "call.turn_index": commitment.turn_index,
        "context.rollback_generation": commitment.rollback_generation,
        "supersedes": supersedes,
        "status": status,
    }


def reconcile_output_tokens(spans: list[dict]) -> int:
    # Sum output tokens only over the terminal attempt of each logical call.
    by_call: dict[str, list[dict]] = {}
    for s in spans:
        by_call.setdefault(s["gen_ai.tool.call.id"], []).append(s)
    total = 0
    for call_id, attempts in by_call.items():
        attempts.sort(key=lambda s: s["retry.attempt"])
        if not attempts:
            raise CallLineageInvariantError(f"empty attempt list for {call_id}")
        terminal = attempts[-1]
        if terminal["status"] not in ("OK", "ERROR"):
            raise CallLineageInvariantError(
                f"call {call_id} has no terminal attempt; last status={terminal['status']}"
            )
        total += terminal.get("gen_ai.usage.output_tokens", 0)
    return total
