# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-roll-back-a-speculative-branch-after-a-divergent-peer-plan-has-already-committed-observable-side-effe.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-roll-back-a-speculative-branch-after-a-divergent-peer-plan-has-already-committed-observable-side-effe.warrant.json
# Markdown SHA-256:   a847681262208c4c04695286340f7ed26c8a7ddbcbd9d618ff42f7a42bc1d1da
# Code AST SHA-256:   21c787bdbef2f5fcae00b52b8ba53fa890f4db5907b6162b26ef99c17ac11656
# Verified Classes:   EffectClass, EffectState, Effect, Branch, RollbackRefused
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class EffectClass(Enum):
    UNOBSERVABLE = "unobservable"
    IDEMPOTENT = "idempotent"
    SYNC_COMPENSABLE = "sync_compensable"
    ASYNC_COMPENSABLE = "async_compensable"
    IRREVERSIBLE = "irreversible"


class EffectState(Enum):
    PENDING = "pending"
    ACCEPTED = "accepted"
    COMPENSATED = "compensated"
    IRREVERSIBLE = "irreversible"


@dataclass
class Effect:
    effect_id: str
    klass: EffectClass
    state: EffectState


@dataclass
class Branch:
    branch_id: str
    speculative: bool
    effects: list[Effect] = field(default_factory=list)


class RollbackRefused(RuntimeError):
    """Raised when a speculative branch cannot be safely discarded because it
    holds non-terminal or irreversible observable effects."""


def _is_terminal_reversible(e: Effect) -> bool:
    if e.klass is EffectClass.UNOBSERVABLE:
        return True
    if e.klass is EffectClass.IDEMPOTENT:
        return True
    if e.klass is EffectClass.SYNC_COMPENSABLE:
        return e.state is EffectState.COMPENSATED
    # ASYNC_COMPENSABLE and IRREVERSIBLE are never terminal-reversible here.
    return False


def rollback_branch(branch: Branch) -> str:
    """Return the disposition of a discarded branch, or refuse.

    Dispositions: 'rolled_back', 'quarantined', 'absorbed'.
    """
    if not branch.speculative:
        raise RollbackRefused(
            f"branch {branch.branch_id} is not speculative; cannot roll back"
        )

    blocking = [e for e in branch.effects if not _is_terminal_reversible(e)]
    if not blocking:
        return "rolled_back"

    irreversible = [e for e in blocking if e.klass is EffectClass.IRREVERSIBLE]
    if irreversible:
        # The branch is entangled with committed world; must be absorbed,
        # not discarded. Winner must re-plan around these effects.
        return "absorbed"

    # Only async-compensable / pending effects remain: quarantine and
    # drive compensation to terminality before the winner may proceed.
    pending = [e for e in blocking if e.state in (EffectState.PENDING, EffectState.ACCEPTED)]
    if pending:
        raise RollbackRefused(
            f"branch {branch.branch_id} has {len(pending)} non-terminal effect(s) "
            f"({[e.effect_id for e in pending]}); quarantine, do not discard"
        )

    raise RollbackRefused(
        f"branch {branch.branch_id} has unclassified blocking effects; "
        "refusing rollback pending reconciliation"
    )
