# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-orphaned-spans-when-a-sub-agent-s-trace-context-is-reparented-by-an-async-tool-call-dag.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-orphaned-spans-when-a-sub-agent-s-trace-context-is-reparented-by-an-async-tool-call-dag.warrant.json
# Markdown SHA-256:   03c0d69afa684816c9dd8c01a17ce765c409077643ae49944024283ec0fb931e
# Code AST SHA-256:   e4da1824ef13cede2ef51fab399f29bc47fce0a9be64802fa56d1886ba76fc76
# Verified Classes:   TraceTopologyFault, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceTopologyFault(RuntimeError):
    """Raised when a reconstructed span DAG violates causal-provenance ordering."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    start_time: float
    end_time: float
    attrs: dict


def validate_provenance(spans: dict[str, Span]) -> None:
    """
    Reject traces where a span's recorded effect (a provenance attribute
    naming a child tool/worker) precedes the child's ancestry routing
    through that span. This is the reparenting signature: the parent
    claims the child, but the child's parent pointer points elsewhere.
    """
    for sid, span in spans.items():
        # Provenance cross-reference: does this span claim to have invoked a tool?
        claimed_child = span.attrs.get("tool.invoked")
        if claimed_child is None:
            continue

        # Find the span that actually owns that tool's causal ancestry.
        child = next(
            (s for s in spans.values()
             if s.attrs.get("tool.name") == claimed_child),
            None,
        )
        if child is None:
            continue  # child not yet collected; out-of-order join, not a fault

        # If the child's ancestry routes through this span, topology is sound.
        if child.parent_span_id == sid:
            continue

        # Otherwise: parent claims the child, but the child is parented
        # elsewhere. If the parent also terminated strictly before the
        # child began, the claim is causally impossible -> reparenting.
        if span.end_time < child.start_time:
            raise TraceTopologyFault(
                f"Span {sid} claims tool '{claimed_child}' (worker "
                f"{span.attrs.get('tool.worker_id')}) but child {child.span_id} "
                f"is parented to {child.parent_span_id}, not {sid}; "
                f"parent ended at {span.end_time} before child began at "
                f"{child.start_time}. Trace context was reparented during "
                f"async dispatch. Quarantine trace; do not attribute "
                f"child cost to parent."
            )


def reconstruct_and_gate(raw_spans: list[Span]) -> dict[str, Span]:
    spans = {s.span_id: s for s in raw_spans}
    # Standard out-of-order join: drop children whose parent is absent
    # only AFTER the provenance gate, so reparented spans are not silently
    # discarded as orphans.
    validate_provenance(spans)
    return spans
