# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-truncation-when-genai-semantic-convention-exporters-silently-drop-gen-ai-usage-on-resumed-agent-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-truncation-when-genai-semantic-convention-exporters-silently-drop-gen-ai-usage-on-resumed-agent-spans.warrant.json
# Markdown SHA-256:   eaf4e23dd427fbc4af9d7b59ad18902bbd7a5cbe49a7a99137886a0ed93f0610
# Code AST SHA-256:   c398798150592d13da78f4757dea89612afbc6cffebe9eaed88cb51ab8d3c0d6
# Verified Classes:   UsageRehydrationError, PersistedSpanState, LiveSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageRehydrationError(RuntimeError):
    """Raised when a resumed span cannot establish its token-usage provenance."""


@dataclass
class PersistedSpanState:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    input_tokens: int = 0
    output_tokens: int = 0
    rehydrated: bool = False


@dataclass
class LiveSpan:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    attributes: dict = field(default_factory=dict)
    input_tokens: int = 0
    output_tokens: int = 0


def open_resumed_span(
    state: PersistedSpanState,
    live_span_ids: set[str],
    checkpoint_accumulator: Optional[dict],
) -> LiveSpan:
    """
    Create a span for a resumed operation. Enforces the invariant:
    a span that cannot rehydrate its usage MUST be marked rehydrated=False
    rather than exported with absent usage attributes.
    """
    is_resumed = state.parent_span_id is not None and state.parent_span_id not in live_span_ids

    span = LiveSpan(
        trace_id=state.trace_id,
        span_id=state.span_id,
        parent_span_id=state.parent_span_id,
    )

    if not is_resumed:
        # Fresh span: accumulator starts at zero, usage attached at end().
        span.attributes["gen_ai.usage.rehydrated"] = True
        return span

    if checkpoint_accumulator is None:
        # Resumed but no accumulator was serialized. We cannot know usage.
        # Do NOT silently emit zero. Flag it.
        span.attributes["gen_ai.usage.rehydrated"] = False
        span.attributes["gen_ai.usage.unavailable_reason"] = "checkpoint_missing_accumulator"
        return span

    try:
        span.input_tokens = int(checkpoint_accumulator["input_tokens"])
        span.output_tokens = int(checkpoint_accumulator["output_tokens"])
    except (KeyError, TypeError, ValueError) as exc:
        raise UsageRehydrationError(
            f"resumed span {state.span_id} has malformed accumulator: {exc!r}"
        ) from exc

    if span.input_tokens < 0 or span.output_tokens < 0:
        raise UsageRehydrationError(
            f"resumed span {state.span_id} has negative token counts "
            f"({span.input_tokens}, {span.output_tokens})"
        )

    span.attributes["gen_ai.usage.rehydrated"] = True
    return span


def end_span(span: LiveSpan) -> dict:
    """Attach usage attributes at end() and return the exported attribute map."""
    if span.attributes.get("gen_ai.usage.rehydrated") is True:
        span.attributes["gen_ai.usage.input_tokens"] = span.input_tokens
        span.attributes["gen_ai.usage.output_tokens"] = span.output_tokens
    else:
        # Explicitly absent — but the flag tells the backend why.
        if "gen_ai.usage.input_tokens" in span.attributes:
            raise UsageRehydrationError(
                f"span {span.span_id} marked unrehydrated but carries usage attributes"
            )
    return span.attributes
