# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-and-verify-rollback-from-resurrecting-a-poisoned-sibling-draft-in-parallel-subagent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-and-verify-rollback-from-resurrecting-a-poisoned-sibling-draft-in-parallel-subagent-execution.warrant.json
# Markdown SHA-256:   6313b43572f829f0b2eea794d9ace6ad57ff9fe35d785a0081e45dff078af9d7
# Code AST SHA-256:   2d67c65cb4a9651b3609db4759418daeab04a6f4924443b297339eed78cc2184
# Verified Classes:   SpeculativeEpochLeak, EpochScopedStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeEpochLeak(RuntimeError):
    """Raised when a live branch reads shared state written by another, uncommitted speculative epoch."""
    pass


class EpochScopedStore:
    def __init__(self):
        # key -> {epoch: value}; only committed epoch is globally readable
        self._slots = {}
        self._committed_epoch = None

    def write(self, epoch, key, value):
        self._slots.setdefault(key, {})[epoch] = value

    def commit(self, epoch):
        self._committed_epoch = epoch

    def read(self, reader_epoch, key):
        slot = self._slots.get(key)
        if not slot:
            return None
        if reader_epoch in slot:
            return slot[reader_epoch]
        if self._committed_epoch in slot:
            return slot[self._committed_epoch]
        # A sibling epoch wrote this key; reading it would launder a
        # speculative draft into a live branch before rollback fires.
        foreign = [e for e in slot if e != reader_epoch]
        raise SpeculativeEpochLeak(
            f"branch epoch {reader_epoch!r} attempted to read key {key!r} "
            f"written only by uncommitted epoch(s) {foreign!r}"
        )


def rollback_epoch(store, epoch, live_epochs):
    if epoch in live_epochs:
        raise SpeculativeEpochLeak(
            f"cannot roll back epoch {epoch!r}: still referenced by live branch(es) {live_epochs!r}"
        )
    # Eviction, not compensation: drop every slot entry for this epoch.
    for key in list(store._slots):
        store._slots[key].pop(epoch, None)
        if not store._slots[key]:
            del store._slots[key]
