# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-speculative-branch-whose-tool-side-effects-have-already-escaped-the-merge-barrier.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-speculative-branch-whose-tool-side-effects-have-already-escaped-the-merge-barrier.warrant.json
# Markdown SHA-256:   d59e02a3c30272af4af09a9b2b94413e2c997bab12405ade64ca7ee43b7a4276
# Code AST SHA-256:   f602eca0ebf3d374ac880bcca51cd91f83e395d53aca6b61cf0ef5e8842ce01f
# Verified Classes:   UncompensatedEffectError, EffectEntry, EffectLedger, SpeculativeOrchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Dict, List
from datetime import datetime


class UncompensatedEffectError(RuntimeError):
    """Raised when a speculative branch is rolled back while its escaped
    effects remain uncompensated, or when a merge is attempted against a
    snapshot that predates an orphaned effect."""
    pass


@dataclass
class EffectEntry:
    effect_id: str
    branch_id: str
    compensation: Callable[[], None] | None
    idempotency_key: str
    committed: bool = False
    compensated: bool = False


@dataclass
class EffectLedger:
    entries: Dict[str, EffectEntry] = field(default_factory=dict)

    def record(self, entry: EffectEntry) -> None:
        self.entries[entry.effect_id] = entry

    def branch_entries(self, branch_id: str) -> List[EffectEntry]:
        return [e for e in self.entries.values() if e.branch_id == branch_id]


class SpeculativeOrchestrator:
    def __init__(self, ledger: EffectLedger) -> None:
        self.ledger = ledger
        self.closed_branches: set[str] = set()

    def rollback_branch(self, branch_id: str) -> None:
        # Restore context snapshot (cheap, local).
        self._restore_snapshot(branch_id)

        # Drain the effect ledger: every escaped effect must be compensated
        # in reverse order before the branch may be marked closed.
        pending = [e for e in self.ledger.branch_entries(branch_id)
                   if not e.compensated and not e.committed]
        for entry in reversed(pending):
            if entry.compensation is None:
                raise UncompensatedEffectError(
                    f"Branch {branch_id} produced non-compensable effect "
                    f"{entry.effect_id} (key={entry.idempotency_key}); "
                    f"rollback is unsound — branch must be committed or "
                    f"prevented, not discarded."
                )
            entry.compensation()
            entry.compensated = True

        self.closed_branches.add(branch_id)

    def merge(self, winning_branch: str, pre_fork_snapshot_time: datetime,
              post_effect_world_time: datetime) -> None:
        # Guard: the surviving branch must reason against the compensated
        # world, not the pre-fork snapshot.
        orphans = [
            e for e in self.ledger.entries.values()
            if not e.compensated and not e.committed
        ]
        if orphans and post_effect_world_time < pre_fork_snapshot_time:
            raise UncompensatedEffectError(
                f"Merge of {winning_branch} computed against pre-fork snapshot "
                f"while {len(orphans)} orphaned effect(s) remain live; "
                f"re-derive the plan from the compensated world."
            )
        # Commit the winning branch's proposed effects here.
        for e in self.ledger.branch_entries(winning_branch):
            e.committed = True

    def _restore_snapshot(self, branch_id: str) -> None:
        # Context-only restoration; deliberately does not touch the ledger.
        pass
