# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-replayed-write-the-tombstone-epoch-gap-in-persistent-agent-memory-poisoning-detection.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-replayed-write-the-tombstone-epoch-gap-in-persistent-agent-memory-poisoning-detection.warrant.json
# Markdown SHA-256:   8751ea5799c11ed0579fd652330e4590ce572275333d60ea374cf3d9b5ed64b1
# Code AST SHA-256:   7eaa6feef7da4e6e5e5b9c90e55754beb31053e50004386bebeaa3165972f03b
# Verified Classes:   ReplayEpochViolation, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ReplayEpochViolation(RuntimeError):
    """Raised when a write's epoch is below the key's live floor (replay poisoning)."""
    pass


class MemoryStore:
    def __init__(self):
        self.entries = {}          # key -> content
        self.min_live_epoch = {}   # key -> int floor

    def admit(self, key, record, floor_replicated: bool):
        # Epoch floor is checked FIRST, before signature/content.
        floor = self.min_live_epoch.get(key, 0)
        if record["epoch"] < floor:
            raise ReplayEpochViolation(
                f"key={key} epoch={record['epoch']} < floor={floor}: "
                f"superseded write replayed (sig valid but stale)"
            )
        if not floor_replicated:
            # Cannot prove freshness; quarantine rather than optimistically admit.
            raise ReplayEpochViolation(
                f"key={key}: floor not yet reconciled across replicas; "
                f"quarantining epoch={record['epoch']} to avoid replay window"
            )
        if not self._sig_ok(record) or not self._content_ok(record):
            raise ReplayEpochViolation(f"key={key}: authenticity/content check failed")
        self.entries[key] = record["content"]
        self.min_live_epoch[key] = max(floor, record["epoch"] + 1)

    def correct(self, key, new_record):
        # Correction atomically raises the floor with the write.
        self.entries[key] = new_record["content"]
        self.min_live_epoch[key] = new_record["epoch"] + 1

    def _sig_ok(self, r): return r.get("sig") is not None
    def _content_ok(self, r): return r.get("content") is not None
