# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-token-accounting-spans-as-non-idempotent-across-a-mid-tool-call-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-token-accounting-spans-as-non-idempotent-across-a-mid-tool-call-resume.warrant.json
# Markdown SHA-256:   fde3e34f57eafce08f9bd1023a6909fe8fade158867081395e35b07523d353db
# Code AST SHA-256:   70f1241b4e53784a6940426f4de1d3edf2e7c58c0ff78ed0a2db0911eaf073d4
# Verified Classes:   SpanEmissionReplayError, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

"""Checkpoint fence for GenAI span emission across mid-tool-call resume.

Prevents silent double-counting of gen_ai.usage.* tokens when an agent
resumes from a checkpoint taken after a span was already exported.
"""

from __future__ import annotations

import hashlib
import json
from dataclasses import dataclass, field


class SpanEmissionReplayError(RuntimeError):
    """Raised when a resumed step would re-emit an already-exported GenAI span."""


@dataclass
class Checkpoint:
    step_id: str
    step_inputs_hash: str
    span_emitted: bool = False
    emitted_span_name: str | None = None
    # Fences recorded for every span already exported for this step.
    emitted_fences: set[str] = field(default_factory=set)


def _fence(span_name: str, step_inputs_hash: str) -> str:
    return hashlib.sha256(f"{span_name}:{step_inputs_hash}".encode()).hexdigest()


def emit_genai_span(
    ckpt: Checkpoint,
    span_name: str,
    usage: dict[str, int],
) -> str:
    """Emit a gen_ai.* span exactly once per (step, span_name, inputs).

    Returns the fence id. Raises SpanEmissionReplayError if this exact
    span was already exported for this step (i.e. we are on a resume path
    that would double-count tokens).
    """
    fence = _fence(span_name, ckpt.step_inputs_hash)

    if fence in ckpt.emitted_fences:
        # A span with usage attributes already left this process for this
        # logical step. Re-emitting would double-count gen_ai.usage.*.
        raise SpanEmissionReplayError(
            f"step={ckpt.step_id} span={span_name} "
            f"already emitted (fence={fence[:12]}); "
            f"refusing to re-emit usage={usage} on resume"
        )

    # --- actual OTel emission would happen here ---
    # span.set_attribute("gen_ai.usage.input_tokens", usage["input_tokens"])
    # span.set_attribute("gen_ai.usage.output_tokens", usage["output_tokens"])
    # span.end()

    ckpt.emitted_fences.add(fence)
    ckpt.span_emitted = True
    ckpt.emitted_span_name = span_name
    return fence


def resume_step(ckpt: Checkpoint, span_name: str, usage: dict[str, int]) -> str:
    """Resume path: consult the fence before touching the emission code."""
    if ckpt.span_emitted and _fence(span_name, ckpt.step_inputs_hash) not in ckpt.emitted_fences:
        # Fence says a span was emitted for this step but not this one:
        # inconsistent checkpoint — fail closed rather than guess.
        raise SpanEmissionReplayError(
            f"inconsistent checkpoint for step={ckpt.step_id}: "
            f"span_emitted=True but fence for {span_name} absent"
        )
    return emit_genai_span(ckpt, span_name, usage)


if __name__ == "__main__":
    ck = Checkpoint(step_id="plan-3", step_inputs_hash=hashlib.sha256(b"search:foo").hexdigest())
    emit_genai_span(ck, "chat", {"input_tokens": 1840, "output_tokens": 212})
    # Simulate eviction + resume re-entering the same step:
    try:
        resume_step(ck, "chat", {"input_tokens": 1840, "output_tokens": 212})
    except SpanEmissionReplayError as e:
        print("caught, ledger protected:", e)
