# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-forget-before-the-retention-window-closes-the-deletion-acknowledgement-inversion-in-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-forget-before-the-retention-window-closes-the-deletion-acknowledgement-inversion-in-memory-tool-apis.warrant.json
# Markdown SHA-256:   523cf1993d6dcaa4962570ea76f3b90a427effe51e8aeb02e0c2a3eadca76369
# Code AST SHA-256:   7ca0a7d56f0a310f5d1aab5138c7be4bc27f978d38e8da6383331e433810242f
# Verified Classes:   UnverifiedForgetError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnverifiedForgetError(RuntimeError):
    """Raised when an agent would record a deletion guarantee the backend has not actually established."""
    pass


def commit_forget_belief(memory_api, scope: str, key: str, now_ts: float) -> dict:
    """
    Issue a scoped forget and only commit the 'erased' belief if the
    derivation readback confirms no live artifacts survive the scope.
    """
    target = memory_api.stat(scope=scope, key=key)
    if target is None:
        return {"status": "absent", "guarantee": "none"}

    # Premature deletion: retention window still open.
    if target.get("retention_until", 0) > now_ts:
        raise UnverifiedForgetError(
            f"refusing forget of {scope}/{key}: retention_until="
            f"{target['retention_until']} still open at {now_ts}; "
            f"backend may no-op or defer"
        )

    ack = memory_api.forget(scope=scope, key=key)
    if not ack.get("deleted"):
        raise UnverifiedForgetError(
            f"forget of {scope}/{key} returned no deletion: {ack!r}"
        )

    # The critical leg: a row-count ack is not an information guarantee.
    derivations = memory_api.derivations(scope=scope, key=key)
    live = [d for d in derivations if d.get("retention_until", 0) > now_ts]
    if live:
        raise UnverifiedForgetError(
            f"forget of {scope}/{key} left {len(live)} live derivative(s) "
            f"outside scope (e.g. {live[0]['scope']}); "
            f"ack={ack!r} is a row guarantee, not an information guarantee"
        )

    return {
        "status": "erased",
        "guarantee": "verified",
        "derivations_checked": len(derivations),
    }
