# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-forget-this-has-already-failed-tombstone-visible-but-content-resident-in-agent-vector-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-forget-this-has-already-failed-tombstone-visible-but-content-resident-in-agent-vector-stores.warrant.json
# Markdown SHA-256:   704be3d9c53de955550bd6f8f77c96336af8f8c271d23ad56efedf25ad45ffa9
# Code AST SHA-256:   b5e14583064418479cab07ea1f0cd232493a5efab9387d3bce6af13dee28389e
# Verified Classes:   ErasureUnverifiableError, ErasurePendingCompactionError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ErasureUnverifiableError(RuntimeError):
    """Raised when an erasure cannot be proven at the physical/derived layer.

    A retrieval miss is NOT a proof of non-residency. This error is the
    agent's refusal to emit a completion attestation it cannot back with a
    physical non-residency proof over the full lineage closure.
    """
    pass


class ErasurePendingCompactionError(ErasureUnverifiableError):
    """Logical delete acknowledged but segment compaction has not run."""
    pass


def verify_erasure(record_id, store, lineage, derived_index):
    """
    Attempt to prove physical non-residency for record_id and its lineage
    closure. Returns True only on a positive physical proof.

    store must expose:
      - physical_scan(record_id) -> bool  (True if bytes/vector still resident)
      - graph_contains(record_id) -> bool (True if ANN node still present)
      - compaction_complete(record_id) -> bool
    lineage must expose:
      - derived_from(record_id) -> set of derived node ids
    derived_index must expose:
      - content_resident(node_id) -> bool
    """
    # 1. Compaction barrier: deferred compaction means erasure is PENDING.
    if not store.compaction_complete(record_id):
        raise ErasurePendingCompactionError(
            f"record {record_id}: logical delete acknowledged but compaction "
            f"has not physically rewritten segments; erasure is pending, not done"
        )

    # 2. Physical layer: bytes and ANN graph membership.
    if store.physical_scan(record_id):
        raise ErasureUnverifiableError(
            f"record {record_id}: tombstoned but content-resident in segment files"
        )
    if store.graph_contains(record_id):
        # Node still acts as a routing waypoint; its statistical shadow
        # biases retrieval for surviving records.
        raise ErasureUnverifiableError(
            f"record {record_id}: ANN graph still contains node; "
            f"deleted record continues to shape neighbor sets"
        )

    # 3. Lineage closure: derived artifacts must be erased or independent.
    derived = lineage.derived_from(record_id)
    if derived is None:
        raise ErasureUnverifiableError(
            f"record {record_id}: no lineage edges recorded; cannot compute "
            f"erasure scope over distilled semantic memory"
        )
    for node_id in derived:
        if derived_index.content_resident(node_id):
            raise ErasureUnverifiableError(
                f"record {record_id}: derived node {node_id} still resident; "
                f"distilled paraphrase recontaminates erased content"
            )

    # Only here — physical proof + closed lineage — is erasure valid.
    return True


def request_erasure(record_id, store, lineage, derived_index, self_check_query):
    """
    Agent-facing erasure path. Demonstrates that a retrieval-miss self-check
    is explicitly NON-EVIDENCE and must not short-circuit verification.
    """
    # A retrieval miss looks like success and must be ignored as proof.
    miss = self_check_query(record_id) is None
    # NOTE: `miss` is deliberately unused for the decision. It is the signal
    # the agent is tempted to trust; it is not a proof of non-residency.

    try:
        proven = verify_erasure(record_id, store, lineage, derived_index)
    except ErasureUnverifiableError:
        # Correct terminal state is PENDING-UNVERIFIED, never "complete".
        return {"record_id": record_id, "state": "pending_unverified",
                "attestation": None}

    return {"record_id": record_id, "state": "erased",
            "attestation": "physical_non_residency_proven", "proven": proven}
