# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-speculative-tool-call-s-side-effect-as-non-rollbackable-and-abort-the-branch-before-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-speculative-tool-call-s-side-effect-as-non-rollbackable-and-abort-the-branch-before-reconciliation.warrant.json
# Markdown SHA-256:   6c89f48c45421d2827c7a7d1e9f969692dead6cc1938e441bbca94433c8d4ac6
# Code AST SHA-256:   cdace09a90224249e1e0fbd703ac3b5b61bc1eb5490196fb98577dc22de4155b
# Verified Classes:   EffectClass, EffectState, BranchState, EffectRecord, Branch, NonRollbackableBranchError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    PURE = "pure"
    BRANCH_LOCAL = "branch_local"
    IDEMPOTENT_EXTERNAL = "idempotent_external"
    NON_IDEMPOTENT_EXTERNAL = "non_idempotent_external"


class EffectState(Enum):
    PENDING = "pending"
    COMMITTED = "committed"
    COMPENSATED = "compensated"


class BranchState(Enum):
    SPECULATIVE = "speculative"
    COMMITTED = "committed"
    ROLLED_BACK = "rolled_back"
    COMPENSATING = "compensating"
    ESCALATED = "escalated"


@dataclass
class EffectRecord:
    effect_class: EffectClass
    effect_key: str
    state: EffectState = EffectState.PENDING
    compensator: Optional[str] = None


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.SPECULATIVE
    effects: list = field(default_factory=list)

    def has_uncompensated_commit(self) -> bool:
        return any(
            e.effect_class == EffectClass.NON_IDEMPOTENT_EXTERNAL
            and e.state == EffectState.COMMITTED
            for e in self.effects
        )


class NonRollbackableBranchError(RuntimeError):
    """Raised when rollback is attempted on a branch with durable external effects."""


def rollback_branch(branch: Branch) -> Branch:
    """Roll back a losing speculative branch.

    Legal only if the branch holds no committed non-idempotent external effect.
    Otherwise the branch must be compensated or escalated, not discarded.
    """
    if branch.state != BranchState.SPECULATIVE:
        raise NonRollbackableBranchError(
            f"branch {branch.branch_id} in state {branch.state.value}; "
            f"only SPECULATIVE branches may be rolled back"
        )

    if branch.has_uncompensated_commit():
        committed = [
            e.effect_key for e in branch.effects
            if e.effect_class == EffectClass.NON_IDEMPOTENT_EXTERNAL
            and e.state == EffectState.COMMITTED
        ]
        raise NonRollbackableBranchError(
            f"branch {branch.branch_id} has committed non-idempotent effects "
            f"{committed}; rollback would silently retain world mutations. "
            f"Route to COMPENSATING or ESCALATED, block reconciliation."
        )

    branch.state = BranchState.ROLLED_BACK
    for e in branch.effects:
        if e.effect_class == EffectClass.BRANCH_LOCAL:
            e.state = EffectState.COMPENSATED
    return branch


def reconcile(branches: list, winner_id: str) -> list:
    """Reconcile a fork. Refuses to proceed while any loser holds durable effects."""
    losers = [b for b in branches if b.branch_id != winner_id]
    for loser in losers:
        if loser.has_uncompensated_commit():
            raise NonRollbackableBranchError(
                f"reconciliation blocked: loser {loser.branch_id} has durable "
                f"external effects that the winner's reasoning does not account for"
            )
    return [rollback_branch(b) for b in losers]
