# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-execute-tool-span-the-orphaned-child-invariant-across-mid-tool-checkpoint-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-execute-tool-span-the-orphaned-child-invariant-across-mid-tool-checkpoint-resume.warrant.json
# Markdown SHA-256:   7d045866ecb0c75e8a3b872d960d6187acf3564e2e7c32cefb7b51ea7c25698e
# Code AST SHA-256:   e7d04ca5c724f3c86a04f2867f5d1abcf75a73f0c10332ae382bdb8e5c857051
# Verified Classes:   OrphanedToolSpanError, TokenAccountingViolationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class OrphanedToolSpanError(RuntimeError):
    """Raised when a resumed agent attempts to re-parent a tool span whose
    end() was never called by a live tracer provider. Re-parenting would
    manufacture an orphan child and a temporal inversion in the trace graph."""
    pass


class TokenAccountingViolationError(RuntimeError):
    """Raised when a resumed tool span would record gen_ai.usage.* while the
    orphaned predecessor's usage is written as zero (a value) instead of
    absent (unknown), causing silent cost undercount."""
    pass


def resume_tool_span(checkpoint: dict, provider) -> str:
    """Decide whether the in-flight tool span from a checkpoint may be
    re-parented. Returns the parent span_id to use for the re-executed
    tool span, or raises if the invariant cannot be satisfied."""
    in_flight = checkpoint.get("in_flight_tool_span_id")
    end_recorded = checkpoint.get("tool_span_end_was_recorded", False)

    if in_flight is None:
        # No tool was open at checkpoint time; safe to start fresh.
        return checkpoint["invoke_agent_span_id"]

    if end_recorded:
        # Span closed before checkpoint; it is a legal, closed ancestor.
        return in_flight

    # Open interval at checkpoint. The span object is gone; only its
    # SpanContext survives. The current provider never emitted it.
    if in_flight not in provider.emitted_span_ids:
        # Invariant: do NOT re-parent. Emit a synthetic closure for the
        # orphan, and start the re-executed tool as a sibling.
        if checkpoint.get("usage_written_as_zero"):
            raise TokenAccountingViolationError(
                f"orphaned span {in_flight} has usage=0; "
                "must be absent (unknown), not zero, to avoid undercount"
            )
        provider.emit_synthetic_closure(
            span_id=in_flight,
            status="ERROR",
            message="orphaned by checkpoint mid-tool; end() never called",
            omit_usage=True,
        )
        # Sibling, not child: same invoke_agent parent as the orphan.
        return checkpoint["invoke_agent_span_id"]

    # The provider claims to have emitted this span_id. On a fresh process
    # this is impossible and indicates a trace-identity collision.
    raise OrphanedToolSpanError(
        f"span_id {in_flight} already emitted by provider "
        f"{provider.id}; refusing to resume span across providers"
    )
