# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-the-speculative-commit-leak-when-a-rolled-back-branch-s-tool-side-effects-survive-merge-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-the-speculative-commit-leak-when-a-rolled-back-branch-s-tool-side-effects-survive-merge-reconciliation.warrant.json
# Markdown SHA-256:   117a2dec0f0bd145b40be4c8ecfa3bf7e6d6a81c0ab46444f4b2561982e43281
# Code AST SHA-256:   f975a169373e41fd312f5119ad41704c8d802e94dc46439903456f6da3bb4c07
# Verified Classes:   SpeculativeCommitLeak, BranchState, EffectLog, Branch, SpeculativeOrchestrator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class SpeculativeCommitLeak(RuntimeError):
    """Raised when a branch is rolled back while its tool effects remain uncommitted or unaudited."""


class BranchState(Enum):
    FORKED = "forked"
    EXECUTING = "executing"
    DRAINING = "draining"
    DRAINED = "drained"
    ROLLED_BACK = "rolled_back"
    COMMITTED = "committed"


@dataclass
class EffectLog:
    branch_id: str
    call_seq: int
    tool: str
    idempotency_key: str
    committed: bool = False
    reversible: bool = True

    def key(self) -> tuple:
        return (self.branch_id, self.call_seq)


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.FORKED
    effects: list = field(default_factory=list)
    drain_timeout_s: float = 30.0


class SpeculativeOrchestrator:
    def __init__(self, pre_fork_snapshot: dict):
        self.snapshot = pre_fork_snapshot
        self.branches: dict = {}
        self.committed_effects: list = []

    def rollback_branch(self, branch: Branch) -> None:
        # Invariant: a branch may only reach ROLLED_BACK via DRAINING -> DRAINED.
        if branch.state in (BranchState.EXECUTING, BranchState.FORKED):
            raise SpeculativeCommitLeak(
                f"branch {branch.branch_id} rolled back from {branch.state.value} "
                f"with {len(branch.effects)} effects possibly in flight; "
                f"must drain first"
            )
        if branch.state is BranchState.DRAINING:
            raise SpeculativeCommitLeak(
                f"branch {branch.branch_id} rollback attempted mid-drain; "
                f"drain_timeout={branch.drain_timeout_s}s not yet resolved"
            )
        if branch.state is not BranchState.DRAINED:
            raise SpeculativeCommitLeak(
                f"branch {branch.branch_id} in unexpected state {branch.state.value}"
            )
        leaked = [e for e in branch.effects if not e.reversible and e.committed]
        if leaked:
            raise SpeculativeCommitLeak(
                f"branch {branch.branch_id} has {len(leaked)} irreversible committed "
                f"effects with no compensation handler: "
                f"{[e.idempotency_key for e in leaked]}"
            )
        branch.state = BranchState.ROLLED_BACK

    def merge(self, surviving: Branch, discarded: list) -> dict:
        # Reconciliation input is committed effects only, never branch summaries.
        for b in discarded:
            self.rollback_branch(b)
        merged = dict(self.snapshot)
        for e in surviving.effects:
            if e.committed:
                merged[e.idempotency_key] = e.tool
        # Post-merge audit: any committed effect attributable to a discarded branch
        # that is not in the merged state is a leak.
        discarded_ids = {b.branch_id for b in discarded}
        for e in self.committed_effects:
            if e.branch_id in discarded_ids and e.idempotency_key not in merged:
                raise SpeculativeCommitLeak(
                    f"post-merge audit: effect {e.idempotency_key} from discarded "
                    f"branch {e.branch_id} present in environment but absent from merge"
                )
        return merged
