# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-verifier-gated-commit-has-already-absorbed-a-divergent-branch-it-is-about-to-roll-back.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-verifier-gated-commit-has-already-absorbed-a-divergent-branch-it-is-about-to-roll-back.warrant.json
# Markdown SHA-256:   054c9972afb2cef1a91432a697ca15774665494bd6aaefc5f227d92aaf3efb00
# Code AST SHA-256:   2642530e06094037c5520cbea14790a796e13c6cca169a67beaf339056bf1163
# Verified Classes:   StaleRollbackError, StateStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class StaleRollbackError(RuntimeError):
    """Raised when a rollback token would clobber a commit that advanced the epoch."""
    pass


@dataclass
class StateStore:
    value: Any = None
    epoch: int = 0
    journal: list = field(default_factory=list)

    def commit(self, branch_id: str, value: Any) -> int:
        self.epoch += 1
        self.value = value
        self.journal.append((self.epoch, branch_id, "commit", value))
        return self.epoch

    def rollback(self, branch_id: str, token_epoch: int) -> None:
        # A rollback is only valid against the epoch it captured from.
        # If a commit has advanced the epoch past the token, this rollback
        # would invert a commit it never saw. Reject, do not apply.
        if token_epoch != self.epoch:
            raise StaleRollbackError(
                f"branch {branch_id} rollback token epoch={token_epoch} "
                f"is stale; current epoch={self.epoch}. "
                f"Refusing to clobber committed state."
            )
        self.epoch += 1
        self.value = None
        self.journal.append((self.epoch, branch_id, "rollback", None))

    def reconcile(self) -> Any:
        # Final committed value = last *commit* op in the journal, not last op.
        committed = [op for op in self.journal if op[2] == "commit"]
        if not committed:
            return None
        return committed[-1][3]


def speculative_execute(store: StateStore, branches: dict[str, Any], winner: str) -> Any:
    tokens = {bid: store.epoch for bid in branches}  # captured before any branch writes
    for bid, val in branches.items():
        store.journal.append((store.epoch, bid, "draft", val))
    store.commit(winner, branches[winner])
    for bid in branches:
        if bid == winner:
            continue
        try:
            store.rollback(bid, tokens[bid])
        except StaleRollbackError:
            # Expected: winner's commit advanced the epoch. Skip, do not clobber.
            continue
    final = store.reconcile()
    if final != branches[winner]:
        raise StaleRollbackError(
            f"post-sweep reconciliation failed: committed {branches[winner]!r} "
            f"but store holds {final!r}"
        )
    return final
