# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-that-a-peer-agent-s-cached-retrieval-plan-still-references.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-that-a-peer-agent-s-cached-retrieval-plan-still-references.warrant.json
# Markdown SHA-256:   7f4122f09ea8904407f15d4fba52f91caa0bd30f4429f0d181570098efcaad18
# Code AST SHA-256:   eadfcad7a103f66371eec52ecd0de840974aaff816241d1a70df376378a656fa
# Verified Classes:   StalePlanError, RetrievalPlan, MemoryService
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class StalePlanError(RuntimeError):
    """Raised when a compiled retrieval plan is executed against an epoch
    older than the scope's tombstone epoch, risking resurrection of
    forgotten memory through a secondary access path."""
    pass


@dataclass
class RetrievalPlan:
    scope: str
    key_handles: List[str]
    embedding_row_ids: List[int]
    pinned_epoch: int
    compiled_at: float


@dataclass
class MemoryService:
    tombstone_epoch: Dict[str, int] = field(default_factory=dict)
    tombstoned_keys: Dict[str, set] = field(default_factory=dict)

    def current_tombstone_epoch(self, scope: str) -> int:
        return self.tombstone_epoch.get(scope, 0)

    def forget(self, scope: str, keys: List[str]) -> None:
        self.tombstoned_keys.setdefault(scope, set()).update(keys)
        # Bumping the epoch is the only signal peers can observe.
        self.tombstone_epoch[scope] = self.current_tombstone_epoch(scope) + 1

    def execute_plan(self, plan: RetrievalPlan) -> Dict[str, object]:
        current = self.current_tombstone_epoch(plan.scope)
        if plan.pinned_epoch < current:
            # The plan was compiled before a forget; its secondary paths
            # (embedding_row_ids) may point into a pre-forget shard.
            raise StalePlanError(
                f"plan for scope={plan.scope!r} pinned at epoch "
                f"{plan.pinned_epoch} but tombstone epoch is {current}; "
                f"recompile before execute to avoid resurrection"
            )
        dead = self.tombstoned_keys.get(plan.scope, set())
        live_keys = [k for k in plan.key_handles if k not in dead]
        return {"keys": live_keys, "row_ids": plan.embedding_row_ids}


def safe_resume(service: MemoryService, plan: RetrievalPlan) -> Dict[str, object]:
    """Resume a cached plan, recompiling if a forget has invalidated it."""
    try:
        return service.execute_plan(plan)
    except StalePlanError:
        plan.pinned_epoch = service.current_tombstone_epoch(plan.scope)
        return service.execute_plan(plan)


if __name__ == "__main__":
    svc = MemoryService()
    plan = RetrievalPlan(
        scope="tenant:4417/session:88",
        key_handles=["k1", "k2", "k3", "k4"],
        embedding_row_ids=[101, 102, 103, 104],
        pinned_epoch=svc.current_tombstone_epoch("tenant:4417/session:88"),
        compiled_at=0.0,
    )
    svc.forget("tenant:4417/session:88", ["k2", "k3"])
    try:
        svc.execute_plan(plan)
    except StalePlanError as exc:
        print(f"blocked resurrection: {exc}")
    result = safe_resume(svc, plan)
    print(f"resumed safely: {result}")
