# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-speculative-side-effects-before-branch-verification-and-the-rollback-cannot-un-emit-them.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-speculative-side-effects-before-branch-verification-and-the-rollback-cannot-un-emit-them.warrant.json
# Markdown SHA-256:   d6a79404a7ae692af0ab6e52b9b0879f30ac614d55de559747aeb942635687f5
# Code AST SHA-256:   545e68753ba47cd25a0ccbb6d93c155940ded547089580a6fdfa25a2ea856cac
# Verified Classes:   SpeculativeEffectLeak, BranchState, EffectIntent, Branch, DeferredEffectGate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class SpeculativeEffectLeak(RuntimeError):
    """Raised when a speculative branch attempts an immediate (non-deferrable) effect."""
    pass


class BranchState(Enum):
    FORKED = "forked"
    VERIFIED_WINNER = "verified_winner"
    ROLLED_BACK = "rolled_back"


@dataclass
class EffectIntent:
    tool: str
    payload: dict
    branch_id: str


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.FORKED
    intents: list = field(default_factory=list)


class DeferredEffectGate:
    """
    Enforces the invariant: no branch may emit an immediate external effect
    before promotion. Immediate tools raise; deferrable tools record intents.
    """

    DEFERRABLE = {"send_email", "post_webhook", "insert_row"}
    IMMEDIATE = {"charge_card", "publish_to_queue"}

    def __init__(self, world: Callable[[str, dict], None]):
        self._world = world
        self._flushed: set = set()

    def call(self, branch: Branch, tool: str, payload: dict) -> None:
        if branch.state is not BranchState.VERIFIED_WINNER:
            if tool in self.IMMEDIATE:
                # The boundary: an immediate effect in a speculative branch is a
                # hard violation, not a compensable event.
                raise SpeculativeEffectLeak(
                    f"branch {branch.branch_id} attempted immediate effect "
                    f"'{tool}' before promotion; fork is unsound"
                )
            if tool in self.DEFERRABLE:
                branch.intents.append(EffectIntent(tool, payload, branch.branch_id))
                return
            raise SpeculativeEffectLeak(
                f"branch {branch.branch_id} called unclassified tool '{tool}'"
            )
        # Promoted branch: flush is allowed, exactly once per intent.
        key = (branch.branch_id, tool, tuple(sorted(payload.items())))
        if key in self._flushed:
            raise SpeculativeEffectLeak(f"duplicate flush of {key}")
        self._flushed.add(key)
        self._world(tool, payload)


def promote_and_flush(gate: DeferredEffectGate, winner: Branch, losers: list) -> None:
    # Ordering: losers are rolled back first, then the winner flushes. Flush is
    # keyed on promotion, never on fork-completion order.
    for b in losers:
        if b.intents:
            # Losers' intents are discarded, never flushed.
            b.intents.clear()
        b.state = BranchState.ROLLED_BACK
    winner.state = BranchState.VERIFIED_WINNER
    for intent in list(winner.intents):
        gate.call(winner, intent.tool, intent.payload)
    winner.intents.clear()


def run_speculation(gate: DeferredEffectGate, branch: Branch, plan: list) -> None:
    for tool, payload in plan:
        gate.call(branch, tool, payload)


# --- Reproduction of the observed failure, now caught -------------------------
if __name__ == "__main__":
    sent = []
    gate = DeferredEffectGate(lambda t, p: sent.append((t, p)))

    linewise = Branch("linewise")
    aggregate = Branch("aggregate")

    # A deferrable tool is fine in a speculative branch: it becomes an intent.
    run_speculation(gate, linewise, [("send_email", {"vendor": "C", "amt": 120})])
    assert sent == [], "deferrable intent must not reach the world pre-promotion"

    # An immediate tool in a speculative branch is the leak. It must raise.
    try:
        run_speculation(gate, aggregate, [("charge_card", {"vendor": "C", "amt": 120})])
    except SpeculativeEffectLeak as e:
        print(f"BLOCKED: {e}")

    # Only the promoted winner's intents reach the world, in promotion order.
    promote_and_flush(gate, winner=linewise, losers=[aggregate])
    assert sent == [("send_email", {"vendor": "C", "amt": 120})]
    print("flushed:", sent)
