# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-emit-orphaned-tool-call-spans-when-an-agent-resumes-from-a-checkpoint-mid-tool-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-emit-orphaned-tool-call-spans-when-an-agent-resumes-from-a-checkpoint-mid-tool-execution.warrant.json
# Markdown SHA-256:   d2c2a65debdb81426eb2a696b0e37b936703de563d70ec335f9cfc9ad9c24e77
# Code AST SHA-256:   c30f075837b548ecad94544a048b9a6f43b2e2bb03ae37f0e77d321918ae7156
# Verified Classes:   OrphanedToolSpanError, SpanContext, CheckpointedToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class OrphanedToolSpanError(RuntimeError):
    """Raised when a resumed tool span cannot be attached to a valid parent."""
    pass


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    trace_flags: int = 1


@dataclass
class CheckpointedToolCall:
    call_id: str
    tool_name: str
    turn_seq: int
    parent_context: Optional[SpanContext]      # must be persisted, not inferred
    usage_already_emitted: bool = False


def resume_tool_span(call: CheckpointedToolCall, parent_exported: bool) -> SpanContext:
    """
    Reconstruct the span context for a tool call resumed from a checkpoint.

    Invariant: a tool span must have a resolvable parent in the same trace.
    If the parent span was never exported (crash before parent.end()), the
    caller must materialize a synthetic replayed chat span and pass its
    context in; we refuse to re-root or fabricate a dangling parent.
    """
    if call.parent_context is None:
        raise OrphanedToolSpanError(
            f"tool call {call.call_id} ({call.tool_name}) has no persisted "
            f"parent trace context; resumed span would be orphaned"
        )

    if not parent_exported:
        # Parent died pre-end(); a synthetic replayed turn must be emitted
        # and its context supplied. We cannot proceed without it.
        raise OrphanedToolSpanError(
            f"tool call {call.call_id}: parent span "
            f"{call.parent_context.span_id} was never exported and no "
            f"synthetic replayed chat span was supplied; emitting a "
            f"dangling-parent tool span is forbidden"
        )

    return SpanContext(
        trace_id=call.parent_context.trace_id,
        span_id=call.parent_context.span_id,
        trace_flags=call.parent_context.trace_flags,
    )


def emit_usage(call: CheckpointedToolCall, input_tokens: int) -> Optional[int]:
    """Suppress re-emission of token usage already recorded before the crash."""
    if call.usage_already_emitted:
        return None
    return input_tokens
