# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-when-auto-compaction-summarizes-before-the-retrieval-index-is-rebuilt.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-when-auto-compaction-summarizes-before-the-retrieval-index-is-rebuilt.warrant.json
# Markdown SHA-256:   2c71b2bb076474f5f39d32832e4c2772e41040b4947d38f2ded4755615750115
# Code AST SHA-256:   3ded7311792c2dce9389f8af1f7b25e8e74dea03e83e678f11de988334311f82
# Verified Classes:   ProvenanceSeveredError, Chunk, SupersessionRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ProvenanceSeveredError(RuntimeError):
    """Raised when retrieval returns a chunk whose source span was compacted
    without a supersession binding. The agent must reconstitute from the live
    digest rather than trust the orphaned fragment."""
    pass


@dataclass(frozen=True)
class Chunk:
    chunk_id: str
    source_turn_range: tuple[int, int]
    content_hash: str
    lineage_epoch: int


@dataclass(frozen=True)
class SupersessionRecord:
    compacted_range: tuple[int, int]
    digest_chunk_id: str
    epoch: int


def admit_chunk(
    chunk: Chunk,
    current_epoch: int,
    supersessions: dict[tuple[int, int], SupersessionRecord],
    live_chunk_ids: set[str],
) -> Chunk:
    # Fast path: chunk was written in the current lineage epoch.
    if chunk.lineage_epoch == current_epoch:
        return chunk

    # Slow path: chunk predates a compaction. It is admissible ONLY if a
    # supersession record re-binds its source range to a live digest span.
    rec: Optional[SupersessionRecord] = supersessions.get(chunk.source_turn_range)
    if rec is not None and rec.digest_chunk_id in live_chunk_ids:
        return chunk

    # Otherwise the chunk's source was compacted and the digest does not
    # cover it. Serving it would hand the agent a fragment whose provenance
    # was severed at compaction time. Fail loud.
    raise ProvenanceSeveredError(
        f"chunk {chunk.chunk_id} (turns {chunk.source_turn_range}, "
        f"epoch {chunk.lineage_epoch}) has no live supersession binding at "
        f"epoch {current_epoch}; reconstitute from digest, do not trust fragment"
    )
