# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-fan-out-before-rollback-divergence-corrupts-the-shared-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-fan-out-before-rollback-divergence-corrupts-the-shared-checkpoint.warrant.json
# Markdown SHA-256:   b65f8fc37584c6529b85236481af7996183da020291c891c1bccce47a9cd02db
# Code AST SHA-256:   a68ff186215e1e4b95267b50b751ac0222cd5596df7fa63229855f7eda84e79a
# Verified Classes:   RollbackDivergenceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RollbackDivergenceError(RuntimeError):
    """Raised when rolling back a losing speculative branch would leave
    externally observable effects that the commit path can still see."""
    pass


# Tool effect classes. Only PURE and BRANCH_LOCAL are safe to execute
# speculatively; ESCAPING tools must be deferred behind an intent log.
PURE = "pure"                 # reads only, no mutation
BRANCH_LOCAL = "branch_local" # writes confined to branch namespace, GC'd on rollback
ESCAPING = "escaping"         # non-idempotent or commit-path-visible mutation


def fork_branch(checkpoint, tools, branch_id):
    """Fork a speculative branch. Refuse to hand out escaping tools."""
    handles = {}
    for name, effect_class in tools.items():
        if effect_class == ESCAPING:
            # Do not grant the live handle; grant a deferred intent recorder.
            handles[name] = DeferredIntent(name, branch_id)
        else:
            handles[name] = LiveHandle(name, branch_id)
    return Branch(checkpoint=checkpoint, branch_id=branch_id, handles=handles)


def rollback(branch, committed_branch_id):
    """Roll back a losing branch. Must be the exact inverse of its execution."""
    if branch.branch_id == committed_branch_id:
        return  # survivor, never rolled back here

    for name, handle in branch.handles.items():
        if isinstance(handle, LiveHandle) and handle.effect_class == ESCAPING:
            # A live escaping handle was granted at fork time; its effects
            # cannot be truncated. This is the invariant violation.
            raise RollbackDivergenceError(
                f"branch {branch.branch_id} held live escaping handle "
                f"'{name}'; truncation cannot undo its external effects, "
                f"and the commit path may already observe them"
            )
        if isinstance(handle, DeferredIntent):
            handle.discard()  # intent log dropped, never replayed

    branch.truncate_to(branch.checkpoint)  # safe: only pure/branch-local effects
    branch.release_namespace()             # GC branch-local writes


def commit(survivor, tools):
    """Replay only the survivor's deferred intents against real tools."""
    for intent in survivor.deferred_intents_in_order():
        effect_class = tools[intent.tool_name]
        if effect_class != ESCAPING:
            raise RollbackDivergenceError(
                f"intent for non-escaping tool '{intent.tool_name}' should "
                f"have executed live, not been deferred; provenance is broken"
            )
        intent.replay_against_real_tool()
    survivor.mark_committed()
