# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-ttl-expiry-against-audit-log-durability-when-a-scoped-forget-call-races-a-concurrent-read-modify-write-on-the-same-me.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-ttl-expiry-against-audit-log-durability-when-a-scoped-forget-call-races-a-concurrent-read-modify-write-on-the-same-me.warrant.json
# Markdown SHA-256:   0cf2c55d82c88529c9cd23122db124a9616ee4fecf9add4c56a6aabafef38127
# Code AST SHA-256:   d6e3d5f77138dba34f55a0b8aee88b58ef93637f436c0bbdaed06c16a17f766c
# Verified Classes:   MemoryBoundaryError, ForgetOutcome, ForgetVerdict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class MemoryBoundaryError(RuntimeError):
    """Raised when a scoped forget/read/write sequence violates a continuity invariant."""


class ForgetOutcome(Enum):
    DURABLE = "durable"            # forget OK, tombstone verified, read returns MISS
    GAP = "gap"                    # forget NOT_FOUND, no tombstone -> deletion unproven
    RESURRECTED = "resurrected"    # forget OK but read returns live gen -> fencing broken


@dataclass(frozen=True)
class ForgetVerdict:
    outcome: ForgetOutcome
    generation: int
    audit_seq: int | None
    detail: str


def forget_and_verify(
    api,
    key: str,
    *,
    read_start_seq: int,
    require_tombstone: bool = True,
) -> ForgetVerdict:
    """
    Execute forget, then verify durability against the audit log and read path.

    `api` must expose:
      - read(key) -> (value, generation, expires_at) | None
      - forget(key) -> {"status": "OK"|"NOT_FOUND", "generation": int, "audit_seq": int|None}
      - audit_query(key, since_seq) -> list[{"audit_seq": int, "generation": int, "op": str}]
    """
    pre = api.read(key)
    if pre is None:
        # Key already absent before forget: only a tombstone can prove intent.
        pre_gen = -1
    else:
        _, pre_gen, _ = pre

    result = api.forget(key)
    status = result["status"]
    gen = result["generation"]
    seq = result.get("audit_seq")

    if status == "NOT_FOUND":
        tombstones = [
            e for e in api.audit_query(key, since_seq=read_start_seq)
            if e["op"] == "forget_tombstone" and e["generation"] >= pre_gen
        ]
        if not tombstones and require_tombstone:
            return ForgetVerdict(
                ForgetOutcome.GAP, pre_gen, None,
                "forget returned NOT_FOUND with no tombstone; deletion unproven",
            )
        return ForgetVerdict(
            ForgetOutcome.DURABLE, pre_gen,
            tombstones[0]["audit_seq"] if tombstones else None,
            "expired-key tombstone present" if tombstones else "no tombstone required",
        )

    if status != "OK":
        raise MemoryBoundaryError(f"unexpected forget status {status!r} for key={key!r}")

    # Verify: read must not return the forgotten generation.
    post = api.read(key)
    if post is not None:
        _, post_gen, _ = post
        if post_gen == gen:
            return ForgetVerdict(
                ForgetOutcome.RESURRECTED, gen, seq,
                f"read after forget returned live generation {gen}; "
                f"write-path generation fencing is broken",
            )
        if post_gen > gen:
            # A concurrent writer allocated a newer generation. Legitimate only
            # if the audit log shows an explicit recreate entry.
            entries = api.audit_query(key, since_seq=seq or read_start_seq)
            if not any(e["op"] == "recreate" and e["generation"] == post_gen for e in entries):
                raise MemoryBoundaryError(
                    f"generation {post_gen} exists after forget of gen {gen} "
                    f"with no recreate audit entry (key={key!r})"
                )

    # Confirm the tombstone for the forgotten generation is durable.
    if seq is None:
        raise MemoryBoundaryError(
            f"forget returned OK for gen {gen} but no audit_seq (key={key!r})"
        )
    tombs = [
        e for e in api.audit_query(key, since_seq=seq)
        if e["op"] in ("forget", "forget_tombstone") and e["generation"] == gen
    ]
    if not tombs:
        raise MemoryBoundaryError(
            f"forget OK for gen {gen} at seq {seq} but no durable tombstone "
            f"found on replay (key={key!r})"
        )

    return ForgetVerdict(ForgetOutcome.DURABLE, gen, seq, "tombstone verified")
