# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-scoped-erasure-request-has-silently-failed-to-propagate-across-an-agent-memory-graph.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-scoped-erasure-request-has-silently-failed-to-propagate-across-an-agent-memory-graph.warrant.json
# Markdown SHA-256:   55954ec92f08b95ae9812c40bb2d6ef81e6f5c5541e0010a5759a48d2b8fbbb4
# Code AST SHA-256:   6f058cfa687fa298979e1c7e9963ce3d4f2e832a3a95818bcc66feace9341f86
# Verified Classes:   ErasurePropagationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ErasurePropagationError(RuntimeError):
    """Raised when a scoped forget leaves reachable derived artifacts."""
    pass


def verify_erasure(memory, source_scope: str, source_ids: list[str],
                   derived_scopes: list[str], probe_queries: list[str]) -> None:
    """
    Post-forget invariant check. Call after forget() returns success.
    Raises ErasurePropagationError if any derived artifact still answers
    a probe query with content whose lineage resolves to an erased source,
    or if lineage is unresolvable (which the read path may mask as empty).
    """
    # 1. Source must be gone.
    for rid in source_ids:
        if memory.read(scope=source_scope, query=rid):
            raise ErasurePropagationError(
                f"source record {rid} still readable in {source_scope}"
            )

    # 2. Every derived scope must not return content traceable to source.
    residuals = []
    for scope in derived_scopes:
        for q in probe_queries:
            hits = memory.read(scope=scope, query=q)
            for hit in hits:
                lineage = hit.get("source_record_ids", [])
                if any(sid in source_ids for sid in lineage):
                    residuals.append((scope, q, hit.get("id")))
                elif not lineage:
                    # Unresolvable lineage is a residual: it may be derived
                    # from the erased source and the read path cannot prove
                    # otherwise. Treat as failure, not as clean.
                    residuals.append((scope, q, hit.get("id"), "dangling"))

    if residuals:
        raise ErasurePropagationError(
            f"erasure did not propagate; {len(residuals)} residual artifacts "
            f"reachable: {residuals[:5]}"
        )

    # 3. Re-derivation must not be able to resurrect erased content.
    for scope in derived_scopes:
        rederived = memory.rederive(scope=scope, since=source_ids)
        if rederived:
            raise ErasurePropagationError(
                f"re-derivation from erased sources produced {len(rederived)} "
                f"artifacts in {scope}; lineage not tombstoned"
            )
