# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-forget-directive-with-the-audit-trail-it-is-legally-required-to-retain-the-tombstone-erasure-split-and-its-replay-h.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-forget-directive-with-the-audit-trail-it-is-legally-required-to-retain-the-tombstone-erasure-split-and-its-replay-h.warrant.json
# Markdown SHA-256:   64f043e6b38c5e0e556b15edc42920ded615869bb266360a531e7ddd38e3988f
# Code AST SHA-256:   3f93999dae893746e4bacab537ef38dd7b6d203464bf9a254975c044df3d8993
# Verified Classes:   ErasureProvenanceViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ErasureProvenanceViolation(RuntimeError):
    """Raised when a forget operation would break audit-chain monotonicity."""
    pass


def forget_memory(memory_id: str, warrant: str, store, ledger, replicas) -> dict:
    # Invariant: provenance cardinality must not decrease. A tombstone must
    # exist for memory_id before any payload is destroyed, and every replica
    # holding the payload must acknowledge destruction.
    if not ledger.has_edge(memory_id):
        # Nothing consumed it; safe to hard-delete, but still tombstone for audit.
        ledger.append_tombstone(memory_id, payload_hash=None, warrant=warrant)
        store.destroy(memory_id)
        return {"status": "erased", "tombstoned": True}

    payload_hash = store.hash_of(memory_id)
    unacked = [r for r in replicas if r.holds(memory_id)]
    if unacked:
        # Fail closed: do not destroy payload while a replica can still
        # re-introduce it (checkpoint resume / context cache).
        raise ErasureProvenanceViolation(
            f"cannot forget {memory_id}: {len(unacked)} replica(s) hold payload "
            f"and are not enrolled in erasure set {[r.id for r in unacked]}"
        )

    # Phase 1: tombstone with intact provenance edges.
    ledger.append_tombstone(memory_id, payload_hash=payload_hash, warrant=warrant)
    # Phase 2: destroy payload only after tombstone is durable.
    store.destroy(memory_id)
    for r in replicas:
        r.purge(memory_id)

    if not ledger.tombstone_is_replayable(memory_id):
        raise ErasureProvenanceViolation(
            f"tombstone for {memory_id} is not replayable; audit chain broken"
        )
    return {"status": "erased", "tombstoned": True, "payload_hash": payload_hash}
