# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-speculative-rollback-and-escalate-to-a-merge-authority-when-a-speculative-branch-has-already-mutated-ex.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-speculative-rollback-and-escalate-to-a-merge-authority-when-a-speculative-branch-has-already-mutated-ex.warrant.json
# Markdown SHA-256:   3404fc9d933941f2196239fcfa83ab760c3bb5aad4dfcb6fe2693ecad52c644c
# Code AST SHA-256:   e8c3ed1945fb3e1adf9d464b233677c09cdc776fff459e62bc577e049ae5a35a
# Verified Classes:   RollbackPreconditionViolated, EffectOutcome, Effect, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class RollbackPreconditionViolated(RuntimeError):
    """Raised when speculative rollback is attempted on a branch whose effect
    ledger cannot be fully compensated. Escalation is required instead."""


class EffectOutcome(Enum):
    COMMITTED = "committed"
    FAILED = "failed"
    AMBIGUOUS = "ambiguous"  # transport error / timeout: may or may not have landed


@dataclass(frozen=True)
class Effect:
    effect_id: str
    tool: str
    entity_key: str
    outcome: EffectOutcome
    compensator: Callable[[Effect], None] | None
    compensator_idempotent: bool


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


def _entities_touched_by_other_live_branches(
    branch: Branch, live_branches: list[Branch]
) -> set[str]:
    touched: set[str] = set()
    for other in live_branches:
        if other.branch_id == branch.branch_id:
            continue
        for e in other.effects:
            touched.add(e.entity_key)
    return touched


def rollback_speculative_branch(
    branch: Branch, live_branches: list[Branch]
) -> None:
    """Roll back a speculative branch iff every committed/ambiguous effect is
    compensable and no live branch aliases its entities. Otherwise raise and
    force escalation to merge-authority.

    The invariant: rollback is a *delete of reversible state*. Any effect that
    may have crossed a tool boundary into externally-observed state must be
    either compensated by a pre-registered idempotent compensator, or the
    branch is not speculative and must not be rolled back.
    """
    # Condition: ambiguous effects invalidate the rollback precondition
    # regardless of entity intersection -- the world model is already wrong.
    ambiguous = [e for e in branch.effects if e.outcome is EffectOutcome.AMBIGUOUS]
    if ambiguous:
        raise RollbackPreconditionViolated(
            f"branch {branch.branch_id}: {len(ambiguous)} ambiguous effect(s) "
            f"({[e.effect_id for e in ambiguous]}); cannot distinguish committed "
            f"from failed. Escalate to merge-authority with effect ledger."
        )

    # Condition: every committed effect must have a pre-registered, idempotent
    # compensator covering its effect class.
    uncompensable = [
        e
        for e in branch.effects
        if e.outcome is EffectOutcome.COMMITTED
        and (e.compensator is None or not e.compensator_idempotent)
    ]
    if uncompensable:
        raise RollbackPreconditionViolated(
            f"branch {branch.branch_id}: committed effects without idempotent "
            f"compensator ({[e.effect_id for e in uncompensable]}); rollback "
            f"would orphan external state. Escalate."
        )

    # Condition: no cross-branch aliasing on committed entities.
    aliased_entities = _entities_touched_by_other_live_branches(branch, live_branches)
    conflicts = [
        e
        for e in branch.effects
        if e.outcome is EffectOutcome.COMMITTED and e.entity_key in aliased_entities
    ]
    if conflicts:
        raise RollbackPreconditionViolated(
            f"branch {branch.branch_id}: committed effects alias entities targeted "
            f"by live branches ({[e.effect_id for e in conflicts]}); rollback is "
            f"not independent. Escalate for merge-authority reconciliation."
        )

    # Preconditions hold: compensate committed effects in reverse order, then
    # discard reversible branch state.
    for effect in reversed(branch.effects):
        if effect.outcome is EffectOutcome.COMMITTED:
            assert effect.compensator is not None  # guaranteed by precondition
            effect.compensator(effect)
    branch.effects.clear()
