# 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-committed-side-effects-it-cannot-roll-back.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-has-already-committed-side-effects-it-cannot-roll-back.warrant.json
# Markdown SHA-256:   bde753e1ccc9e10e72f8098193e6455b567fbd863cdee21bc331de42cef7903f
# Code AST SHA-256:   47db326f002303179f90fffc8e132b1470e28f57de18c08169bdd9e4e6b775ad
# Verified Classes:   RollbackIntegrityError, ToolClass, Effect, Coordinator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class RollbackIntegrityError(RuntimeError):
    """Raised when a discarded branch left unreconciled side effects."""
    pass


class ToolClass(Enum):
    SPECULATION_SAFE = "speculation_safe"   # private or compensable+journalled
    COMMIT_ONLY = "commit_only"             # non-compensable external effect


@dataclass
class Effect:
    branch_id: str
    tool: str
    kind: str            # "emit" | "commit" | "compensate"
    effect_id: str


@dataclass
class Coordinator:
    journal: list[Effect] = field(default_factory=list)

    def reconcile(self, discarded_branches: set[str]) -> None:
        emitted = {
            e.effect_id for e in self.journal
            if e.kind == "emit" and e.branch_id in discarded_branches
        }
        resolved = {
            e.effect_id for e in self.journal
            if e.kind in ("commit", "compensate")
        }
        leaked = emitted - resolved
        if leaked:
            raise RollbackIntegrityError(
                f"discarded branches {sorted(discarded_branches)} leaked "
                f"{len(leaked)} unreconciled effects: {sorted(leaked)}"
            )


def enforce_gateway(
    tool_class: ToolClass, phase: str, branch_id: str, tool: str, effect_id: str
) -> Effect:
    if phase == "speculative" and tool_class is ToolClass.COMMIT_ONLY:
        # Do not execute; hand back a deferred token for commit-phase replay.
        raise RollbackIntegrityError(
            f"branch {branch_id} attempted commit-only tool {tool!r} "
            f"during speculation; effect {effect_id} must be deferred"
        )
    return Effect(branch_id, tool, "emit", effect_id)
