# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-trace-reconstruction-has-silently-diverged-across-federated-agent-spans-and-tool-call-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-trace-reconstruction-has-silently-diverged-across-federated-agent-spans-and-tool-call-boundaries.warrant.json
# Markdown SHA-256:   ebef6bfec670c6448000aa0052c17adeb711e065fa2fb8e96d087414afa06611
# Code AST SHA-256:   9c00cf85349b836a0808e6376655398b6dd213071c25f65c30e3c5e5ba290e10
# Verified Classes:   CausalReconstructionDivergence, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalReconstructionDivergence(RuntimeError):
    """Raised when a federated trace is structurally valid but causally unsound."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    trace_id: str
    emitter: str
    start_ns: int
    end_ns: int
    logical_call_id: Optional[str] = None
    attempt: int = 0


def reconstruct_causal_order(spans: list[Span], clock_offset_ns: dict[str, int]) -> list[Span]:
    """Order spans by propagated causal edges; refuse to guess where propagation is absent."""
    by_id = {s.span_id: s for s in spans}

    # 1. Detect temporal containment violations: a span nested inside another
    #    span it is not causally descended from, with no propagated parent link.
    for outer in spans:
        for inner in spans:
            if inner is outer or inner.parent_span_id is not None:
                continue
            if outer.start_ns < inner.start_ns < inner.end_ns < outer.end_ns:
                if not _is_descendant(inner, outer, by_id):
                    raise CausalReconstructionDivergence(
                        f"span {inner.span_id} ({inner.emitter}) is temporally contained in "
                        f"{outer.span_id} ({outer.emitter}) but has no propagated parent link; "
                        f"timestamp fallback is unsound"
                    )

    # 2. Refuse to order causally-linked spans when clock offset exceeds causal slack.
    for a in spans:
        for b in spans:
            if a.emitter == b.emitter or a.parent_span_id != b.span_id:
                continue
            slack = abs(a.start_ns - b.end_ns)
            offset = abs(clock_offset_ns.get(a.emitter, 0) - clock_offset_ns.get(b.emitter, 0))
            if offset >= slack:
                raise CausalReconstructionDivergence(
                    f"clock offset {offset}ns between {a.emitter} and {b.emitter} "
                    f"exceeds causal slack {slack}ns for edge {b.span_id}->{a.span_id}; "
                    f"order is UNORDERED, not timestamp-resolvable"
                )

    # 3. Detect retry-induced duplicate responses for one logical call.
    seen: dict[tuple[str, int], Span] = {}
    for s in spans:
        if s.logical_call_id is None:
            continue
        key = (s.logical_call_id, s.attempt)
        if key in seen and seen[key].span_id != s.span_id:
            raise CausalReconstructionDivergence(
                f"duplicate response for logical call {s.logical_call_id} attempt {s.attempt}: "
                f"{seen[key].span_id} and {s.span_id}; retry must fork, not splice"
            )
        seen[key] = s

    # Only propagated edges are trusted; everything else is returned for explicit labeling.
    return sorted(spans, key=lambda s: s.start_ns)


def _is_descendant(span: Span, ancestor: Span, by_id: dict[str, Span]) -> bool:
    cur = span
    while cur.parent_span_id is not None:
        parent = by_id.get(cur.parent_span_id)
        if parent is None:
            return False
        if parent.span_id == ancestor.span_id:
            return True
        cur = parent
    return False
