# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-speculative-sub-plan-execution-and-roll-back-a-committed-side-effect-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-speculative-sub-plan-execution-and-roll-back-a-committed-side-effect-ledger.warrant.json
# Markdown SHA-256:   4132e0ca2ce3a3600b6e71bf99b14fd7d46f29acb47023ac8c510e0605e53070
# Code AST SHA-256:   4dcdbe84eb44b01768f48928bf4ec2dfb85bdf61fb764698a713051ee6647b21
# Verified Classes:   EffectClass, RollbackNotPermitted, Effect, Ledger, Fork, SpeculativeController
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List


class EffectClass(Enum):
    REVERSIBLE = "reversible"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class RollbackNotPermitted(RuntimeError):
    """Raised when rollback is attempted on a branch with irreversible commits."""


@dataclass
class Effect:
    branch_id: str
    tool: str
    effect_class: EffectClass
    compensated: bool = False


@dataclass
class Ledger:
    effects: List[Effect] = field(default_factory=list)

    def for_branch(self, branch_id: str) -> List[Effect]:
        return [e for e in self.effects if e.branch_id == branch_id]


@dataclass
class Fork:
    branch_id: str
    state: str = "SPECULATIVE"  # SPECULATIVE | COMMITTED | REVERTED | SPENT | COMPENSATING


class SpeculativeController:
    def __init__(self, ledger: Ledger):
        self.ledger = ledger

    def rollback(self, fork: Fork) -> str:
        effects = self.ledger.for_branch(fork.branch_id)
        irreversible = [
            e for e in effects
            if e.effect_class == EffectClass.IRREVERSIBLE and not e.compensated
        ]
        if irreversible:
            # Boundary: divergence alone is not sufficient grounds for rollback.
            fork.state = "SPENT"
            raise RollbackNotPermitted(
                f"branch {fork.branch_id} has {len(irreversible)} irreversible "
                f"commit(s): {[e.tool for e in irreversible]}; "
                f"transition to COMPENSATING, not REVERTED"
            )
        for e in effects:
            if e.effect_class == EffectClass.REVERSIBLE:
                e.compensated = True  # reverted
            elif e.effect_class == EffectClass.COMPENSABLE and not e.compensated:
                e.compensated = True  # compensation emitted
        fork.state = "REVERTED"
        self._check_aggregate_invariants()
        return fork.state

    def _check_aggregate_invariants(self) -> None:
        # Per-revert success does not imply aggregate consistency.
        outbound = [
            e for e in self.ledger.effects
            if e.tool == "send_notification" and not e.compensated
        ]
        if len(outbound) > 1:
            raise RollbackNotPermitted(
                f"aggregate invariant violated: {len(outbound)} live notifications"
            )
