# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-span-linked-trajectory-replay-as-invalid-when-tool-selection-drift-is-inferred-from-a-replayed-span-whose-par.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-span-linked-trajectory-replay-as-invalid-when-tool-selection-drift-is-inferred-from-a-replayed-span-whose-par.warrant.json
# Markdown SHA-256:   ac2513eae13dfe9e2a39fc6afadbe0dc8f5d15b758e8fca485db66f78ee67c4a
# Code AST SHA-256:   272e0e98db5adab46f654a5113344222835e0436d71ffd50d1853d485b86c440
# Verified Classes:   InadmissibleTrajectoryError, Span
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class InadmissibleTrajectoryError(RuntimeError):
    """Raised when a replayed trajectory cannot be used as drift evidence."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    trace_id: str
    tool_name: Optional[str]
    sampling_epoch: int
    retry_attempt: int
    start_time: float
    end_time: float
    resolved: bool


def assert_replayable_as_evidence(spans: list[Span]) -> None:
    """
    Gate a reconstructed trajectory before it is fed to a tool-selection
    drift detector. Raises InadmissibleTrajectoryError on any violation.
    """
    if not spans:
        raise InadmissibleTrajectoryError("empty trajectory")

    trace_ids = {s.trace_id for s in spans}
    if len(trace_ids) != 1:
        raise InadmissibleTrajectoryError(
            f"trajectory spans multiple trace_ids: {trace_ids}"
        )

    epochs = {s.sampling_epoch for s in spans}
    if len(epochs) != 1:
        raise InadmissibleTrajectoryError(
            f"mixed sampling epochs {epochs}: parent re-emitted under a "
            f"different sampling decision; replay is not admissible"
        )

    unresolved = [s.span_id for s in spans if not s.resolved]
    if unresolved:
        raise InadmissibleTrajectoryError(
            f"unresolved parent links for spans {unresolved}: replayer applied "
            f"link repair; trajectory is contaminated"
        )

    by_parent: dict[str, list[Span]] = {}
    for s in spans:
        if s.parent_span_id is not None:
            by_parent.setdefault(s.parent_span_id, []).append(s)

    for parent_id, children in by_parent.items():
        attempts = {c.retry_attempt for c in children}
        if len(attempts) > 1:
            raise InadmissibleTrajectoryError(
                f"children of {parent_id} span multiple retry attempts "
                f"{attempts}: attempts must be segmented before drift scoring"
            )

    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.parent_span_id and s.parent_span_id in by_id:
            p = by_id[s.parent_span_id]
            if s.start_time < p.start_time or s.end_time > p.end_time:
                raise InadmissibleTrajectoryError(
                    f"span {s.span_id} interval [{s.start_time},{s.end_time}] "
                    f"violates parent {p.span_id} interval "
                    f"[{p.start_time},{p.end_time}]: child belongs to a "
                    f"different parent generation"
                )
