# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-speculative-multi-agent-rollback-when-divergent-branch-outcomes-invalidate-committed-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-speculative-multi-agent-rollback-when-divergent-branch-outcomes-invalidate-committed-side-effects.warrant.json
# Markdown SHA-256:   d9fdd565bc2ad4243eeb05852b4a22c8b40bb7163cae95c5f5498b01762cefa6
# Code AST SHA-256:   e9ed5b21b09107fad04b2bb1d7df76d108c9dbea496a2322efaaebcdcecf40dc
# Verified Classes:   EffectClass, UnsoundRollbackError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from enum import Enum


class EffectClass(Enum):
    REVERSIBLE = "reversible"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class UnsoundRollbackError(RuntimeError):
    """Raised when a divergent branch cannot be soundly rolled back
    because it committed an externally observable, irreversible effect."""


def rollback_branch(branch_id: str, committed_effects: list[dict]) -> None:
    """Attempt to roll back a divergent speculative branch.

    A branch is only rollback-safe if every committed effect is
    REVERSIBLE, COMPENSABLE (with a verified inverse), or non-observable.
    Otherwise we must refuse and escalate rather than report a false-clean
    rollback.
    """
    unsafe = []
    for eff in committed_effects:
        cls = eff["class"]
        if cls is EffectClass.IRREVERSIBLE:
            unsafe.append(eff)
        elif cls is EffectClass.COMPENSABLE and not eff.get("inverse_verified"):
            unsafe.append(eff)

    if unsafe:
        raise UnsoundRollbackError(
            f"branch {branch_id!r} cannot be rolled back: "
            f"{len(unsafe)} committed effect(s) are not soundly reversible "
            f"(e.g. {unsafe[0]['name']!r}). Quarantine and reconcile."
        )

    # Safe path: drop context, release budget, apply inverses if any.
    for eff in committed_effects:
        if eff["class"] is EffectClass.COMPENSABLE:
            eff["inverse"]()
