# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-parallel-branch-commit-an-irreversible-external-effect-before-the-winning-branch-is-known-and-how-do-we-bound-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-parallel-branch-commit-an-irreversible-external-effect-before-the-winning-branch-is-known-and-how-do-we-bound-it.warrant.json
# Markdown SHA-256:   7995443586a8c171100eaeb918de19f3d13fc4ad6078611eb90ae74828ea19b6
# Code AST SHA-256:   7f5128111d1a4dbbc32a770932577e9cce01c27e834c23e2248cc360ffaebbd4
# Verified Classes:   EffectClass, SpeculativeEffectViolation, ToolCall, Branch, EffectLog
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    PURE = "pure"
    IDEMPOTENT_KEYED = "idempotent_keyed"
    EFFECTFUL_DEFERRED = "effectful_deferred"


class SpeculativeEffectViolation(RuntimeError):
    """Raised when a speculative branch emits an effect that rollback cannot undo."""


@dataclass(frozen=True)
class ToolCall:
    tool: str
    effect_class: EffectClass
    branch_id: str
    task_id: str
    step_index: int
    idempotency_key: Optional[str] = None


@dataclass
class Branch:
    branch_id: str
    committed: bool = False


class EffectLog:
    """Write-ahead log; the single sink consulted by both rollback and arbitration."""

    def __init__(self) -> None:
        self._entries: list[ToolCall] = []

    def record(self, call: ToolCall) -> None:
        self._entries.append(call)

    def has_effect(self, branch_id: str) -> bool:
        return any(
            e.branch_id == branch_id and e.effect_class is EffectClass.EFFECTFUL_DEFERRED
            for e in self._entries
        )


def dispatch(branch: Branch, call: ToolCall, log: EffectLog) -> None:
    if branch.committed:
        log.record(call)
        return

    if call.effect_class is EffectClass.PURE:
        return

    if call.effect_class is EffectClass.IDEMPOTENT_KEYED:
        expected = f"{call.task_id}:{call.branch_id}:{call.step_index}"
        if call.idempotency_key != expected:
            raise SpeculativeEffectViolation(
                f"branch {call.branch_id} emitted keyed effect {call.tool} "
                f"with key {call.idempotency_key!r}, expected {expected!r}; "
                f"a re-run or duplicate branch would not collapse."
            )
        log.record(call)
        return

    # EFFECTFUL_DEFERRED inside an uncommitted branch: must be staged, not dispatched.
    raise SpeculativeEffectViolation(
        f"branch {call.branch_id} attempted irreversible tool {call.tool!r} "
        f"(step {call.step_index}) before arbitration commit; "
        f"rollback would discard branch state but leave the external effect."
    )
