# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-scoped-forget-tombstone-that-was-never-applied-to-the-semantic-tier.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-scoped-forget-tombstone-that-was-never-applied-to-the-semantic-tier.warrant.json
# Markdown SHA-256:   e15708fcc6701b69da34f0f6c25e7be33cdf1e733bb205b4eef0c910548103c3
# Code AST SHA-256:   504b26fbb1be8577402db3353dd3058dda7a815b274e3dd95898c335017989fa
# Verified Classes:   UnconfirmedForgetError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnconfirmedForgetError(RuntimeError):
    """Raised when a scoped forget returns success but derived facts survive."""
    pass


def scoped_forget(memory, scope: str, watermark: float, now: float) -> None:
    """
    Two-phase scoped forget with tombstone monotonicity and commit-time
    revalidation. Raises if the forget cannot be confirmed across tiers.
    """
    ack = memory.forget(scope=scope)
    if not ack.get("ok"):
        raise UnconfirmedForgetError(f"forget rejected for scope={scope}: {ack}")

    # Phase 2: the semantic tier may still be distilling traces captured
    # before the tombstone. A post-forget read is only authoritative once
    # the distillation watermark has advanced past the forget timestamp.
    if watermark < now:
        raise UnconfirmedForgetError(
            f"cannot confirm forget for scope={scope}: distillation watermark "
            f"{watermark} has not passed forget time {now}; tombstone may be "
            f"overtaken by in-flight commits"
        )

    survivors = memory.read(scope=scope, tiers=("episodic", "semantic"))
    if survivors:
        # A derived fact outlived its source scope. This is the resurrection
        # window: the tombstone was applied to episodic only, and a
        # distillation commit landed after the delete.
        raise UnconfirmedForgetError(
            f"forget for scope={scope} unconfirmed: {len(survivors)} derived "
            f"fact(s) survived, e.g. {survivors[0]!r}; re-issue with "
            f"derivation invalidation or escalate as integrity event"
        )
    return None
