# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-tool-side-effect-as-irreversible-before-the-rollback-barrier-is-drained.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-tool-side-effect-as-irreversible-before-the-rollback-barrier-is-drained.warrant.json
# Markdown SHA-256:   911ded890b3e7ddbd4edcf5b23444124bc300e62c12d21efb1f19aa74727ef2a
# Code AST SHA-256:   010d8b673b60a14da8496b9cca2cc88ea60f84af3dc49751a0a04ea033655313
# Verified Classes:   EffectState, OrphanedEffectError, EffectSlot, EffectJournal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EffectState(Enum):
    RESERVED = "reserved"
    EMITTED = "emitted"
    ORPHANED = "orphaned"
    COMMITTED = "committed"
    COMPENSATED = "compensated"


class OrphanedEffectError(RuntimeError):
    """Raised when a rollback barrier would discard an effect slot that has
    already been emitted to the external world without a dedup handle."""


@dataclass
class EffectSlot:
    logical_id: str          # e.g. "refund:invoice:4471" — branch-independent
    state: EffectState = EffectState.RESERVED
    idempotency_key: Optional[str] = None
    owning_branch: Optional[str] = None


class EffectJournal:
    """Barrier-exempt journal. Writes are synchronous at dispatch time so the
    handle survives branch death. Never deleted on rollback."""

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

    def reserve(self, logical_id: str, branch_id: str) -> EffectSlot:
        slot = self._slots.get(logical_id)
        if slot is None:
            slot = EffectSlot(logical_id=logical_id, owning_branch=branch_id)
            self._slots[logical_id] = slot
        elif slot.state in (EffectState.EMITTED, EffectState.ORPHANED):
            # Sibling branch must reuse the existing handle, not re-dispatch.
            raise OrphanedEffectError(
                f"slot {logical_id} already emitted under key "
                f"{slot.idempotency_key!r}; sibling branch {branch_id} must "
                f"reuse it, not issue a duplicate effect"
            )
        return slot

    def mark_emitted(self, logical_id: str, key: str) -> None:
        slot = self._slots[logical_id]
        slot.state = EffectState.EMITTED
        slot.idempotency_key = key

    def orphan(self, logical_id: str) -> None:
        slot = self._slots[logical_id]
        if slot.state == EffectState.EMITTED:
            slot.state = EffectState.ORPHANED


def drain_rollback_barrier(
    journal: EffectJournal, branch_id: str, branch_claimed_slots: list[str]
) -> None:
    """Called when a branch is rolled back. Must refuse to drain if any claimed
    slot has escaped without a recorded handle."""
    for logical_id in branch_claimed_slots:
        slot = journal._slots.get(logical_id)
        if slot is None:
            continue
        if slot.state == EffectState.RESERVED:
            # Dispatched but no handle recorded: dedup capability lost.
            raise OrphanedEffectError(
                f"slot {logical_id} reserved by {branch_id} but never reached "
                f"EMITTED; handle lost, refusing rollback"
            )
        if slot.state in (EffectState.EMITTED, EffectState.ORPHANED):
            # Effect is live in the world. Do not delete the slot; mark orphaned
            # and force reconciliation before any sibling commit.
            journal.orphan(logical_id)


def commit_branch(
    journal: EffectJournal, branch_id: str, branch_claimed_slots: list[str]
) -> None:
    """Reconciler commit path. Rejects a branch that would duplicate an
    already-emitted effect slot."""
    for logical_id in branch_claimed_slots:
        slot = journal._slots.get(logical_id)
        if slot is None:
            continue
        if slot.state in (EffectState.EMITTED, EffectState.ORPHANED):
            if slot.owning_branch != branch_id:
                raise OrphanedEffectError(
                    f"branch {branch_id} cannot commit slot {logical_id}: "
                    f"already emitted by {slot.owning_branch} under key "
                    f"{slot.idempotency_key!r}"
                )
        slot.state = EffectState.COMMITTED
