# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-rollback-invalidation-from-non-idempotent-side-effects-during-multi-agent-branch-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-rollback-invalidation-from-non-idempotent-side-effects-during-multi-agent-branch-reconciliation.warrant.json
# Markdown SHA-256:   861f104552977e2dcfeeba5af88a9d9e30766ab4841b27673fc173d6ca776e01
# Code AST SHA-256:   c2c1f0375f6cbbc9d731943472f8fa440d570fb7bb4dc4219eaa49f9afc6f3a8
# Verified Classes:   BranchState, UnrollbackableBranchError, EffectJournal, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class BranchState(Enum):
    SPECULATIVE = "speculative"
    PROMOTED = "promoted"
    QUARANTINED = "quarantined"
    CANCELLED = "cancelled"


class UnrollbackableBranchError(RuntimeError):
    """Raised when a speculative branch is asked to cancel while holding
    non-idempotent or indeterminate external effects."""


@dataclass
class EffectJournal:
    committed: list = field(default_factory=list)      # confirmed external writes
    in_flight: list = field(default_factory=list)      # request sent, response unread

    def is_inert(self) -> bool:
        return not self.committed and not self.in_flight

    def is_indeterminate(self) -> bool:
        return bool(self.in_flight)


@dataclass
class Branch:
    name: str
    state: BranchState = BranchState.SPECULATIVE
    journal: EffectJournal = field(default_factory=EffectJournal)
    has_mutation_credential: bool = False


def cancel_branch(branch: Branch) -> BranchState:
    """Transition a speculative branch toward discard.

    Invariant: a branch may only reach CANCELLED if its effect journal is
    provably empty AND it never held a credential capable of external
    mutation during the speculative window. Otherwise it must be quarantined.
    """
    if branch.state is not BranchState.SPECULATIVE:
        raise UnrollbackableBranchError(
            f"{branch.name}: cancel requires SPECULATIVE, got {branch.state}"
        )

    if branch.has_mutation_credential and branch.journal.is_inert():
        # Credential existed but journal looks clean; still not provably inert
        # because in-flight responses may be unread. Treat as indeterminate.
        branch.state = BranchState.QUARANTINED
        return branch.state

    if branch.journal.is_indeterminate():
        raise UnrollbackableBranchError(
            f"{branch.name}: {len(branch.journal.in_flight)} in-flight effect(s) "
            f"with unread responses; cannot prove rollback. Quarantine required."
        )

    if branch.journal.committed:
        raise UnrollbackableBranchError(
            f"{branch.name}: {len(branch.journal.committed)} committed "
            f"non-idempotent effect(s); rollback would double-apply. "
            f"Compensate before discard."
        )

    branch.state = BranchState.CANCELLED
    return branch.state


def reconcile(winner: Branch, losers: list[Branch]) -> Branch:
    """Promote winner only after every loser is provably inert or compensated."""
    for loser in losers:
        try:
            cancel_branch(loser)
        except UnrollbackableBranchError:
            # Escalate: loser touched the world. Winner must compensate the
            # loser's journal before canonical state is finalized.
            if loser.journal.committed or loser.journal.is_indeterminate():
                raise UnrollbackableBranchError(
                    f"reconciliation blocked: {loser.name} is unrollbackable "
                    f"(committed={len(loser.journal.committed)}, "
                    f"in_flight={len(loser.journal.in_flight)}). "
                    f"Winner {winner.name} must compensate before promotion."
                )
    winner.state = BranchState.PROMOTED
    return winner
