# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-cryptographic-memory-erasure-as-an-atomic-commit-rather-than-a-best-effort-fan-out-and-what-breaks-when-i.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-cryptographic-memory-erasure-as-an-atomic-commit-rather-than-a-best-effort-fan-out-and-what-breaks-when-i.warrant.json
# Markdown SHA-256:   1f63964fa17bdd5dea9f31b585b1a22e47b704a52163faa7489cf11ecb0c307c
# Code AST SHA-256:   edbbb60a4f77e53ae81504c43a4ff7a90ab40c0eab07a1ecc8e06f0c501c9aa2
# Verified Classes:   ForgetCommitViolation, ForgetState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ForgetCommitViolation(RuntimeError):
    """Raised when a forget operation would violate the atomic-commit invariant
    across index, plaintext cache, key custodian, and audit ledger."""
    pass


class ForgetState:
    PENDING = "pending"
    COMMITTED = "committed"


def execute_forget(subject_id, index, cache, kms, audit, reconcile_deadline_s):
    # Phase 0: durable intent. Nothing irreversible until this is fsynced.
    seq = audit.append_pending(op="forget", subject=subject_id)
    audit.fsync(seq)

    # Phase 1: tombstone index and CONFIRM plaintext eviction.
    index.tombstone(subject_id)
    evicted = cache.evict_subject(subject_id, confirm=True)
    if not evicted:
        # Do NOT destroy the key: plaintext would outlive it (Trace C).
        raise ForgetCommitViolation(
            f"plaintext eviction unconfirmed for {subject_id}; "
            f"aborting before irreversible KEK destroy (audit seq {seq} left pending)"
        )

    # Phase 2: irreversible step. Timeout is UNKNOWN, not failure.
    result = kms.destroy_kek(subject_id, on_timeout="unknown")
    if result == "unknown":
        actual = kms.query_kek_state(subject_id)
        if actual not in ("destroyed", "absent"):
            # Indeterminate: cannot retry an irreversible op blindly (Trace A).
            raise ForgetCommitViolation(
                f"KEK state indeterminate for {subject_id} at audit seq {seq}; "
                f"escalate, do not retry destroy"
            )
    elif result != "destroyed":
        raise ForgetCommitViolation(
            f"KEK destroy failed hard for {subject_id} at audit seq {seq}"
        )

    # Phase 3: only now is 'committed' a truthful certificate.
    audit.commit(seq)
    return seq


def reconcile_pending(audit, kms, now, reconcile_deadline_s):
    for entry in audit.pending_older_than(reconcile_deadline_s, now):
        state = kms.query_kek_state(entry.subject)
        if state in ("destroyed", "absent"):
            audit.commit(entry.seq)  # erasure landed; ledger was under-claiming
        elif state == "alive":
            # Plaintext may or may not have been evicted; cannot auto-resolve.
            raise ForgetCommitViolation(
                f"pending forget seq {entry.seq} for {entry.subject} has a live KEK "
                f"past deadline; manual adjudication required"
            )
        else:
            raise ForgetCommitViolation(
                f"pending forget seq {entry.seq} has unresolvable KEK state {state!r}"
            )
