# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-orphaned-child-spans-after-a-mid-trace-parent-eviction-genai-span-correlation-failure-in-multi-hop-agent-trace-rec.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-orphaned-child-spans-after-a-mid-trace-parent-eviction-genai-span-correlation-failure-in-multi-hop-agent-trace-rec.warrant.json
# Markdown SHA-256:   3d9ca8540e69180304f964398690b1c84057b2df23b431faa0e872a08bfdf42e
# Code AST SHA-256:   a2a80f139dacbdcb7743622571b913c62d5f6c0a4c288e13051cca90f85d2d09
# Verified Classes:   AncestryResolutionError, Span, Reconstructor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AncestryResolutionError(RuntimeError):
    """Raised when a span's ancestry cannot be resolved within the grace window."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    trace_id: str
    name: str
    ancestry_unresolved: bool = False
    missing_parent_id: Optional[str] = None


@dataclass
class Reconstructor:
    grace_window_s: float
    reparent_orphans: bool = False
    _pending: dict = field(default_factory=dict)  # parent_id -> [children]
    _resolved: dict = field(default_factory=dict)  # span_id -> Span

    def ingest(self, span: Span, now: float) -> None:
        self._resolved[span.span_id] = span
        # Adopt any children that were waiting on this span as parent.
        waiting = self._pending.pop(span.span_id, [])
        for child in waiting:
            child.missing_parent_id = None
            child.ancestry_unresolved = False
        # If this span itself has an absent parent, park it.
        if span.parent_span_id and span.parent_span_id not in self._resolved:
            self._pending.setdefault(span.parent_span_id, []).append(span)

    def finalize(self, now: float) -> list[Span]:
        """Flush pending orphans whose grace window has elapsed."""
        out = []
        for parent_id, children in self._pending.items():
            for child in children:
                if self.reparent_orphans:
                    # Explicitly forbidden: fabricates ancestry.
                    raise AncestryResolutionError(
                        f"Refusing to reparent orphan {child.span_id} "
                        f"(missing parent {parent_id}) — fabricated ancestry"
                    )
                child.ancestry_unresolved = True
                child.missing_parent_id = parent_id
                out.append(child)
        self._pending.clear()
        return out


def causal_path(spans: list[Span], target_id: str) -> list[Span]:
    """Walk ancestry; refuse to fabricate edges through unresolved spans."""
    by_id = {s.span_id: s for s in spans}
    if target_id not in by_id:
        raise AncestryResolutionError(f"span {target_id} not in trace")
    path = []
    cur = by_id[target_id]
    while cur is not None:
        if cur.ancestry_unresolved:
            raise AncestryResolutionError(
                f"causal path broken at {cur.span_id}: "
                f"missing parent {cur.missing_parent_id}"
            )
        path.append(cur)
        cur = by_id.get(cur.parent_span_id) if cur.parent_span_id else None
    return path
