# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-orphaned-tool-latency-when-span-links-break-across-a-resumed-agent-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-orphaned-tool-latency-when-span-links-break-across-a-resumed-agent-loop.warrant.json
# Markdown SHA-256:   7d81e058e33a9ef22697c686cfd8ec34523110da574d76346582f644f204f787
# Code AST SHA-256:   0e6c4debd507235c10aa36d3006a13f9ff1b1f4cf7f2ab45e7ffe4042e60ee09
# Verified Classes:   OrphanedToolSpanError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class OrphanedToolSpanError(RuntimeError):
    """Raised when a resumed agent loop cannot attribute a pending tool call to its issuing reasoning step."""
    pass


def resume_loop(checkpoint: dict, tracer) -> None:
    """
    Reconstruct trace context for a resumed agent loop.

    Invariant: every pending tool call must carry a 'caused_by_step_id' attribute
    recorded at issue time. Parent links are NOT trusted across the resume boundary
    because the resume path re-roots the trace and silently reassigns latency.
    """
    pending = checkpoint.get("pending_tool_calls", [])
    for call in pending:
        step_id = call.get("caused_by_step_id")
        if not step_id:
            raise OrphanedToolSpanError(
                f"Pending tool call {call.get('tool_name')!r} (id={call.get('call_id')!r}) "
                f"has no caused_by_step_id attribute. Resuming would re-parent this span "
                f"under the resume handler and orphan its latency from the issuing reasoning "
                f"step. Fail closed: do not resume."
            )

        # Reconstruct parent context from the attribute, not from the live tree.
        parent_ctx = tracer.extract_context(step_id)
        if parent_ctx is None:
            raise OrphanedToolSpanError(
                f"caused_by_step_id={step_id!r} does not resolve to a known span. "
                f"The issuing reasoning step was flushed or lost; latency attribution "
                f"for {call.get('tool_name')!r} cannot be reconstructed."
            )

        with tracer.start_as_current_span(
            name=f"tool.{call['tool_name']}",
            context=parent_ctx,
            attributes={"caused_by_step_id": step_id, "resumed": True},
        ):
            tracer.record_pending_call(call)
