# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-scoped-memory-forget-as-non-durable-until-the-tombstone-is-replayed-against-the-backing-store.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-scoped-memory-forget-as-non-durable-until-the-tombstone-is-replayed-against-the-backing-store.warrant.json
# Markdown SHA-256:   60d23c1ddfb9e6d43c79d211eef563c206ee9a47e9684649f1265b442bf18eed
# Code AST SHA-256:   1a8a943d1dd75bd8de6d984d411abfb9699a3c93c49dcf88cdc627cd9526dc35
# Verified Classes:   DeletionNotDurableError, DeletionIntent, MemoryTool
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class DeletionNotDurableError(RuntimeError):
    """Raised when a scoped forget cannot be confirmed durable against the write log."""


@dataclass
class DeletionIntent:
    scope: str
    key: str
    expected_version: int
    issued_at: float
    confirmed_offset: int | None = None


@dataclass
class MemoryTool:
    # Simulated backing store: last write offset per (scope, key)
    write_offsets: dict[tuple[str, str], int] = field(default_factory=dict)
    tombstone_offsets: dict[str, int] = field(default_factory=dict)
    _next_offset: int = 100

    def forget(self, scope: str, key: str, expected_version: int) -> dict:
        # Tombstone lands on an independent channel; may lag the write log.
        tid = f"t-{self._next_offset}"
        self.tombstone_offsets[tid] = self._next_offset
        self._next_offset += 1
        return {"ok": True, "tombstone_id": tid, "durable": False}


def forget_durably(tool: MemoryTool, intent: DeletionIntent, deadline_s: float = 1.0) -> DeletionIntent:
    """Re-issue forget until the tombstone offset is ordered after the last write.

    Raises DeletionNotDurableError if the tombstone channel cannot be shown to
    cover the write it is meant to delete, so the caller never advances past a
    provisional deletion.
    """
    start = time.monotonic()
    last_write = tool.write_offsets.get((intent.scope, intent.key), -1)

    while time.monotonic() - start < deadline_s:
        resp = tool.forget(intent.scope, intent.key, intent.expected_version)
        tomb_offset = tool.tombstone_offsets[resp["tombstone_id"]]

        # Invariant: tombstone must be ordered AFTER the write it deletes.
        if tomb_offset > last_write:
            intent.confirmed_offset = tomb_offset
            return intent

        # Tombstone landed on a channel that does not order against writes.
        # Do not treat ok:true as terminal; retry within the deadline.
        time.sleep(0.05)

    raise DeletionNotDurableError(
        f"forget for {intent.scope}/{intent.key} (v={intent.expected_version}) "
        f"could not be confirmed durable: tombstone channel is not ordered "
        f"against write offset {last_write}. Treat deletion as PROVISIONAL; "
        f"carry intent in checkpoint and re-issue before any read of scope."
    )
