# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-has-already-mutated-shared-external-state-before-its-rollback-point.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-has-already-mutated-shared-external-state-before-its-rollback-point.warrant.json
# Markdown SHA-256:   00799cd42b5093a176449547cb5d72f8a30a87e03ac520140a24068f7fbd3780
# Code AST SHA-256:   3b92389b78c7a0c7dfdf77fc3392dcf90d7594930ed77b79bbf0f98c58bf7bb6
# Verified Classes:   EffectState, SpeculationBoundaryError, Effect, Branch, SpeculativeOrchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EffectState(Enum):
    PROPOSED = "proposed"      # journaled, not applied
    IN_FLIGHT = "in_flight"    # transport executing
    APPLIED = "applied"        # crossed boundary, world mutated
    DISCARDED = "discarded"    # rolled back cleanly


class SpeculationBoundaryError(RuntimeError):
    """Raised when a commit/rollback decision violates effect-ordering or rollback-completeness."""


@dataclass
class Effect:
    tool: str
    args: dict
    reversible: bool
    state: EffectState = EffectState.PROPOSED
    inverse: Any = None  # callable or descriptor for compensation


@dataclass
class Branch:
    branch_id: str
    journal: list[Effect] = field(default_factory=list)
    self_reports_clean: bool = True  # what the branch's semantic memory claims


class SpeculativeOrchestrator:
    def __init__(self, branches: list[Branch]):
        self.branches = branches

    def _live_effects(self, b: Branch) -> list[Effect]:
        return [e for e in b.journal if e.state in (EffectState.IN_FLIGHT, EffectState.APPLIED)]

    def commit(self, winner_id: str) -> None:
        winner = next(b for b in self.branches if b.branch_id == winner_id)
        losers = [b for b in self.branches if b.branch_id != winner_id]

        # Commit barrier: no branch may have an effect in flight.
        for b in self.branches:
            in_flight = [e for e in b.journal if e.state is EffectState.IN_FLIGHT]
            if in_flight:
                raise SpeculationBoundaryError(
                    f"commit barrier violated: branch {b.branch_id} has "
                    f"{len(in_flight)} in-flight effect(s); drain before deciding"
                )

        # Rollback-completeness: a loser that reports clean but holds an
        # applied irreversible effect is the silent-leak case.
        for b in losers:
            leaked = [
                e for e in self._live_effects(b)
                if e.state is EffectState.APPLIED and not e.reversible
            ]
            if leaked and b.self_reports_clean:
                raise SpeculationBoundaryError(
                    f"branch {b.branch_id} self-reports clean but has "
                    f"{len(leaked)} applied irreversible effect(s): "
                    f"{[e.tool for e in leaked]}; cannot roll back safely"
                )
            for e in self._live_effects(b):
                if e.reversible and e.inverse is not None:
                    e.inverse()  # compensate
                e.state = EffectState.DISCARDED

        # Apply winner's journal atomically.
        for e in winner.journal:
            if e.state is EffectState.PROPOSED:
                e.state = EffectState.APPLIED


def run_fork(branches: list[Branch], winner_id: str) -> None:
    orch = SpeculativeOrchestrator(branches)
    orch.commit(winner_id)
