# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-orphaned-causal-spans-when-genai-semantic-conventions-are-applied-across-a-multi-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-orphaned-causal-spans-when-genai-semantic-conventions-are-applied-across-a-multi-agent-handoff.warrant.json
# Markdown SHA-256:   846f346db364028a23e599984f0c8b1af11c44f5b38822ee0dfc6f39e4c312a6
# Code AST SHA-256:   1dc4888b08ae18402b950f92b27eadb04014074e4e799ef660a1998926f9d195
# Verified Classes:   CausalLinkViolation, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class CausalLinkViolation(RuntimeError):
    """Raised when a GenAI span's causal parent is semantically inconsistent."""

@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    agent_id: str
    operation_name: str
    start_time: float
    end_time: float

HANDOFF_PREDECESSOR = {
    "executor": "planner",
    "synthesizer": "executor",
}

def validate_causal_link(span: Span, parent: Optional[Span]) -> None:
    expected_parent_agent = HANDOFF_PREDECESSOR.get(span.agent_id)
    if expected_parent_agent is None:
        return  # root agent, no predecessor required
    if parent is None:
        raise CausalLinkViolation(
            f"span {span.span_id} (agent={span.agent_id}) has no resolvable "
            f"parent span; expected predecessor agent={expected_parent_agent}. "
            f"Likely lost OTel context across an async boundary."
        )
    if parent.trace_id != span.trace_id:
        raise CausalLinkViolation(
            f"trace_id mismatch: span {span.span_id} trace={span.trace_id} "
            f"parent {parent.span_id} trace={parent.trace_id}"
        )
    if parent.agent_id != expected_parent_agent:
        raise CausalLinkViolation(
            f"semantic parent mismatch: span {span.span_id} agent={span.agent_id} "
            f"expected parent agent={expected_parent_agent} but parent "
            f"{parent.span_id} agent={parent.agent_id}. Schema-conformant but "
            f"causally orphaned; do not repair via conversation.id."
        )
    if span.start_time < parent.end_time:
        raise CausalLinkViolation(
            f"temporal inversion: span {span.span_id} starts {span.start_time} "
            f"before parent {parent.span_id} ends {parent.end_time}"
        )
