# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-cryptographically-forgotten-memory-block-is-still-referenced-by-an-in-flight-tool-call-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-cryptographically-forgotten-memory-block-is-still-referenced-by-an-in-flight-tool-call-warrant.warrant.json
# Markdown SHA-256:   bf53f3db1131db99dc4d8c6bbc7a8c07b88ecbe87048bad9c760d5e687f6adea
# Code AST SHA-256:   a6e2a704a3c9c701f0b0a24a561b14fe1868d3c85297bdfb908526f0d9f850eb
# Verified Classes:   ForgettingBoundaryError, ForgetPhase, Warrant, ForgetAck, MemoryBroker
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Set


class ForgettingBoundaryError(RuntimeError):
    """Raised when a forget ack cannot be trusted as a visibility guarantee."""


class ForgetPhase(Enum):
    QUIESCE = "quiesce"
    DESTROY = "destroy"


@dataclass
class Warrant:
    handle: str
    epoch: int
    cek_captured_at: float
    ttl: float
    derived_from: Optional[str] = None


@dataclass
class ForgetAck:
    handle: str
    phase: ForgetPhase
    drained: List[str] = field(default_factory=list)
    cascaded: List[str] = field(default_factory=list)


class MemoryBroker:
    def __init__(self) -> None:
        self._warrants: Dict[str, List[Warrant]] = {}
        self._derived: Dict[str, Set[str]] = {}
        self._destroyed: Set[str] = set()

    def issue_warrant(self, w: Warrant) -> None:
        if w.handle in self._destroyed:
            raise ForgettingBoundaryError(
                f"refusing warrant for destroyed handle {w.handle}"
            )
        self._warrants.setdefault(w.handle, []).append(w)
        if w.derived_from:
            self._derived.setdefault(w.derived_from, set()).add(w.handle)

    def forget(self, handle: str, now: float) -> ForgetAck:
        # Phase 1: quiesce. Drain or expire outstanding warrants.
        outstanding = self._warrants.get(handle, [])
        drained: List[str] = []
        for w in outstanding:
            if now - w.cek_captured_at > w.ttl:
                drained.append(f"expired:{w.handle}@{w.epoch}")
            else:
                # Cannot force-drain a captured-by-value CEK; must wait.
                return ForgetAck(handle=handle, phase=ForgetPhase.QUIESCE,
                                 drained=drained)
        # Phase 2: destroy CEK and cascade to descendants.
        self._destroyed.add(handle)
        cascaded: List[str] = []
        for child in self._derived.get(handle, set()):
            if child in self._destroyed:
                continue
            child_ack = self.forget(child, now)
            if child_ack.phase is not ForgetPhase.DESTROY:
                raise ForgettingBoundaryError(
                    f"cascade stalled at {child}: phase={child_ack.phase.value}"
                )
            cascaded.append(child)
        return ForgetAck(handle=handle, phase=ForgetPhase.DESTROY,
                         drained=drained, cascaded=cascaded)


def assert_forget_complete(ack: ForgetAck) -> None:
    """Agent-side guard: refuse to treat a phase-1 ack as completion."""
    if ack.phase is not ForgetPhase.DESTROY:
        raise ForgettingBoundaryError(
            f"forget({ack.handle}) returned phase={ack.phase.value}; "
            f"drained={ack.drained}; content may still be readable by "
            f"outstanding warrants. Do not certify."
        )
    if not ack.cascaded and ack.handle not in ():
        # A phase-2 ack with no cascade is only valid if the broker
        # confirmed there were no descendants; otherwise suspect a
        # missing derived-handle index.
        pass


if __name__ == "__main__":
    broker = MemoryBroker()
    broker.issue_warrant(Warrant(handle="h_alpha", epoch=1,
                                 cek_captured_at=0.0, ttl=10.0))
    broker.issue_warrant(Warrant(handle="h_beta", epoch=1,
                                 cek_captured_at=0.0, ttl=10.0,
                                 derived_from="h_alpha"))
    ack = broker.forget("h_alpha", now=2.0)
    assert_forget_complete(ack)  # raises: phase=quiesce, W-1 still live
