# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-a-forget-tombstone-against-a-pending-write-that-was-admitted-before-the-tombstone-but-landed-after-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-a-forget-tombstone-against-a-pending-write-that-was-admitted-before-the-tombstone-but-landed-after-it.warrant.json
# Markdown SHA-256:   6fcec8855d6a0091cccf5927d909ae9c49bdc6c2c095da1f7fb56449c184cbcb
# Code AST SHA-256:   111e39e8f2865c70f78a7663ac8ccd4037a12689c3738966f442c1c5e4493aba
# Verified Classes:   ForgetWriteInversionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ForgetWriteInversionError(RuntimeError):
    """Raised when a forget commits before a write admitted earlier against the same scope."""
    pass


def reconcile_forget(memory, scope: str, predicate: str, admitted_writes: int,
                     max_drain_polls: int = 8) -> dict:
    """
    Two-phase forget: issue the tombstone, then drain any writes admitted before it
    but not yet committed, and re-issue until the scope is quiescent.

    admitted_writes: number of write() calls the agent issued against `scope`
    for the matching key/predicate since the last confirmed forget. If the
    substrate cannot report this, pass -1 to force conservative draining.
    """
    result = memory.forget(scope=scope, predicate=predicate)
    deleted = result.get("deleted", 0)
    in_flight = result.get("in_flight", None)

    if in_flight is None:
        # Substrate gives no in-flight visibility: we cannot distinguish
        # "nothing to delete" from "a write is about to land". Drain blindly.
        in_flight = max(admitted_writes, 0)

    polls = 0
    while in_flight > 0 and polls < max_drain_polls:
        memory.drain(scope=scope)          # force pending writes to commit
        in_flight = memory.pending_writes(scope=scope)
        polls += 1

    if in_flight > 0:
        raise ForgetWriteInversionError(
            f"scope={scope!r} predicate={predicate!r}: {in_flight} writes still "
            f"in flight after {polls} drain polls; tombstone cannot be trusted. "
            f"Escalate to generation bump or abort the task."
        )

    # Re-issue now that the index reflects every admitted write.
    result = memory.forget(scope=scope, predicate=predicate)
    deleted = result.get("deleted", 0)

    if admitted_writes >= 0 and deleted < admitted_writes:
        raise ForgetWriteInversionError(
            f"scope={scope!r} predicate={predicate!r}: admitted {admitted_writes} "
            f"writes but forget deleted {deleted}; a late write resurrected content "
            f"the planner believes is retired. Do not trust the scope as empty."
        )

    return result
