# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-divergent-speculative-branch-when-rollback-reconciliation-silently-commits-a-superseded-sibling-s-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-divergent-speculative-branch-when-rollback-reconciliation-silently-commits-a-superseded-sibling-s-side-effects.warrant.json
# Markdown SHA-256:   afb0f47ebb667e90323b299e87f04053f3614e4f2ccadffa5831612228de235a
# Code AST SHA-256:   aa0489a0c1c68cc354eeff032235a50f1eeab059cb6e1e50a0b38dafabb5ed25
# Verified Classes:   BranchState, EffectStatus, ZombieBranchError, Effect, Branch, SpeculativeOrchestrator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional


class BranchState(Enum):
    RUNNING = "running"
    COMMITTED = "committed"
    ABANDONED = "abandoned"


class EffectStatus(Enum):
    PENDING = "pending"
    SUCCEEDED = "succeeded"
    FAILED = "failed"
    CANCELLED = "cancelled"


class ZombieBranchError(RuntimeError):
    """Raised when a commit is attempted while a losing branch has non-quiescent effects."""


@dataclass
class Effect:
    branch_token: str
    tool: str
    status: EffectStatus = EffectStatus.PENDING
    compensated: bool = False


@dataclass
class Branch:
    token: str
    state: BranchState = BranchState.RUNNING
    effects: List[Effect] = field(default_factory=list)


class SpeculativeOrchestrator:
    def __init__(self) -> None:
        self.branches: Dict[str, Branch] = {}

    def register(self, token: str) -> Branch:
        b = Branch(token=token)
        self.branches[token] = b
        return b

    def issue_effect(self, token: str, tool: str) -> Effect:
        e = Effect(branch_token=token, tool=tool)
        self.branches[token].effects.append(e)
        return e

    def resolve_effect(self, token: str, tool: str, status: EffectStatus) -> None:
        # Late results are attributed by branch token, even if the branch is abandoned.
        for e in self.branches[token].effects:
            if e.tool == tool and e.status is EffectStatus.PENDING:
                e.status = status
                return
        raise KeyError(f"no pending effect {tool!r} on branch {token!r}")

    def _non_quiescent(self, token: str) -> List[Effect]:
        return [e for e in self.branches[token].effects if e.status is EffectStatus.PENDING]

    def commit(self, winner: str, timeout_s: float = 5.0) -> None:
        deadline = time.monotonic() + timeout_s
        while True:
            zombies = {
                tok: self._non_quiescent(tok)
                for tok, b in self.branches.items()
                if tok != winner and self._non_quiescent(tok)
            }
            if not zombies:
                break
            if time.monotonic() >= deadline:
                # Fail closed: do not finalize the commit.
                raise ZombieBranchError(
                    f"commit of {winner!r} blocked: zombie branches with pending effects: "
                    + ", ".join(f"{t}={[e.tool for e in es]}" for t, es in zombies.items())
                )
            time.sleep(0.05)

        for tok, b in self.branches.items():
            if tok == winner:
                b.state = BranchState.COMMITTED
                continue
            b.state = BranchState.ABANDONED
            for e in b.effects:
                if e.status is EffectStatus.SUCCEEDED and not e.compensated:
                    # Token-scoped compensation, not log-order-dependent.
                    self._compensate(e)

        # Post-commit invariant: no abandoned token may survive in committed state.
        self._verify_no_abandoned_effects()

    def _compensate(self, e: Effect) -> None:
        e.compensated = True  # real impl reverts by branch token at the executor

    def _verify_no_abandoned_effects(self) -> None:
        abandoned = {t for t, b in self.branches.items() if b.state is BranchState.ABANDONED}
        leaked = [
            e for t in abandoned for e in self.branches[t].effects
            if e.status is EffectStatus.SUCCEEDED and not e.compensated
        ]
        if leaked:
            raise ZombieBranchError(
                f"post-commit leak: {len(leaked)} uncompensated effects from abandoned branches: "
                + ", ".join(f"{e.branch_token}:{e.tool}" for e in leaked)
            )
