# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-own-rollback-log-when-speculative-branches-re-merge-across-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-own-rollback-log-when-speculative-branches-re-merge-across-agents.warrant.json
# Markdown SHA-256:   03e8b3a944676d442ab1991bd2bd767c4604e4dfe31a6898f4ce456f33611bf5
# Code AST SHA-256:   af30765faf74cfaad6b4eb020bc761104ef1c1a4b28934a385cbcfdc5e0a961d
# Verified Classes:   RollbackDivergenceError, JournalEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any


class RollbackDivergenceError(RuntimeError):
    """Raised when a speculative branch's journal cannot be soundly replayed
    because an overlapping branch mutated a key in its write/read set between
    snapshot and rollback. Signals that semantic reconciliation is required."""


@dataclass(frozen=True)
class JournalEntry:
    key: str
    value_old: Any
    version_at_read: int
    is_write: bool


def rollback_branch(
    journal: list[JournalEntry],
    current_versions: dict[str, int],
    committed_writes: set[str],
) -> list[tuple[str, Any]]:
    """Replay a losing branch's inverse journal, but only where sound.

    Returns the list of (key, value) restorations that are safe to apply.
    Raises RollbackDivergenceError if any entry is unsound, so the caller
    escalates to semantic re-derivation instead of silently clobbering.
    """
    restorations: list[tuple[str, Any]] = []
    for entry in journal:
        if not entry.is_write:
            # Read-set entries: a committed write to a key this branch read
            # invalidates the branch's basis; cannot be fixed by replay.
            if entry.key in committed_writes:
                raise RollbackDivergenceError(
                    f"read-set key {entry.key!r} was committed by another "
                    f"branch after snapshot (version_at_read="
                    f"{entry.version_at_read}); syntactic replay unsound"
                )
            continue

        current = current_versions.get(entry.key, 0)
        if current != entry.version_at_read:
            # Another branch wrote this key after our snapshot: our undo
            # would resurrect a superseded value or delete a changed key.
            raise RollbackDivergenceError(
                f"write-set key {entry.key!r} diverged: journal expected "
                f"version {entry.version_at_read}, found {current}; "
                f"escalate to semantic reconciliation"
            )
        restorations.append((entry.key, entry.value_old))
    return restorations


def reconcile_loser(
    journal: list[JournalEntry],
    current_versions: dict[str, int],
    committed_writes: set[str],
    semantic_rederive,
) -> None:
    try:
        restorations = rollback_branch(journal, current_versions, committed_writes)
    except RollbackDivergenceError as exc:
        # Do NOT replay. Re-invoke the branch owner against the committed view.
        semantic_rederive(reason=str(exc))
        return
    apply_restorations(restorations)


def apply_restorations(restorations: list[tuple[str, Any]]) -> None:
    # Storage-layer apply; only reached when the journal is provably sound.
    for key, value in restorations:
        _store_put(key, value)


def _store_put(key: str, value: Any) -> None:  # placeholder for real store
    raise NotImplementedError
