# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-genai-span-as-non-canonical-when-child-tool-call-spans-outlive-the-parent-agent-span-s-recorded-end-time.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-genai-span-as-non-canonical-when-child-tool-call-spans-outlive-the-parent-agent-span-s-recorded-end-time.warrant.json
# Markdown SHA-256:   5c00e2366ff3323a175363a081beacc6f3dfb293eae1ab4e5fc9ab40b5838efb
# Code AST SHA-256:   e24459d46c99f1f2918a8e069361f6dad7dd1770c3ecd37e58b0ca6171e712c4
# Verified Classes:   NonCanonicalSpanError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class NonCanonicalSpanError(RuntimeError):
    """Raised when a child span outlives its parent without a valid dispatch record."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: str | None
    operation: str
    start_time: float
    end_time: float
    attrs: dict


def canonicalize_child(
    parent: Span,
    child: Span,
    dispatched_tool_ids: FrozenSet[str],
    skew_tolerance: float,
) -> None:
    """
    Enforce the concurrent-dispatch invariant for a child of an agent span.
    Raises NonCanonicalSpanError if the child is a non-canonical orphan.
    """
    if child.operation != "gen_ai.tool.call":
        return  # invariant applies only to tool-call children

    if child.start_time < parent.start_time or child.start_time > parent.end_time:
        raise NonCanonicalSpanError(
            f"tool span {child.span_id} was not dispatched within parent "
            f"{parent.span_id} interval [{parent.start_time}, {parent.end_time}]"
        )

    outlives_parent = child.end_time > parent.end_time + skew_tolerance
    if not outlives_parent:
        return  # normal synchronous completion

    tool_id = child.attrs.get("gen_ai.tool.call.id")
    if not tool_id or tool_id not in dispatched_tool_ids:
        raise NonCanonicalSpanError(
            f"tool span {child.span_id} outlives parent {parent.span_id} but its "
            f"gen_ai.tool.call.id={tool_id!r} is not in the parent's dispatch record; "
            f"likely a late span from a prior turn with a colliding trace id"
        )

    if any(k.startswith("gen_ai.usage.") for k in child.attrs):
        raise NonCanonicalSpanError(
            f"tool span {child.span_id} carries gen_ai.usage.* attributes; "
            f"usage belongs to the model call, not the tool — cost aggregation "
            f"will double-count against parent {parent.span_id}"
        )
