# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-retrieval-fidelity-when-a-parent-agent-s-compaction-rewrites-the-memory-keys-its-subagents-were-pinned-to.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-retrieval-fidelity-when-a-parent-agent-s-compaction-rewrites-the-memory-keys-its-subagents-were-pinned-to.warrant.json
# Markdown SHA-256:   68aa99b2fdc444e5e1924beeedff4142d9a035ef8e6a9d729761cc325f3f7526
# Code AST SHA-256:   9402fb31532db1443b9c37dc8d694c3d5af8381e38b5c6d0a231d1467c8d7820
# Verified Classes:   StaleHandleError, SilentCollisionError, Handle, Chunk, EpochGuardedStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleHandleError(RuntimeError):
    """Raised when a subagent dereferences a memory handle from a prior compaction epoch."""
    pass


class SilentCollisionError(RuntimeError):
    """Raised when a handle slot has been reused for semantically unrelated content."""
    pass


@dataclass(frozen=True)
class Handle:
    epoch: int
    chunk_id: str
    content_hash: str


@dataclass
class Chunk:
    epoch: int
    chunk_id: str
    content_hash: str
    text: str
    tombstone_target: Optional[str] = None  # set when merged into a summary chunk


class EpochGuardedStore:
    def __init__(self) -> None:
        self.current_epoch = 0
        self._chunks: dict[tuple[int, str], Chunk] = {}

    def put(self, chunk_id: str, text: str, content_hash: str) -> Handle:
        key = (self.current_epoch, chunk_id)
        self._chunks[key] = Chunk(self.current_epoch, chunk_id, content_hash, text)
        return Handle(self.current_epoch, chunk_id, content_hash)

    def compact(self, merges: dict[str, str]) -> None:
        """merges maps source_id -> target_id. Originals become tombstones; slots are NOT reused."""
        for src, tgt in merges.items():
            key = (self.current_epoch, src)
            if key in self._chunks:
                self._chunks[key].tombstone_target = tgt
        self.current_epoch += 1  # flip epoch AFTER tombstones are written

    def dereference(self, handle: Handle) -> Chunk:
        if handle.epoch != self.current_epoch:
            # Hard stop: never best-effort a cross-epoch read.
            raise StaleHandleError(
                f"handle {handle.chunk_id} pinned at epoch {handle.epoch}, "
                f"store is at epoch {self.current_epoch}; re-ground from current epoch"
            )
        chunk = self._chunks.get((handle.epoch, handle.chunk_id))
        if chunk is None:
            raise StaleHandleError(f"handle {handle.chunk_id} absent at epoch {handle.epoch}")
        if chunk.content_hash != handle.content_hash:
            # Same slot, different content => slot was illegally reused.
            raise SilentCollisionError(
                f"slot {handle.chunk_id} rebound: expected hash {handle.content_hash}, "
                f"found {chunk.content_hash}"
            )
        if chunk.tombstone_target is not None:
            raise StaleHandleError(
                f"handle {handle.chunk_id} was merged into {chunk.tombstone_target}; "
                f"re-retrieve via tombstone target"
            )
        return chunk


def resume_subagent_read(store: EpochGuardedStore, pinned: Handle) -> str:
    """Called when a subagent resumes after a possible parent compaction."""
    try:
        return store.dereference(pinned).text
    except StaleHandleError as e:
        # Correct behavior: re-ground from current epoch, do not trust the old read.
        raise StaleHandleError(f"subagent must re-ground: {e}") from e
    except SilentCollisionError as e:
        raise SilentCollisionError(f"grounding corrupted, abort synthesis: {e}") from e
