# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-merge-rollback-invalidation-and-the-commit-fence-invariant-in-parallel-branch.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-merge-rollback-invalidation-and-the-commit-fence-invariant-in-parallel-branch.warrant.json
# Markdown SHA-256:   0b9faeef50452c0d480186a2a8aef70f198da5021a196cb9cb52350ec3d6a7a7
# Code AST SHA-256:   ebb5e201ab9d5d74275a97b54bf32ae669851d6060137f8666f871686c48e7a9
# Verified Classes:   Reversibility, CommitFenceViolation, Effect, Branch, CompensatorLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Reversibility(Enum):
    REVERSIBLE = "reversible"          # has a verified compensator
    WITHHELD = "withheld"              # staged, not yet applied
    IRREVERSIBLE = "irreversible"      # applied, no compensator


class CommitFenceViolation(RuntimeError):
    """Raised when a speculative branch is squashed while holding an
    unledgered irreversible effect, or while a tool call is in flight."""
    pass


@dataclass
class Effect:
    handle: str
    tool: str
    reversibility: Reversibility
    applied: bool = True


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

    def record_effect(self, effect: Effect) -> None:
        self.effects.append(effect)


@dataclass
class CompensatorLedger:
    # handle -> compensator callable name; presence means "verified inverse exists"
    entries: dict[str, str] = field(default_factory=dict)

    def has(self, handle: str) -> bool:
        return handle in self.entries


def classify_for_squash(branch: Branch, ledger: CompensatorLedger) -> str:
    """Decide whether a losing branch may be silently squashed.

    Returns one of: 'safe_to_squash', 'must_drain', 'must_promote'.
    Raises CommitFenceViolation if the branch holds an applied irreversible
    effect whose handle is absent from the ledger (the silent-leak case).
    """
    if branch.in_flight_calls > 0:
        # Fence-escape risk: an effect could land after the rewind.
        return "must_drain"

    for effect in branch.effects:
        if not effect.applied:
            continue
        if effect.reversibility is Reversibility.IRREVERSIBLE:
            if ledger.has(effect.handle):
                # Ledgered irreversible effect with a compensator -> squashable.
                continue
            # Applied, irreversible, no compensator. Squashing would orphan
            # the live effect and discard the only handle to it.
            raise CommitFenceViolation(
                f"branch {branch.branch_id} holds unledgered irreversible "
                f"effect {effect.handle} ({effect.tool}); silent squash "
                f"forbidden -- promote to committed or halt for reconciliation"
            )
        if effect.reversibility is Reversibility.REVERSIBLE and not ledger.has(
            effect.handle
        ):
            # Declared reversible but no verified compensator: manifest lie.
            raise CommitFenceViolation(
                f"branch {branch.branch_id} effect {effect.handle} declared "
                f"reversible but absent from compensator ledger"
            )

    return "safe_to_squash"


def merge_speculative(
    branches: list[Branch], winner_id: str, ledger: CompensatorLedger
) -> list[str]:
    dispositions: list[str] = []
    for b in branches:
        if b.branch_id == winner_id:
            dispositions.append(f"{b.branch_id}:commit")
            continue
        try:
            disposition = classify_for_squash(b, ledger)
        except CommitFenceViolation:
            # Re-raise with branch context; orchestrator must halt, not guess.
            raise
        dispositions.append(f"{b.branch_id}:{disposition}")
    return dispositions
