# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-rolled-back-speculative-branch-when-a-sibling-agent-s-tool-call-has-already-been-committed-to-an-external-side-effe.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-rolled-back-speculative-branch-when-a-sibling-agent-s-tool-call-has-already-been-committed-to-an-external-side-effe.warrant.json
# Markdown SHA-256:   23a28548a54e68a6cfb56d0c0f508cc5796d503eeb7253c49e4e26d1ea7e0737
# Code AST SHA-256:   0c39baf3ba2e050c35694805eec960b380d8317c8c6091bec669727320c3ad77
# Verified Classes:   EffectClass, RollbackIneligibleError, ToolEffect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    PURE = "pure"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class RollbackIneligibleError(RuntimeError):
    """Raised when a branch cannot be rolled back because an irreversible
    effect it produced has become observable to a surviving sibling or to
    shared memory. Rolling back and replaying would duplicate the effect."""


@dataclass
class ToolEffect:
    effect_type: str
    target: str
    effect_class: EffectClass
    inverse_registered: bool = False
    observed_by_siblings: bool = False
    distilled_to_shared_memory: bool = False


@dataclass
class Branch:
    branch_id: str
    effects: list[ToolEffect] = field(default_factory=list)
    memory_writes_shared: bool = False


def authorize_rollback(branch: Branch, surviving_siblings: list[Branch]) -> bool:
    """Decide whether `branch` may be rolled back. Returns True only if every
    effect is safely revertible and unobserved. Raises otherwise."""
    for eff in branch.effects:
        if eff.effect_class is EffectClass.PURE:
            continue
        if eff.effect_class is EffectClass.COMPENSABLE and eff.inverse_registered:
            continue
        # IRREVERSIBLE (or compensable without a usable inverse)
        if eff.observed_by_siblings or eff.distilled_to_shared_memory:
            raise RollbackIneligibleError(
                f"branch {branch.branch_id}: effect {eff.effect_type} on "
                f"{eff.target} is irreversible and already observable to a "
                f"surviving sibling or shared memory; rollback would duplicate it"
            )
        # Irreversible but unobserved: permit only with a tombstone that the
        # replayed branch's executor will consult before re-issuing the call.
        if not branch.memory_writes_shared:
            return True
    if branch.memory_writes_shared:
        raise RollbackIneligibleError(
            f"branch {branch.branch_id}: shared memory write survived an "
            f"irreversible effect; replay would read its own stale premise"
        )
    return True


def reconcile(selected: Branch, siblings: list[Branch]) -> None:
    for sib in siblings:
        if sib is selected:
            continue
        authorize_rollback(sib, [b for b in siblings if b is not selected])
