# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-optimistic-tool-invocation-after-a-branch-and-verify-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-optimistic-tool-invocation-after-a-branch-and-verify-rollback.warrant.json
# Markdown SHA-256:   1928a67d731883214b36fa15ea44e1eee511d761a6839d33788482cf1714acdd
# Code AST SHA-256:   8bd3d0c158b3eb926a46e769257c7ca262759eeef80a2ec4180888599f2cd8c2
# Verified Classes:   OrphanedSideEffectError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OrphanedSideEffectError(RuntimeError):
    """Raised when a rolled-back branch leaves an un-compensated world mutation."""
    pass


NON_COMPENSABLE = {"register_resource", "enqueue_job", "notify_owner", "authorize_payment"}


def rollback_branch(branch, effect_ledger, compensation_queue):
    """Discard a losing branch's reasoning, but never its world-mutating acks.

    effect_ledger[branch.id] holds (tool, token, ack_status) tuples recorded at
    optimistic-invocation time. Rollback is legal only if every acked effect is
    either idempotent-replayable by the winner or queued for compensation.
    """
    for tool, token, ack in effect_ledger.get(branch.id, []):
        if ack not in ("201", "202", "200"):
            continue  # no world mutation acknowledged; safe to discard
        if tool in NON_COMPENSABLE and not compensation_queue.has(token):
            raise OrphanedSideEffectError(
                f"branch {branch.id} acked {tool}(token={token}) with no "
                f"compensation; silent rollback would orphan world state"
            )
        compensation_queue.require(token, tool)

    branch.discard_reasoning()
    return True


def speculate(subtask, branches):
    """Fork only if every tool is idempotent-or-compensable; else serialize."""
    if subtask.tools & NON_COMPENSABLE:
        return subtask.execute_serialized()  # single-writer behind verifier
    return subtask.fork_and_verify(branches)
