# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-reconstructed-causal-edge-as-untrusted-attribution-collapse-from-clock-skewed-span-joins-in-multi-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-reconstructed-causal-edge-as-untrusted-attribution-collapse-from-clock-skewed-span-joins-in-multi-agent-traces.warrant.json
# Markdown SHA-256:   e1145216ddfebc293395f5e9a2f66c117040fd3892185c37b4297c507808ea02
# Code AST SHA-256:   dfa274811bbb272e1816000f12a0f8cc5e0fb8b4ea3c015198609cfabf787e44
# Verified Classes:   CausalAttributionError, Span, DropRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalAttributionError(RuntimeError):
    """Raised when an anomaly would be attributed across an untrustworthy edge."""


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    start_ns: int
    end_ns: int


@dataclass
class DropRecord:
    trace_id: str
    dropped_span_id: str


SKEW_TOLERANCE_NS = 50_000_000  # 50 ms


def reconstruct_edge(
    child: Span,
    candidates: list[Span],
    drop_records: list[DropRecord],
) -> Span:
    """Return the corroborated parent for `child`, or raise if the edge is untrusted.

    Enforces: unique temporal enclosure, monotonic containment (parent.end >= child.start),
    and a known drop record for the missing declared parent. Refuses otherwise.
    """
    if child.parent_span_id is None:
        raise CausalAttributionError(
            f"span {child.span_id} declares no parent; nothing to reconstruct"
        )

    declared_present = any(s.span_id == child.parent_span_id for s in candidates)
    if declared_present:
        # Recorded edge — always trustworthy, no reconstruction needed.
        return next(s for s in candidates if s.span_id == child.parent_span_id)

    enclosing = [
        s for s in candidates
        if s.trace_id == child.trace_id
        and s.start_ns <= child.start_ns
        and child.end_ns <= s.end_ns
        and s.end_ns >= child.start_ns  # monotonicity: no negative causal latency
    ]

    if len(enclosing) != 1:
        raise CausalAttributionError(
            f"span {child.span_id}: enclosure non-unique ({len(enclosing)} candidates); "
            "fan-out ambiguity — refusing to reconstruct edge"
        )

    parent = enclosing[0]

    if parent.end_ns < child.start_ns:
        raise CausalAttributionError(
            f"span {child.span_id}: parent {parent.span_id} ends "
            f"{(child.start_ns - parent.end_ns) / 1e6:.1f} ms before child starts; "
            "negative causal latency"
        )

    has_drop = any(
        d.trace_id == child.trace_id and d.dropped_span_id == child.parent_span_id
        for d in drop_records
    )
    if not has_drop:
        raise CausalAttributionError(
            f"span {child.span_id}: declared parent {child.parent_span_id} missing "
            "with no drop record; exporter behavior unknown — refusing to reconstruct"
        )

    return parent  # inferred_corroborated_by_drop_record
