# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-retention-policy-erasure-conflict-when-a-write-lands-on-a-tombstone-mid-erasure.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-retention-policy-erasure-conflict-when-a-write-lands-on-a-tombstone-mid-erasure.warrant.json
# Markdown SHA-256:   dde7959edd082a9a397529ede2848bea13c1cb8c464bce39dbeaae2858584e03
# Code AST SHA-256:   58b2faa57462510be090d31713f7633aa4edac1728ec91c1082bb88f6e2e1b67
# Verified Classes:   ErasureWriteConflict, ErasureState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ErasureWriteConflict(RuntimeError):
    """Raised when a write targets a key with an unsatisfied erasure obligation."""
    pass


class ErasureState:
    LIVE = "LIVE"
    ERASURE_PENDING = "ERASURE_PENDING"
    ERASED = "ERASED"


def guarded_write(store, key, payload, now):
    """
    Write to a memory key, refusing to resurrect a record whose erasure
    obligation is still in flight. Consults the authoritative erasure log,
    never the (possibly lagging) working index, and never compares timestamps.
    """
    # Authoritative state from the erasure state machine, not the replica index.
    state = store.erasure_log.state_of(key)

    if state == ErasureState.ERASURE_PENDING:
        tomb = store.erasure_log.tombstone(key)
        raise ErasureWriteConflict(
            f"write to {key!r} refused: erasure pending since {tomb.erased_at} "
            f"(compact_by={tomb.compact_by}). Do not resurrect; re-create under a "
            f"fresh key with a new consent basis, or drop the memory."
        )

    if state == ErasureState.ERASED:
        # Key is gone; a write here is a re-creation, which requires explicit consent.
        raise ErasureWriteConflict(
            f"write to {key!r} refused: record already ERASED. "
            f"Re-creation requires an explicit RECONSENT transition and a new key."
        )

    # state == LIVE: monotonic invariant permits the update.
    return store.write(key, payload, now)


def consolidate(store, key, payload, now):
    try:
        return guarded_write(store, key, payload, now)
    except ErasureWriteConflict as exc:
        # The agent must NOT treat this as a transient error to retry.
        # It must drop the memory and proceed, or re-create under a fresh key.
        store.agent_log.record_dropped(key, reason=str(exc))
        return None
