# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-memory-deletion-tombstone-has-failed-to-propagate-across-a-fan-out-read-path.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-memory-deletion-tombstone-has-failed-to-propagate-across-a-fan-out-read-path.warrant.json
# Markdown SHA-256:   9a59354597d679ae1c448d3bcaaada1a84d6309a3b4d800c0aaceae3c9c754dc
# Code AST SHA-256:   29b2a1baade1ee40ed0a2574087a5d89dfe62b1620b5f6ab449ea24f0755d60c
# Verified Classes:   TombstoneConvergenceError, Tombstone, TombstoneFilter
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field

class TombstoneConvergenceError(RuntimeError):
    """Raised when a read or write would violate the tombstone filter invariant."""
    pass

@dataclass
class Tombstone:
    record_id: str
    emitted_at: float
    convergence_deadline: float  # emitted_at + max propagation bound

@dataclass
class TombstoneFilter:
    tombstones: dict = field(default_factory=dict)

    def register(self, record_id: str, emitted_at: float, propagation_bound_s: float) -> None:
        self.tombstones[record_id] = Tombstone(
            record_id=record_id,
            emitted_at=emitted_at,
            convergence_deadline=emitted_at + propagation_bound_s,
        )

    def _active(self, now: float) -> set:
        return {t.record_id for t in self.tombstones.values() if now < t.convergence_deadline}

    def filter_read(self, record: dict, now: float) -> dict:
        active = self._active(now)
        chain = set(record.get("provenance", {}).get("chain", []))
        hit = chain & active
        if hit:
            raise TombstoneConvergenceError(
                f"read returned record {record.get('record_id')} whose provenance "
                f"cites tombstoned IDs {sorted(hit)} still within convergence window"
            )
        return record

    def guard_write(self, write_payload: dict, now: float) -> dict:
        active = self._active(now)
        cited = set(write_payload.get("inferred_from", []))
        hit = cited & active
        if hit:
            raise TombstoneConvergenceError(
                f"write would launder tombstoned IDs {sorted(hit)} into a new record "
                f"before convergence deadline"
            )
        return write_payload

    def prune(self, now: float) -> None:
        for rid in [r for r, t in self.tombstones.items() if now >= t.convergence_deadline]:
            del self.tombstones[rid]
