# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-genai-span-s-parent-child-topology-when-a-tool-call-span-outlives-its-enclosing-agent-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-genai-span-s-parent-child-topology-when-a-tool-call-span-outlives-its-enclosing-agent-invocation.warrant.json
# Markdown SHA-256:   9adff9325e74c43bf7264883320402909ee4794f8dad0f8d9e4fa985e87bdaa8
# Code AST SHA-256:   ebb6b10b6d5b652f7f659ce0ebbb0fa56312b20d5f3d2be9616630e041d1f828
# Verified Classes:   TemporalContainmentViolation, SpanRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TemporalContainmentViolation(RuntimeError):
    """Raised when a GenAI tool span's parent closed before the tool started."""
    pass


@dataclass
class SpanRecord:
    span_id: str
    parent_span_id: Optional[str]
    operation: str          # e.g. "chat", "execute_tool"
    start_ns: int
    end_ns: Optional[int]   # None while still open


def validate_genai_topology(spans: dict[str, SpanRecord]) -> None:
    """
    Enforce: a span's parent must not have ended before the child started.
    GenAI tool spans dispatched asynchronously routinely violate this when
    the invocation span is closed before the tool worker emits its span.
    """
    for span in spans.values():
        if span.parent_span_id is None:
            continue
        parent = spans.get(span.parent_span_id)
        if parent is None:
            # dangling parent id: restart boundary, do not silently re-root
            raise TemporalContainmentViolation(
                f"span {span.span_id} references missing parent "
                f"{span.parent_span_id}; treat as restart orphan, not a child"
            )
        if parent.end_ns is not None and parent.end_ns < span.start_ns:
            raise TemporalContainmentViolation(
                f"span {span.span_id} ({span.operation}) starts at "
                f"{span.start_ns} but parent {parent.span_id} "
                f"({parent.operation}) ended at {parent.end_ns}; "
                f"emit a SpanLink instead of a parent edge"
            )


def emit_tool_span(
    invocation: SpanRecord,
    tool_span_id: str,
    start_ns: int,
) -> SpanRecord:
    """
    Correct emission for an async tool call: the invocation span has already
    closed, so a parent edge would assert temporal containment that does not
    hold. Link to the invocation, parent to the agent-loop root instead.
    """
    if invocation.end_ns is not None and invocation.end_ns < start_ns:
        # invocation already closed -> must not use it as parent
        return SpanRecord(
            span_id=tool_span_id,
            parent_span_id=None,          # caller supplies agent-loop root
            operation="execute_tool",
            start_ns=start_ns,
            end_ns=None,
        )
    # synchronous path: containment holds, parent edge is sound
    return SpanRecord(
        span_id=tool_span_id,
        parent_span_id=invocation.span_id,
        operation="execute_tool",
        start_ns=start_ns,
        end_ns=None,
    )
