# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-tombstoned-memory-whose-forget-audit-receipt-was-committed-but-whose-physical-erasure-never-propagated-to-a-retrieval-re.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-tombstoned-memory-whose-forget-audit-receipt-was-committed-but-whose-physical-erasure-never-propagated-to-a-retrieval-re.warrant.json
# Markdown SHA-256:   2259b046f2154b98b623b0b2505c4902bd3fc1ac7d8b87a0eab88c9b4041d9c1
# Code AST SHA-256:   e3bc5adccb20b179ef6f1afdce0ae3191eb4b5147c6675036ece5248687a4e37
# Verified Classes:   ErasurePropagationError, Tombstone, ReadSurface
# Defensive Guards:   8 fail-closed invariants (zero external deps)

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

class ErasurePropagationError(RuntimeError):
    """Raised when a forget receipt exists but erasure has not reached a read surface."""
    pass

@dataclass
class Tombstone:
    mem_id: str
    erased_at: int          # seq at which primary committed tombstone
    warrant: str
    receipt: str
    horizon: dict           # surface -> guaranteed_seq (C3)

@dataclass
class ReadSurface:
    name: str
    tombstone_seq: int      # highest tombstone seq this surface has applied
    payloads: dict = field(default_factory=dict)  # mem_id -> text (may be stale)

def assert_erased(tomb: Tombstone,
                  surfaces: list,
                  in_flight_snapshot_seqs: list,
                  reintro_hits: list,
                  cooldown_open: bool) -> None:
    # C1: every read surface must have applied a tombstone_seq >= erased_at
    for s in surfaces:
        if s.tombstone_seq < tomb.erased_at:
            raise ErasurePropagationError(
                f"surface={s.name} tombstone_seq={s.tombstone_seq} "
                f"< erased_at={tomb.erased_at}; receipt {tomb.receipt} not honored"
            )
        if tomb.mem_id in s.payloads:
            raise ErasurePropagationError(
                f"surface={s.name} still serves payload for {tomb.mem_id}"
            )

    # C2: no in-flight derived pipeline may have snapshotted before erasure
    for snap in in_flight_snapshot_seqs:
        if snap < tomb.erased_at:
            raise ErasurePropagationError(
                f"in-flight distillation snapshot_seq={snap} < erased_at="
                f"{tomb.erased_at}; flush barrier required before assertion"
            )

    # C4: re-introduction watch must be clean and cooldown closed
    if reintro_hits:
        raise ErasurePropagationError(
            f"semantic re-introduction of {tomb.mem_id} detected: {reintro_hits}"
        )
    if cooldown_open:
        raise ErasurePropagationError(
            f"re-introduction cooldown still open for {tomb.mem_id}; "
            f"refuse to assert erasure to principal"
        )

def forget_and_assert(memory_api, mem_id: str, reason: str,
                      cooldown_s: float = 120.0,
                      probe_surfaces=("exact", "vector", "summary")) -> Tombstone:
    resp = memory_api.forget(mem_id, reason=reason)
    if resp.get("status") != "committed":
        raise ErasurePropagationError(f"forget not committed: {resp}")

    tomb = Tombstone(
        mem_id=mem_id,
        erased_at=resp["erased_at"],
        warrant=resp["warrant"],
        receipt=resp["receipt"],
        horizon=resp.get("horizon", {}),
    )

    # C3: refuse to trust a receipt with an unbounded/empty propagation horizon
    if not tomb.horizon:
        raise ErasurePropagationError(
            f"receipt {tomb.receipt} carries no propagation horizon; "
            f"cannot assert physical erasure"
        )

    deadline = time.time() + cooldown_s
    while time.time() < deadline:
        surfaces = memory_api.read_surfaces(probe_surfaces)
        in_flight = memory_api.in_flight_snapshot_seqs()
        reintro = memory_api.semantic_near_dupes(mem_id, since=tomb.erased_at)
        if memory_api.all_flushed(in_flight) and not reintro:
            assert_erased(tomb, surfaces, in_flight, reintro,
                          cooldown_open=False)
            return tomb
        time.sleep(1.0)

    raise ErasurePropagationError(
        f"erasure of {mem_id} unverified within {cooldown_s}s; "
        f"do not assert to principal"
    )
