# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-causality-when-otel-genai-spans-cross-an-async-collector-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-causality-when-otel-genai-spans-cross-an-async-collector-boundary.warrant.json
# Markdown SHA-256:   a224e2a2ecd0b82f631bb78ae190023074daf8740b9fa0538cef3197df96f83e
# Code AST SHA-256:   6ae54fa0385e0e4b94a7326b74642e8f6a6f023412bdd3ebaa53c8aff538f9df
# Verified Classes:   GenAICausalityViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GenAICausalityViolation(RuntimeError):
    """Raised when a GenAI trace cannot reconstruct tool-call causality
    because a referenced gen_ai.tool.call.id has no defining tool span."""


def assert_tool_call_causality(spans: list[dict]) -> None:
    """Verify cross-span referential integrity for gen_ai.tool.call.id.

    Each span is a dict with 'trace_id', 'name', 'attributes', and optional
    'references' (list of call.id values the span's payload points at).
    """
    defined: dict[str, set[str]] = {}
    for span in spans:
        if span["name"] == "gen_ai.tool.call":
            call_id = span["attributes"].get("gen_ai.tool.call.id")
            if call_id is None:
                raise GenAICausalityViolation(
                    f"tool span {span.get('span_id')} in trace "
                    f"{span['trace_id']} emitted without gen_ai.tool.call.id; "
                    "linkage attribute dropped or stamped after span-end"
                )
            defined.setdefault(span["trace_id"], set()).add(call_id)

    for span in spans:
        for ref in span.get("references", []):
            if ref not in defined.get(span["trace_id"], set()):
                raise GenAICausalityViolation(
                    f"span {span.get('span_id')} in trace {span['trace_id']} "
                    f"references gen_ai.tool.call.id={ref!r} but no tool span "
                    "defines it; collector processor likely dropped the "
                    "attribute or batching split the causal pair"
                )
