# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-forget-before-write-when-a-scoped-retention-policy-collides-with-an-in-flight-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-forget-before-write-when-a-scoped-retention-policy-collides-with-an-in-flight-tool-call.warrant.json
# Markdown SHA-256:   6decfac001d2a577237e43f341a79fe6732a1c44a10359c1a54cd73bf74b5d47
# Code AST SHA-256:   8d278d61124623e56457400334f3c4bbf416c8405d63ec8c3bb821e18fd09544
# Verified Classes:   ErasureConflict, WriteRequest, ScopedMemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Optional
import time


class ErasureConflict(RuntimeError):
    """Raised when a write would resurrect data erased by a prior forget."""
    pass


@dataclass
class WriteRequest:
    scope: str
    subject: str
    key: str
    value: str
    source_epochs: Set[int]          # read-epochs of every record this write derives from
    derived_from: Set[str] = field(default_factory=set)  # source keys, for lineage closure


class ScopedMemoryStore:
    def __init__(self) -> None:
        self._data: Dict[str, Dict[str, str]] = {}          # scope -> key -> value
        self._key_subject: Dict[str, Dict[str, str]] = {}   # scope -> key -> subject
        self._forget_epoch: Dict[str, int] = {}             # f"{scope}|{subject}" -> epoch
        self._epoch_counter: int = 0

    def _mint_epoch(self) -> int:
        self._epoch_counter += 1
        return self._epoch_counter

    def read(self, scope: str, subject: str, key: str) -> tuple[str, int]:
        subj_key = f"{scope}|{subject}"
        if subj_key in self._forget_epoch and key in self._data.get(scope, {}):
            # subject is under erasure barrier; reads of surviving keys are epoch-tagged
            pass
        epoch = self._mint_epoch()
        return self._data.get(scope, {})[key], epoch

    def write(self, req: WriteRequest) -> None:
        subj_key = f"{req.scope}|{req.subject}"
        watermark = self._forget_epoch.get(subj_key, 0)

        # Invariant: no write whose causal read predates a committed forget may commit.
        if req.source_epochs and min(req.source_epochs) < watermark:
            raise ErasureConflict(
                f"write to {req.scope}/{req.key} for subject {req.subject} "
                f"sourced from epoch {min(req.source_epochs)} which predates "
                f"forget watermark {watermark}; resurrection refused"
            )

        # Derived-closure check: any source key that was erased under this subject
        # taints the write even if the literal target key is new.
        for src in req.derived_from:
            if self._key_subject.get(req.scope, {}).get(src) == req.subject:
                if self._forget_epoch.get(f"{req.scope}|{req.subject}", 0) > 0:
                    raise ErasureConflict(
                        f"write to {req.scope}/{req.key} derives from erased key {src}; "
                        f"derived-closure resurrection refused"
                    )

        self._data.setdefault(req.scope, {})[req.key] = req.value
        self._key_subject.setdefault(req.scope, {})[req.key] = req.subject

    def forget(self, scope: str, subject: str, drain_epoch: Optional[int] = None) -> int:
        """Erase subject; advance watermark past all in-flight read-epochs."""
        subj_key = f"{scope}|{subject}"
        # Barrier: watermark must exceed every read-epoch the caller knows is in flight.
        self._forget_epoch[subj_key] = max(
            self._forget_epoch.get(subj_key, 0),
            drain_epoch if drain_epoch is not None else self._epoch_counter,
        )
        deleted = 0
        for key, subj in list(self._key_subject.get(scope, {}).items()):
            if subj == subject:
                self._data.get(scope, {}).pop(key, None)
                self._key_subject[scope].pop(key, None)
                deleted += 1
        return deleted


def distill_and_persist(store: ScopedMemoryStore, scope: str, subject: str,
                        raw_key: str, distilled_key: str) -> None:
    raw_value, read_epoch = store.read(scope, subject, raw_key)
    # Simulate a multi-step loop whose write commits after a concurrent forget.
    time.sleep(0.05)
    store.write(WriteRequest(
        scope=scope,
        subject=subject,
        key=distilled_key,
        value=f"distilled:{raw_value[:32]}",
        source_epochs={read_epoch},
        derived_from={raw_key},
    ))
