# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-order-corruption-in-distributed-traces-across-federated-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-order-corruption-in-distributed-traces-across-federated-agent-hops.warrant.json
# Markdown SHA-256:   aebd57bd31dac3e2698212f56e21b910873f74a1517132781dd4b07a9bc76bb3
# Code AST SHA-256:   3f617e6fc56370733cff7c9ad4853786c36b49f75dd18e820ad2e98ad9a1b999
# Verified Classes:   CausalOrderCorruption, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, List, Optional, Set


class CausalOrderCorruption(RuntimeError):
    """Raised when an assembled federated trace's parent-edge DAG
    disagrees with its payload-lineage DAG (a re-rooted hop)."""


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    # The span whose OUTPUT this span actually consumed. Distinct from
    # parent_span_id: parent = "spawned during", consumed = "caused by".
    consumed_span_id: Optional[str] = None
    children: List[str] = field(default_factory=list)


def _ancestors(spans: Dict[str, Span], span_id: str) -> Set[str]:
    """Return the set of strict ancestors of span_id via parent edges."""
    seen: Set[str] = set()
    cur = spans[span_id].parent_span_id
    while cur is not None:
        if cur in seen:  # cycle guard; a cyclic DAG is a separate defect
            break
        seen.add(cur)
        cur = spans[cur].parent_span_id if cur in spans else None
    return seen


def verify_causal_lineage(spans: Dict[str, Span]) -> None:
    """Enforce: for every span, consumed_span_id must be an ancestor of
    parent_span_id (or equal to it). A consumed input that is merely a
    SIBLING of the parent means the hop re-rooted and the causal edge
    was lost, even though the tree is acyclic and parent-complete."""
    for sid, span in spans.items():
        if span.consumed_span_id is None:
            continue
        if span.consumed_span_id not in spans:
            raise CausalOrderCorruption(
                f"span {sid}: consumed_span_id {span.consumed_span_id} "
                f"absent from assembled trace (cross-federation drop)"
            )
        if span.parent_span_id is None:
            # A span with a consumed input but no parent is a re-root.
            raise CausalOrderCorruption(
                f"span {sid}: consumed {span.consumed_span_id} but has no "
                f"parent edge — hop re-rooted the trace at deserialization"
            )
        lineage = _ancestors(spans, sid) | {span.parent_span_id}
        if span.consumed_span_id not in lineage:
            raise CausalOrderCorruption(
                f"span {sid}: consumed {span.consumed_span_id} is NOT an "
                f"ancestor of parent {span.parent_span_id}; parent-edge "
                f"DAG disagrees with payload-lineage DAG (CAUSAL_REORDER)"
            )


def assemble_and_admit(raw_spans: List[Span]) -> Dict[str, Span]:
    """Join per-hop exports, then admit the trace only if causally faithful.
    Quarantined traces must NOT be fed to an auditor that orders by trace."""
    spans: Dict[str, Span] = {s.span_id: s for s in raw_spans}
    for s in raw_spans:
        if s.parent_span_id is not None and s.parent_span_id in spans:
            spans[s.parent_span_id].children.append(s.span_id)
    verify_causal_lineage(spans)  # raises CausalOrderCorruption on re-root
    return spans


# --- Trigger trace: V consumed W1.tool_call, but W1 re-rooted V under W1.root.
raw = [
    Span("P.root", "t1", None),
    Span("W1.root", "t1", "P.root"),
    Span("W1.tool_call", "t1", "W1.root"),
    # V's parent is W1.root (sibling of the span it consumed) -> corruption.
    Span("V.verify", "t1", "W1.root", consumed_span_id="W1.tool_call"),
]

try:
    assemble_and_admit(raw)
except CausalOrderCorruption as e:
    # Operational response: quarantine trace, fall back to payload hashes.
    print(f"QUARANTINED: {e}")
