# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-resumed-agent-span-because-opentelemetry-genai-token-usage-attributes-disagree-across-a-checkpoint-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-resumed-agent-span-because-opentelemetry-genai-token-usage-attributes-disagree-across-a-checkpoint-boundary.warrant.json
# Markdown SHA-256:   97baeb2dddd398d3eca9cc6eebaf85b8ec2662686445d4bf5bfc17cd1bdb9972
# Code AST SHA-256:   9502a4d9acdbd8aaea56e177d89051f7780e5b00deec187cb27126cf83667318
# Verified Classes:   UnreconcilableSpanError, Checkpoint, ContinuationSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnreconcilableSpanError(RuntimeError):
    """Raised when a resumed agent span cannot be safely exported for accounting."""


@dataclass
class Checkpoint:
    trace_id: str
    last_span_id: str
    conversation_id: str
    checkpoint_seq: int
    input_tokens_so_far: int


@dataclass
class ContinuationSpan:
    trace_id: Optional[str]
    conversation_id: Optional[str]
    checkpoint_seq: Optional[int]
    gen_ai_usage_input_tokens: Optional[int] = None
    gen_ai_usage_output_tokens: Optional[int] = None
    usage_scope: Optional[str] = None          # must be "interval" if usage set
    resume_from_checkpoint: bool = False
    span_links: list = field(default_factory=list)


def build_continuation_span(
    checkpoint: Checkpoint,
    restored_trace_id: Optional[str],
    rehydrated_input_tokens: int,
    output_tokens: int,
) -> ContinuationSpan:
    span = ContinuationSpan(
        trace_id=restored_trace_id,
        conversation_id=checkpoint.conversation_id,
        checkpoint_seq=checkpoint.checkpoint_seq + 1,
        resume_from_checkpoint=True,
    )

    # Invariant 1: trace continuity. If the tracer could not be restored,
    # we must link explicitly rather than silently orphan the span.
    if restored_trace_id is None:
        span.span_links.append(
            {"linked_trace_id": checkpoint.trace_id,
             "linked_span_id": checkpoint.last_span_id}
        )
        # Orphaned trace_id is not itself fatal, but it must be recorded.
        span.trace_id = None

    # Invariant 2: usage scope must be declared before usage is written.
    span.gen_ai_usage_input_tokens = rehydrated_input_tokens
    span.gen_ai_usage_output_tokens = output_tokens
    span.usage_scope = "interval"

    # Invariant 3: reconcilability gate. A span with usage but no scope,
    # or with a broken checkpoint sequence, must not be exported as-is.
    if span.gen_ai_usage_input_tokens is not None and span.usage_scope != "interval":
        raise UnreconcilableSpanError(
            f"usage attributes set without agent.usage.scope on "
            f"conversation={checkpoint.conversation_id} seq={span.checkpoint_seq}"
        )
    if span.checkpoint_seq != checkpoint.checkpoint_seq + 1:
        raise UnreconcilableSpanError(
            f"checkpoint sequence gap: expected {checkpoint.checkpoint_seq + 1}, "
            f"got {span.checkpoint_seq} for conversation={checkpoint.conversation_id}"
        )
    if span.conversation_id is None:
        raise UnreconcilableSpanError(
            "continuation span missing gen_ai.conversation.id; "
            "cannot reconcile against pre-checkpoint usage"
        )
    return span


def export_for_accounting(span: ContinuationSpan) -> dict:
    # Fail closed: never hand a poisoned record to the ledger.
    if span.gen_ai_usage_input_tokens is not None and span.usage_scope != "interval":
        raise UnreconcilableSpanError(
            f"refusing to export span with undeclared usage scope: "
            f"conversation={span.conversation_id}"
        )
    return {
        "gen_ai.operation.name": "invoke_agent",
        "gen_ai.conversation.id": span.conversation_id,
        "gen_ai.usage.input_tokens": span.gen_ai_usage_input_tokens,
        "gen_ai.usage.output_tokens": span.gen_ai_usage_output_tokens,
        "agent.usage.scope": span.usage_scope,
        "agent.resume.from_checkpoint": span.resume_from_checkpoint,
        "agent.checkpoint.seq": span.checkpoint_seq,
        "span_links": span.span_links,
    }
