# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-speculative-branch-but-a-downstream-agent-has-already-emitted-an-irreversible-external-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-speculative-branch-but-a-downstream-agent-has-already-emitted-an-irreversible-external-side-effect.warrant.json
# Markdown SHA-256:   d8d32edf9c4cb3209684d53e142d659b4a0b6fa44ff693f4b9e00fa8ce8a3deb
# Code AST SHA-256:   3a25978e76762f3028a45a57b6c2943dfff837c03d1d07589b0f4bc9399c54bb
# Verified Classes:   SpeculationSafetyError, EffectClass, Tool, EffectJournal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

"""Guards speculative branch dispatch against irreversible side effects
escaping rollback. See record 2026-11-14."""

from __future__ import annotations

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


class SpeculationSafetyError(RuntimeError):
    """Raised when a branch would perform an irreversible effect that
    branch rollback cannot undo."""


class EffectClass(Enum):
    CONTAINED = "contained"          # writes only coordinator-owned state
    COMPENSABLE = "compensable"      # reversible via registered cancel path
    IRREVERSIBLE = "irreversible"    # external, durable, no undo


@dataclass(frozen=True)
class Tool:
    name: str
    effect: EffectClass


@dataclass
class EffectJournal:
    """Append-only; never truncated by branch rollback."""
    entries: list[tuple[str, str]] = field(default_factory=list)

    def record(self, branch_id: str, tool_name: str) -> None:
        self.entries.append((branch_id, tool_name))

    def effects_for(self, branch_id: str) -> list[str]:
        return [t for b, t in self.entries if b == branch_id]


def assert_speculable(branch_id: str, tools: Iterable[Tool]) -> None:
    """Refuse to dispatch a branch whose toolset can escape rollback."""
    offenders = [t.name for t in tools if t.effect is EffectClass.IRREVERSIBLE]
    if offenders:
        raise SpeculationSafetyError(
            f"branch {branch_id!r} exposes irreversible tools {offenders}; "
            "these must be commit-phase-only, not speculated"
        )


def invoke_in_branch(
    branch_id: str, tool: Tool, journal: EffectJournal
) -> None:
    """Every effect is journaled out-of-band before it is performed, so
    rollback can at least *see* what escaped."""
    if tool.effect is EffectClass.IRREVERSIBLE:
        raise SpeculationSafetyError(
            f"refusing irreversible tool {tool.name!r} inside speculative "
            f"branch {branch_id!r}"
        )
    journal.record(branch_id, tool.name)
    # ... perform the (contained or compensable) effect here ...


def rollback_branch(branch_id: str, journal: EffectJournal) -> list[str]:
    """Rollback discards branch state but must surface escaped effects."""
    escaped = [
        t for t in journal.effects_for(branch_id)
        if t not in {"contained_write"}
    ]
    if escaped:
        raise SpeculationSafetyError(
            f"branch {branch_id!r} rolled back with un-compensated effects "
            f"{escaped}; reconciliation required"
        )
    return escaped
