# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forget-call-has-silently-degraded-into-a-shadow-because-scoped-retention-revocation-did-not-propagate-to-a-derived.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forget-call-has-silently-degraded-into-a-shadow-because-scoped-retention-revocation-did-not-propagate-to-a-derived.warrant.json
# Markdown SHA-256:   87a9a296e5ae692a309784107fe344c03a2edea0c202a101b3890383be6437c4
# Code AST SHA-256:   f2fc2c5a1294c09466f935e7d9dd9c5166c4eaf12226aa07d935efaf4ab7e557
# Verified Classes:   ShadowRevocationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ShadowRevocationError(RuntimeError):
    """Raised when a forget call's revocation did not propagate to derived memories."""
    pass


def verify_revocation_closure(memory_tool, forget_scope, pre_forget_snapshot, subject_key):
    """
    Post-forget guardrail. Confirms that no derived memory still surfaces content
    whose provenance intersects the forgotten scope.

    pre_forget_snapshot: dict of {store_name: set(record_ids)} captured before forget.
    subject_key: the identity dimension (e.g. user id) the revocation was *intended* for,
                 which may differ from the tag/scope actually passed to forget().
    """
    result = memory_tool.forget(scope=forget_scope)
    if result.get("status") != "ok":
        raise ShadowRevocationError(
            f"forget did not succeed: {result.get('status')!r}"
        )

    # A scoped 'ok' is NOT closure. Check whether the tool even reports derivation.
    derived_revoked = result.get("derived_revoked")
    if derived_revoked is None:
        # No cascade capability advertised: must verify manually across stores.
        residuals = []
        for store_name, prior_ids in pre_forget_snapshot.items():
            current = memory_tool.read(
                store=store_name,
                scope={subject_key: forget_scope.get(subject_key)},
            )
            # Records that survived the forget under a rewritten scope.
            survivors = {r["id"] for r in current} & prior_ids
            for rec_id in survivors:
                rec = memory_tool.get(store=store_name, record_id=rec_id)
                provenance = rec.get("derived_from", [])
                if provenance and set(provenance) & set(result.get("tombstoned_ids", [])):
                    residuals.append((store_name, rec_id, provenance))

        if residuals:
            raise ShadowRevocationError(
                "revocation did not close over derived memories: "
                f"{len(residuals)} residual record(s) with provenance in forgotten set; "
                f"first={residuals[0]!r}. Issue subject-scoped forget against each store."
            )

    # Even with cascade advertised, an in-flight distillation can commit after return.
    in_flight = memory_tool.list_jobs(scope=forget_scope, state="running")
    if in_flight:
        raise ShadowRevocationError(
            f"distillation job(s) in-flight against forgotten scope: {in_flight!r}; "
            "revocation barrier required before trusting closure."
        )

    return True
