# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-resumed-otel-genai-agent-span-when-gen-ai-usage-input-tokens-is-replayed-from-a-checkpoint-after-a-tool-ca.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-resumed-otel-genai-agent-span-when-gen-ai-usage-input-tokens-is-replayed-from-a-checkpoint-after-a-tool-ca.warrant.json
# Markdown SHA-256:   579690b465b610c5fed51ca680624aa136188701a272d50bb0aa6eee40c9791a
# Code AST SHA-256:   52c50aedb55dd280820c26343b7a45aca576bb225980d618098904109789d77e
# Verified Classes:   ReplayedUsageViolation, CheckpointedSpan, ResumeContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ReplayedUsageViolation(RuntimeError):
    """Raised when a resumed agent span would carry checkpointed token usage
    after a tool-call retry or model re-execution, violating the OTel GenAI
    usage-attribute invariant (usage must describe this execution only)."""
    pass


@dataclass
class CheckpointedSpan:
    span_id: str
    trace_id: str
    input_tokens: int
    output_tokens: int
    finish_reasons: list
    exported: bool          # was it acknowledged by the collector pre-crash?
    tool_result_cached: bool  # is the retried tool result served from cache?
    model_invocation_skipped: bool


@dataclass
class ResumeContext:
    tool_call_retried: bool
    model_reran: bool
    observed_input_tokens: Optional[int] = None
    observed_output_tokens: Optional[int] = None


def build_resumed_span(ckpt: CheckpointedSpan, ctx: ResumeContext) -> dict:
    # Determine whether this resume is a pure replay (safe to carry usage)
    pure_replay = (
        ckpt.exported
        and ckpt.tool_result_cached
        and ckpt.model_invocation_skipped
        and not ctx.tool_call_retried
        and not ctx.model_reran
    )

    if pure_replay:
        # Duplicate span: same IDs, original usage, backend dedups by span_id.
        return {
            "trace_id": ckpt.trace_id,
            "span_id": ckpt.span_id,
            "gen_ai.usage.input_tokens": ckpt.input_tokens,
            "gen_ai.usage.output_tokens": ckpt.output_tokens,
            "gen_ai.response.finish_reasons": ckpt.finish_reasons,
            "gen_ai.agent.replayed": True,
        }

    # Re-execution path: usage MUST be freshly measured.
    if ctx.observed_input_tokens is None or ctx.observed_output_tokens is None:
        raise ReplayedUsageViolation(
            f"Resume of span {ckpt.span_id} retried a tool call or re-ran the "
            f"model but supplied no freshly observed token counts. Refusing to "
            f"attach checkpointed usage ({ckpt.input_tokens} in / "
            f"{ckpt.output_tokens} out) to a re-executed attempt."
        )

    if ctx.observed_input_tokens == ckpt.input_tokens and ctx.model_reran:
        raise ReplayedUsageViolation(
            f"Span {ckpt.span_id} re-ran the model yet reports identical input "
            f"tokens ({ckpt.input_tokens}); this indicates the checkpointed "
            f"usage was copied instead of measured."
        )

    return {
        "trace_id": ckpt.trace_id,
        "span_id": f"{ckpt.span_id}-retry",   # NEW id: distinct attempt
        "gen_ai.usage.input_tokens": ctx.observed_input_tokens,
        "gen_ai.usage.output_tokens": ctx.observed_output_tokens,
        "gen_ai.response.finish_reasons": ckpt.finish_reasons,
        "gen_ai.agent.replayed": False,
        "gen_ai.agent.prior_span_id": ckpt.span_id,
        "gen_ai.agent.prior_input_tokens": ckpt.input_tokens,
        "gen_ai.agent.prior_output_tokens": ckpt.output_tokens,
    }
