# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-an-optimistic-tool-call-commit-when-a-parallel-speculative-branch-rolls-back-across-a-shared-side-effect-ledg.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-an-optimistic-tool-call-commit-when-a-parallel-speculative-branch-rolls-back-across-a-shared-side-effect-ledg.warrant.json
# Markdown SHA-256:   41d4157681cb1a09a719ca8247857961d0f768fcd438390020db8392be972646
# Code AST SHA-256:   b9d335b0578332d66f7aa3a0492ca5467a523edc8269e094a443b12ccf299f7e
# Verified Classes:   UnreconcilableLedger, Compensation, LedgerState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnreconcilableLedger(RuntimeError):
    """Raised when a compensation's precondition was invalidated by a concurrent commit."""
    pass


@dataclass(frozen=True)
class Compensation:
    branch_id: str
    target_resource: str
    precondition_version: int
    intent_hash: str
    has_recall_path: bool  # False for fire-and-forget side effects


@dataclass(frozen=True)
class LedgerState:
    resource: str
    current_version: int
    poisoned: bool


def execute_compensation(comp: Compensation, ledger: LedgerState) -> None:
    """Apply a losing branch's compensation, or abort if the precondition is stale.

    The precondition check is necessary but NOT sufficient: a matching version
    can still mask a superseding commit with an identical intent_hash. The
    caller must have already drained the quiesce barrier before invoking this.
    """
    if ledger.poisoned:
        raise UnreconcilableLedger(
            f"resource {ledger.resource} is poisoned; "
            f"branch {comp.branch_id} cannot compensate"
        )

    if comp.precondition_version != ledger.current_version:
        # A concurrent commit advanced the ledger past this compensation's
        # snapshot. The compensation was computed against a state that no
        # longer exists; executing it would clobber an intervening write.
        if not comp.has_recall_path:
            raise UnreconcilableLedger(
                f"stale compensation for {comp.target_resource} at "
                f"v{comp.precondition_version} (ledger v{ledger.current_version}) "
                f"with irreversible side effect and no recall path; "
                f"abort and escalate to serialized repair"
            )
        raise UnreconcilableLedger(
            f"stale compensation for {comp.target_resource} at "
            f"v{comp.precondition_version} (ledger v{ledger.current_version}); "
            f"quiesce barrier was violated"
        )

    # Precondition holds: safe to apply the inverse.
    _apply_inverse(comp)


def _apply_inverse(comp: Compensation) -> None:
    # Placeholder for the actual inverse operation against the ledger.
    ...
