# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-ttl-forget-race-in-scoped-memory-tool-apis-when-a-deletion-tombstone-and-a-retention-expiry-collide.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-ttl-forget-race-in-scoped-memory-tool-apis-when-a-deletion-tombstone-and-a-retention-expiry-collide.warrant.json
# Markdown SHA-256:   fcb9b9cb9ffda4e29df2c46e83a73acac336818db5438aa746ccbe23011363ff
# Code AST SHA-256:   4681df3d6e3fccaf3fe3f350e703bfef1ca636dbb189fbaf50345ce83fcf014d
# Verified Classes:   ForgetRaceError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ForgetRaceError(RuntimeError):
    """Raised when a forget call cannot prove its obligation was met."""
    pass


def forget_record(store, read_paths, scope: str, key: str) -> dict:
    """Honor an RTBF forget for `key` in `scope`.

    Absence of the record is NOT sufficient evidence of forget. If the record
    is absent but no tombstone exists, a TTL expiry may have raced the forget
    and a lagging read path may still serve the value. In that case we must
    write an unconditional tombstone before reporting success.
    """
    record = store.get(scope, key)
    tombstone = store.get_tombstone(scope, key)

    if record is not None:
        store.write_tombstone(scope, key, reason="forget")
        store.delete(scope, key)
        return {"deleted": 1, "already_forgotten": False}

    if tombstone is not None:
        return {"deleted": 0, "already_forgotten": True}

    # Ambiguous: record absent, no tombstone. Could be TTL expiry that beat us.
    # We must still write a tombstone so lagging read paths are suppressed.
    store.write_tombstone(scope, key, reason="forget_after_expiry")

    # Verify no read path still serves the value. If one does, the tombstone
    # did not propagate and the forget obligation is unmet.
    for path in read_paths:
        if path.get(scope, key) is not None:
            raise ForgetRaceError(
                f"post-forget leakage for {scope}/{key} on read path "
                f"{path.name!r}; tombstone not yet effective"
            )

    return {"deleted": 0, "already_forgotten": False, "tombstone_reason": "forget_after_expiry"}
