# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-pre-executes-speculative-tool-calls-against-a-verifier-that-later-rejects-the-plan-orphaned-side-effects-and-the-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-pre-executes-speculative-tool-calls-against-a-verifier-that-later-rejects-the-plan-orphaned-side-effects-and-the-commit.warrant.json
# Markdown SHA-256:   c6c9940ce98ca764503fad303261bcadcad424b1165b5a44f33f1a53be187246
# Code AST SHA-256:   d0d2e389a2643c4edc51b26648e7c4d9b4ad0fe0f06db356277f0da5923744ec
# Verified Classes:   EffectClass, SpeculationViolation, PlanStep, AcceptToken, CommitGate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Set


class EffectClass(Enum):
    PURE = "pure"
    IDEMPOTENT = "idempotent"
    EFFECTFUL = "effectful"


class SpeculationViolation(RuntimeError):
    """Raised when speculative pre-execution crosses the commit gate."""
    pass


@dataclass
class PlanStep:
    step_id: str
    tool: str
    effect: EffectClass
    has_idempotency_key: bool = False


@dataclass
class AcceptToken:
    plan_branch_id: str
    accepted_steps: Set[str] = field(default_factory=set)


class CommitGate:
    """
    Enforces: no EFFECTFUL step may be pre-executed before a step-scoped
    accept token covers it. PURE and keyed-IDEMPOTENT steps may speculate.
    """

    def __init__(self) -> None:
        self._executed_effects: Dict[str, List[str]] = {}

    def _is_speculatable(self, step: PlanStep) -> bool:
        if step.effect is EffectClass.PURE:
            return True
        if step.effect is EffectClass.IDEMPOTENT and step.has_idempotency_key:
            return True
        return False

    def speculate(self, branch_id: str, step: PlanStep, token: AcceptToken) -> None:
        if self._is_speculatable(step):
            self._record(branch_id, step)
            return
        # Effectful (or unkeyed idempotent): must be accepted, step-scoped.
        if step.step_id not in token.accepted_steps or token.plan_branch_id != branch_id:
            raise SpeculationViolation(
                f"step {step.step_id} ({step.tool}) is effectful and not covered "
                f"by a step-scoped accept token for branch {branch_id}; "
                f"pre-execution would orphan a side effect on rejection"
            )
        self._record(branch_id, step)

    def _record(self, branch_id: str, step: PlanStep) -> None:
        self._executed_effects.setdefault(branch_id, []).append(step.step_id)

    def compensate(self, branch_id: str, executed: List[str]) -> List[str]:
        # Compensate by effect handle, never by plan order.
        return [s for s in executed if s in self._executed_effects.get(branch_id, [])]


def run_speculative_plan(branch_id: str, steps: List[PlanStep], token: AcceptToken) -> None:
    gate = CommitGate()
    for step in steps:
        gate.speculate(branch_id, step, token)


if __name__ == "__main__":
    # Rejected branch: verifier accepted only S1, rejected the rest.
    token = AcceptToken(plan_branch_id="P", accepted_steps={"S1"})
    steps = [
        PlanStep("S1", "read_ledger", EffectClass.PURE),
        PlanStep("S2", "compute_adjustment", EffectClass.PURE),
        PlanStep("S3", "post_journal_entry", EffectClass.EFFECTFUL),  # fence
    ]
    try:
        run_speculative_plan("P", steps, token)
    except SpeculationViolation as exc:
        print(f"BLOCKED before orphaned side effect: {exc}")
