# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-gdpr-erasure-proof-as-invalid-after-a-forget-api-call-returns-success.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-gdpr-erasure-proof-as-invalid-after-a-forget-api-call-returns-success.warrant.json
# Markdown SHA-256:   d2a9d867d73558ddcb23573f8d074a2264468eabd79b18d2c3df27d0010f29be
# Code AST SHA-256:   3242910492b7db6588b67c060c45601a46f04b4b3e2bcf6e9285a9dc2177ca70
# Verified Classes:   UnfoundedErasureProof, DerivedNode, ErasureContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnfoundedErasureProof(RuntimeError):
    """Raised when an instance attempts to sign an erasure proof whose
    derivation closure or replica convergence is unverified."""


@dataclass
class DerivedNode:
    node_id: str
    provenance_subjects: list[str]
    content_digest: str


@dataclass
class ErasureContext:
    subject_id: str
    tombstone: str
    replica_acks: dict[str, bool]
    derived_nodes: list[DerivedNode] = field(default_factory=list)
    rederived_clean: dict[str, bool] = field(default_factory=dict)


def assert_closure(ctx: ErasureContext) -> None:
    # 1. Replica convergence: every replica must have read back the tombstone.
    unacked = [r for r, ok in ctx.replica_acks.items() if not ok]
    if unacked:
        raise UnfoundedErasureProof(
            f"replicas {unacked} did not confirm tombstone {ctx.tombstone}"
        )

    # 2. Derivation closure: every node touching the subject must be
    #    deleted or re-derived clean from surviving sources.
    for node in ctx.derived_nodes:
        if ctx.subject_id not in node.provenance_subjects:
            continue
        survivors = [s for s in node.provenance_subjects if s != ctx.subject_id]
        if len(survivors) == 0:
            raise UnfoundedErasureProof(
                f"derived node {node.node_id} is single-source and must be deleted"
            )
        if not ctx.rederived_clean.get(node.node_id, False):
            raise UnfoundedErasureProof(
                f"derived node {node.node_id} not re-derived clean after "
                f"removing {ctx.subject_id}"
            )


def emit_erasure_proof(ctx: ErasureContext) -> str:
    assert_closure(ctx)
    material = f"{ctx.subject_id}:{ctx.tombstone}:{sorted(ctx.replica_acks)}"
    return "sha256:" + hashlib.sha256(material.encode()).hexdigest()


# Trace replay of the auditor-7 incident: M-88 survives with 3 other sources
# but was never re-derived, so the proof must be refused.
incident = ErasureContext(
    subject_id="S-4412",
    tombstone="sha256:9f3c",
    replica_acks={"r1": True, "r2": True, "r3": True},
    derived_nodes=[
        DerivedNode("M-88", ["S-4412", "S-1001", "S-2200", "S-3300"], "sha256:aa11"),
    ],
    rederived_clean={},  # never re-derived -> closure unproven
)
try:
    emit_erasure_proof(incident)
except UnfoundedErasureProof as e:
    print("proof refused:", e)  # correct outcome
