# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-emit-orphaned-execute-tool-spans-when-its-parent-agent-span-is-sampled-out-mid-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-emit-orphaned-execute-tool-spans-when-its-parent-agent-span-is-sampled-out-mid-loop.warrant.json
# Markdown SHA-256:   31a0799ddd71bef60aeb04e67718edecfa71903bc0eaca41ad9174fdef08f1bb
# Code AST SHA-256:   1df9c91c466204b282be110be9e50cdf8c87b20b30e8f5de4ac7244e1f72f270
# Verified Classes:   OrphanedToolSpanError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class OrphanedToolSpanError(RuntimeError):
    """Raised when an execute_tool span is retained without a retained invoke_agent ancestor."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    operation_name: str          # gen_ai.operation.name
    sampled: bool


def assert_tool_spans_anchored(spans: list[Span]) -> None:
    """
    Enforce the invariant: every retained execute_tool span must have a retained
    invoke_agent ancestor in the same exported batch set. Called at collector
    ingest, before the batch is written to the trace store.
    """
    by_id = {s.span_id: s for s in spans if s.sampled}

    for span in spans:
        if not span.sampled or span.operation_name != "execute_tool":
            continue

        # Walk ancestors; the parent may be in a prior batch, so a miss here
        # is the exact condition we must surface rather than swallow.
        cursor = by_id.get(span.parent_span_id) if span.parent_span_id else None
        while cursor is not None and cursor.operation_name != "invoke_agent":
            cursor = by_id.get(cursor.parent_span_id) if cursor.parent_span_id else None

        if cursor is None:
            raise OrphanedToolSpanError(
                f"execute_tool span {span.span_id} retained with no retained "
                f"invoke_agent ancestor (parent_span_id={span.parent_span_id}); "
                f"sampling policy assigns different retention to parent and child "
                f"across an export boundary — trace is structurally invalid."
            )


def ingest_batch(spans: list[Span]) -> None:
    assert_tool_spans_anchored(spans)
    # ... persist batch to trace store ...
