# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-s-tool-call-side-effects-survived-its-own-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-s-tool-call-side-effects-survived-its-own-rollback.warrant.json
# Markdown SHA-256:   4f64bcda6490323e1aa95c8b034ba8ed80e70695a8a46d1672e827434fcfb8a7
# Code AST SHA-256:   4c1c5d1a05109e87c42213373785de3ab5482aec134efebf9215ed86acdec5a0
# Verified Classes:   OrphanedSpeculativeEffect, ToolContract, BranchHandle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class OrphanedSpeculativeEffect(RuntimeError):
    """Raised when a speculative branch's tool-call effects survive rollback."""
    pass


class ToolContract:
    def __init__(self, name: str, read_only: bool, revocable: bool, idempotent: bool):
        self.name = name
        self.read_only = read_only
        self.revocable = revocable
        self.idempotent = idempotent


class BranchHandle:
    def __init__(self, branch_id: str):
        self.branch_id = branch_id
        self.effect_tokens = []  # tokens minted by effectful calls
        self.released = False


def dispatch_speculative_call(handle: BranchHandle, contract: ToolContract, call_args: dict):
    """Dispatch a tool call from a speculative branch, enforcing the effect contract."""
    if handle.released:
        raise OrphanedSpeculativeEffect(
            f"branch {handle.branch_id} dispatched a call after handle release"
        )
    if contract.read_only:
        return {"kind": "read", "result": _execute(contract, call_args)}
    if not contract.revocable and not contract.idempotent:
        # Boundary decision: non-revocable effectful tools may not be speculated.
        raise OrphanedSpeculativeEffect(
            f"tool {contract.name} is effectful and non-revocable; "
            f"branch {handle.branch_id} may not invoke it speculatively"
        )
    token = _execute_effectful(contract, call_args, scope=handle.branch_id)
    handle.effect_tokens.append((contract.name, token))
    return {"kind": "effect", "token": token}


def abort_branch(handle: BranchHandle, revoker):
    """Two-phase rollback: revoke all effect tokens, verify, then release."""
    unrevoked = []
    for tool_name, token in handle.effect_tokens:
        ok = revoker.revoke(token)
        if not ok:
            unrevoked.append((tool_name, token))
    if unrevoked:
        # Do NOT release the handle: the effects are still live and must be
        # surfaced to a global commit-time invariant or a human.
        raise OrphanedSpeculativeEffect(
            f"branch {handle.branch_id} abort left unrevoked effects: {unrevoked}"
        )
    handle.effect_tokens.clear()
    handle.released = True


def verify_global_invariant(effect_namespace, predicate):
    """Commit-time backstop: a surviving branch asserts over the whole namespace."""
    if not predicate(effect_namespace):
        raise OrphanedSpeculativeEffect(
            "commit-time invariant violated: effect namespace contains "
            "entries not attributable to any live branch"
        )
