# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-tombstone-durability-when-a-memory-write-tool-acknowledges-deletion-before-the-provenance-index-has-been-invalidated.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-tombstone-durability-when-a-memory-write-tool-acknowledges-deletion-before-the-provenance-index-has-been-invalidated.warrant.json
# Markdown SHA-256:   8d36da18a829697b2a149642279b1a943c23d87014a6a7c6ff0507a2042272ca
# Code AST SHA-256:   a201f2430c1f04749c12aad10963c25ae4f6e111e7f01bc5b2a8f8318926fabe
# Verified Classes:   TombstonedProvenanceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TombstonedProvenanceError(RuntimeError):
    """Raised when a memory write cites provenance that resolves to a durable tombstone."""


# The tombstone set MUST be read in the same transaction as the record store
# that backs both `read` and `write`. If `forget` acks before the tombstone is
# visible here, the resurrection window is open.
def write_memory(key, value, provenance, record_store, tombstone_set):
    if not provenance:
        raise TombstonedProvenanceError(
            f"write({key!r}) has empty provenance; cannot establish lineage"
        )
    for source_id in provenance:
        if tombstone_set.contains(source_id):
            # This is the resurrection path: a retrieval hit on a forgotten
            # record is being laundered into a fresh, higher-revision write.
            raise TombstonedProvenanceError(
                f"write({key!r}) cites tombstoned source {source_id!r}; "
                f"refusing to resurrect deleted memory"
            )
    revision = record_store.put(key, value, provenance)
    return {"ok": True, "revision": revision}


def forget_memory(key, record_store, tombstone_set, provenance_gc):
    # Order matters: make the tombstone durable BEFORE the record-store delete
    # is acknowledged, so any concurrent write that reads the tombstone set
    # will see it. Then enqueue (async) provenance-index compaction.
    tombstone_id = tombstone_set.add(key)          # durable first
    record_store.delete(key)                        # then delete payload
    provenance_gc.enqueue(key, tombstone_id)        # compaction may lag; barrier holds
    return {"status": "deleted", "tombstone_id": tombstone_id}
