# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-forget-that-arrives-mid-derivation-erasure-tombstone-ordering-against-in-flight-retrieval-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-forget-that-arrives-mid-derivation-erasure-tombstone-ordering-against-in-flight-retrieval-fan-out.warrant.json
# Markdown SHA-256:   52ab9b5fc445da19ede4acf3502ad6e4b73145289c4da343d7aff1cb9bec345d
# Code AST SHA-256:   2fa2d93a69694cdffdb08873c6207a2e3551bae3ae7bc1158dc79e0542fef0d4
# Verified Classes:   ErasedProjectionError, EraseEpochLeak, Projection, EraseEpoch, ScopedMemory
# Defensive Guards:   10 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import Iterable


class ErasedProjectionError(RuntimeError):
    """Raised when a read would surface a projection quarantined by an active erase-epoch."""


class EraseEpochLeak(RuntimeError):
    """Raised when an epoch outlives its TTL without retirement (availability hazard)."""


@dataclass
class Projection:
    key: str
    scope: str
    provenance: frozenset[str]
    body: str
    written_epoch: int = 0


@dataclass
class EraseEpoch:
    epoch_id: int
    tombstoned_ids: frozenset[str]
    ttl_ticks: int
    ticks_elapsed: int = 0
    retired: bool = False

    def intersects(self, prov: Iterable[str]) -> bool:
        return bool(self.tombstoned_ids & frozenset(prov))


class ScopedMemory:
    def __init__(self) -> None:
        self._records: dict[str, str] = {}
        self._projections: dict[str, Projection] = {}
        self._epochs: dict[int, EraseEpoch] = {}
        self._next_epoch = 1

    # --- read path (must apply tombstone filter even on fast get-by-id) ---
    def read(self, key: str) -> str:
        for ep in self._epochs.values():
            if not ep.retired and key in ep.tombstoned_ids:
                raise ErasedProjectionError(f"record {key} erased under epoch {ep.epoch_id}")
        if key not in self._records:
            raise KeyError(key)
        return self._records[key]

    def read_projection(self, key: str) -> str:
        proj = self._projections.get(key)
        if proj is None:
            raise KeyError(key)
        for ep in self._epochs.values():
            if not ep.retired and ep.intersects(proj.provenance):
                raise ErasedProjectionError(
                    f"projection {key} quarantined by epoch {ep.epoch_id}; "
                    f"provenance intersects tombstoned ids"
                )
        return proj.body

    # --- write path for derived artifacts (must observe active epochs) ---
    def write_projection(self, key: str, scope: str, provenance: Iterable[str], body: str) -> None:
        prov = frozenset(provenance)
        for ep in self._epochs.values():
            if not ep.retired and ep.intersects(prov):
                raise ErasedProjectionError(
                    f"refusing derived write {key}: provenance intersects epoch {ep.epoch_id}"
                )
        self._projections[key] = Projection(key, scope, prov, body)

    # --- forget with epoch fencing ---
    def forget(self, scope: str, target_ids: Iterable[str], ttl_ticks: int = 30) -> int:
        ids = frozenset(target_ids)
        if not ids:
            return 0
        ep = EraseEpoch(self._next_epoch, ids, ttl_ticks)
        self._epochs[ep.epoch_id] = ep
        self._next_epoch += 1
        # tombstone the source of truth
        for rid in ids:
            self._records.pop(rid, None)
        # transitive quarantine of already-written derived projections
        for key, proj in list(self._projections.items()):
            if ep.intersects(proj.provenance):
                proj.written_epoch = ep.epoch_id  # quarantined; unreadable via read_projection
        return ep.epoch_id

    def tick(self) -> None:
        for ep in self._epochs.values():
            if ep.retired:
                continue
            ep.ticks_elapsed += 1
            if ep.ticks_elapsed > ep.ttl_ticks:
                raise EraseEpochLeak(
                    f"epoch {ep.epoch_id} exceeded TTL {ep.ttl_ticks} without retirement; "
                    f"derived scopes remain unreadable"
                )

    def retire_epoch(self, epoch_id: int) -> None:
        ep = self._epochs.get(epoch_id)
        if ep is None:
            raise KeyError(epoch_id)
        ep.retired = True
        for key in [k for k, p in self._projections.items() if p.written_epoch == epoch_id]:
            del self._projections[key]  # physical deletion on retirement


def verify_erasure(mem: ScopedMemory, projection_key: str, source_key: str) -> None:
    """Post-erase verification must distinguish source-erase success from projection survival."""
    try:
        mem.read(source_key)
    except ErasedProjectionError:
        pass
    else:
        raise ErasedProjectionError(f"source {source_key} still readable; erase failed at source")
    try:
        mem.read_projection(projection_key)
    except ErasedProjectionError:
        # quarantined, not necessarily failed — caller must check epoch retirement
        raise
    else:
        raise ErasedProjectionError(
            f"derived projection {projection_key} survives erase with no active epoch; "
            f"orphan summary leaked past forget()"
        )
