# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-store-forget-call-as-a-hard-precondition-rather-than-a-best-effort-cleanup.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-store-forget-call-as-a-hard-precondition-rather-than-a-best-effort-cleanup.warrant.json
# Markdown SHA-256:   b90f4321927fba80292b07e2604a31fe8e38b0c82067e325bd78246e53025330
# Code AST SHA-256:   ace84e6de2855a7940eaa4f6a4750a52d6af54b0f1d37c77cb686bc31c99a91f
# Verified Classes:   ForgetInvariantViolation, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ForgetInvariantViolation(RuntimeError):
    """Raised when a forgotten pattern is still observable via a read path."""
    pass


class MemoryStore:
    def __init__(self, records=None, tombstone_lag_s=0.0):
        # records: key -> {"value": ..., "weight": float}
        self.records = dict(records or {})
        self.tombstones = set()
        self.tombstone_lag_s = tombstone_lag_s

    def forget(self, key):
        # Tombstone written to primary; read path may lag.
        self.tombstones.add(key)
        return "ok"

    def read(self, pattern):
        # Naive scan path: does NOT consult tombstones (the leak).
        import fnmatch
        return {k: v for k, v in self.records.items() if fnmatch.fnmatch(k, pattern)}


def forget_with_barrier(store, pattern, probe_attempts=2):
    """Forget a pattern and assert it is unreachable before returning.

    Hard precondition: after this returns, no read over `pattern`
    in the same causal chain may return a record.
    """
    store.forget(pattern)  # best-effort tombstone

    for attempt in range(probe_attempts):
        leaked = store.read(pattern)
        if not leaked:
            return  # invariant holds; safe to proceed
        # Scan path still serves the record: tombstone did not cover scans.
        # Attempt to widen the tombstone to the concrete keys.
        for key in list(leaked):
            store.tombstones.add(key)
            store.records.pop(key, None)  # physically remove from scan path

    leaked = store.read(pattern)
    if leaked:
        raise ForgetInvariantViolation(
            f"forget({pattern!r}) succeeded but pattern still readable: "
            f"{sorted(leaked)} — scan path not covered by tombstone set; "
            f"do not proceed on the assumption the record is gone"
        )


def resume_from_checkpoint(store, plan_pattern):
    # Agent reconstructs context via a pattern read after forgetting.
    forget_with_barrier(store, plan_pattern)
    context = store.read(plan_pattern)
    if context:
        raise ForgetInvariantViolation(
            "context reconstruction observed a forgotten record; "
            "stale-memory drift would compound downstream"
        )
    return context
