# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-has-silently-committed-irreversible-side-effects-before-its-draft-was-ever-verified.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-has-silently-committed-irreversible-side-effects-before-its-draft-was-ever-verified.warrant.json
# Markdown SHA-256:   9644f99b57c2fc36732bcbd7c80baf7a893af34869b3b6e0fcf444218281a2c7
# Code AST SHA-256:   65a11c74987cfc28b4296b0846fa1a128acf81467e38acd5dcfa9cca88ca95fa
# Verified Classes:   SpeculativeEscapeError, Reversibility, ToolCall, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class SpeculativeEscapeError(RuntimeError):
    """Raised when a speculative branch dispatched an irreversible effect
    before commit, or when rollback cannot reconcile against external state."""


class Reversibility(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"
    UNANNOTATED = "unannotated"  # treated as irreversible


@dataclass
class ToolCall:
    name: str
    args: dict
    reversibility: Reversibility


@dataclass
class Branch:
    branch_id: str
    committed: bool = False
    dispatched: list[ToolCall] = field(default_factory=list)
    pending_intents: list[ToolCall] = field(default_factory=list)


def dispatch_from_branch(branch: Branch, call: ToolCall) -> None:
    """Dispatch a tool call from a branch that has not yet been committed.

    Enforces the dispatch-time invariant: irreversible or unannotated calls
    are buffered as pending intents and never executed speculatively.
    """
    if call.reversibility is Reversibility.REVERSIBLE:
        branch.dispatched.append(call)
        return

    # Irreversible or unannotated: buffer, do not execute.
    branch.pending_intents.append(call)


def rollback(branch: Branch, external_log_lookup: Callable[[str], list]) -> None:
    """Roll back an uncommitted branch.

    Truncating the ledger is not sufficient. Every dispatched call must be
    reconciled against the external system's log. If reconciliation is
    impossible or shows an escaped effect, raise instead of reporting success.
    """
    if branch.committed:
        raise SpeculativeEscapeError(
            f"rollback called on committed branch {branch.branch_id}"
        )

    for call in branch.dispatched:
        if call.reversibility is not Reversibility.REVERSIBLE:
            raise SpeculativeEscapeError(
                f"branch {branch.branch_id} dispatched irreversible call "
                f"{call.name!r} before commit; effect may have escaped"
            )
        try:
            observed = external_log_lookup(call.name)
        except Exception as exc:
            raise SpeculativeEscapeError(
                f"rollback cannot reconcile {call.name!r} on branch "
                f"{branch.branch_id}: external log unavailable"
            ) from exc
        if observed:
            raise SpeculativeEscapeError(
                f"branch {branch.branch_id} rollback found {len(observed)} "
                f"escaped effect(s) for {call.name!r}; ledger truncation "
                f"would have hidden them"
            )

    # Safe to discard: nothing dispatched, or everything reconciled clean.
    branch.dispatched.clear()
    branch.pending_intents.clear()
