# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollback-from-reusing-externally-observable-tool-side-effects-as-a-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollback-from-reusing-externally-observable-tool-side-effects-as-a-checkpoint.warrant.json
# Markdown SHA-256:   a7dde1a4d20d78b2d4f75fe61407eb8b129aa0e9e83f12396ad64afcd41449e0
# Code AST SHA-256:   d4c27b9f98270814bb362bc33d63193adeea2d97dfa6dbdeecf7e22f89691dc7
# Verified Classes:   EffectClass, SpeculativeRollbackError, EffectCursor, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    IDEMPOTENT = "idempotent"
    REVERSIBLE = "reversible"
    NON_INVERTIBLE = "non_invertible"


class SpeculativeRollbackError(RuntimeError):
    """Raised when rollback would leave an external effect unaccounted for."""


@dataclass
class EffectCursor:
    """Tracks external effects caused by a branch, separate from its context."""
    pending: set[str] = field(default_factory=set)      # proposed, not yet committed
    committed: set[str] = field(default_factory=set)    # in the world
    compensations: set[str] = field(default_factory=set)


@dataclass
class Branch:
    branch_id: str
    context: dict
    cursor: EffectCursor
    verdict_hash: str | None = None


def classify_tool(tool_name: str, registry: dict[str, EffectClass]) -> EffectClass:
    # Unclassified tools are non-invertible by default: serialization, not corruption.
    return registry.get(tool_name, EffectClass.NON_INVERTIBLE)


def fork_branch(parent: Branch, branch_id: str, tools_used: list[str],
                registry: dict[str, EffectClass]) -> Branch:
    child = Branch(branch_id=branch_id, context=dict(parent.context),
                   cursor=EffectCursor())
    for tool in tools_used:
        cls = classify_tool(tool, registry)
        if cls is EffectClass.NON_INVERTIBLE:
            # Staged: the branch may only propose this effect.
            child.cursor.pending.add(f"{tool}:proposed")
        elif cls is EffectClass.REVERSIBLE:
            # Compensation is scheduled at fork time, not rollback time.
            child.cursor.compensations.add(f"{tool}:compensate")
    return child


def rollback_branch(branch: Branch, committed_effects: set[str]) -> None:
    """Roll back a speculative branch. Fails if any effect leaked past the barrier."""
    leaked = branch.cursor.committed - committed_effects
    if leaked:
        raise SpeculativeRollbackError(
            f"branch {branch.branch_id} committed effects not in orchestrator "
            f"log: {sorted(leaked)}; rollback would diverge belief from world"
        )
    # Cancel scheduled compensations; discard context; drop pending proposals.
    branch.cursor.compensations.clear()
    branch.cursor.pending.clear()
    branch.context.clear()
    branch.verdict_hash = None


def commit_branch(branch: Branch, orchestrator_log: set[str],
                  execute: Callable[[str], None]) -> None:
    """Only path by which a branch's non-invertible effects enter the world."""
    if branch.verdict_hash is None:
        raise SpeculativeRollbackError(
            f"branch {branch.branch_id} has no verdict bound to its execution hash"
        )
    for proposal in sorted(branch.cursor.pending):
        execute(proposal)
        orchestrator_log.add(proposal)
        branch.cursor.committed.add(proposal)
    branch.cursor.pending.clear()
    branch.cursor.compensations.clear()
