# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-causal-span-linking-from-silently-collapsing-in-multi-agent-genai-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-causal-span-linking-from-silently-collapsing-in-multi-agent-genai-traces.warrant.json
# Markdown SHA-256:   c3f5a59b48d5e1741afc96880b4e2a71264863c0f873dd31b48bb2e6a19b854d
# Code AST SHA-256:   f2122d63aa9d7f4bab8f122c27181b7e1d07b76f7b1813520920fb49152080df
# Verified Classes:   CausalLinkInvariantError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalLinkInvariantError(RuntimeError):
    """Raised when a span's causal edge is neither backed by a parent edge
    nor by an explicit link record, or when start-time ordering contradicts
    the declared parent without a repair annotation."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    start_ns: int
    end_ns: int
    causal_predecessor_id: Optional[str] = None
    link_type: Optional[str] = None          # e.g. "caused_by"
    clock_skew_corrected: bool = False


def validate_causal_span(span: Span, spans_by_id: dict) -> None:
    # Invariant 1: a declared parent must exist and not post-date the child,
    # unless the skew was explicitly repaired.
    if span.parent_span_id is not None:
        parent = spans_by_id.get(span.parent_span_id)
        if parent is None:
            raise CausalLinkInvariantError(
                f"span {span.span_id} references missing parent "
                f"{span.parent_span_id}"
            )
        if span.start_ns < parent.start_ns and not span.clock_skew_corrected:
            raise CausalLinkInvariantError(
                f"span {span.span_id} starts before its parent "
                f"{parent.span_id} without clock_skew_corrected annotation; "
                f"reorder would silently invert the causal edge"
            )

    # Invariant 2: a causal edge must be backed by a parent edge or an
    # explicit link record. Timestamp inference alone is not admissible.
    if span.causal_predecessor_id is not None:
        backed_by_parent = span.causal_predecessor_id == span.parent_span_id
        backed_by_link = (
            span.link_type == "caused_by"
            and span.causal_predecessor_id in spans_by_id
        )
        if not (backed_by_parent or backed_by_link):
            raise CausalLinkInvariantError(
                f"span {span.span_id} claims causal predecessor "
                f"{span.causal_predecessor_id} with no parent edge and no "
                f"caused_by link record; trace is causally unsound"
            )

    # Invariant 3: cross-tree handoffs must not be forced into a parent edge.
    if (
        span.parent_span_id is not None
        and span.causal_predecessor_id is not None
        and span.causal_predecessor_id != span.parent_span_id
        and span.link_type != "caused_by"
    ):
        raise CausalLinkInvariantError(
            f"span {span.span_id} has divergent parent and causal predecessor "
            f"without a caused_by link; cross-tree handoff was coerced"
        )
