# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-causal-replay-sampling-when-high-cardinality-reasoning-traces-alias-across-retry-epochs.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-causal-replay-sampling-when-high-cardinality-reasoning-traces-alias-across-retry-epochs.warrant.json
# Markdown SHA-256:   f4b6beff322f7827933a8c017b3a68d0c445f7a7ff9052a35a9a35e0cb86cc75
# Code AST SHA-256:   1bf428749a7578470f9bb5e09bbd2aaa586ffc3db08040e98bf54263478e4176
# Verified Classes:   ReplayLineageError, Step
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class ReplayLineageError(RuntimeError):
    """Raised when a sampled trajectory mixes steps from distinct retry epochs."""


@dataclass(frozen=True)
class Step:
    trace_id: str
    epoch_id: int
    step_seq: int
    payload: str


def assemble_causal_replay(steps: Iterable[Step]) -> list[Step]:
    """
    Reconstruct a causally ordered replay from sampled steps.

    Invariant: all retained steps must share one (trace_id, epoch_id) lineage.
    Sampling is permitted to drop whole epochs, never to interleave them.
    """
    ordered = sorted(steps, key=lambda s: (s.epoch_id, s.step_seq))
    if not ordered:
        return []

    trace_ids = {s.trace_id for s in ordered}
    if len(trace_ids) != 1:
        raise ReplayLineageError(
            f"replay spans multiple trace_ids: {sorted(trace_ids)}"
        )

    epochs = {s.epoch_id for s in ordered}
    if len(epochs) != 1:
        # This is the aliasing failure: step_seq collides across epochs and the
        # reconstructed timeline would be causally false. Refuse rather than guess.
        raise ReplayLineageError(
            f"trace {ordered[0].trace_id!r} mixes epochs {sorted(epochs)}; "
            "sampler violated epoch-atomicity — drop the whole chain and re-sample"
        )

    seqs = [s.step_seq for s in ordered]
    if seqs != list(range(len(seqs))):
        raise ReplayLineageError(
            f"non-contiguous step_seq within epoch {epochs.pop()}: {seqs}"
        )
    return ordered


def sample_chain_atomically(steps: Iterable[Step], keep: bool) -> list[Step]:
    """All-or-nothing retention at the retry-chain granularity."""
    chain = list(steps)
    if not keep:
        return []
    epochs = {s.epoch_id for s in chain}
    if len(epochs) > 1:
        raise ReplayLineageError(
            "refusing to emit a partially sampled multi-epoch chain; "
            "evict the entire chain instead"
        )
    return chain
