# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-from-mesh-memory-when-a-tombstone-is-garbage-collected-before-its-causal-epoch-closes.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-from-mesh-memory-when-a-tombstone-is-garbage-collected-before-its-causal-epoch-closes.warrant.json
# Markdown SHA-256:   c947acb28289b97fad76fe33df8044cdf37a91e2d109a52385657fd0e1499d78
# Code AST SHA-256:   a7d91bcc795ff99ab68dfef5325008025f4a6ff5cfe42e7d47715c5e18d1194b
# Verified Classes:   CausalGhostError, CausalDigest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CausalGhostError(RuntimeError):
    """Raised when a record cites a parent that was tombstoned and collected."""


@dataclass
class CausalDigest:
    """Compact record of collected tombstones, keyed by epoch."""
    horizon_epochs: int
    digests: dict = field(default_factory=dict)  # epoch -> frozenset of key hashes

    def record_collection(self, epoch: int, keys: list) -> None:
        self.digests[epoch] = frozenset(
            hashlib.sha256(k.encode()).hexdigest() for k in keys
        )
        # Evict epochs older than horizon
        cutoff = epoch - self.horizon_epochs
        for e in [e for e in self.digests if e < cutoff]:
            del self.digests[e]

    def was_collected(self, key: str, epoch: int) -> bool:
        h = hashlib.sha256(key.encode()).hexdigest()
        return h in self.digests.get(epoch, frozenset())


def ingest_derived_record(record: dict, live_keys: set, digest: CausalDigest) -> None:
    """Accept a derived record only if its parent is live or provably collected."""
    parent = record["provenance"]["parent"]
    parent_epoch = record["provenance"]["parent_epoch"]
    if parent in live_keys:
        return  # parent still live, safe
    if digest.was_collected(parent, parent_epoch):
        raise CausalGhostError(
            f"record {record['id']} cites parent {parent}@{parent_epoch}, "
            f"which was tombstoned and collected; quarantine and re-derive"
        )
    # Parent absent, not in digest: could be a genuine gap or an out-of-horizon
    # ghost. Fail closed rather than resurrect from snapshot.
    raise CausalGhostError(
        f"record {record['id']} cites unknown parent {parent}@{parent_epoch}; "
        f"refusing to hydrate from snapshot (resurrection path)"
    )
