# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-lineage-when-opentelemetry-genai-span-attributes-are-exported-asynchronously-across-a-checkpoint-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-lineage-when-opentelemetry-genai-span-attributes-are-exported-asynchronously-across-a-checkpoint-boundary.warrant.json
# Markdown SHA-256:   6b4621a2f32408a77f1fc814006bb6e4ebab73b0c45e9ad6e04d004abcb02171
# Code AST SHA-256:   13bf29468aa0a88508610f5ddf1b73864ffbcda5e0cb6676a2614db9e4f3734c
# Verified Classes:   LineageDiscontinuityError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class LineageDiscontinuityError(RuntimeError):
    """Raised when a resumed agent cannot reconstruct tool-call lineage
    because the checkpoint boundary fell inside an unended GenAI span
    and the SpanContext / tool-call id were not persisted."""
    pass


def resume_task(checkpoint: dict, emit_span) -> None:
    # Invariant: a checkpoint taken mid-span must carry the span context
    # and the tool-call id, or lineage cannot be reconstructed.
    in_flight = checkpoint.get("open_span")
    if in_flight is not None:
        ctx = in_flight.get("span_context")
        call_id = in_flight.get("gen_ai.tool.call.id")
        if ctx is None or call_id is None:
            raise LineageDiscontinuityError(
                "checkpoint boundary inside unended span "
                f"span_id={in_flight.get('span_id')!r} but "
                f"span_context={'present' if ctx else 'MISSING'} "
                f"tool_call_id={'present' if call_id else 'MISSING'}; "
                "resuming would split token accounting across two traces"
            )
        # Replay path: re-parent the resumed tool span under the persisted
        # context and reuse the persisted call id as the idempotency key.
        emit_span(
            parent_context=ctx,
            attributes={
                "gen_ai.tool.call.id": call_id,
                "gen_ai.operation.name": "resume",
                "gen_ai.usage.input_tokens": checkpoint["pre_checkpoint_input_tokens"],
                "gen_ai.usage.output_tokens": checkpoint["pre_checkpoint_output_tokens"],
            },
        )
    # Safe to continue: either no open span, or lineage was replayed.
