# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-retention-boundary-has-been-silently-violated-by-a-write-then-forget-race-in-agent-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-retention-boundary-has-been-silently-violated-by-a-write-then-forget-race-in-agent-memory-tool-apis.warrant.json
# Markdown SHA-256:   426d19ef590baff7c09da141387f961aeae756db4a02cb3c45024fb198cb0264
# Code AST SHA-256:   98a90b0134e09875082056b724bd25665bceb59bf6f59e529994c58897b530a1
# Verified Classes:   RetentionBoundaryViolation, MemoryRecord, ScopedMemoryClient
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RetentionBoundaryViolation(RuntimeError):
    """Raised when a read under a forgotten scope returns a live record."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    scope: list
    created_at: int
    version: int
    tombstone_applied_at: Optional[int] = None


@dataclass
class ScopedMemoryClient:
    _store: dict = field(default_factory=dict)

    def write(self, record_id: str, scope: list, body: str, now: int) -> MemoryRecord:
        rec = MemoryRecord(record_id=record_id, scope=list(scope),
                           created_at=now, version=len(self._store) + 1)
        self._store[record_id] = rec
        return rec

    def forget(self, scope_tag: str, known_ids: list, now: int) -> int:
        # Snapshot-scan tombstone: only touches IDs the caller knows about.
        # A retry-duplicate with the same scope tag but a new ID survives.
        n = 0
        for rid in known_ids:
            rec = self._store.get(rid)
            if rec and scope_tag in rec.scope and rec.tombstone_applied_at is None:
                rec.tombstone_applied_at = now
                n += 1
        return n

    def read(self, scope_tag: str) -> list:
        return [r for r in self._store.values()
                if scope_tag in r.scope and r.tombstone_applied_at is None]


def forget_and_verify(client: ScopedMemoryClient, scope_tag: str,
                      known_ids: list, now: int, max_rounds: int = 3) -> None:
    """Forget a scope and assert emptiness. Raises if survivors persist."""
    for round_no in range(max_rounds):
        client.forget(scope_tag, known_ids, now + round_no)
        survivors = client.read(scope_tag)
        if not survivors:
            return
        # Widen the ID set to the survivors and retry: the survivors are
        # precisely the records the caller did not know about.
        known_ids = [r.record_id for r in survivors]
    survivors = client.read(scope_tag)
    if survivors:
        raise RetentionBoundaryViolation(
            f"scope {scope_tag!r} still live after {max_rounds} forget rounds: "
            f"{[(r.record_id, r.version, r.scope) for r in survivors]}"
        )
