# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-an-agent-span-become-semantically-invalid-when-a-tool-call-attribute-is-recorded-before-the-model-invocation-event-that-produc.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-an-agent-span-become-semantically-invalid-when-a-tool-call-attribute-is-recorded-before-the-model-invocation-event-that-produc.warrant.json
# Markdown SHA-256:   47134f4385bd7a5a616b86231dc93054d3598cf9c19582c5e78bb681c6c4bedd
# Code AST SHA-256:   e06ed6fef2e72b2facfde403c384fdb72737fe86e27aa71a8c2a53d09451f912
# Verified Classes:   ToolCallCausalityError, InvocationEvent, ToolCallSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ToolCallCausalityError(RuntimeError):
    """Raised when a tool-call span lacks a prior, matching model-invocation event."""
    pass


@dataclass
class InvocationEvent:
    tool_call_id: str
    emitted_at_ns: int


@dataclass
class ToolCallSpan:
    tool_call_id: str
    started_at_ns: int


def assert_tool_call_causality(
    span: ToolCallSpan,
    invocation: Optional[InvocationEvent],
) -> None:
    if invocation is None:
        raise ToolCallCausalityError(
            f"tool-call span {span.tool_call_id!r} has no preceding "
            "model-invocation event; span is orphaned and unattributable"
        )
    if invocation.tool_call_id != span.tool_call_id:
        raise ToolCallCausalityError(
            f"tool-call id mismatch: span={span.tool_call_id!r} "
            f"invocation={invocation.tool_call_id!r}; "
            "the model's proposed id was not propagated"
        )
    if span.started_at_ns < invocation.emitted_at_ns:
        raise ToolCallCausalityError(
            f"tool-call span for {span.tool_call_id!r} started "
            f"{invocation.emitted_at_ns - span.started_at_ns}ns before its "
            "invocation event; buffer the span until the event flushes"
        )
