# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-memory-forget-as-a-two-phase-barrier-rather-than-a-fire-and-forget-tombstone.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-memory-forget-as-a-two-phase-barrier-rather-than-a-fire-and-forget-tombstone.warrant.json
# Markdown SHA-256:   5db958deea02f5751af7f8b6e23eb24d991de919f794cf40de0d689ee4be9173
# Code AST SHA-256:   4657ca317c113e44b6f0ac846274e1e2ffc1d166622fe3f0203fc6d54d079e9b
# Verified Classes:   ErasureProtocolError, ForgetPhase, Replica, ForgetRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class ErasureProtocolError(RuntimeError):
    """Raised when a forget cannot be safely committed as a single-phase tombstone."""


class ForgetPhase(Enum):
    PENDING = "pending"
    QUIESCED = "quiesced"
    COMMITTED = "committed"
    DEBT = "debt_open"


@dataclass
class Replica:
    org: str
    holds_derivative: bool
    acked_quiesce: bool = False


@dataclass
class ForgetRequest:
    namespace: str
    key: str
    compliance_bound: bool
    replicas: list[Replica]
    provenance_edges_complete: bool
    phase: ForgetPhase = ForgetPhase.PENDING
    debt: list[str] = field(default_factory=list)


def requires_two_phase(req: ForgetRequest) -> bool:
    # Any peer with derivation/replication rights, or compliance obligation,
    # or missing provenance, forces the barrier.
    if req.compliance_bound:
        return True
    if any(r.holds_derivative for r in req.replicas):
        return True
    if not req.provenance_edges_complete:
        return True
    return False


def commit_forget(req: ForgetRequest, force: bool = False) -> ForgetPhase:
    if not requires_two_phase(req):
        # Sole-reader, no derivation: single-phase tombstone is sound.
        req.phase = ForgetPhase.COMMITTED
        return req.phase

    unacked = [r.org for r in req.replicas if r.holds_derivative and not r.acked_quiesce]
    if unacked:
        if not force:
            raise ErasureProtocolError(
                f"forget of {req.namespace}/{req.key} blocked: "
                f"unacked derivative-holding replicas {unacked}; "
                f"tombstone would leave reconstructable copies"
            )
        # Force-commit is permitted ONLY as debt, never as 'complete'.
        req.debt = unacked
        req.phase = ForgetPhase.DEBT
        return req.phase

    req.phase = ForgetPhase.QUIESCED
    # Barrier satisfied: all reachable derivations quiesced.
    req.phase = ForgetPhase.COMMITTED
    return req.phase


def audit_erasure_complete(req: ForgetRequest) -> bool:
    # An erasure is only reportable as complete when committed AND no debt.
    if req.phase is ForgetPhase.DEBT or req.debt:
        raise ErasureProtocolError(
            f"cannot report erasure of {req.key} complete: "
            f"open debt against {req.debt}"
        )
    return req.phase is ForgetPhase.COMMITTED
