# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-an-optimistic-tool-call-branch-it-can-no-longer-reconcile-after-a-speculative-peer-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-an-optimistic-tool-call-branch-it-can-no-longer-reconcile-after-a-speculative-peer-rollback.warrant.json
# Markdown SHA-256:   a81fcc7e08fe3b3048440eeb39105ce26a92d23f96ba102ff31ca3cf80f1263c
# Code AST SHA-256:   13baa4d2df77c0be069d0c0ce430db1d651f8ef4d697dcc7fdca9aafe8e46bcc
# Verified Classes:   UnreconcilableSpeculativeBranch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnreconcilableSpeculativeBranch(RuntimeError):
    """Raised when a speculative branch cannot be safely rolled back because a
    peer commit mutated the resource after the pre-image was captured."""
    pass


def rollback_speculative_branch(intent, resource_store):
    """
    intent: {branch_id, pre_image, captured_version, delta}
    Refuses inverse rollback if the resource version has moved since capture.
    """
    current = resource_store.read(intent["resource_id"])
    if current["version"] != intent["captured_version"]:
        # A peer committed between our capture and this rollback. The additive
        # inverse would layer on top of that commit and silently corrupt state.
        raise UnreconcilableSpeculativeBranch(
            f"branch {intent['branch_id']} captured version "
            f"{intent['captured_version']} but resource is now at "
            f"{current['version']}; inverse rollback would be a forward write. "
            f"Escalating to compensation."
        )
    # Safe: version matches, inverse restores exactly the captured pre-image.
    restored = resource_store.apply_delta(
        intent["resource_id"], -intent["delta"], expected_version=current["version"]
    )
    if restored["version"] != intent["captured_version"] + 1:
        raise UnreconcilableSpeculativeBranch(
            f"CAS rollback for {intent['branch_id']} produced unexpected "
            f"version {restored['version']}"
        )
    return {"branch_id": intent["branch_id"], "state": "ROLLED_BACK"}
