# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-multi-agent-execution-and-collapse-to-a-single-authoritative-branch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-multi-agent-execution-and-collapse-to-a-single-authoritative-branch.warrant.json
# Markdown SHA-256:   f62737b3037be3e36122380524b8d05d59b16ee5ba6ec068f4f0f900f7c9455a
# Code AST SHA-256:   9801045e49e5ab17e677ea7bdabcfc05b0872bfca4c008d4585135e31ea3098e
# Verified Classes:   SpeculativeBoundaryError, EffectClass, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SpeculativeBoundaryError(RuntimeError):
    """Raised when a branch has emitted an irreversible effect and the
    orchestrator is asked to compensate it without a non-interference proof."""


class EffectClass(Enum):
    BUFFERED = "buffered"      # safe to prune with compensation
    EMITTED = "emitted"        # irreversible; consumers outside our control


@dataclass
class Branch:
    name: str
    effects: list = field(default_factory=list)  # list[EffectClass]

    def has_emitted(self) -> bool:
        return any(e is EffectClass.EMITTED for e in self.effects)


def prune_losers(branches: list, winner: str, non_interference_proof: dict) -> list:
    """
    Prune non-winning branches. Compensate only buffered effects.
    If a loser has emitted an effect, require an explicit proof of
    non-interference; otherwise refuse to roll back and demand collapse.
    """
    pruned = []
    for b in branches:
        if b.name == winner:
            continue
        if b.has_emitted():
            if not non_interference_proof.get(b.name):
                raise SpeculativeBoundaryError(
                    f"branch {b.name!r} emitted an irreversible effect before "
                    f"commit; compensating rollback would race unknown consumers. "
                    f"Collapse to the authoritative branch instead of pruning."
                )
            # Proof present: abandon without compensation, leave effects in place.
            pruned.append((b.name, "abandoned_no_compensation"))
        else:
            pruned.append((b.name, "compensated_buffered"))
    return pruned


def run_speculative(branches: list, winner: str, proof: dict) -> list:
    for b in branches:
        if b.has_emitted() and b.name != winner:
            # Boundary crossed: do not even attempt the normal prune path.
            result = prune_losers(branches, winner, proof)
            return result
    return prune_losers(branches, winner, proof)
