# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-a-scoped-retention-forget-against-in-flight-write-leases-before-acknowledging-deletion.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-a-scoped-retention-forget-against-in-flight-write-leases-before-acknowledging-deletion.warrant.json
# Markdown SHA-256:   2e45f99f8c511cd50a26168823f64357659ef47a4e0cc367d498b0596432ddca
# Code AST SHA-256:   bc6b3560deb0f343b02b4f66c32d723c7d3ae70fe727a7b9480bde6619a1a1af
# Verified Classes:   HotForgetUnverifiedError, ScopeState, RetentionGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class HotForgetUnverifiedError(RuntimeError):
    """Raised when a forget is acknowledged on a non-quiescent scope
    without a post-materialization-window confirming read."""
    pass


@dataclass
class ScopeState:
    last_write_accepted_at: float | None = None
    last_forget_at: float | None = None
    confirming_read_at: float | None = None


class RetentionGuard:
    MATERIALIZATION_WINDOW_S = 0.5  # transport acceptance -> index materialization

    def __init__(self) -> None:
        self._scopes: dict[str, ScopeState] = {}

    def _state(self, scope: str) -> ScopeState:
        return self._scopes.setdefault(scope, ScopeState())

    def on_write_accepted(self, scope: str) -> None:
        self._state(scope).last_write_accepted_at = time.monotonic()

    def on_forget_acknowledged(self, scope: str) -> None:
        self._state(scope).last_forget_at = time.monotonic()
        self._state(scope).confirming_read_at = None

    def on_confirming_read(self, scope: str, empty: bool) -> None:
        if empty:
            self._state(scope).confirming_read_at = time.monotonic()

    def is_hot(self, scope: str) -> bool:
        s = self._state(scope)
        if s.last_write_accepted_at is None:
            return False
        # Hot if a write was accepted within the window before the forget,
        # or if no forget has occurred yet.
        if s.last_forget_at is None:
            return True
        return (s.last_forget_at - s.last_write_accepted_at) < self.MATERIALIZATION_WINDOW_S

    def acknowledge_erasure(self, scope: str) -> None:
        s = self._state(scope)
        if s.last_forget_at is None:
            raise HotForgetUnverifiedError(
                f"no forget issued for scope {scope!r}; cannot acknowledge erasure"
            )
        if self.is_hot(scope):
            # Hot scope: require a confirming read issued after the window elapsed.
            if s.confirming_read_at is None:
                raise HotForgetUnverifiedError(
                    f"scope {scope!r} is hot (write accepted within "
                    f"{self.MATERIALIZATION_WINDOW_S}s of forget) and has no "
                    f"confirming read; resurrection possible"
                )
            elapsed = s.confirming_read_at - s.last_forget_at
            if elapsed < self.MATERIALIZATION_WINDOW_S:
                raise HotForgetUnverifiedError(
                    f"confirming read for {scope!r} issued at +{elapsed:.3f}s, "
                    f"before materialization window "
                    f"{self.MATERIALIZATION_WINDOW_S}s; read may have raced "
                    f"a straggler write"
                )
        # Cold scope, or hot scope with a post-window confirming read: safe.
        s.last_write_accepted_at = None
        s.last_forget_at = None
        s.confirming_read_at = None
