# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-forget-acknowledgement-as-non-final-until-deletion-attestation-converges-across-replicas.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-forget-acknowledgement-as-non-final-until-deletion-attestation-converges-across-replicas.warrant.json
# Markdown SHA-256:   ef2c5844b8dee860f8d8cbbf3f73c67ee5493f7a025bb08b8d1223556f09a0ca
# Code AST SHA-256:   767e66328806e5a988221f0b01fa068d3d4db5684ddf282d1a506e462dc2c906
# Verified Classes:   DeletionAttestationError, MemoryTool, DeletionBelief
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Protocol


class DeletionAttestationError(RuntimeError):
    """Raised when an agent attempts to act on deletion before attestation converges."""


class MemoryTool(Protocol):
    def forget(self, key: str) -> str: ...
    def attest(self, key: str) -> dict: ...
    def compaction_epoch(self) -> int: ...


@dataclass
class DeletionBelief:
    key: str
    forgotten_at: float
    attested_replicas: int = 0
    replica_count: int = 0
    epoch_at_forget: int = 0
    epoch_at_attest: int = -1
    quarantined: bool = False

    def is_final(self) -> bool:
        return (
            self.replica_count > 0
            and self.attested_replicas == self.replica_count
            and self.epoch_at_attest > self.epoch_at_forget
        )


def assert_absence_safe(
    belief: DeletionBelief,
    tool: MemoryTool,
    task_horizon_s: float,
    max_resurrection_window_s: float,
) -> None:
    """Gate any reasoning that asserts a key is absent.

    Raises if the forget acknowledgement has not converged across replicas
    and survived at least one retention compaction epoch.
    """
    if belief.quarantined:
        raise DeletionAttestationError(
            f"key {belief.key!r} is quarantined; absence may not be asserted"
        )

    report = tool.attest(belief.key)
    belief.attested_replicas = report["attested"]
    belief.replica_count = report["replicas"]
    belief.epoch_at_attest = tool.compaction_epoch()

    if belief.attested_replicas < belief.replica_count:
        raise DeletionAttestationError(
            f"key {belief.key!r} attested on "
            f"{belief.attested_replicas}/{belief.replica_count} replicas; "
            f"a lagging replica can resurrect the record (Trace A)"
        )

    if belief.epoch_at_attest <= belief.epoch_at_forget:
        raise DeletionAttestationError(
            f"key {belief.key!r} tombstone has not survived a compaction epoch "
            f"(forget@{belief.epoch_at_forget}, now@{belief.epoch_at_attest}); "
            f"reaper may drop it before propagation (Trace B)"
        )

    if task_horizon_s > max_resurrection_window_s:
        raise DeletionAttestationError(
            f"task horizon {task_horizon_s}s exceeds retention "
            f"max_resurrection_window {max_resurrection_window_s}s for key "
            f"{belief.key!r}; re-attestation checkpoint required, not a "
            f"one-shot absence assertion"
        )


def forget_with_barrier(
    tool: MemoryTool,
    key: str,
    task_horizon_s: float,
    max_resurrection_window_s: float,
    poll_timeout_s: float = 30.0,
) -> DeletionBelief:
    ack = tool.forget(key)
    if ack != "deleted":
        raise DeletionAttestationError(f"forget({key!r}) did not acknowledge: {ack!r}")

    belief = DeletionBelief(
        key=key,
        forgotten_at=time.monotonic(),
        epoch_at_forget=tool.compaction_epoch(),
    )

    deadline = time.monotonic() + poll_timeout_s
    while time.monotonic() < deadline:
        try:
            assert_absence_safe(
                belief, tool, task_horizon_s, max_resurrection_window_s
            )
            return belief
        except DeletionAttestationError:
            time.sleep(0.25)

    belief.quarantined = True
    raise DeletionAttestationError(
        f"forget({key!r}) ack received but attestation did not converge within "
        f"{poll_timeout_s}s; key quarantined, absence may not be asserted"
    )
