# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-execute-a-fork-and-then-fail-to-roll-back-cleanly-when-a-sibling-branch-s-tool-call-diverges.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-execute-a-fork-and-then-fail-to-roll-back-cleanly-when-a-sibling-branch-s-tool-call-diverges.warrant.json
# Markdown SHA-256:   05e7e47d1ef10e1fcd3eaf036ab63714593e88e5d34137bcfd85c574f7d205d0
# Code AST SHA-256:   8a250447b839158c5572f44a687e397d6030040a6669ae9a7037958c4e439d4d
# Verified Classes:   UnsafeSpeculationError, EffectToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnsafeSpeculationError(RuntimeError):
    """Raised when a speculative branch is discarded while holding an
    unrevoked effect token, i.e. its tool effects have landed in the world
    but the branch is being rolled back as if it never ran."""


class EffectToken:
    def __init__(self, branch_id: str, tool: str, revocable: bool):
        self.branch_id = branch_id
        self.tool = tool
        self.revocable = revocable
        self.revoked = False


def rollback_branch(branch_id: str, tokens: list[EffectToken]) -> None:
    """Discard a speculative branch. Enforces the invariant that no branch
    is discarded while holding an unrevoked, non-revocable effect token."""
    outstanding = [t for t in tokens if not t.revoked]
    for token in outstanding:
        if not token.revocable:
            # The effect landed and cannot be compensated. Discarding the
            # branch now would leave a phantom write in the world with no
            # committed transition in the ledger.
            raise UnsafeSpeculationError(
                f"branch {branch_id} holds unrevoked non-revocable effect "
                f"token for tool {token.tool!r}; rollback would leave a "
                f"phantom write. Refusing to discard."
            )
        # Revocable: emit compensating call before dropping branch state.
        _emit_compensation(token)
        token.revoked = True
    _drop_branch_state(branch_id)


def _emit_compensation(token: EffectToken) -> None:
    # Placeholder: real implementation calls tool-specific revoke endpoint.
    pass


def _drop_branch_state(branch_id: str) -> None:
    # Placeholder: real implementation frees context and branch node.
    pass


def fork_and_speculate(branch_id: str, calls: list[dict]) -> list[EffectToken]:
    """Fork a branch and execute its tool calls, returning effect tokens.
    Refuses to fork if any call is effect-bearing and non-revocable, because
    such a branch cannot be safely discarded on divergence."""
    tokens = []
    for call in calls:
        if call["effect_bearing"] and not call["revocable"]:
            raise UnsafeSpeculationError(
                f"branch {branch_id} requests non-revocable effect-bearing "
                f"tool {call['tool']!r}; speculative fork is unsound. "
                f"Serialize this branch or use a dry-run-capable variant."
            )
        tokens.append(EffectToken(branch_id, call["tool"], call["revocable"]))
    return tokens
