# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-trace-splice-forgery-in-post-hoc-incident-replay-when-the-observability-pipeline-correlates-traces-evals-and-incident-repl.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-trace-splice-forgery-in-post-hoc-incident-replay-when-the-observability-pipeline-correlates-traces-evals-and-incident-repl.warrant.json
# Markdown SHA-256:   85ebf1c0afc88c17e688e9b6ae44d6fce4ea6ceb097a508c221f887c37bf39f8
# Code AST SHA-256:   d26cee196fdd26602d83d5f1e7825756ee37740ac49111cfa5af225e2ea43681
# Verified Classes:   EpochSpliceError, Record
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class EpochSpliceError(RuntimeError):
    """Raised when a join would bind records from two execution epochs."""


@dataclass(frozen=True)
class Record:
    incident_id: str
    span_id: str
    epoch: int
    source: str  # "trace" | "eval" | "replay"
    payload: dict


def assert_epoch_coherent(records: Iterable[Record]) -> None:
    """
    Pre-join guard. For every (incident_id, span_id) key, all records
    must share a single epoch. Any key with >1 epoch is a splice candidate
    and must be quarantined, not rendered.
    """
    by_key: dict[tuple[str, str], set[int]] = {}
    for r in records:
        key = (r.incident_id, r.span_id)
        by_key.setdefault(key, set()).add(r.epoch)

    spliced = {k: sorted(v) for k, v in by_key.items() if len(v) > 1}
    if spliced:
        # Fail closed: do not emit a best-effort timeline.
        detail = "; ".join(
            f"{incident}/{span} seen in epochs {epochs}"
            for (incident, span), epochs in spliced.items()
        )
        raise EpochSpliceError(
            f"epoch splice detected across {len(spliced)} span key(s): {detail}. "
            f"Re-derive incident from source before rendering."
        )


def render_incident(records: list[Record]) -> dict:
    assert_epoch_coherent(records)  # must run before any join/render
    # Only reached if every span key is single-epoch.
    return {"spans": len({(r.incident_id, r.span_id) for r in records})}
