# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-execution-when-a-rollback-invalidates-a-sibling-branch-s-optimistic-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-execution-when-a-rollback-invalidates-a-sibling-branch-s-optimistic-tool-call.warrant.json
# Markdown SHA-256:   cc42d89e96081b484672ed242980fbee2c0ae08c4e0279a40745035a5abc34e1
# Code AST SHA-256:   9cf41b92803310ccf69c53ff36c3fb5b3afc8c0005f583043e65ce88b8b1bdc1
# Verified Classes:   SharedResourceRollbackViolation, BranchGrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SharedResourceRollbackViolation(RuntimeError):
    """Raised when a speculative branch attempts a snapshot-restore rollback
    on a resource it does not exclusively own."""
    pass


class BranchGrant:
    """Coordinator-issued ownership record for a speculative branch."""

    def __init__(self, branch_id: str, resource: str, exclusive: bool,
                 snapshot_version: int):
        self.branch_id = branch_id
        self.resource = resource
        self.exclusive = exclusive
        self.snapshot_version = snapshot_version


def authorize_rollback(grant: BranchGrant, current_version: int,
                       cas_capable: bool) -> str:
    """Decide whether a branch may roll back a resource, and by what mechanism.

    Returns the rollback mechanism to use. Raises if no sound mechanism exists.
    """
    if grant.exclusive:
        # Exclusive ownership: snapshot-restore is sound because no sibling
        # could have written in the window.
        return "snapshot_restore"

    if current_version != grant.snapshot_version:
        # A sibling advanced the resource after our snapshot. Blind restore
        # would erase their write. We must use an inverse operation, and only
        # if the tool supports conditional writes.
        if not cas_capable:
            raise SharedResourceRollbackViolation(
                f"branch {grant.branch_id} cannot roll back shared resource "
                f"{grant.resource}: snapshot version {grant.snapshot_version} "
                f"is stale (current {current_version}) and tool is not "
                f"CAS-capable. Refusing to emit compensating write."
            )
        return "inverse_operation_cas"

    # Version unchanged: our snapshot still reflects the resource, so
    # snapshot-restore is safe even on a shared resource.
    return "snapshot_restore"


def execute_rollback(grant: BranchGrant, current_version: int,
                     cas_capable: bool, apply_fn) -> None:
    mechanism = authorize_rollback(grant, current_version, cas_capable)
    if mechanism == "snapshot_restore":
        apply_fn.restore_snapshot(grant.resource, grant.snapshot_version)
    elif mechanism == "inverse_operation_cas":
        ok = apply_fn.inverse_cas(grant.resource, grant.snapshot_version,
                                  current_version)
        if not ok:
            # CAS lost the race to yet another writer; surface rather than
            # silently overwrite.
            raise SharedResourceRollbackViolation(
                f"CAS rollback for branch {grant.branch_id} on "
                f"{grant.resource} lost race; manual reconciliation required."
            )
    else:
        raise SharedResourceRollbackViolation(
            f"unknown rollback mechanism {mechanism!r}"
        )
