# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-resumed-agent-trace-after-opentelemetry-genai-span-re-emission-corrupts-token-accounting.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-resumed-agent-trace-after-opentelemetry-genai-span-re-emission-corrupts-token-accounting.warrant.json
# Markdown SHA-256:   6b290e75bafb35c20c6f2c0bf027f7e6822c60ee6c5dfb02a54bed1c9bf0264b
# Code AST SHA-256:   9c785b5830acbae706766618029138ef7aaeeb1a55f672f3db2ff7b853ddc136
# Verified Classes:   ResumeMergeUndefinedError, BillingState, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumeMergeUndefinedError(RuntimeError):
    """Raised when a resumed agent span cannot be merged with its predecessor
    because the checkpoint did not persist provider-side billing state."""


@dataclass
class BillingState:
    provider_request_id: str
    billed: bool
    input_tokens: int
    output_tokens: int


@dataclass
class Span:
    trace_id: str
    span_id: str
    operation_name: str
    status: str  # "OK" | "UNSET" | "ERROR"
    input_tokens: int
    output_tokens: int


def resolve_resumed_span(
    predecessor: Span,
    resumed: Span,
    billing_state: Optional[BillingState],
) -> Span:
    """Decide how to reconcile a resumed span with its unclosed predecessor.

    Returns the span to emit. Raises ResumeMergeUndefinedError when the merge
    is undefined (no billing state) and the caller must quarantine.
    """
    if predecessor.trace_id != resumed.trace_id:
        raise ResumeMergeUndefinedError(
            f"trace mismatch: {predecessor.trace_id} vs {resumed.trace_id}"
        )
    if predecessor.status != "UNSET":
        # Predecessor closed cleanly; resumed span is a genuinely new generation.
        return resumed

    if billing_state is None:
        raise ResumeMergeUndefinedError(
            f"cannot reconcile spans {predecessor.span_id} and {resumed.span_id}: "
            f"checkpoint persisted no billing state for provider_request_id "
            f"of trace {predecessor.trace_id}; quarantine required"
        )

    if billing_state.billed:
        # Provider charged the pre-checkpoint generation; resumed generation
        # re-sent history and was charged again. Sum both, mark the merge.
        return Span(
            trace_id=resumed.trace_id,
            span_id=resumed.span_id,
            operation_name=resumed.operation_name,
            status="OK",
            input_tokens=predecessor.input_tokens + resumed.input_tokens,
            output_tokens=predecessor.output_tokens + resumed.output_tokens,
        )

    # Pre-checkpoint generation was never billed; supersede the predecessor.
    return Span(
        trace_id=resumed.trace_id,
        span_id=resumed.span_id,
        operation_name=resumed.operation_name,
        status="OK",
        input_tokens=resumed.input_tokens,
        output_tokens=resumed.output_tokens,
    )
