# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-rolled-back-speculative-branch-whose-tool-side-effects-already-committed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-rolled-back-speculative-branch-whose-tool-side-effects-already-committed.warrant.json
# Markdown SHA-256:   11698a535f27c6009da4ad2e818584cddcef7064325b0eb0142941e5b9738dc7
# Code AST SHA-256:   bac5e9bfde1efd1980ce07b070eb7ecf91d34f8c0cd993b996f3e98f98195fae
# Verified Classes:   RollbackSafetyError, EffectClass, ToolEffect, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class RollbackSafetyError(RuntimeError):
    """Raised when a speculative branch cannot be safely rolled back because
    its committed tool effects are not subsumed by the committed branch and
    lack executed compensators."""


class EffectClass(Enum):
    READ_ONLY = "read_only"
    IDEMPOTENT_WRITE = "idempotent_write"
    MUTATING = "mutating"


@dataclass
class ToolEffect:
    tool: str
    args_hash: str
    effect_class: EffectClass
    compensator_ref: Optional[str] = None  # None => no undo path


@dataclass
class Branch:
    branch_id: str
    checkpoint_id: str
    effect_log: list[ToolEffect] = field(default_factory=list)


def _effect_key(e: ToolEffect) -> tuple[str, str]:
    return (e.tool, e.args_hash)


def rollback_speculative_branch(
    speculative: Branch,
    committed: Branch,
    compensator_executor,
) -> None:
    """Roll back `speculative` only if its effect set is subsumed by
    `committed` or every residual effect has a compensator that executes
    successfully. Otherwise raise RollbackSafetyError and leave the branch
    frozen for escalation."""
    committed_keys = {_effect_key(e) for e in committed.effect_log}
    residual = [
        e for e in speculative.effect_log
        if _effect_key(e) not in committed_keys
        and e.effect_class is not EffectClass.READ_ONLY
    ]

    if not residual:
        return  # safe: no leaked effects

    # Attempt compensators in reverse invocation order.
    unhandled: list[ToolEffect] = []
    for effect in reversed(residual):
        if effect.compensator_ref is None:
            unhandled.append(effect)
            continue
        ok = compensator_executor(effect.compensator_ref, effect.args_hash)
        if not ok:
            unhandled.append(effect)

    if unhandled:
        raise RollbackSafetyError(
            f"branch {speculative.branch_id} at checkpoint "
            f"{speculative.checkpoint_id} cannot be rolled back: "
            f"{len(unhandled)} uncompensated effect(s) already committed "
            f"to the environment. Escalate with effect log; do not resume "
            f"committed branch from checkpoint (world state is stale). "
            f"Unhandled: {[(e.tool, e.args_hash) for e in unhandled]}"
        )
    # All residual effects compensated; rollback is safe.
