# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-provenance-quarantine-when-a-forget-operation-races-a-concurrent-write-on-the-same-memory-key.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-provenance-quarantine-when-a-forget-operation-races-a-concurrent-write-on-the-same-memory-key.warrant.json
# Markdown SHA-256:   8bed39bc14f0bc1d99e65204eddcdacf35dc9707002b80409e9c72aa369be012
# Code AST SHA-256:   1cf0b7248399e5be4afe07604cc04ca54a3d6d8bc439ca6d3016c16f3abfe485
# Verified Classes:   ProvenanceQuarantineError, Tombstone, Store
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ProvenanceQuarantineError(RuntimeError):
    """Raised when a write carries a provenance generation at or below the
    forgotten generation for its key, i.e. it would resurrect a forgotten
    (possibly tainted) memory. The write is quarantined, not dropped."""
    pass


@dataclass
class Tombstone:
    forgotten_gen: int
    reason: str
    at: float


@dataclass
class Store:
    records: dict = field(default_factory=dict)       # key -> payload
    tombstones: dict = field(default_factory=dict)     # key -> Tombstone
    quarantine: list = field(default_factory=list)     # forensic holding area

    def forget(self, key: str, current_gen: int, reason: str) -> None:
        # Bump a durable per-key generation that OUTLIVES the record.
        prior = self.tombstones.get(key)
        new_gen = max(current_gen, prior.forgotten_gen if prior else 0) + 1
        self.tombstones[key] = Tombstone(new_gen, reason, time.time())
        self.records.pop(key, None)

    def write(self, key: str, payload: dict, provenance_gen: int) -> None:
        tomb = self.tombstones.get(key)
        if tomb is not None and provenance_gen <= tomb.forgotten_gen:
            # Order-independent guard: a write constructed before the forget
            # cannot land after it, regardless of flush timing.
            self.quarantine.append(
                {"key": key, "gen": provenance_gen,
                 "forgotten_gen": tomb.forgotten_gen, "payload": payload}
            )
            raise ProvenanceQuarantineError(
                f"write to {key!r} carries gen {provenance_gen} <= "
                f"forgotten gen {tomb.forgotten_gen}; quarantined as "
                f"resurrection of forgotten memory ({tomb.reason})"
            )
        self.records[key] = payload


def demo_race() -> None:
    s = Store()
    s.records["K"] = {"text": "poisoned", "taint": True}
    # Retrieval pass R1 constructs a pending write at gen 7.
    pending_gen = 7
    # Auditor forgets K, tombstoning gen 8.
    s.forget("K", current_gen=7, reason="source-allowlist-fail")
    # The stale write flushes late; guard must fire.
    s.write("K", {"text": "poisoned", "taint": False}, provenance_gen=pending_gen)


if __name__ == "__main__":
    demo_race()
