# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-call-rollback-has-already-been-invalidated-by-a-sibling-agent-s-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-call-rollback-has-already-been-invalidated-by-a-sibling-agent-s-commit.warrant.json
# Markdown SHA-256:   a12c8cc6ba0d849e98f769445559c92483ac877d5467a73f6a296b7ec642a5cb
# Code AST SHA-256:   7b77c1b26c5cfe414d5444d371fa45a7f5416b7e19f9e6b0330d23a90170c2fc
# Verified Classes:   StaleRollbackError, Slot
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class StaleRollbackError(RuntimeError):
    """Raised when semantic rollback would overwrite a sibling agent's committed effect."""
    pass


class Slot:
    def __init__(self, quantity: int, version: int):
        self.quantity = quantity
        self.version = version


def semantic_rollback(slot: Slot, snapshot_version: int, pre_image_quantity: int) -> None:
    # The rollback is only valid if the resource has not advanced since the
    # speculative write took its snapshot. Re-reading to "get current state"
    # is exactly the trap: it hides the divergence.
    if slot.version != snapshot_version:
        raise StaleRollbackError(
            f"rollback invalid: snapshot_version={snapshot_version} "
            f"but current_version={slot.version}; a sibling agent has committed. "
            f"Reconcile against current state instead of restoring pre-image "
            f"{pre_image_quantity}."
        )
    slot.quantity = pre_image_quantity
    slot.version += 1


def safe_commit_or_rollback(slot: Slot, snapshot_version: int, pre_image_quantity: int,
                            speculative_commit) -> str:
    if slot.version == snapshot_version:
        speculative_commit(slot)
        return "committed"
    # Diverged: do NOT roll back blindly. Attempt reconciliation.
    semantic_rollback(slot, snapshot_version, pre_image_quantity)  # raises
    return "rolled_back"
