# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-gdpr-erasure-proof-is-invalid-in-an-agent-vector-store-deletion-tombstones-that-survive-ann-index-rebuilds-but-not.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-gdpr-erasure-proof-is-invalid-in-an-agent-vector-store-deletion-tombstones-that-survive-ann-index-rebuilds-but-not.warrant.json
# Markdown SHA-256:   0908940fa4c45c094121b4ee66b2ef703659480ef338a8bf0a31c9f2e3588457
# Code AST SHA-256:   f43c46205c2b019a01927a642bdfc8241290f430f9ba6c6f5987e55dd3e3dae7
# Verified Classes:   ErasureProofInvalid, LineageGraph, ErasureProof
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Optional


class ErasureProofInvalid(RuntimeError):
    """Raised when an erasure proof cannot be issued as VALID.

    This is not a deletion failure; it is a proof-soundness failure.
    The tombstone may be correct at canonical/ANN layers while the
    derivation layer still encodes the erased subject.
    """


@dataclass
class LineageGraph:
    # record_id -> set of derived sink ids synthesized from it
    derivation_children: Dict[str, Set[str]] = field(default_factory=dict)
    # sink_id -> measured recoverability of any single erased source [0,1]
    reconstruction_bound: Dict[str, float] = field(default_factory=dict)
    live_sinks: Set[str] = field(default_factory=set)
    erased_sinks: Set[str] = field(default_factory=set)


@dataclass
class ErasureProof:
    erased_id: str
    canonical_absent: bool
    ann_tombstoned: bool
    sinks_reachable: int
    sinks_erased: int
    sinks_bounded: int
    max_recoverability: float
    recoverability_threshold: float = 0.30

    def status(self) -> str:
        if not (self.canonical_absent and self.ann_tombstoned):
            return "INVALID"
        covered = self.sinks_erased + self.sinks_bounded
        if covered < self.sinks_reachable:
            return "INCOMPLETE"
        if self.max_recoverability > self.recoverability_threshold:
            return "INVALID"
        return "VALID"


def build_proof(
    graph: LineageGraph,
    erased_id: str,
    canonical_absent: bool,
    ann_tombstoned: bool,
    threshold: float = 0.30,
) -> ErasureProof:
    # Downward closure over derivation edges -- the whole point.
    reachable: Set[str] = set()
    frontier = [erased_id]
    while frontier:
        node = frontier.pop()
        for child in graph.derivation_children.get(node, set()):
            if child not in reachable:
                reachable.add(child)
                frontier.append(child)

    sinks_erased = 0
    sinks_bounded = 0
    max_rec = 0.0
    for sink in reachable:
        if sink in graph.erased_sinks:
            sinks_erased += 1
            continue
        bound = graph.reconstruction_bound.get(sink)
        if bound is None:
            # No measured bound => presume live. Never assume safe.
            if sink in graph.live_sinks:
                max_rec = max(max_rec, 1.0)
            continue
        max_rec = max(max_rec, bound)
        if bound <= threshold:
            sinks_bounded += 1

    proof = ErasureProof(
        erased_id=erased_id,
        canonical_absent=canonical_absent,
        ann_tombstoned=ann_tombstoned,
        sinks_reachable=len(reachable),
        sinks_erased=sinks_erased,
        sinks_bounded=sinks_bounded,
        max_recoverability=max_rec,
        recoverability_threshold=threshold,
    )

    if proof.status() == "INVALID":
        raise ErasureProofInvalid(
            f"erasure of {erased_id} unsound: "
            f"reachable={proof.sinks_reachable} "
            f"erased={proof.sinks_erased} "
            f"bounded={proof.sinks_bounded} "
            f"max_recoverability={proof.max_recoverability:.2f} "
            f"(threshold={threshold})"
        )
    if proof.status() == "INCOMPLETE":
        raise ErasureProofInvalid(
            f"erasure of {erased_id} cannot be certified: "
            f"{proof.sinks_reachable - proof.sinks_erased - proof.sinks_bounded} "
            f"derivation sink(s) lack a measured reconstruction bound; "
            f"issue INCOMPLETE, not VALID"
        )
    return proof
