# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-forget-acknowledgment-with-in-flight-retrieval-that-has-already-left-the-store.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-forget-acknowledgment-with-in-flight-retrieval-that-has-already-left-the-store.warrant.json
# Markdown SHA-256:   ae31cf2f1cf84e6d0c7f66f9881178728a45e5607276e0cc5be2d4ac337afc77
# Code AST SHA-256:   6e63a11ef61b3e3453655f11700b1de6dbcc24959a46b53fec923a2c2edf112c
# Verified Classes:   IncompleteForgetError, ForgetLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class IncompleteForgetError(RuntimeError):
    """Raised when a forget ack is treated as terminal while agent-side
    reachable state (derived writes or live context) still contains the
    forgotten record's content."""
    pass


@dataclass
class ForgetLedger:
    # source_record_id -> set of derived record ids written from it
    derived: Dict[str, Set[str]] = field(default_factory=dict)
    # record ids currently present in the live context window
    live_context: Set[str] = field(default_factory=set)

    def record_write(self, source_id: str, derived_id: str) -> None:
        self.derived.setdefault(source_id, set()).add(derived_id)

    def closure(self, source_id: str) -> Set[str]:
        """Transitive closure of derived records reachable from source_id."""
        seen: Set[str] = set()
        stack = [source_id]
        while stack:
            cur = stack.pop()
            for d in self.derived.get(cur, ()):
                if d not in seen:
                    seen.add(d)
                    stack.append(d)
        return seen


def reconcile_forget(
    ledger: ForgetLedger,
    source_id: str,
    ack: dict,
    scrub_available: bool,
) -> None:
    """Enforce the erasure invariant before allowing the ack to be treated
    as terminal. Raises IncompleteForgetError if the agent-side closure is
    non-empty and cannot be emptied."""
    if ack.get("deleted", 0) < 1:
        raise IncompleteForgetError(
            f"store did not confirm deletion of {source_id!r}: {ack!r}"
        )

    # 1. Derived-write leakage: cascade forget over the closure.
    pending = ledger.closure(source_id)
    if pending:
        # In a real implementation these are forget() tool calls; here we
        # assert the caller has already issued them and they succeeded.
        unconfirmed = {d for d in pending if d not in ack.get("cascaded", set())}
        if unconfirmed:
            raise IncompleteForgetError(
                f"derived records still live after forget of {source_id!r}: "
                f"{sorted(unconfirmed)}"
            )

    # 2. Live-context reference: source must be scrubbed or rolled over.
    if source_id in ledger.live_context:
        if not scrub_available:
            raise IncompleteForgetError(
                f"{source_id!r} still present in live context and runtime "
                f"cannot scrub; mark scope forget-pending and refuse to emit "
                f"downstream artifacts until context rolls over"
            )
        ledger.live_context.discard(source_id)

    # 3. Ack-scope ambiguity: scope_remaining must not be read as
    #    "whole scope empty" unless the ack partitions match.
    if ack.get("scope_remaining", 0) == 0 and ack.get("scope") is not None:
        # No assertion possible here without the store's partition metadata;
        # record the parse so downstream consumers don't over-read the ack.
        ack["_parsed_as"] = "key-partition-empty, not scope-empty"

    # Closure is empty on both sides: ack is now terminal.
    return


def handle_forget_ack(ledger: ForgetLedger, source_id: str, ack: dict,
                      scrub_available: bool) -> str:
    try:
        reconcile_forget(ledger, source_id, ack, scrub_available)
    except IncompleteForgetError as e:
        return f"FORGET-INCOMPLETE: {e}"
    return "FORGET-COMPLETE"
