# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-speculative-branch-rollback-as-unsafe-when-a-parallel-branch-has-already-committed-a-non-idempotent-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-speculative-branch-rollback-as-unsafe-when-a-parallel-branch-has-already-committed-a-non-idempotent-tool.warrant.json
# Markdown SHA-256:   5461fd4970b5f3ed40fb3c3a4792f2ebb4072c4dbe0e254349d07bc7ff4353a0
# Code AST SHA-256:   09c1a5df1b822ae88aa2d2e73a7750b395c9cd99478cb053262e47bf57f223d4
# Verified Classes:   SpeculationSafetyError, Visibility, Reversibility, ToolSpec, Branch, SpeculativeConnector
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SpeculationSafetyError(RuntimeError):
    """Raised when a speculative branch attempts an effect that cannot be safely rolled back."""
    pass


class Visibility(Enum):
    SANDBOXED = "sandboxed"      # effect stays inside branch-local state
    EXTERNAL = "external"        # effect escapes to a system the orchestrator does not own


class Reversibility(Enum):
    REVERSIBLE = "reversible"    # verified compensating operation exists
    IRREVERSIBLE = "irreversible"


@dataclass(frozen=True)
class ToolSpec:
    name: str
    visibility: Visibility
    reversibility: Reversibility
    deferred_capable: bool = False  # connector can buffer until commit


@dataclass
class Branch:
    branch_id: str
    committed: bool = False
    live_effects: list = field(default_factory=list)  # (tool_name, action_id) not yet reverted


class SpeculativeConnector:
    def __init__(self, registry: dict[str, ToolSpec], deferral_enabled: bool):
        self.registry = registry
        self.deferral_enabled = deferral_enabled

    def is_speculation_safe(self, spec: ToolSpec) -> bool:
        if spec.visibility is Visibility.SANDBOXED:
            return True
        if spec.reversibility is Reversibility.REVERSIBLE:
            return True
        # externally visible AND irreversible: only safe if the connector can defer it
        return self.deferral_enabled and spec.deferred_capable

    def invoke(self, branch: Branch, tool_name: str, action_id: str, payload: dict):
        spec = self.registry.get(tool_name)
        if spec is None:
            raise SpeculationSafetyError(f"unknown tool {tool_name!r}")

        if not branch.committed and not self.is_speculation_safe(spec):
            # Refuse BEFORE the effect escapes. This is the guardrail.
            raise SpeculationSafetyError(
                f"branch {branch.branch_id} is speculative and {tool_name!r} is "
                f"external+irreversible without deferral; refusing to execute"
            )

        if not branch.committed and self.deferral_enabled and spec.deferred_capable:
            # Synthetic accepted-pending response; real call fires on commit only.
            return {"status": "accepted_pending_commit", "action_id": action_id}

        # Execute for real.
        result = self._execute(tool_name, action_id, payload)
        branch.live_effects.append((tool_name, action_id))
        return result

    def _execute(self, tool_name: str, action_id: str, payload: dict):
        return {"status": "ok", "tool": tool_name, "action_id": action_id}


def rollback_branch(branch: Branch, connector: SpeculativeConnector):
    """Discard a speculative branch. Refuses if the branch holds a live external effect."""
    for tool_name, action_id in branch.live_effects:
        spec = connector.registry[tool_name]
        if spec.visibility is Visibility.EXTERNAL and spec.reversibility is Reversibility.IRREVERSIBLE:
            # The invariant: never discard a branch while it holds an un-reverted,
            # externally visible, irreversible effect.
            raise SpeculationSafetyError(
                f"cannot roll back branch {branch.branch_id}: live irreversible "
                f"effect {tool_name!r} (action {action_id!r}) must be compensated "
                f"or promoted to the canonical resolution set first"
            )
    branch.live_effects.clear()
    return {"status": "rolled_back", "branch_id": branch.branch_id}


# --- reproduction of the observed failure ---
registry = {
    "billing.issue_refund": ToolSpec("billing.issue_refund", Visibility.EXTERNAL, Reversibility.IRREVERSIBLE),
    "billing.create_credit": ToolSpec("billing.create_credit", Visibility.EXTERNAL, Reversibility.IRREVERSIBLE),
    "ticketing.create_escalation": ToolSpec("ticketing.create_escalation", Visibility.EXTERNAL, Reversibility.IRREVERSIBLE),
    "billing.get_balance": ToolSpec("billing.get_balance", Visibility.SANDBOXED, Reversibility.REVERSIBLE),
}

# Naive orchestrator: deferral disabled, branches call tools directly during speculation.
connector = SpeculativeConnector(registry, deferral_enabled=False)
branch_a = Branch("A")
try:
    connector.invoke(branch_a, "billing.issue_refund", "act-1", {"amount": 40})
    # If the guardrail were absent, the refund would have landed here.
    rollback_branch(branch_a, connector)
except SpeculationSafetyError as e:
    print(f"guardrail held: {e}")

# With deferral enabled, the refund is buffered and rollback is safe.
deferred = SpeculativeConnector(registry, deferral_enabled=True)
branch_b = Branch("B")
resp = deferred.invoke(branch_b, "billing.issue_refund", "act-2", {"amount": 40})
print("speculative response:", resp)  # accepted_pending_commit, no external effect
print("rollback:", rollback_branch(branch_b, deferred))
