# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-revokes-a-memory-scope-mid-replay-and-the-forget-tool-returns-success-before-the-write-ahead-log-is-truncated.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-revokes-a-memory-scope-mid-replay-and-the-forget-tool-returns-success-before-the-write-ahead-log-is-truncated.warrant.json
# Markdown SHA-256:   808397f8b642abf61dde19755d8f3bab40aaa84a23d06258bd460a7c85572d28
# Code AST SHA-256:   35ed8e57bd2479dae80013c7042fbd7b8d1d7a9a96f42b53bad80270014d09fd
# Verified Classes:   RevocationLeakError, RevocationAuthority, DataPlane
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Optional


class RevocationLeakError(RuntimeError):
    """Raised when a read would observe a scope whose revocation is durable
    in the authority plane but not yet reflected in the data plane."""


@dataclass
class RevocationAuthority:
    # scope -> epoch at which it was revoked. Durable before forget() returns.
    revoked: Dict[str, int] = field(default_factory=dict)

    def revoke(self, scope: str, epoch: int) -> None:
        self.revoked[scope] = epoch

    def current_epoch(self, scope: str) -> Optional[int]:
        return self.revoked.get(scope)


@dataclass
class DataPlane:
    # scope -> {key: value}; rebuilt by forward WAL replay on recovery.
    index: Dict[str, Dict[str, str]] = field(default_factory=dict)
    replayed_through: int = 0

    def apply_write(self, scope: str, key: str, value: str) -> None:
        self.index.setdefault(scope, {})[key] = value

    def apply_revoke(self, scope: str) -> None:
        self.index.pop(scope, None)


def read_scope(
    scope: str,
    reader_epoch: int,
    authority: RevocationAuthority,
    data: DataPlane,
    *,
    recovery_complete: bool,
) -> Dict[str, str]:
    revoked_at = authority.current_epoch(scope)
    if revoked_at is not None and reader_epoch <= revoked_at:
        raise RevocationLeakError(
            f"scope {scope!r} revoked at epoch {revoked_at}; "
            f"reader epoch {reader_epoch} predates revocation"
        )
    if not recovery_complete and scope in data.index:
        # Data plane is mid-replay; a scope absent from the authority but
        # present here may be a pre-tombstone re-materialization.
        raise RevocationLeakError(
            f"scope {scope!r} readable during replay but not yet "
            f"cleared by authority; refusing to serve"
        )
    return dict(data.index.get(scope, {}))


def forget(
    scope: str,
    epoch: int,
    authority: RevocationAuthority,
    data: DataPlane,
) -> dict:
    # Authority write is durable first; data-plane purge is deferred.
    authority.revoke(scope, epoch)
    return {"revoked": True, "purge_pending": True, "purge_epoch": epoch}
