# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-span-parentage-before-correlation-not-after-the-orphaned-tool-span-amplification-failure-in-llm-observability-pipelin.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-span-parentage-before-correlation-not-after-the-orphaned-tool-span-amplification-failure-in-llm-observability-pipelin.warrant.json
# Markdown SHA-256:   02d7ded692455c28470b73b7b640433f7a5eaff970b785ef10b97215d978ff0d
# Code AST SHA-256:   47e33093f10744ca8b33497efd53e27278d8a54eda1b9fde2bf87525a3b854b6
# Verified Classes:   UnresolvedParentError, Span, IngestReconciler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class UnresolvedParentError(RuntimeError):
    """Raised when a child span's parent cannot be resolved within the
    same trace identity before the reconciliation deadline expires."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    name: str
    emitted_at: float = field(default_factory=time.monotonic)


class IngestReconciler:
    """Holds child spans pending parent arrival, keyed by (trace_id, parent_span_id).
    Never reparents across trace identities. Quarantines on deadline expiry."""

    def __init__(self, deadline_s: float = 30.0):
        self.deadline_s = deadline_s
        self._pending: dict[tuple[str, str], list[Span]] = {}
        self.orphans: list[Span] = []
        self.resolved: list[Span] = []

    def ingest(self, span: Span) -> None:
        if span.parent_span_id is None:
            # Root span: resolve any children that were waiting on it.
            self._resolve_children(span)
            self.resolved.append(span)
            return
        key = (span.trace_id, span.span_id)
        # This span may itself be a parent awaited by others; resolve those.
        self._resolve_children(span)
        # Now this span waits on its own parent.
        self._pending.setdefault((span.trace_id, span.parent_span_id), []).append(span)
        self._sweep(now=span.emitted_at)

    def _resolve_children(self, parent: Span) -> None:
        waiting = self._pending.pop((parent.trace_id, parent.span_id), [])
        self.resolved.extend(waiting)

    def _sweep(self, now: float) -> None:
        expired = [
            k for k, children in self._pending.items()
            if children and (now - children[0].emitted_at) > self.deadline_s
        ]
        for k in expired:
            self.orphans.extend(self._pending.pop(k))

    def finalize(self) -> None:
        """At shutdown, any still-pending child is an unresolved parentage:
        quarantine it rather than letting a query-time join reparent it."""
        for key, children in self._pending.items():
            trace_id, parent_id = key
            for child in children:
                if child.trace_id != trace_id:
                    raise UnresolvedParentError(
                        f"cross-trace parentage: child {child.span_id} "
                        f"in trace {child.trace_id} references parent "
                        f"{parent_id} in trace {trace_id}"
                    )
            self.orphans.extend(children)
        self._pending.clear()

    def assert_no_cross_trace_join(self, child: Span, resolved_parent: Span) -> None:
        if child.trace_id != resolved_parent.trace_id:
            raise UnresolvedParentError(
                f"refusing to join child {child.span_id} (trace {child.trace_id}) "
                f"to parent {resolved_parent.span_id} (trace {resolved_parent.trace_id}); "
                f"same-ID collision across traces"
            )
