# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-orphaned-tool-call-spans-from-corrupting-genai-trace-causality-under-concurrent-sub-agent-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-orphaned-tool-call-spans-from-corrupting-genai-trace-causality-under-concurrent-sub-agent-fan-out.warrant.json
# Markdown SHA-256:   bbc4ef43d2f026e641cbe719f31936f39c4a6ab068ccc244251bd704218e0a12
# Code AST SHA-256:   4e47ba1d81ad1d439ba08f8ad8a0d0f6c02d57bca87c5deb9ba26a8ead8deda2
# Verified Classes:   CausalityInvariantError, Span
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalityInvariantError(RuntimeError):
    """Raised when a tool-call span violates the GenAI trace causality invariant."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_span_id: Optional[str]
    operation_name: str
    tool_call_id: Optional[str]
    start_ns: int
    end_ns: int


def assert_tool_span_causality(
    tool_span: Span,
    invocation_spans: dict[str, Span],
    max_concurrent_tool_calls: int,
) -> None:
    if tool_span.operation_name != "execute_tool":
        raise CausalityInvariantError(
            f"expected execute_tool span, got {tool_span.operation_name!r}"
        )
    if tool_span.tool_call_id is None:
        raise CausalityInvariantError(
            f"tool span {tool_span.span_id} missing gen_ai.tool.call.id"
        )
    parent = invocation_spans.get(tool_span.parent_span_id or "")
    if parent is None:
        raise CausalityInvariantError(
            f"tool span {tool_span.span_id} parents to unknown span "
            f"{tool_span.parent_span_id!r}"
        )
    if parent.start_ns > tool_span.start_ns:
        raise CausalityInvariantError(
            f"tool span {tool_span.span_id} starts before its parent "
            f"{parent.span_id} (start_ns {tool_span.start_ns} < {parent.start_ns})"
        )
    if tool_span.end_ns > parent.end_ns:
        # The orphan condition: child outlives parent.
        if max_concurrent_tool_calls > 1 and parent.operation_name == "chat":
            raise CausalityInvariantError(
                f"tool span {tool_span.span_id} (call_id={tool_span.tool_call_id}) "
                f"ends at {tool_span.end_ns} after parent chat span {parent.span_id} "
                f"ended at {parent.end_ns}; concurrency={max_concurrent_tool_calls} "
                f"requires an invoke_agent bracket, not a chat parent"
            )
        raise CausalityInvariantError(
            f"tool span {tool_span.span_id} outlives parent {parent.span_id} "
            f"without an invoke_agent bracket"
        )
