# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fork-a-speculative-branch-that-later-cannot-reconcile-its-tool-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fork-a-speculative-branch-that-later-cannot-reconcile-its-tool-side-effects.warrant.json
# Markdown SHA-256:   1a4a76c79be75fa51e3b9bae3d0dec4c0a96191f9bffd8a71da138c80e27f9ce
# Code AST SHA-256:   249a031fa1350213e88b69efd5a4951b900e46654c4bd1c6e3df139eac7ec9c4
# Verified Classes:   EffectClass, UnreconcilableBranchError, EffectRecord, EffectLedger
# Defensive Guards:   8 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    IDEMPOTENT_KEYED = "idempotent_keyed"   # safe to run speculatively
    DEFERRABLE = "deferrable"               # intent only; execute post-vote
    REVERSIBLE = "reversible"               # run, but record inverse handle
    IRREVERSIBLE = "irreversible"           # must serialize, never speculate


class UnreconcilableBranchError(RuntimeError):
    """Raised when a discarded speculative branch left world residue
    that the orchestrator has no key or inverse to undo."""


@dataclass
class EffectRecord:
    corr_key: str
    branch_id: str
    effect_class: EffectClass
    inverse_handle: Optional[str] = None
    committed: bool = False
    compensated: bool = False


@dataclass
class EffectLedger:
    records: dict[str, EffectRecord] = field(default_factory=dict)

    def pre_mint(self, corr_key: str, branch_id: str, cls: EffectClass) -> None:
        if corr_key in self.records:
            raise UnreconcilableBranchError(
                f"correlation key {corr_key} already minted; branch {branch_id} "
                f"cannot fork with a colliding key"
            )
        self.records[corr_key] = EffectRecord(corr_key, branch_id, cls)

    def record_inverse(self, corr_key: str, inverse_handle: str) -> None:
        rec = self.records.get(corr_key)
        if rec is None:
            raise UnreconcilableBranchError(
                f"inverse recorded for unminted key {corr_key}; effect escaped the ledger"
            )
        if rec.effect_class is not EffectClass.REVERSIBLE:
            raise UnreconcilableBranchError(
                f"key {corr_key} classified {rec.effect_class}; inverse handle not applicable"
            )
        rec.inverse_handle = inverse_handle

    def reconcile(self, winning_branch: str, compensate) -> None:
        for rec in self.records.values():
            if rec.branch_id == winning_branch:
                rec.committed = True
                continue
            # losing branch: must resolve to no-op or confirmed compensation
            if rec.effect_class in (EffectClass.IDEMPOTENT_KEYED, EffectClass.DEFERRABLE):
                rec.compensated = True  # dropped intent / keyed no-op
            elif rec.effect_class is EffectClass.REVERSIBLE:
                if rec.inverse_handle is None:
                    raise UnreconcilableBranchError(
                        f"losing branch {rec.branch_id} ran reversible effect {rec.corr_key} "
                        f"but recorded no inverse handle; cannot compensate"
                    )
                compensate(rec.inverse_handle)
                rec.compensated = True
            else:  # IRREVERSIBLE
                raise UnreconcilableBranchError(
                    f"losing branch {rec.branch_id} committed irreversible effect "
                    f"{rec.corr_key}; world residue cannot be rolled back"
                )
        unresolved = [
            r.corr_key for r in self.records.values()
            if not r.committed and not r.compensated
        ]
        if unresolved:
            raise UnreconcilableBranchError(
                f"rollback declared with unresolved effects: {unresolved}"
            )


def gate_speculative_call(
    ledger: EffectLedger, branch_id: str, corr_key: Optional[str], cls: EffectClass
) -> None:
    if cls is EffectClass.IRREVERSIBLE:
        raise UnreconcilableBranchError(
            f"branch {branch_id} attempted irreversible effect {corr_key} inside a "
            f"speculative fork; serialize this call post-vote"
        )
    if corr_key is None:
        raise UnreconcilableBranchError(
            f"branch {branch_id} issued {cls.value} call with no pre-minted key; "
            f"effect would escape the ledger"
        )
    if corr_key not in ledger.records:
        ledger.pre_mint(corr_key, branch_id, cls)
