# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forget-acknowledgment-has-not-propagated-to-a-derived-episodic-to-semantic-summary-before-it-re-derives-the-deleted.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forget-acknowledgment-has-not-propagated-to-a-derived-episodic-to-semantic-summary-before-it-re-derives-the-deleted.warrant.json
# Markdown SHA-256:   aecf62ad65e9da97bec51cbefa034403ef19535bb5d04701be20f690c1612793
# Code AST SHA-256:   cb16b895c73e40c88f83e79a22eadd4e47bcfb1b2f96721c1506b15fd93cd9ef
# Verified Classes:   PropagationIncompleteError, DeletionBarrier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class PropagationIncompleteError(RuntimeError):
    """Raised when a forget ack has not propagated to a derived retrieval tier."""
    def __init__(self, fact_id: str, token: str, probe_hits: list[str]):
        self.fact_id = fact_id
        self.token = token
        self.probe_hits = probe_hits
        super().__init__(
            f"forget ack for {fact_id} (token={token}) is not cold: "
            f"derived tiers still return {probe_hits}"
        )


@dataclass
class DeletionBarrier:
    fact_id: str
    token: str
    canonical_terms: list[str]
    deadline_s: float
    opened_at: float = field(default_factory=time.monotonic)

    def expired(self) -> bool:
        return (time.monotonic() - self.opened_at) > self.deadline_s


def verify_cold_or_fail(
    barrier: DeletionBarrier,
    semantic_liveness_check,   # (fact_id) -> bool, ID-keyed, authoritative
    index_probe,               # (terms) -> list[str], content-based fallback
) -> None:
    """Confirm the derived tiers are cold; fail closed otherwise.

    A truthful 'deleted' ack from the episodic layer does NOT imply the
    semantic fact or its embedding entry is gone. We require an ID-keyed
    liveness check and a content probe to both come back cold.
    """
    if semantic_liveness_check(barrier.fact_id):
        raise PropagationIncompleteError(
            barrier.fact_id, barrier.token,
            probe_hits=[f"semantic_fact:{barrier.fact_id}"],
        )

    hits = index_probe(barrier.canonical_terms)
    if hits:
        raise PropagationIncompleteError(
            barrier.fact_id, barrier.token, probe_hits=hits,
        )

    if barrier.expired():
        # Cold but past SLA: still fail closed, do not silently trust.
        raise PropagationIncompleteError(
            barrier.fact_id, barrier.token,
            probe_hits=["sla_expired_without_confirmation"],
        )
