# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-tool-call-spans-when-opentelemetry-genai-semantic-conventions-lose-parent-linkage-across-a-mid-task-checkpoi.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-tool-call-spans-when-opentelemetry-genai-semantic-conventions-lose-parent-linkage-across-a-mid-task-checkpoi.warrant.json
# Markdown SHA-256:   6d01d9cb5e4b5e95b715c82bcfdb51bcecd2c63c4ea61a082c88d215551a5e2e
# Code AST SHA-256:   34cce02ccf36eaee02789206d23aa6c078cae78b03d34023d39ce7cc79e562e3
# Verified Classes:   OrphanedToolSpanError, SpanContext, ToolSpan, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class OrphanedToolSpanError(RuntimeError):
    """Raised when a resumed agent emits a tool-call span whose parent is not
    present in the trace and which is not explicitly marked unverified."""
    pass


@dataclass
class SpanContext:
    trace_id: str
    span_id: str

@dataclass
class ToolSpan:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    tool_call_id: str
    resumed_unverified: bool = False

@dataclass
class Checkpoint:
    pending_tool_call_id: str
    trace_id: str
    parent_span_context: Optional[SpanContext]  # None if not persisted


def reconcile_resumed_tool_span(
    checkpoint: Checkpoint,
    exported_span_ids: set[tuple[str, str]],
    new_worker_root: SpanContext,
) -> ToolSpan:
    ctx = checkpoint.parent_span_context
    if ctx is not None:
        # Re-emit parent under original identity; guard against span_id collision.
        key = (ctx.trace_id, ctx.span_id)
        if key in exported_span_ids:
            raise OrphanedToolSpanError(
                f"resume would duplicate span_id {ctx.span_id} in trace {ctx.trace_id}; "
                "checkpoint parent context is stale or double-exported"
            )
        return ToolSpan(
            trace_id=ctx.trace_id,
            span_id=f"tool-{checkpoint.pending_tool_call_id}",
            parent_span_id=ctx.span_id,
            tool_call_id=checkpoint.pending_tool_call_id,
            resumed_unverified=False,
        )

    # No persisted SpanContext: must NOT copy trace_id alone.
    if checkpoint.trace_id == new_worker_root.trace_id:
        raise OrphanedToolSpanError(
            "resumed worker inherited trace_id without parent span_id; "
            "this creates a structurally-valid but semantically orphaned tool span"
        )
    return ToolSpan(
        trace_id=new_worker_root.trace_id,
        span_id=f"tool-{checkpoint.pending_tool_call_id}",
        parent_span_id=new_worker_root.span_id,
        tool_call_id=checkpoint.pending_tool_call_id,
        resumed_unverified=True,
    )


def validate_trace_invariant(spans: list[ToolSpan]) -> None:
    ids = {(s.trace_id, s.span_id) for s in spans}
    for s in spans:
        parent_present = (s.trace_id, s.parent_span_id) in ids if s.parent_span_id else False
        if not parent_present and not s.resumed_unverified:
            raise OrphanedToolSpanError(
                f"tool span {s.span_id} in trace {s.trace_id} has no exported parent "
                f"{s.parent_span_id} and is not marked resumed_unverified"
            )
