# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-decayed-memory-reads-against-provenance-tagged-writes-before-the-forget-tool-s-auditable-deletion-tombstone-commits.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-decayed-memory-reads-against-provenance-tagged-writes-before-the-forget-tool-s-auditable-deletion-tombstone-commits.warrant.json
# Markdown SHA-256:   64bd954463877c25907a7362e298d7f0e18b9d82e792783b11edb06032ba0504
# Code AST SHA-256:   7d845062efd214479f19952493e494d3b4c9eb20a5fa22e66d8bd53fcdbf908d
# Verified Classes:   MemorySkewError, ReadPath, RecordView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class MemorySkewError(RuntimeError):
    """Raised when a forget tombstone would be applied to a version the
    instance did not actually read. Signals read/write skew across decay."""


class ReadPath(Enum):
    PERSISTING = "persisting"   # recomputes and stores decay weight
    PREVIEW = "preview"         # evaluates without mutating decay index


@dataclass(frozen=True)
class RecordView:
    key: str
    value: str
    weight: float
    write_epoch: int
    provenance: str


def plan_forget(
    observed: RecordView,
    current: RecordView,
    action_threshold: float,
    read_path: ReadPath,
) -> str:
    """Decide between forget-and-replace and write-over.

    The invariant: a forget may only be issued against the exact
    (key, write_epoch, provenance) triple that was read. If the current
    version has drifted, the instance must NOT forget.
    """
    if read_path is ReadPath.PERSISTING:
        # The staleness probe itself mutated the decay index; any concurrent
        # reader now sees a weight this instance caused. Refuse to act.
        raise MemorySkewError(
            f"staleness probe on {observed.key} used persisting read path; "
            "probe mutated decay index and cannot be trusted as an observation"
        )

    if observed.weight >= action_threshold:
        return "no_action"

    # Version pin: the triple observed must still be current.
    if (
        current.write_epoch != observed.write_epoch
        or current.provenance != observed.provenance
    ):
        # A concurrent provenance-tagged write landed between read and forget.
        # Key-scoped forget would destroy it. Degrade to write-over.
        raise MemorySkewError(
            f"forget precondition failed on {observed.key}: "
            f"observed epoch {observed.write_epoch}/{observed.provenance}, "
            f"current epoch {current.write_epoch}/{current.provenance}; "
            "must re-read and supersede by write, not delete"
        )

    return "forget_and_replace"


def execute_forget(
    observed: RecordView,
    current: RecordView,
    action_threshold: float,
    read_path: ReadPath,
    forget_tool,
) -> None:
    decision = plan_forget(observed, current, action_threshold, read_path)
    if decision == "forget_and_replace":
        # Version-scoped forget: pass the epoch so the service can reject
        # a commit-time mismatch rather than applying to the wrong version.
        forget_tool(
            key=observed.key,
            expected_write_epoch=observed.write_epoch,
            expected_provenance=observed.provenance,
        )
    elif decision == "no_action":
        return
    else:  # pragma: no cover - defensive
        raise MemorySkewError(f"unhandled decision {decision!r}")
