# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-genai-span-that-carries-a-valid-gen-ai-tool-call-id-but-no-resolvable-parent-invocation-the-tool-call-lineage-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-genai-span-that-carries-a-valid-gen-ai-tool-call-id-but-no-resolvable-parent-invocation-the-tool-call-lineage-invariant.warrant.json
# Markdown SHA-256:   371a2a67fc03f6686ba1e6ccea0f01158e78f21cb93bcd1f1b49174d8e7bbd21
# Code AST SHA-256:   2dc3f6b0161300ee6b6c77f97a52399b97a8163eb60747a1f13d20c468768a8c
# Verified Classes:   LineageInvariantError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class LineageInvariantError(RuntimeError):
    """Raised when a GenAI tool span cannot be bound to a model invocation."""
    pass


MODEL_OPS = {"chat", "text_completion", "invoke_agent", "generate_content"}


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    operation_name: str          # gen_ai.operation.name
    tool_call_id: Optional[str]  # gen_ai.tool.call.id
    start_ns: int
    end_ns: int


def resolve_invocation_ancestor(tool_span: Span, trace: dict[str, Span]) -> Span:
    """
    Return the unique model-invocation ancestor for a tool span, repairing
    when unambiguous. Raise LineageInvariantError when lineage cannot be
    established without fabrication.
    """
    if not tool_span.tool_call_id:
        raise LineageInvariantError(
            f"span {tool_span.span_id} has no gen_ai.tool.call.id; not a tool span"
        )

    # Walk the declared parent chain first.
    cursor = trace.get(tool_span.parent_span_id or "")
    while cursor is not None:
        if cursor.operation_name in MODEL_OPS:
            return cursor
        cursor = trace.get(cursor.parent_span_id or "")

    # Parent chain failed (dropped context). Attempt unambiguous repair:
    # exactly one model span in the trace whose window brackets the tool span.
    candidates = [
        s for s in trace.values()
        if s.operation_name in MODEL_OPS
        and s.start_ns <= tool_span.start_ns
        and s.end_ns >= tool_span.end_ns
    ]

    if len(candidates) == 1:
        return candidates[0]

    if not candidates:
        raise LineageInvariantError(
            f"tool span {tool_span.span_id} (call_id={tool_span.tool_call_id}) "
            f"has no model-invocation ancestor in trace; cannot bind lineage"
        )

    raise LineageInvariantError(
        f"tool span {tool_span.span_id} (call_id={tool_span.tool_call_id}) "
        f"has {len(candidates)} candidate invocation ancestors; "
        f"ambiguous, refusing to fabricate lineage"
    )
