# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-plan-when-a-compensating-action-s-precondition-has-been-invalidated-by-a-sibling-branch-s-side.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-plan-when-a-compensating-action-s-precondition-has-been-invalidated-by-a-sibling-branch-s-side.warrant.json
# Markdown SHA-256:   36962292a0f572bb7af16b2c6095259af1f757e91e1adfa0c285ed22cb4b1514
# Code AST SHA-256:   d0d45f31aad011804d50a0e71567afeca6c1a586e2912895bffcd9d0ad6d31e6
# Verified Classes:   CompensationPreconditionInvalidated, FactVersion, Compensation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class CompensationPreconditionInvalidated(RuntimeError):
    """Raised when a compensating action's captured precondition no longer holds
    at execution time and the divergence cannot be safely re-derived."""


@dataclass(frozen=True)
class FactVersion:
    value: int
    version: int


@dataclass(frozen=True)
class Compensation:
    branch_id: str
    read_set: Mapping[str, FactVersion]   # captured at schedule time
    recomputable: bool                    # additive within speculative set?


def execute_compensation(
    comp: Compensation,
    current: Mapping[str, FactVersion],
    speculative_writers: frozenset[str],
) -> int:
    """Apply a compensation only if every captured fact version is unchanged.

    Returns the delta to apply. Raises if the precondition was invalidated by a
    writer outside the additive speculative set, or if the compensation is
    opaque and any version diverged.
    """
    diverged = {
        fact: (captured.version, current[fact].version)
        for fact, captured in comp.read_set.items()
        if fact not in current or current[fact].version != captured.version
    }

    if not diverged:
        # Fast path: world unchanged since capture. Safe to apply captured delta.
        return sum(c.value - current[f].value for f, c in comp.read_set.items())

    # Divergence detected. Only safe to re-derive if the compensation is
    # additive-recomputable AND every diverging fact was written by a sibling
    # inside the same speculative set whose delta is known.
    external_touched = {
        fact for fact in diverged
        if fact not in speculative_writers
    }
    if external_touched or not comp.recomputable:
        raise CompensationPreconditionInvalidated(
            f"branch={comp.branch_id} compensation precondition invalidated: "
            f"diverged={diverged} external_writers={external_touched} "
            f"recomputable={comp.recomputable}; halting plan, escalate to auditor"
        )

    # Re-derive against post-merge snapshot; captured delta still additive.
    return sum(c.value - current[f].value for f, c in comp.read_set.items())


def commit_compensation(comp: Compensation, delta: int, ledger: dict) -> None:
    """Apply the compensation and enforce the runtime reconciliation invariant."""
    for fact in comp.read_set:
        ledger[fact] = ledger.get(fact, 0) + delta
    # Runtime guard: never let a compensation mint phantom effects.
    if ledger.get("balance", 0) + sum(
        v for k, v in ledger.items() if k.startswith("reserved_")
    ) != ledger.get("_initial", ledger.get("balance", 0)):
        raise CompensationPreconditionInvalidated(
            f"branch={comp.branch_id} post-compensation reconciliation failed; "
            f"ledger={ledger}"
        )
