# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-span-orphaning-when-causal-trace-links-are-reconstructed-across-non-deterministic-replays.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-span-orphaning-when-causal-trace-links-are-reconstructed-across-non-deterministic-replays.warrant.json
# Markdown SHA-256:   3c9f6c354fa66a7b090e7ebe7975889727dc1553b3aa57d5b302c72a8dde7d94
# Code AST SHA-256:   21453797e226b0251b71e8195a7d9b9609d01c01b07842608dd74990b522474d
# Verified Classes:   TraceLinkageError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class TraceLinkageError(RuntimeError):
    """Raised when a reconstructed causal edge fails the replay-anchored linkage invariant."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    start_time: float
    end_time: float
    input_hash: str
    output_hash: str


def validate_causal_edge(parent: Span, child: Span) -> None:
    """Enforce the three-part linkage invariant for one parent->child edge.

    A valid edge requires: same trace root, non-inverted temporal order, and a
    child input hash derivable from the parent output hash.
    """
    if parent.trace_id != child.trace_id:
        raise TraceLinkageError(
            f"cross-trace edge: parent {parent.span_id} in {parent.trace_id} "
            f"feeds child {child.span_id} in {child.trace_id} (resume boundary severed)"
        )
    if parent.end_time > child.start_time:
        raise TraceLinkageError(
            f"temporal inversion: child {child.span_id} starts {child.start_time} "
            f"before parent {parent.span_id} ends {parent.end_time}"
        )
    expected = hashlib.sha256(parent.output_hash.encode()).hexdigest()
    if expected != child.input_hash:
        raise TraceLinkageError(
            f"decision-hash divergence on edge {parent.span_id}->{child.span_id}: "
            f"child input {child.input_hash} not derivable from parent output {parent.output_hash}"
        )


def replay_decision_chain(spans: list[Span]) -> list[str]:
    """Reconstruct and validate a full causal chain; return ordered span ids.

    Orphans are quarantined, never promoted to roots. Any invalid edge aborts
    the replay so a broken trace cannot be laundered into a plausible one.
    """
    by_id = {s.span_id: s for s in spans}
    children = {s.parent_span_id: s for s in spans if s.parent_span_id}
    roots = [s for s in spans if s.parent_span_id is None]

    if len(roots) != 1:
        raise TraceLinkageError(
            f"expected exactly one root, found {len(roots)}: "
            f"{[r.span_id for r in roots]} (orphans must be quarantined, not re-rooted)"
        )

    chain, cursor = [], roots[0]
    while cursor is not None:
        chain.append(cursor.span_id)
        nxt = children.get(cursor.span_id)
        if nxt is not None:
            validate_causal_edge(cursor, nxt)
        cursor = nxt

    if len(chain) != len(spans):
        missing = set(by_id) - set(chain)
        raise TraceLinkageError(f"unreachable spans from root: {sorted(missing)}")
    return chain
