# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-rollback-and-escalate-to-branch-reconciliation-in-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-rollback-and-escalate-to-branch-reconciliation-in-multi-agent-execution.warrant.json
# Markdown SHA-256:   151388c3cd6435777d8244602c4735137d7adfe319d5e9e81b9f9468c9cbef6b
# Code AST SHA-256:   73ac1f1e0f3458bb7abcb0422a1670a7d149e4fff5d3d7925724402b91a299d2
# Verified Classes:   RollbackEligibilityError, ToolClass, Obligation, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class RollbackEligibilityError(RuntimeError):
    """Raised when a branch is rolled back despite carrying external obligations."""


class ToolClass(Enum):
    SNAPSHOT_REVERSIBLE = "snapshot_reversible"
    IDEMPOTENT_REPLAY_SAFE = "idempotent_replay_safe"
    RECONCILIATION_REQUIRED = "reconciliation_required"


@dataclass
class Obligation:
    tool: str
    key: str
    tool_class: ToolClass
    acknowledged: bool


@dataclass
class Branch:
    branch_id: str
    obligations: list[Obligation] = field(default_factory=list)
    state: str = "running"


def rollback_branch(branch: Branch, snapshot_restore) -> None:
    reconciliation_debt = [
        o for o in branch.obligations
        if o.tool_class is ToolClass.RECONCILIATION_REQUIRED and o.acknowledged
    ]
    unknown = [
        o for o in branch.obligations
        if o.tool_class is ToolClass.RECONCILIATION_REQUIRED and not o.acknowledged
    ]
    if reconciliation_debt or unknown:
        raise RollbackEligibilityError(
            f"branch {branch.branch_id} cannot be rolled back: "
            f"{len(reconciliation_debt)} acknowledged and {len(unknown)} unknown "
            f"reconciliation-required obligations survive the snapshot. "
            f"Escalate to reconciliation and compensate before commit."
        )
    snapshot_restore()
    branch.state = "rolled_back"


def reconcile_branch(branch: Branch, compensator) -> None:
    for obligation in branch.obligations:
        if obligation.tool_class is ToolClass.RECONCILIATION_REQUIRED:
            compensator.compensate(obligation)
    branch.state = "reconciled"
