# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-lineage-when-a-tool-call-span-is-re-emitted-after-checkpoint-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-lineage-when-a-tool-call-span-is-re-emitted-after-checkpoint-resume.warrant.json
# Markdown SHA-256:   37c6ee36d7b660d95ddd73ab075073ca002a22dc8f51e08b18f09a770e0ca5fc
# Code AST SHA-256:   fac2344c5e4d0260f23646657e8b1160f25ae1e427554741f50c195627f50419
# Verified Classes:   SpanLineageError, Checkpoint, ResumedSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SpanLineageError(RuntimeError):
    """Raised when a resumed tool call cannot be linked to its original span."""


@dataclass
class Checkpoint:
    call_id: str
    span_id: Optional[str]
    trace_id: Optional[str]
    span_exported: bool


@dataclass
class ResumedSpan:
    call_id: str
    trace_id: str
    span_id: str
    linked_to: Optional[str]
    attempt: int


def resume_tool_call(cp: Checkpoint, new_trace_id: str, new_span_id: str) -> ResumedSpan:
    if cp.span_exported and (cp.span_id is None or cp.trace_id is None):
        # Original span is durable in the collector but its identity was lost.
        # Re-execution would mint an unlinkable twin keyed to the same call id.
        raise SpanLineageError(
            f"call {cp.call_id!r} was exported but span identity was not "
            f"checkpointed; refusing to re-invoke (would create divergent twin)"
        )
    if cp.span_exported:
        return ResumedSpan(
            call_id=cp.call_id,
            trace_id=cp.trace_id,
            span_id=new_span_id,
            linked_to=cp.span_id,
            attempt=2,
        )
    # Original span never left the process; safe to emit as first attempt.
    return ResumedSpan(
        call_id=cp.call_id,
        trace_id=new_trace_id,
        span_id=new_span_id,
        linked_to=None,
        attempt=1,
    )
