# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-causal-span-linking-silently-rewires-a-replay-the-orphaned-parent-divergence-in-distributed-decision-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-causal-span-linking-silently-rewires-a-replay-the-orphaned-parent-divergence-in-distributed-decision-traces.warrant.json
# Markdown SHA-256:   2cd980a7feacac66616099906dbd79b22ef81ead662cbb10b56050eacc58eabe
# Code AST SHA-256:   a1b455c3e369df8f555c9da6bd7a13f7b30e6b0d81ce3b725604ccf38b5752d9
# Verified Classes:   CausalFidelityError, Span, ReconstructedTrace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalFidelityError(RuntimeError):
    """Raised when a reconstructed trace is link-integral but not ancestry-faithful."""
    pass


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    input_fingerprint: Optional[str] = None   # hash of consumed parent output
    output_fingerprint: Optional[str] = None  # hash of produced output
    is_declared_root: bool = False


@dataclass
class ReconstructedTrace:
    trace_id: str
    spans: dict = field(default_factory=dict)
    unresolved: list = field(default_factory=list)
    replay_safe: bool = True


def reconstruct(spans: list) -> ReconstructedTrace:
    rt = ReconstructedTrace(trace_id=spans[0].trace_id if spans else "")
    for s in spans:
        rt.spans[s.span_id] = s

    for s in spans:
        # Invariant 1: null parent on a non-root span is a fidelity fault,
        # NOT a cue to reparent to root. Quarantine; do not fabricate an edge.
        if s.parent_span_id is None and not s.is_declared_root:
            rt.unresolved.append(s.span_id)
            rt.replay_safe = False
            continue
        if s.parent_span_id is None:
            continue
        parent = rt.spans.get(s.parent_span_id)
        if parent is None:
            rt.unresolved.append(s.span_id)
            rt.replay_safe = False
            continue
        # Invariant 2: integrity is not fidelity. The child must carry a
        # fingerprint of the parent output it actually consumed.
        if s.input_fingerprint is not None and \
           parent.output_fingerprint is not None and \
           s.input_fingerprint != parent.output_fingerprint:
            rt.unresolved.append(s.span_id)
            rt.replay_safe = False

    # Invariant 3: a non-root leaf whose output was consumed by nobody
    # signals a severed causal edge even if every join "succeeded".
    consumed = {s.parent_span_id for s in spans if s.parent_span_id}
    for s in spans:
        if s.is_declared_root or s.span_id in consumed:
            continue
        if s.output_fingerprint is not None:
            rt.replay_safe = False
            raise CausalFidelityError(
                f"span {s.span_id} in trace {rt.trace_id} produced output "
                f"consumed by no child; suspected severed causal edge "
                f"(parent_span_id={s.parent_span_id!r}). Replay narrative "
                f"would be self-consistent and false."
            )
    return rt


def assert_replayable(rt: ReconstructedTrace) -> None:
    if not rt.replay_safe or rt.unresolved:
        raise CausalFidelityError(
            f"trace {rt.trace_id} is not replay-safe: "
            f"{len(rt.unresolved)} unresolved span(s) {rt.unresolved}. "
            f"Refusing to render a fabricated ancestry."
        )
