# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-checkpoint-before-speculative-branch-execution-to-prevent-irreversible-tool-side-effects-from-surviving-a-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-checkpoint-before-speculative-branch-execution-to-prevent-irreversible-tool-side-effects-from-surviving-a-rollback.warrant.json
# Markdown SHA-256:   a76942ad216a2e253cf0b67f0dad293a820b02eb912e9c6ecfda1617c1dba920
# Code AST SHA-256:   f7e92bb0c5f136b95d6e8df411597b423b620728dd54b638a8785514ee90471e
# Verified Classes:   ToolSafety, UncleanRollbackError, EffectEntry, Branch, CommitBarrierExecutor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List


class ToolSafety(Enum):
    ROLLBACK_SAFE = "rollback_safe"      # idempotent or shadow-backed
    COMPENSABLE = "compensable"          # has a registered compensator
    COMMITTING = "committing"            # irreversible once invoked


class UncleanRollbackError(RuntimeError):
    """Raised when a discarded branch left non-rollback-safe effects in the world."""
    pass


@dataclass
class EffectEntry:
    branch_id: str
    tool: str
    safety: ToolSafety
    compensator: str | None
    invoked: bool = False
    compensated: bool = False


@dataclass
class Branch:
    branch_id: str
    effects: List[EffectEntry] = field(default_factory=list)


class CommitBarrierExecutor:
    def __init__(self, tool_registry: Dict[str, ToolSafety]):
        self.registry = tool_registry

    def invoke_in_branch(self, branch: Branch, tool: str, compensator: str | None = None) -> EffectEntry:
        safety = self.registry.get(tool)
        if safety is None:
            raise UncleanRollbackError(f"tool {tool!r} has no declared safety class; cannot speculate")
        if safety is ToolSafety.COMMITTING and compensator is None:
            # Refuse to fire a committing tool inside a speculative frame.
            raise UncleanRollbackError(
                f"branch {branch.branch_id}: committing tool {tool!r} invoked speculatively "
                f"without compensator; must be queued as pending commit effect"
            )
        entry = EffectEntry(branch_id=branch.branch_id, tool=tool, safety=safety,
                            compensator=compensator, invoked=True)
        branch.effects.append(entry)
        return entry

    def rollback(self, branch: Branch) -> None:
        # Compensate in reverse order, then verify nothing unsafe survives.
        for entry in reversed(branch.effects):
            if entry.invoked and entry.compensator and not entry.compensated:
                entry.compensated = True  # compensator dispatch elided
        leaked = [
            e for e in branch.effects
            if e.invoked and not e.compensated
            and e.safety is not ToolSafety.ROLLBACK_SAFE
        ]
        if leaked:
            raise UncleanRollbackError(
                f"rollback of branch {branch.branch_id} left {len(leaked)} uncompensated "
                f"effect(s): {[e.tool for e in leaked]}; escalate as reconciliation conflict"
            )
