# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-retention-governance-conflict-when-a-memory-tool-s-forget-api-is-shadowed-by-provenance-linked-replicas.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-retention-governance-conflict-when-a-memory-tool-s-forget-api-is-shadowed-by-provenance-linked-replicas.warrant.json
# Markdown SHA-256:   e75b6c0b02af6aabda69554dc672f4218b87d42401f35b0362a17cf2d9d9eef4
# Code AST SHA-256:   62b80c6bdfbf967e45149c8b19e1aaac0ef446e8aa91e441b27d60bea7f59357
# Verified Classes:   ShadowedForgetError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ShadowedForgetError(RuntimeError):
    """Raised when a forget is shadowed by a provenance-linked replica
    whose retention class outranks the forget request's authority class.
    The record was tombstoned but the erasure obligation was not met."""
    pass


RETENTION_ORDER = {
    "ephemeral": 0,
    "session": 1,
    "semantic_durable": 2,
    "legal_hold": 3,
}


def forget_with_verification(store, record_id, authority_class, reason):
    # Phase 1: issue the forget on the record identity.
    store.forget(record_id, reason=reason)

    # Phase 2: read the transitive provenance closure. A store that only
    # returns direct edges cannot support this check; treat as unverifiable.
    closure = store.provenance_closure(record_id, transitive=True)
    if closure is None:
        raise ShadowedForgetError(
            f"store returned no transitive closure for {record_id}; "
            f"forget is unverifiable and must not be reported complete"
        )

    authority_rank = RETENTION_ORDER[authority_class]
    shadowing = []
    for member in closure:
        if member.get("audit_exempt"):
            continue
        member_rank = RETENTION_ORDER[member["retention_class"]]
        if member_rank >= authority_rank and not member.get("tombstoned"):
            shadowing.append(member)

    if shadowing:
        # Forget was shadowed: at least one live replica outranks the request.
        # Do not report erasure. Escalate or issue derivative forgets.
        raise ShadowedForgetError(
            f"forget({record_id}) shadowed by {len(shadowing)} live replica(s) "
            f"with retention >= {authority_class}: "
            f"{[m['id'] for m in shadowing]}; erasure obligation NOT met"
        )

    return {"record": record_id, "closure_size": len(closure), "verified": True}


def read_with_ancestor_filter(store, query, authority_class):
    # A read is governance-safe only if it drops records whose provenance
    # closure contains a tombstoned ancestor dominating the read's authority.
    results = store.read(query)
    authority_rank = RETENTION_ORDER[authority_class]
    safe = []
    for rec in results:
        closure = store.provenance_closure(rec["id"], transitive=True) or []
        leaked = any(
            m.get("tombstoned")
            and RETENTION_ORDER[m["retention_class"]] >= authority_rank
            for m in closure
        )
        if leaked:
            # Ancestor was erased at or above this authority; do not surface.
            continue
        safe.append(rec)
    return safe
