# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-tool-call-lineage-has-silently-detached-from-its-parent-span-under-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-tool-call-lineage-has-silently-detached-from-its-parent-span-under-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   88fe763e348c7b44616f93a520397a8c90ee4707182aa72ad25a1beef5a9da0e
# Code AST SHA-256:   8f94f1ea2d8e428daabdd2a874561ca7615362aa7573558a8951b0bc25c17212
# Verified Classes:   LineageDetachmentError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class LineageDetachmentError(RuntimeError):
    """Raised when a tool-call span's lineage or accounting has detached
    from its parent invocation span under GenAI semantic conventions."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_span_id: str | None
    trace_id: str
    operation_name: str
    tool_call_id: str | None
    usage_input_tokens: int | None
    usage_output_tokens: int | None
    start_time_ns: int
    end_time_ns: int

    @property
    def is_tool_span(self) -> bool:
        return self.operation_name == "execute_tool"

    @property
    def is_invocation_span(self) -> bool:
        return self.operation_name in {"chat", "text_completion", "embeddings"}


def assert_lineage_invariant(spans: Iterable[Span]) -> None:
    """Enforce the four-part continuity invariant for GenAI tool-call lineage.

    Rejects the batch before export if any span violates:
      1. usage attributes only on invocation spans
      2. tool_call_id unique within (trace_id, parent_span_id)
      3. child time bounds contained within parent time bounds
      4. no cached-template re-parenting (usage on tool span is the fingerprint)
    """
    by_id = {s.span_id: s for s in spans}
    seen_tool_ids: dict[tuple[str, str], str] = {}

    for span in by_id.values():
        # (1) usage attributes must never ride on a tool span.
        if span.is_tool_span and (
            span.usage_input_tokens is not None
            or span.usage_output_tokens is not None
        ):
            raise LineageDetachmentError(
                f"tool span {span.span_id} carries gen_ai.usage.* attributes; "
                f"this is the fingerprint of a cached span template re-parented "
                f"into a new invocation (op={span.operation_name})"
            )

        # (2) tool_call_id must be unique per parent, not per trace.
        if span.is_tool_span and span.tool_call_id is not None:
            key = (span.trace_id, span.parent_span_id or "")
            prior = seen_tool_ids.get(key)
            if prior is not None and prior != span.span_id:
                raise LineageDetachmentError(
                    f"tool_call_id {span.tool_call_id!r} collides across spans "
                    f"{prior} and {span.span_id} under parent "
                    f"{span.parent_span_id}; lineage cannot be resolved"
                )
            seen_tool_ids[key] = span.span_id

        # (3) temporal containment.
        if span.parent_span_id is None:
            continue
        parent = by_id.get(span.parent_span_id)
        if parent is None:
            continue
        if span.start_time_ns < parent.start_time_ns:
            raise LineageDetachmentError(
                f"span {span.span_id} starts ({span.start_time_ns}) before "
                f"parent {parent.span_id} ({parent.start_time_ns}); "
                f"cached-template timestamp copy suspected"
            )
        if span.end_time_ns > parent.end_time_ns:
            raise LineageDetachmentError(
                f"span {span.span_id} ends ({span.end_time_ns}) after "
                f"parent {parent.span_id} ({parent.end_time_ns}); "
                f"tool execution escaped its invocation window"
            )
