# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-replayed-otel-span-graphs-before-it-can-trust-a-multi-agent-trace-the-causal-orphan-inversion-at-span-re-parenting-bo.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-replayed-otel-span-graphs-before-it-can-trust-a-multi-agent-trace-the-causal-orphan-inversion-at-span-re-parenting-bo.warrant.json
# Markdown SHA-256:   10008f09c4b560a70ccdc206bda7b7828e3ef7401070b414fc4b92ad52bf0106
# Code AST SHA-256:   771c6f0e9c67a62a5bc0bd30d30ce4886779eba627dea13e97479b6613d8840a
# Verified Classes:   CausalReconstructionError, Span, Trace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalReconstructionError(RuntimeError):
    """Raised when a trace cannot be finalized without inventing causal edges."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    start_time: float
    end_time: float
    links: list[str] = field(default_factory=list)
    attributes: dict = field(default_factory=dict)


@dataclass
class Trace:
    trace_id: str
    spans: dict[str, Span] = field(default_factory=dict)

    def watermark(self) -> float:
        return max((s.end_time for s in self.spans.values()), default=0.0)

    def orphans(self) -> list[Span]:
        return [
            s for s in self.spans.values()
            if s.parent_span_id is not None and s.parent_span_id not in self.spans
        ]


def finalize_trace(trace: Trace, grace_window: float) -> Trace:
    """
    Finalize a trace only if every parent edge is observed or the grace window
    has elapsed for each orphan. Never re-parent to a timestamp-nearest span.
    """
    wm = trace.watermark()
    for orphan in trace.orphans():
        # A link may legitimately carry the causal edge when the parent span
        # was emitted by a different process and its parent_span_id is stale.
        if any(link in trace.spans for link in orphan.links):
            continue
        if wm - orphan.start_time <= grace_window:
            raise CausalReconstructionError(
                f"trace {trace.trace_id} not quiescent: span {orphan.span_id} "
                f"orphaned with parent {orphan.parent_span_id} still within "
                f"grace window ({wm - orphan.start_time:.3f}s <= {grace_window}s)"
            )
        # Grace elapsed and parent never arrived: mark, do not synthesize.
        orphan.attributes["causal_orphan"] = True
        orphan.attributes["unresolved_parent_span_id"] = orphan.parent_span_id
    return trace


def replay(trace: Trace, grace_window: float = 2.0) -> Trace:
    finalized = finalize_trace(trace, grace_window)
    for span in finalized.spans.values():
        if span.attributes.get("causal_orphan"):
            raise CausalReconstructionError(
                f"refusing to verify trace {trace.trace_id}: span {span.span_id} "
                f"is a causal orphan; parent-child input propagation is undefined"
            )
    return finalized
