# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-forget-acknowledgement-when-its-memory-backend-reports-deletion-success-over-a-multi-tenant-vector-store.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-forget-acknowledgement-when-its-memory-backend-reports-deletion-success-over-a-multi-tenant-vector-store.warrant.json
# Markdown SHA-256:   a165ec62e0cb8ff88172b427bd21de32ab5fedbc9e9dc6751246c03e0a05193e
# Code AST SHA-256:   a961a66790469dcf29b22353689e56f304d196e613865939fe3b930dcb48d795
# Verified Classes:   UnverifiedForgetError, ForgetAck, MemoryTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class UnverifiedForgetError(RuntimeError):
    """Raised when an agent attempts an irreversible action that depends on
    a forget acknowledgement that has not been verified by a clean read-back."""


@dataclass
class ForgetAck:
    entity_id: str
    verification: str          # "read_back" | "quorum" | "none"
    propagation_bound_ms: Optional[int]
    acknowledged_at: float = field(default_factory=time.monotonic)


@dataclass
class MemoryTool:
    """Minimal contract surface. Backend is assumed to be a multi-tenant
    vector store with eventual-consistency read replicas."""
    _store: dict
    _pending: set = field(default_factory=set)

    def forget(self, entity_id: str) -> ForgetAck:
        # Backend enqueues a tombstone and returns immediately.
        self._pending.add(entity_id)
        return ForgetAck(
            entity_id=entity_id,
            verification="none",        # schema default; the trap
            propagation_bound_ms=None,  # unknown across replicas
        )

    def read(self, entity_id: str, min_consistency: str = "eventual") -> list:
        if min_consistency == "strong":
            # Primary-routed read: tombstone is applied here.
            if entity_id in self._pending:
                return []
        return self._store.get(entity_id, [])


def assert_erased_or_escalate(tool: MemoryTool, ack: ForgetAck) -> None:
    """Gate irreversible actions on a verified empty read, not on the ack."""
    if ack.verification == "none" or ack.propagation_bound_ms is None:
        # Downgrade: ack is intent, not proof. Force read-back.
        survivors = tool.read(ack.entity_id, min_consistency="strong")
        if survivors:
            raise UnverifiedForgetError(
                f"forget({ack.entity_id}) acknowledged but record still "
                f"reachable via strong read: {len(survivors)} chunk(s) live. "
                f"verification={ack.verification}, "
                f"propagation_bound_ms={ack.propagation_bound_ms}. "
                f"Refusing irreversible action; re-issue forget and escalate."
            )
        # Clean read-back: locally verified, but siblings may still be poisoned.
        # Caller must record this and avoid cross-instance irreversible actions
        # until propagation_bound_ms is known.
        return
    if ack.verification == "quorum":
        # Caller is responsible for supplying quorum confirmations.
        raise UnverifiedForgetError(
            f"forget({ack.entity_id}) requires quorum confirmation; "
            f"none supplied to this gate."
        )
    # verification == "read_back" with a finite bound: trust but re-read.
    if tool.read(ack.entity_id, min_consistency="strong"):
        raise UnverifiedForgetError(
            f"forget({ack.entity_id}) claimed read_back verification but "
            f"strong read returned live chunks; contract violation."
        )


def approve_refund(tool: MemoryTool, ack: ForgetAck, amount: int) -> str:
    # The irreversible action is gated on the verification, not the ack.
    assert_erased_or_escalate(tool, ack)
    return f"approved {amount}"
