# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-whose-tool-side-effects-already-landed-before-rollback-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-whose-tool-side-effects-already-landed-before-rollback-reconciliation.warrant.json
# Markdown SHA-256:   651c362409c1aa13fa2554c42ae7dc64533b7c1592b3df7609af7134518a106c
# Code AST SHA-256:   0e1e3fc0af69a4393b44d4191acd711b0cc7df15c78514500e646f4e54595109
# Verified Classes:   IncompleteRollbackError, EffectEntry, EffectLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class IncompleteRollbackError(RuntimeError):
    """Raised when a branch cannot be fully neutralized because an effect
    landed without a durable handle, or a handle was reconstructed unsafely."""
    pass


@dataclass
class EffectEntry:
    branch_id: str
    tool_call_id: str
    tool: str
    handle: Optional[str]          # recorded handle; None means effect landed but handle lost
    idempotency_key: str
    committed: bool = False
    compensated: bool = False


@dataclass
class EffectLedger:
    entries: list[EffectEntry] = field(default_factory=list)

    def record(self, entry: EffectEntry) -> None:
        self.entries.append(entry)

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

    def is_closed(self) -> bool:
        return all(e.committed or e.compensated for e in self.entries)


def rollback_branch(ledger: EffectLedger, branch_id: str, destroy) -> None:
    """Neutralize a losing branch strictly via recorded handles.

    Never reconstruct a handle from a spec: if the handle is missing, the
    effect is unrecoverable and we must fail loudly rather than guess.
    """
    for entry in ledger.for_branch(branch_id):
        if entry.committed:
            # A losing branch must never have committed effects.
            raise IncompleteRollbackError(
                f"branch {branch_id} has committed effect {entry.tool_call_id} "
                f"({entry.tool}) that cannot be rolled back"
            )
        if entry.compensated:
            continue
        if entry.handle is None:
            # Effect landed, handle lost to context truncation. Do NOT infer.
            raise IncompleteRollbackError(
                f"branch {branch_id} effect {entry.tool_call_id} ({entry.tool}) "
                f"landed with no durable handle; orphan is unmanageable"
            )
        destroy(entry.handle)
        entry.compensated = True


def reconcile(ledger: EffectLedger, winner_id: str, loser_ids: list[str],
              destroy, commit) -> None:
    for entry in ledger.for_branch(winner_id):
        commit(entry.handle)
        entry.committed = True
    for loser in loser_ids:
        rollback_branch(ledger, loser, destroy)
    if not ledger.is_closed():
        raise IncompleteRollbackError(
            "effect ledger not closed after reconciliation; "
            "external state may diverge from recorded state"
        )
