# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-acknowledges-a-gdpr-erasure-before-its-replica-quorum-has-durably-applied-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-acknowledges-a-gdpr-erasure-before-its-replica-quorum-has-durably-applied-it.warrant.json
# Markdown SHA-256:   660fd2e5410c32db24f7c3731c48732a5ef6419f13774956463a655aba5bc8c6
# Code AST SHA-256:   64bc2195d43911a6cbd816256d74f1cf6debf09f1ba58034b0f18435d995ed1e
# Verified Classes:   ErasureAckError, AckState, ReplicaState, DerivationEdge, ErasureRequest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ErasureAckError(RuntimeError):
    """Raised when an erasure acknowledgement would over-claim closure."""


class AckState(Enum):
    ORDERED = "ordered"      # durably ordered on a quorum, not yet applied everywhere
    APPLIED = "applied"      # durably applied across the full read-set
    PENDING = "pending"      # not yet ordered on a quorum; must not be treated as erased


@dataclass(frozen=True)
class ReplicaState:
    replica_id: str
    tombstone_seq: int | None          # None => tombstone not applied
    serves_subject_closure: bool       # could this replica serve S's derivation closure?


@dataclass(frozen=True)
class DerivationEdge:
    derived_fact_id: str
    source_subject: str
    consumer_record_id: str            # record written by a consumer that read the fact


@dataclass
class ErasureRequest:
    subject: str
    replicas: FrozenSet[ReplicaState]
    derivation_edges: tuple[DerivationEdge, ...] = field(default_factory=tuple)
    quorum: int = 2


def acknowledge_erasure(req: ErasureRequest) -> AckState:
    """
    Return a typed acknowledgement. Never returns APPLIED unless the full
    read-set has applied the tombstone AND no derivation edge from the subject
    points at a consumer record that was written after tombstone ordering.
    """
    if req.quorum < 1 or req.quorum > len(req.replicas):
        raise ErasureAckError(
            f"invalid quorum {req.quorum} for {len(req.replicas)} replicas"
        )

    applied = [r for r in req.replicas if r.tombstone_seq is not None]
    pending = [r for r in req.replicas if r.tombstone_seq is None]

    # Any replica that can still serve the subject's closure and has not
    # applied the tombstone is a live leak window.
    leaking = [r for r in pending if r.serves_subject_closure]
    if leaking:
        # We may still be able to claim ORDERED if a quorum has applied.
        if len(applied) >= req.quorum:
            return AckState.ORDERED
        return AckState.PENDING

    if len(applied) < req.quorum:
        return AckState.PENDING

    # Quorum applied and no replica is serving the closure. Now check for
    # distillation laundering: a consumer record derived from the subject
    # that was written after ordering is outside the tombstone's closure set.
    laundered = [
        e for e in req.derivation_edges
        if e.source_subject == req.subject and e.consumer_record_id
    ]
    if laundered:
        raise ErasureAckError(
            f"subject {req.subject!r} has {len(laundered)} derivation edge(s) "
            f"into consumer records outside the tombstone closure; "
            f"cannot claim APPLIED — closure walk required"
        )

    return AckState.APPLIED


def emit_warrant(req: ErasureRequest) -> dict:
    state = acknowledge_erasure(req)
    if state is AckState.PENDING:
        # Refuse to emit a success-shaped warrant.
        raise ErasureAckError(
            f"refusing to emit erasure warrant for {req.subject!r}: "
            f"state is PENDING, not ordered on quorum"
        )
    return {
        "subject": req.subject,
        "state": state.value,
        "quorum": req.quorum,
        "replicas": sorted(r.replica_id for r in req.replicas),
    }
