# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-a-forget-tool-call-as-a-tombstone-rather-than-a-delete-and-why-silent-resurrection-follows-a-scoped-retention-mismatch.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-a-forget-tool-call-as-a-tombstone-rather-than-a-delete-and-why-silent-resurrection-follows-a-scoped-retention-mismatch.warrant.json
# Markdown SHA-256:   648ba1a454e2652183827daef9338de4d3d7480992ce06b458cb2cf949d0e88e
# Code AST SHA-256:   d658075740048c1279362fe04519a224b528bdab263476261104dcee22c6b98f
# Verified Classes:   ResurrectionDetected, UnverifiedForget, MemoryAPI
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from typing import Callable


class ResurrectionDetected(RuntimeError):
    """Raised when a key marked forgotten in one scope reappears via a derived scope."""


class UnverifiedForget(RuntimeError):
    """Raised when a forget cannot be confirmed against the full read surface."""


@dataclass
class MemoryAPI:
    # authoritative scopes only; derived scopes are simulated by promoting jobs
    scopes: dict[str, dict[str, str]] = field(default_factory=dict)
    tombstones: set[str] = field(default_factory=set)  # global, if supported
    supports_global_tombstone: bool = False
    max_derivation_lag_s: float = 2.0

    def write(self, scope: str, key: str, value: str) -> None:
        self.scopes.setdefault(scope, {})[key] = value

    def read(self, scope: str, key: str) -> str | None:
        if self.supports_global_tombstone and key in self.tombstones:
            return None
        return self.scopes.get(scope, {}).get(key)

    def forget(self, scope: str, key: str) -> dict:
        removed = 1 if self.scopes.get(scope, {}).pop(key, None) is not None else 0
        if self.supports_global_tombstone:
            self.tombstones.add(key)
        return {"status": "deleted", "scope": scope, "keys_removed": removed}


def forget_with_confirmation(
    api: MemoryAPI,
    key: str,
    authoritative_scope: str,
    derived_scopes: list[str],
    recheck_after_s: float,
    clock: Callable[[], float] = time.monotonic,
    sleep: Callable[[float], None] = time.sleep,
) -> None:
    # Phase 1: mark
    api.forget(authoritative_scope, key)
    for scope in derived_scopes:
        api.forget(scope, key)

    # Phase 2: confirm against the full read surface, bounded by derivation lag
    if api.supports_global_tombstone:
        if key not in api.tombstones:
            raise UnverifiedForget(
                f"forget of {key!r} did not register a global tombstone; "
                "derived scopes may still resurrect it"
            )
        return

    # No global tombstone: wait out the maximum derivation lag and re-read every scope
    deadline = clock() + max(recheck_after_s, api.max_derivation_lag_s)
    while clock() < deadline:
        sleep(min(0.25, deadline - clock()))
        for scope in [authoritative_scope, *derived_scopes]:
            if api.read(scope, key) is not None:
                raise ResurrectionDetected(
                    f"key {key!r} reappeared in scope {scope!r} after forget; "
                    "a pre-forget derivative was re-promoted"
                )
    # clean across the whole surface for the full lag window
    return


def _demo() -> None:
    api = MemoryAPI(supports_global_tombstone=False, max_derivation_lag_s=0.5)
    api.write("episodic", "user.home_city", "Lisbon")
    # simulate a distillation job that captured the value before the forget
    in_flight = api.read("episodic", "user.home_city")

    try:
        forget_with_confirmation(
            api,
            key="user.home_city",
            authoritative_scope="episodic",
            derived_scopes=["semantic", "index"],
            recheck_after_s=0.5,
            sleep=lambda s: (time.sleep(s), api.write("semantic", "user.home_city", in_flight or "")),
        )
    except ResurrectionDetected as exc:
        # correct outcome: the agent learns the forget was not global
        print(f"handled: {exc}")


if __name__ == "__main__":
    _demo()
