# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-race-when-a-losing-branch-has-already-committed-irreversible-side-effects-before-the-winner-is.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-race-when-a-losing-branch-has-already-committed-irreversible-side-effects-before-the-winner-is.warrant.json
# Markdown SHA-256:   c8b3150d95ca6019b81d67416739a02ef01c4ac359b44b6325f05f9cdb7ef89e
# Code AST SHA-256:   d3e1aec222f0373b63a6b1570b01e5e6ed950e0cfa1891a37b53c9e6ca3b5c79
# Verified Classes:   EffectClass, SpeculationInvariantViolation, EffectJournal, Branch, Orchestrator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    READ_ONLY = "read_only"
    IDEMPOTENT = "idempotent"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class SpeculationInvariantViolation(RuntimeError):
    """Raised when a branch emits an effect it was not cleared to emit,
    or when reconciliation would discard a branch whose committed effects
    are neither idempotent nor compensable."""


@dataclass
class EffectJournal:
    # Survives branch discard. Keyed by branch_id -> list of committed effect handles.
    committed: dict[str, list[dict]] = field(default_factory=dict)

    def record(self, branch_id: str, effect: dict) -> None:
        self.committed.setdefault(branch_id, []).append(effect)

    def handles_for(self, branch_id: str) -> list[dict]:
        return list(self.committed.get(branch_id, []))


@dataclass
class Branch:
    branch_id: str
    holds_effect_lease: bool = False
    discarded: bool = False


class Orchestrator:
    def __init__(self) -> None:
        self.journal = EffectJournal()

    def emit_effect(
        self,
        branch: Branch,
        effect_class: EffectClass,
        effect: dict,
        idempotency_key: Optional[str] = None,
    ) -> None:
        if branch.discarded:
            raise SpeculationInvariantViolation(
                f"branch {branch.branch_id} attempted emission after discard"
            )
        if effect_class is EffectClass.IRREVERSIBLE and not branch.holds_effect_lease:
            # The race is now in an unreconcilable state; abort, do not merely discard.
            raise SpeculationInvariantViolation(
                f"branch {branch.branch_id} emitted IRREVERSIBLE effect "
                f"{effect!r} without effect-class lease; race must be aborted, "
                f"not reconciled"
            )
        if effect_class is EffectClass.IDEMPOTENT and not idempotency_key:
            raise SpeculationInvariantViolation(
                f"branch {branch.branch_id} emitted IDEMPOTENT effect without "
                f"orchestrator-injected idempotency key"
            )
        # Commit to the shared journal BEFORE the call returns, so a loser's
        # effect is always compensable from the journal even after trace discard.
        self.journal.record(branch.branch_id, {"effect": effect, "class": effect_class})

    def reconcile(self, winner_id: str, losers: list[Branch]) -> None:
        for loser in losers:
            handles = self.journal.handles_for(loser.branch_id)
            for h in handles:
                if h["class"] is EffectClass.IRREVERSIBLE:
                    raise SpeculationInvariantViolation(
                        f"cannot discard branch {loser.branch_id}: it committed "
                        f"IRREVERSIBLE effect {h['effect']!r} with no compensation "
                        f"handle; manual reconciliation required"
                    )
                if h["class"] is EffectClass.COMPENSABLE:
                    self._compensate(h["effect"])
            loser.discarded = True  # trace discard only; journal retained

    def _compensate(self, effect: dict) -> None:
        # Real implementation calls the inverse tool (e.g. payments.reverse_refund).
        ...
