# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-to-replay-a-multi-agent-trace-when-otel-genai-span-timestamps-are-monotonic-but-parent-child-causality-is-not.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-to-replay-a-multi-agent-trace-when-otel-genai-span-timestamps-are-monotonic-but-parent-child-causality-is-not.warrant.json
# Markdown SHA-256:   4dd2f61482bff83fda39fe1d8cfb8baf08dd1bf20ee461de5422af921f0d12c9
# Code AST SHA-256:   a67fa01b5c63f4e90e7555fc07ea0ebf189f294624cd75d00c555c74c5f07fac
# Verified Classes:   CausalReplayInversionError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalReplayInversionError(RuntimeError):
    """Raised when a child span's start_time precedes its parent's end_time,
    making timestamp-based causal reconstruction unsound."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    start_ms: int
    end_ms: int
    causal_token: Optional[int] = None  # Lamport counter, if instrumented


def reconstruct_causal_order(spans: list[Span]) -> list[Span]:
    by_id = {s.span_id: s for s in spans}

    # Guardrail 1: detect temporal inversions before any sorting.
    for s in spans:
        if s.parent_id is None:
            continue
        parent = by_id.get(s.parent_id)
        if parent is None:
            continue
        if s.start_ms < parent.end_ms:
            if s.causal_token is None or parent.causal_token is None:
                raise CausalReplayInversionError(
                    f"Child {s.span_id} starts at {s.start_ms}ms, before "
                    f"parent {parent.span_id} ends at {parent.end_ms}ms, and "
                    f"no causal token is available to disambiguate. "
                    f"Replay is causally underdetermined; refuse to narrate."
                )
            if s.causal_token <= parent.causal_token:
                raise CausalReplayInversionError(
                    f"Causal token violation: child {s.span_id} token "
                    f"{s.causal_token} <= parent {parent.span_id} token "
                    f"{parent.causal_token}. Handoff instrumentation is broken."
                )

    # Guardrail 2: order by causal token when present; otherwise by parentage
    # depth, never by raw timestamp across process boundaries.
    def depth(s: Span) -> int:
        d, cur = 0, s
        while cur.parent_id is not None:
            cur = by_id[cur.parent_id]
            d += 1
        return d

    return sorted(
        spans,
        key=lambda s: (s.causal_token if s.causal_token is not None else depth(s)),
    )
