# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculation-rather-than-roll-back-a-divergent-branch-in-multi-agent-branch-and-verify-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculation-rather-than-roll-back-a-divergent-branch-in-multi-agent-branch-and-verify-execution.warrant.json
# Markdown SHA-256:   b0b51484a44cd8301c5541ecf9f7783b98c929c61c01f5823efdb8fd8610d6df
# Code AST SHA-256:   885d648674c844130e2899d6271ee09ff38ad0c443c4c53b25ce686ce0a24544
# Verified Classes:   SpeculationAborted, EffectKind, Effect, Fork
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class SpeculationAborted(RuntimeError):
    """Raised when a fork must be aborted rather than rolled back."""


class EffectKind(Enum):
    REVERSIBLE = "reversible"      # confined to orchestrator-owned state
    IRREVERSIBLE = "irreversible"  # crossed an external commit boundary


@dataclass
class Effect:
    branch_id: str
    kind: EffectKind
    compensating_op: Optional[str] = None  # must be registered at emit time
    idempotent_compensation: bool = False


@dataclass
class Fork:
    branches: dict[str, list[Effect]] = field(default_factory=dict)
    frozen: bool = False

    def emit(self, branch_id: str, effect: Effect) -> None:
        if self.frozen:
            raise SpeculationAborted(
                f"branch {branch_id} attempted emit after fork was frozen"
            )
        self.branches.setdefault(branch_id, []).append(effect)

    def contamination_boundary_crossed(self) -> bool:
        return any(
            e.kind is EffectKind.IRREVERSIBLE
            for effects in self.branches.values()
            for e in effects
        )

    def rollback_eligible(self) -> bool:
        """Rollback is valid only if every irreversible effect has a
        registered, idempotent compensating operation."""
        for effects in self.branches.values():
            for e in effects:
                if e.kind is EffectKind.IRREVERSIBLE:
                    if e.compensating_op is None or not e.idempotent_compensation:
                        return False
        return True


def resolve_divergence(fork: Fork, divergent_branch: str) -> str:
    """Decide between rollback and abort for a diverged branch.

    The decision is a property of the whole fork's effect journal, not of
    the divergent branch alone.
    """
    if not fork.contamination_boundary_crossed():
        # Pure divergence: rollback is a state operation, safe.
        fork.branches.pop(divergent_branch, None)
        return "rolled_back"

    if fork.rollback_eligible():
        # Irreversible effects exist but are all compensable and idempotent.
        # Freeze first so no sibling emits during compensation.
        fork.frozen = True
        return "rolled_back_with_compensation"

    # Contamination boundary crossed with no safe compensation.
    # Rolling back now would leave external state divergent from the
    # checkpoint while reporting local consistency. Abort instead.
    fork.frozen = True
    raise SpeculationAborted(
        f"fork contaminated by irreversible effect on branch "
        f"{divergent_branch!r} with no idempotent compensation; "
        f"freeze and reconcile rather than roll back"
    )
