# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-speculative-branch-that-has-already-passed-verification-the-divergent-tool-outcome-rollback-trap.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-speculative-branch-that-has-already-passed-verification-the-divergent-tool-outcome-rollback-trap.warrant.json
# Markdown SHA-256:   c71904e7a3cadd45e739b142304e46f57901b500be7cad66e2d7b7b23962791b
# Code AST SHA-256:   9a0381fbe7b28d422c0fa3dba95c5062c46a7985b6adfbbc13fa443ac9a8ae94
# Verified Classes:   StaleVerificationError, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Mapping


class StaleVerificationError(RuntimeError):
    """Raised when a branch's commit is attempted against resource versions
    that differ from those its verification was evaluated against."""


@dataclass
class Branch:
    branch_id: str
    read_set: Mapping[str, int]      # resource -> version observed during execution
    write_set: Mapping[str, int]     # resource -> version the write is conditional on
    verified: bool = False


def commit_branch(branch: Branch, live_versions: Mapping[str, int]) -> None:
    if not branch.verified:
        raise StaleVerificationError(
            f"branch {branch.branch_id} is not verified; refusing commit"
        )

    # The core check: verification is only a license to write if the world
    # it was evaluated against is still the live world.
    stale_reads = {
        res: (version, live_versions.get(res))
        for res, version in branch.read_set.items()
        if live_versions.get(res) != version
    }
    if stale_reads:
        raise StaleVerificationError(
            f"branch {branch.branch_id} verified against stale resource versions: "
            f"{stale_reads}; re-verify against live state before commit"
        )

    # Writes must be conditional on the exact version they were planned against.
    for res, expected in branch.write_set.items():
        if live_versions.get(res) != expected:
            raise StaleVerificationError(
                f"branch {branch.branch_id} write to {res!r} expected version "
                f"{expected}, live version is {live_versions.get(res)}; "
                f"compare-and-swap would fail closed"
            )

    # Only here — read-set fresh AND write-set CAS-valid — is commit permitted.
    for res, version in branch.write_set.items():
        live_versions[res] = version + 1


def rollback_branch(branch: Branch, live_versions: Mapping[str, int]) -> None:
    # Rollback must restore every resource the branch touched to the version
    # its siblings may have read, before sibling verification is trusted.
    for res, expected in branch.write_set.items():
        if live_versions.get(res) != expected + 1:
            raise StaleVerificationError(
                f"rollback of {branch.branch_id} found {res!r} at unexpected "
                f"version {live_versions.get(res)}; effect-complete rollback impossible"
            )
        live_versions[res] = expected
