# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-forget-as-a-two-phase-operation-across-the-memory-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-forget-as-a-two-phase-operation-across-the-memory-tool-boundary.warrant.json
# Markdown SHA-256:   221dd9d1fc0e2dbfdba5a5d242912381a17a1b620e9480934902ed027ed99f53
# Code AST SHA-256:   e626b0dd905a7a1b6648ab3034d745aa014c4d299e89da242950837b84a72461
# Verified Classes:   ForgetReachabilityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ForgetReachabilityError(RuntimeError):
    """Raised when a forget operation reports success but the datum
    remains reachable through a derivative scope or live context."""
    pass


def two_phase_forget(memory, datum_id, target_scope, live_context, peers):
    # Phase 1: backend tombstone over the declared scope.
    result = memory.forget(scope=target_scope, datum_id=datum_id)
    if result["status"] != "deleted":
        raise ForgetReachabilityError(
            f"backend refused forget for {datum_id} in {target_scope}"
        )

    # Phase 2a: evict any context-resident copy.
    if live_context.contains(datum_id):
        live_context.evict(datum_id)

    # Phase 2b: invalidate derivative scopes not covered by the predicate.
    derivative_scopes = memory.derivative_scopes_of(datum_id)
    uncovered = [s for s in derivative_scopes if not target_scope.contains(s)]
    for scope in uncovered:
        memory.invalidate_derivatives(scope, source=datum_id)

    # Phase 2c: notify peers sharing the scope.
    for peer in peers.sharing(target_scope):
        peer.invalidate(datum_id, scope=target_scope)

    # Post-condition probe: fail closed if any path still resolves.
    probe_scopes = [target_scope] + uncovered
    for scope in probe_scopes:
        if memory.retrieve(scope=scope, query=datum_id):
            raise ForgetReachabilityError(
                f"datum {datum_id} still reachable in {scope} after forget"
            )
    if live_context.contains(datum_id):
        raise ForgetReachabilityError(
            f"datum {datum_id} still resident in live context after eviction"
        )

    return {"status": "forgotten", "datum_id": datum_id, "scopes_drained": probe_scopes}
