# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-scoped-forget-tombstone-and-a-concurrent-episodic-write-race-across-the-retention-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-scoped-forget-tombstone-and-a-concurrent-episodic-write-race-across-the-retention-horizon.warrant.json
# Markdown SHA-256:   add0275906f725522ca0e4d4d2c1bd9bf5ef72bcb4d725e27cd0b0cd84c4ae17
# Code AST SHA-256:   1d961422c1e655a07cac5f26991ca355b2e13bddc1155812f92cef9d03382701
# Verified Classes:   StaleSnapshotResurrection, TombstoneCollision, WriteIntent, ScopeState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleSnapshotResurrection(RuntimeError):
    """Raised when a write whose read-snapshot predates the scope fence
    would commit content that a forget() certified as deleted."""


class TombstoneCollision(RuntimeError):
    """Raised when a write targets a key carrying an active tombstone."""


@dataclass
class WriteIntent:
    key: str
    scope: str
    content: str
    snapshot_epoch: int


@dataclass
class ScopeState:
    scope_fence: int = 0          # monotonic; bumped by forget()
    tombstoned_keys: frozenset = frozenset()
    tombstoned_hashes: frozenset = frozenset()


def commit_write(intent: WriteIntent, state: ScopeState, content_hash: str) -> None:
    # Primary invariant: causal ordering across the scope, not the key.
    if intent.snapshot_epoch < state.scope_fence:
        raise StaleSnapshotResurrection(
            f"write to {intent.scope}/{intent.key} carries snapshot_epoch "
            f"{intent.snapshot_epoch} < scope_fence {state.scope_fence}; "
            f"re-derive from a post-fence read before committing"
        )

    # Secondary: key and content-hash tombstones.
    if intent.key in state.tombstoned_keys:
        raise TombstoneCollision(
            f"key {intent.key} in {intent.scope} is tombstoned"
        )
    if content_hash in state.tombstoned_hashes:
        raise TombstoneCollision(
            f"content hash {content_hash} matches a tombstone in {intent.scope}"
        )

    # Safe commit path (persist omitted for brevity).
    return None


def forget(scope: str, key: str, content_hash: str, state: ScopeState) -> ScopeState:
    # Bump the fence: every in-flight write with an older snapshot is now stale.
    return ScopeState(
        scope_fence=state.scope_fence + 1,
        tombstoned_keys=state.tombstoned_keys | {key},
        tombstoned_hashes=state.tombstoned_hashes | {content_hash},
    )


# --- Failure trace reproduction ---
state = ScopeState(scope_fence=0)

# Distillation worker reads at epoch 0, before any forget.
stale_intent = WriteIntent(
    key="sem:acct_4471_summary",
    scope="user:semantic",
    content="account acct_4471 requested closure",
    snapshot_epoch=0,
)

# User deletion request lands and forget() bumps the fence.
state = forget(
    scope="user:semantic",
    key="PII:acct_4471",
    content_hash="sha256:deadbeef",
    state=state,
)

# The stale write now attempts to commit a fresh key with old content.
commit_write(stale_intent, state, content_hash="sha256:cafef00d")
# -> StaleSnapshotResurrection: snapshot_epoch 0 < scope_fence 1
