# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forgotten-memory-has-been-reconstituted-by-semantic-distillation-across-a-scoped-retention-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forgotten-memory-has-been-reconstituted-by-semantic-distillation-across-a-scoped-retention-boundary.warrant.json
# Markdown SHA-256:   61a9db326f2593d39dbdc0eb7940bb54dac709cdf8ee486bf4d12b373e610d4c
# Code AST SHA-256:   be1a5462fa70f88f2b856695bcb082c7dbc343a88d0a5807ec934ee05d8eecf0
# Verified Classes:   ErasureResidueError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ErasureResidueError(RuntimeError):
    """Raised when a forget() call cannot guarantee information erasure
    because derived artifacts outlive the source without complete provenance,
    or because a merged node cannot be redacted without over-erasing another
    data subject's retained fact."""


def enforce_erasure(store, erased_id: str, subject_id: str) -> dict:
    """
    store must expose:
      store.get_record(id) -> {scope, retention_rank, subject_id} | None
      store.derived_from(id) -> list[{node_id, scope, retention_rank,
                                     source_ids, contributor_count, subject_ids}]
      store.delete(node_id)
      store.redact(node_id, subject_id)  # removes one contributor, recomputes embedding
    """
    src = store.get_record(erased_id)
    if src is None:
        return {"erased": True, "note": "already absent at record layer"}

    derived = store.derived_from(erased_id)
    traversed = {src["scope"]}

    for node in derived:
        traversed.add(node["scope"])

        # (b) provenance must be complete
        if not node.get("source_ids"):
            raise ErasureResidueError(
                f"derived node {node['node_id']} in scope {node['scope']} "
                f"has no source_ids; erasure of {erased_id} cannot be verified "
                f"(retention_rank {node['retention_rank']} > "
                f"{src['retention_rank']})"
            )

        # (c) merge across distinct data subjects
        other_subjects = set(node["subject_ids"]) - {subject_id}
        if other_subjects:
            if node["contributor_count"] <= 1:
                # sole-contributor node mislabeled; deletion is safe
                store.delete(node["node_id"])
            else:
                # must redact in place, not delete
                store.redact(node["node_id"], subject_id)
        else:
            store.delete(node["node_id"])

    store.delete(erased_id)

    # post-condition: no derived artifact may still reference the erased id
    residual = store.derived_from(erased_id)
    if residual:
        raise ErasureResidueError(
            f"post-erasure residue: {len(residual)} derived nodes still "
            f"reference {erased_id} after traversal"
        )

    return {
        "erased": True,
        "scopes_traversed": sorted(traversed),
        "merged_nodes_redacted": sum(
            1 for n in derived if set(n["subject_ids"]) - {subject_id}
        ),
    }
