# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-reconcile-divergent-speculative-branches-when-a-rollback-target-has-already-been-mutated-by-a-sibling-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-reconcile-divergent-speculative-branches-when-a-rollback-target-has-already-been-mutated-by-a-sibling-agent.warrant.json
# Markdown SHA-256:   32077bd8c67cd81c0697bd1083def1f91683cc44131d36d0551f0b344ce6a98d
# Code AST SHA-256:   f3db6509bf8a8e96c1a0dee16c7081ea6c1f5d299ed528f7dcfe261bce99c992
# Verified Classes:   EffectClass, RollbackPoisonedError, Effect
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class EffectClass(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"
    UNCOMMITTED = "uncommitted"


class RollbackPoisonedError(RuntimeError):
    """Raised when a rollback target is unsafe due to a sibling's irreversible effect."""


@dataclass(frozen=True)
class Effect:
    branch_id: str
    effect_class: EffectClass
    committed: bool


def assert_rollback_safe(
    checkpoint_id: int,
    requesting_branch: str,
    effects_since_checkpoint: list[Effect],
) -> None:
    """
    Enforce the invariant: rollback to a checkpoint is legal only if every
    irreversible, committed effect since the checkpoint belongs to the
    requesting branch (and can therefore be compensated by it).
    """
    for e in effects_since_checkpoint:
        if e.effect_class is EffectClass.IRREVERSIBLE and e.committed:
            if e.branch_id != requesting_branch:
                raise RollbackPoisonedError(
                    f"checkpoint {checkpoint_id} poisoned: sibling branch "
                    f"'{e.branch_id}' committed an irreversible effect; "
                    f"refusing rollback for '{requesting_branch}'. "
                    f"Use compensation or promote-and-rebase instead."
                )


def rollback(checkpoint_id: int, requesting_branch: str, effects: list[Effect]) -> str:
    assert_rollback_safe(checkpoint_id, requesting_branch, effects)
    return f"rolled back to {checkpoint_id} for {requesting_branch}"
