# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-causal-link-in-otel-genai-attribute-schemas-for-multi-agent-trace-correlation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-causal-link-in-otel-genai-attribute-schemas-for-multi-agent-trace-correlation.warrant.json
# Markdown SHA-256:   ecc72ba207271a1fa080a9f17a8244ec61f171d6f0908ce4b673d24bd62c1d69
# Code AST SHA-256:   884c14661629593b770e5e80349be163327ca7846c117da9d460c4cc7b2050f3
# Verified Classes:   CausalLinkIntegrityError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class CausalLinkIntegrityError(RuntimeError):
    """Raised when OTel GenAI attributes cannot support causal reconstruction."""
    pass


@dataclass(frozen=True)
class GenAISpan:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    agent_id: str
    conversation_id: str
    operation_name: str | None
    start_ns: int
    end_ns: int


def _overlap(a: GenAISpan, b: GenAISpan) -> bool:
    return a.start_ns < b.end_ns and b.start_ns < a.end_ns


def validate_causal_links(spans: Iterable[GenAISpan], expected_agents: int) -> None:
    spans = list(spans)
    by_trace: dict[str, list[GenAISpan]] = {}
    for s in spans:
        by_trace.setdefault(s.trace_id, []).append(s)

    for trace_id, group in by_trace.items():
        agent_ids = {s.agent_id for s in group}
        if len(agent_ids) < expected_agents:
            raise CausalLinkIntegrityError(
                f"trace {trace_id}: agent.id cardinality {len(agent_ids)} "
                f"< expected {expected_agents}; agents fused under shared id"
            )

        # Composite key must identify exactly one non-nested causal node.
        by_key: dict[tuple[str, str], list[GenAISpan]] = {}
        for s in group:
            by_key.setdefault((s.agent_id, s.conversation_id), []).append(s)
        for key, siblings in by_key.items():
            for i in range(len(siblings)):
                for j in range(i + 1, len(siblings)):
                    if _overlap(siblings[i], siblings[j]):
                        raise CausalLinkIntegrityError(
                            f"trace {trace_id}: key {key} maps to overlapping "
                            f"non-nested spans {siblings[i].span_id}/"
                            f"{siblings[j].span_id}; retry collision"
                        )

        # Every child of a GenAI parent must carry an operation name.
        parents = {s.span_id for s in group if s.operation_name}
        for s in group:
            if s.parent_span_id in parents and not s.operation_name:
                raise CausalLinkIntegrityError(
                    f"trace {trace_id}: span {s.span_id} under GenAI parent "
                    f"{s.parent_span_id} lacks gen_ai.operation.name; edge dropped"
                )

    # conversation.id must not span traces without explicit links.
    conv_to_traces: dict[str, set[str]] = {}
    for s in spans:
        conv_to_traces.setdefault(s.conversation_id, set()).add(s.trace_id)
    for conv, traces in conv_to_traces.items():
        if len(traces) > 1:
            raise CausalLinkIntegrityError(
                f"conversation {conv} spans traces {sorted(traces)} with no "
                f"explicit span link; causal edge unproven"
            )
