# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-tombstone-it-never-received-orphaned-memory-replicas-in-federated-forget-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-tombstone-it-never-received-orphaned-memory-replicas-in-federated-forget-propagation.warrant.json
# Markdown SHA-256:   127c2c483385ea532afe10e1d17a1110180320bbae96784e5550d86e77b5d940
# Code AST SHA-256:   434fe7e01cff5ea542f894131d15b13dbb5f0e6ba4140d50e4628dddd5113f5c
# Verified Classes:   ForgetPropagationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ForgetPropagationError(RuntimeError):
    pass


def admit_record_sync(record_epoch: int,
                      tombstone_epoch: int | None,
                      peer_tombstone_watermark: int,
                      local_watermark: int) -> bool:
    """Decide whether a replica may materialize a record from a peer.

    Invariant: a record may be synced only if its write epoch is strictly
    greater than the peer's absorbed-tombstone watermark, OR the peer
    supplies the matching tombstone. Otherwise the record is either
    already-dead (tombstone exists) or un-verifiable (peer has not
    absorbed the tombstone that would kill it).
    """
    if record_epoch <= peer_tombstone_watermark:
        if tombstone_epoch is None:
            raise ForgetPropagationError(
                f"record epoch {record_epoch} <= peer watermark "
                f"{peer_tombstone_watermark} but no tombstone supplied; "
                f"refusing sync to avoid resurrection"
            )
        if tombstone_epoch < record_epoch:
            raise ForgetPropagationError(
                f"tombstone epoch {tombstone_epoch} predates record epoch "
                f"{record_epoch}; tombstone does not dominate record"
            )
        return False  # tombstoned, do not materialize
    if local_watermark < peer_tombstone_watermark:
        raise ForgetPropagationError(
            f"local watermark {local_watermark} behind peer "
            f"{peer_tombstone_watermark}; replay tombstone log first"
        )
    return True


def gc_tombstone(tombstone_epoch: int, replica_watermarks: dict[str, int]) -> bool:
    """GC a tombstone only when every replica has absorbed past it."""
    min_watermark = min(replica_watermarks.values())
    if tombstone_epoch >= min_watermark:
        raise ForgetPropagationError(
            f"cannot GC tombstone epoch {tombstone_epoch}: replica "
            f"watermark floor is {min_watermark}; GC would allow "
            f"resurrection via anti-entropy"
        )
    return True
