# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-speculative-branch-contamination-when-optimistic-tool-invocations-produce-irreversible-external-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-speculative-branch-contamination-when-optimistic-tool-invocations-produce-irreversible-external-side-effects.warrant.json
# Markdown SHA-256:   ca6c490f24808ef0b75cb559546438e599fd7a14a2c2de41411be2837677c6bc
# Code AST SHA-256:   457a37cd34785b9099654728bb335dadf05c970c9906ec050033e6167adde2f0
# Verified Classes:   EffectClass, SpeculativeContaminationError, ToolSpec, EffectJournal
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    IDEMPOTENT = "idempotent"
    REVERSIBLE = "reversible"   # has a verified compensation handle
    IRREVERSIBLE = "irreversible"


class SpeculativeContaminationError(RuntimeError):
    """Raised when a speculative branch would commit an irreversible effect
    or read unsnapshotted external state before the commit barrier."""


@dataclass
class ToolSpec:
    name: str
    effect: EffectClass
    reads_external_state: bool = False
    compensate: Callable[[dict], None] | None = None


@dataclass
class EffectJournal:
    entries: list[tuple[ToolSpec, dict]] = field(default_factory=list)

    def record(self, spec: ToolSpec, args: dict) -> None:
        self.entries.append((spec, args))

    def compensate_reverse(self) -> None:
        for spec, args in reversed(self.entries):
            if spec.effect is EffectClass.REVERSIBLE and spec.compensate:
                spec.compensate(args)


def assert_speculable(spec: ToolSpec, committed: bool) -> None:
    """Enforce the rollback-completeness invariant before any tool call."""
    if committed:
        return  # committed branch may invoke any effect class
    if spec.effect is EffectClass.IRREVERSIBLE:
        raise SpeculativeContaminationError(
            f"tool '{spec.name}' is irreversible and cannot be invoked "
            f"inside the optimistic window; defer to post-commit"
        )
    if spec.reads_external_state:
        raise SpeculativeContaminationError(
            f"tool '{spec.name}' reads unsnapshotted external state; "
            f"route to fork-time snapshot or execute behind commit barrier"
        )


def run_branch(tools: dict[str, ToolSpec], calls: list[tuple[str, dict]],
               committed: bool, journal: EffectJournal) -> None:
    for name, args in calls:
        spec = tools[name]
        assert_speculable(spec, committed)
        journal.record(spec, args)
        # ... invoke tool ...
