# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-side-effects-from-surviving-reconciliation-when-optimistic-agent-branches-fork-on-non-idempotent-external-ca.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-side-effects-from-surviving-reconciliation-when-optimistic-agent-branches-fork-on-non-idempotent-external-ca.warrant.json
# Markdown SHA-256:   33dc385693b68760ad9e36cc442de82b98b43dac405185655c2abd08ab2ea72d
# Code AST SHA-256:   396ab5d293ddb01572399d4e6c2848b519205fbe7c9d3b2fb02125f289ecfe5a
# Verified Classes:   SpeculationBoundaryViolation, SideEffectClass, ToolSpec, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class SpeculationBoundaryViolation(RuntimeError):
    """Raised when a speculative branch attempts an irreversible external
    side effect before the commit vector is decided."""
    pass


class SideEffectClass(Enum):
    PURE = "pure"
    IDEMPOTENT_OUTCOME_KEYED = "idempotent_outcome_keyed"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


@dataclass
class ToolSpec:
    name: str
    side_effect_class: SideEffectClass
    # Must derive from intended outcome, NOT branch identity.
    outcome_key: Callable[[dict], str] | None = None


@dataclass
class Branch:
    branch_id: str
    committed: bool = False
    effects: list[str] = field(default_factory=list)


def guard_speculative_call(
    tool: ToolSpec,
    args: dict,
    branch: Branch,
    commit_decided: bool,
    lease_held: bool,
) -> str:
    """Enforce the invariant: no irreversible external write from an
    undecided speculative branch unless a pessimistic lease is held."""
    if tool.side_effect_class is SideEffectClass.IRREVERSIBLE:
        if not commit_decided and not lease_held:
            raise SpeculationBoundaryViolation(
                f"branch {branch.branch_id} attempted irreversible tool "
                f"{tool.name!r} while commit vector undecided and no lease held; "
                f"refusing to leak a non-compensable side effect"
            )
    if tool.side_effect_class is SideEffectClass.IDEMPOTENT_OUTCOME_KEYED:
        if tool.outcome_key is None:
            raise SpeculationBoundaryViolation(
                f"tool {tool.name!r} declared outcome-keyed but provides no "
                f"outcome_key; branch-keyed dedup would defeat reconciliation"
            )
        # Key must not embed branch identity.
        key = tool.outcome_key(args)
        if branch.branch_id in key:
            raise SpeculationBoundaryViolation(
                f"idempotency key {key!r} embeds branch id {branch.branch_id!r}; "
                f"speculative branches would not collapse on reconcile"
            )
        branch.effects.append(key)
        return key
    branch.effects.append(f"{tool.name}:{branch.branch_id}")
    return branch.branch_id


def reconcile(branches: list[Branch], winner_id: str) -> list[str]:
    """Execute compensations for non-selected branches. Fails loudly if a
    discarded branch carried an irreversible effect (should be unreachable
    if guard_speculative_call was enforced)."""
    leaked: list[str] = []
    for b in branches:
        if b.branch_id == winner_id:
            b.committed = True
            continue
        for eff in b.effects:
            if eff.startswith("IRREVERSIBLE:"):
                leaked.append(eff)
    if leaked:
        raise SpeculationBoundaryViolation(
            f"reconciliation found irreversible effects on discarded branches: {leaked}"
        )
    return [b.branch_id for b in branches if b.committed]
