# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-merges-when-rollback-is-not-idempotent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-merges-when-rollback-is-not-idempotent.warrant.json
# Markdown SHA-256:   26e8d56a0bd1a8f67dc32325255a28cef467a011a28507a8c22c3459c82468c9
# Code AST SHA-256:   6b7a9c593d11dee627c5d64e3cfee281dc9058b10d05394d16cd4f1bbe6d8158
# Verified Classes:   SpeculationInvariantError, BranchState, ToolCall, Branch
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class SpeculationInvariantError(RuntimeError):
    """Raised when a branch merge/rollback would violate the closure or quiescence invariant."""


class BranchState(Enum):
    RUNNING = "running"
    CLOSED = "closed"          # all tool calls terminal
    MERGED = "merged"
    ROLLED_BACK = "rolled_back"


@dataclass
class ToolCall:
    call_id: str
    resource_key: str          # branch-unique addressable token, NOT a shared column
    terminal: bool = False


@dataclass
class Branch:
    branch_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    state: BranchState = BranchState.RUNNING
    calls: list[ToolCall] = field(default_factory=list)
    merge_record_committed: bool = False

    def issue_call(self, resource_key: str) -> ToolCall:
        if self.state is not BranchState.RUNNING:
            raise SpeculationInvariantError(
                f"branch {self.branch_id} issued call after closure; state={self.state}"
            )
        call = ToolCall(call_id=str(uuid.uuid4()), resource_key=resource_key)
        self.calls.append(call)
        return call

    def is_closed(self) -> bool:
        return all(c.terminal for c in self.calls)


def drain_barrier(branches: list[Branch], timeout_s: float) -> None:
    """Block until every branch's in-flight tool calls are terminal. Cancellation
    requests alone are insufficient — a remote may ignore them (the version++ bug)."""
    import time
    deadline = time.monotonic() + timeout_s
    while time.monotonic() < deadline:
        if all(b.is_closed() for b in branches):
            for b in branches:
                if b.state is BranchState.RUNNING:
                    b.state = BranchState.CLOSED
            return
        time.sleep(0.01)
    unclosed = [b.branch_id for b in branches if not b.is_closed()]
    raise SpeculationInvariantError(
        f"drain barrier timed out with unclosed branches: {unclosed}; "
        f"rollback would race in-flight tool calls"
    )


def merge_winner(winner: Branch, losers: list[Branch]) -> None:
    if not winner.is_closed():
        raise SpeculationInvariantError(
            f"cannot merge branch {winner.branch_id}: effect log not closed"
        )
    # Commit merge record BEFORE any compensator runs (fixes read-your-writes race).
    winner.merge_record_committed = True
    winner.state = BranchState.MERGED

    for loser in losers:
        if not loser.is_closed():
            raise SpeculationInvariantError(
                f"cannot roll back branch {loser.branch_id}: effect log not closed; "
                f"in-flight calls would land after compensation"
            )
        if not loser.merge_record_committed:
            # Compensator must match on branch-unique keys only.
            for call in loser.calls:
                if call.resource_key == winner.calls[0].resource_key if winner.calls else False:
                    raise SpeculationInvariantError(
                        f"rollback of {loser.branch_id} would touch winner resource "
                        f"{call.resource_key}; shared-singleton write is not speculatable"
                    )
        loser.state = BranchState.ROLLED_BACK
