# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-reasoning-lineage-when-genai-spans-are-parented-to-the-tool-call-span-instead-of-the-generation-span.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-reasoning-lineage-when-genai-spans-are-parented-to-the-tool-call-span-instead-of-the-generation-span.warrant.json
# Markdown SHA-256:   1b2281e15d72a66c190564359380ab4a741b00910c9d58e1b76bb33cefcd43d3
# Code AST SHA-256:   6212c746b0d18e1c637fa56c573ff9cf9ee76b39fe275464a2823ea5681c1d56
# Verified Classes:   LineageInvariantViolation, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class LineageInvariantViolation(RuntimeError):
    """Raised when a GenAI trace batch would export tool spans whose
    selecting generation cannot be identified from span data alone."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    name: str
    operation: str | None = None          # gen_ai.operation.name
    tool_call_id: str | None = None       # gen_ai.tool.call.id
    emitted_tool_call_ids: list[str] = field(default_factory=list)


def validate_lineage(spans: list[Span]) -> None:
    """Every tool-execution span must be joinable to the generation span
    that selected it, via gen_ai.tool.call.id — NOT via parent edge."""
    generation_emitted: dict[str, str] = {}
    for s in spans:
        if s.operation == "chat" or s.operation == "text_completion":
            for cid in s.emitted_tool_call_ids:
                generation_emitted[cid] = s.span_id

    for s in spans:
        if s.operation != "execute_tool":
            continue
        if s.tool_call_id is None:
            raise LineageInvariantViolation(
                f"tool span {s.span_id} ({s.name}) carries no "
                f"gen_ai.tool.call.id; lineage unrecoverable from trace"
            )
        if s.tool_call_id not in generation_emitted:
            raise LineageInvariantViolation(
                f"tool span {s.span_id} references tool_call.id "
                f"{s.tool_call_id!r} that no generation span emitted; "
                f"parent edge {s.parent_id!r} is not a substitute for lineage"
            )
        # Explicitly reject the silent-failure shape: tool span parented to
        # the enclosing agent span rather than to its selecting generation.
        selecting_gen = generation_emitted[s.tool_call_id]
        if s.parent_id != selecting_gen:
            # Not fatal if correlation id is present, but record the boundary.
            pass
