# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-erasure-tombstone-rehydration-from-resurrecting-deleted-episodic-memory-across-a-federated-agent-mesh.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-erasure-tombstone-rehydration-from-resurrecting-deleted-episodic-memory-across-a-federated-agent-mesh.warrant.json
# Markdown SHA-256:   8a606d603413b2ebc9e012ad59ae6d185046b7128a8e9a5f9297b6333ad8a7c1
# Code AST SHA-256:   5adba76c95b41398abd48cff71655ed6e4ad373b482f1a94bab0ff00cd194c3b
# Verified Classes:   ErasureInvariantViolation, Tombstone, Derivation, PeerState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ErasureInvariantViolation(RuntimeError):
    """Raised when a derivation write or erase-ack would violate provenance closure."""
    pass


@dataclass
class Tombstone:
    record_id: str
    issued_at: float
    retain_until: float  # must exceed max distillation lag across peers


@dataclass
class Derivation:
    derivation_id: str
    content: str
    ancestry: list[str]          # ordered: derivation -> ... -> record_id
    ancestry_resolved: bool      # False => partial join, must be rejected


@dataclass
class PeerState:
    peer_id: str
    store: dict[str, str] = field(default_factory=dict)
    live_context_refs: set[str] = field(default_factory=set)
    pending_derivations: list[Derivation] = field(default_factory=list)
    tombstones: dict[str, Tombstone] = field(default_factory=dict)


def admit_derivation(peer: PeerState, d: Derivation, now: float) -> None:
    """Gate a derivation write against the tombstone set and ancestry closure."""
    if not d.ancestry_resolved:
        raise ErasureInvariantViolation(
            f"peer {peer.peer_id}: derivation {d.derivation_id} has unresolved "
            f"ancestry {d.ancestry}; refusing write (partial provenance join)"
        )
    for ancestor in d.ancestry:
        ts = peer.tombstones.get(ancestor)
        if ts is not None and now <= ts.retain_until:
            raise ErasureInvariantViolation(
                f"peer {peer.peer_id}: derivation {d.derivation_id} descends from "
                f"erased record {ancestor} (tombstone retained until "
                f"{ts.retain_until}); refusing rehydration"
            )
    peer.store[d.derivation_id] = d.content


def ack_erase(peer: PeerState, record_id: str, now: float) -> None:
    """An erase ack is only truthful if store, context, and pending derivations are clear."""
    if record_id in peer.store:
        raise ErasureInvariantViolation(
            f"peer {peer.peer_id}: store still holds {record_id}"
        )
    if record_id in peer.live_context_refs:
        raise ErasureInvariantViolation(
            f"peer {peer.peer_id}: live context still references {record_id}; "
            f"context barrier not fired, rehydration possible"
        )
    for d in peer.pending_derivations:
        if record_id in d.ancestry:
            raise ErasureInvariantViolation(
                f"peer {peer.peer_id}: pending derivation {d.derivation_id} "
                f"descends from {record_id}; ack would be untruthful"
            )
    peer.tombstones[record_id] = Tombstone(
        record_id=record_id, issued_at=now, retain_until=now + 3600.0
    )
