# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-tracked-eviction-from-silently-orphaning-derived-memories-in-agent-read-write-forget-memory-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-tracked-eviction-from-silently-orphaning-derived-memories-in-agent-read-write-forget-memory-apis.warrant.json
# Markdown SHA-256:   47f84af14890c8c088a5f45fca893316289970235569964ef9f6f2f2a73d1e05
# Code AST SHA-256:   bdf5070c86d499d96d33c0db9f948854d84096157bc77628f3a68b682f7f0922
# Verified Classes:   OrphanedProvenanceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class OrphanedProvenanceError(RuntimeError):
    """Raised when eviction would leave a live record pointing at a dead parent,
    or when a read hits a record whose provenance cannot be resolved."""
    pass


def forget_with_closure(store, record_id, strategy="refuse"):
    # strategy in {"cascade", "tombstone", "refuse"}
    if strategy not in {"cascade", "tombstone", "refuse"}:
        raise OrphanedProvenanceError(f"unknown eviction strategy: {strategy}")

    with store.write_lock():  # serialization point: no concurrent writers
        dependents = store.find_live_dependents(record_id)

        if dependents and strategy == "refuse":
            raise OrphanedProvenanceError(
                f"cannot evict {record_id}: live dependents {sorted(dependents)} "
                f"hold provenance pointers; resolve them first"
            )

        if strategy == "cascade":
            # cycle-safe transitive eviction
            frontier, seen = [record_id], set()
            while frontier:
                cur = frontier.pop()
                if cur in seen:
                    continue
                seen.add(cur)
                frontier.extend(store.find_live_dependents(cur))
            for rid in seen:
                store.hard_delete(rid)
            return {"evicted": sorted(seen), "strategy": "cascade"}

        if strategy == "tombstone":
            store.replace_with_tombstone(
                record_id, reason="policy_eviction", content_hash=store.hash(record_id)
            )
            return {"evicted": [record_id], "strategy": "tombstone",
                    "dependents_flagged": sorted(dependents)}

        # strategy == "refuse" with no dependents: plain eviction
        store.hard_delete(record_id)
        return {"evicted": [record_id], "strategy": "refuse"}


def read_with_provenance_check(store, record_id):
    rec = store.get(record_id)
    if rec is None:
        return {"status": "NOT_FOUND", "id": record_id}
    if rec.get("tombstoned"):
        return {"status": "EVICTED", "id": record_id, "reason": rec["reason"]}

    unresolved = [p for p in rec.get("derived_from", []) if not store.is_resolvable(p)]
    if unresolved:
        # fail closed: do not let the caller treat this as grounded
        raise OrphanedProvenanceError(
            f"read({record_id}) has unresolved provenance {unresolved}; "
            f"record must not be served as grounded"
        )
    return {"status": "OK", "id": record_id, "record": rec}
