# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-merges-from-resurrecting-effects-that-the-rollback-already-committed.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-merges-from-resurrecting-effects-that-the-rollback-already-committed.warrant.json
# Markdown SHA-256:   3b87905e8b9421213c84fe98655901dae98513e9d4037a827ec9fe78191ca2f9
# Code AST SHA-256:   f5f8ff134418038bc6483d2210a6d6b312e3a0c64c1c19be773159fc92770d5f
# Verified Classes:   SpeculativeMergeError, Effect, EffectLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class SpeculativeMergeError(RuntimeError):
    """Raised when a speculative merge would resurrect or duplicate a compensated effect."""


@dataclass
class Effect:
    cursor: int
    target: str          # object the effect touches, e.g. "accounts.plan"
    kind: str            # "rename" | "drop" | "create" | "compensation"
    idempotency_token: str | None = None


@dataclass
class EffectLedger:
    effects: List[Effect] = field(default_factory=list)
    _cursor: int = 0

    def record(self, target: str, kind: str, token: str | None = None) -> Effect:
        self._cursor += 1
        e = Effect(self._cursor, target, kind, token)
        self.effects.append(e)
        return e

    def highest_cursor_for(self, target: str) -> int:
        return max((e.cursor for e in self.effects if e.target == target), default=0)

    def compensation_cursor_for(self, target: str) -> int:
        return max(
            (e.cursor for e in self.effects
             if e.target == target and e.kind == "compensation"),
            default=0,
        )


def merge_winner(
    ledger: EffectLedger,
    winner_log: List[Effect],
    snapshot_cursor: int,
) -> None:
    """
    Apply a winner's effect-log against the branch-point snapshot.
    Rejects any effect whose target was compensated after the snapshot,
    because replaying it would resurrect or duplicate a rolled-back effect.
    """
    for eff in winner_log:
        comp_cursor = ledger.compensation_cursor_for(eff.target)
        if comp_cursor > snapshot_cursor:
            # The object was re-materialized by a loser's rollback after S0.
            # A name-based probe would falsely conclude the effect is unapplied.
            if eff.idempotency_token is None:
                raise SpeculativeMergeError(
                    f"merge of {eff.kind} on {eff.target!r} (cursor {eff.cursor}) "
                    f"would replay against a compensated object "
                    f"(compensation at cursor {comp_cursor} > snapshot {snapshot_cursor}); "
                    f"no idempotency token present, merge is unsound"
                )
            # With a token, the merger can prove prior application without probing identity.
        ledger.record(eff.target, eff.kind, eff.idempotency_token)


def run_speculation() -> None:
    ledger = EffectLedger()
    # B1 wins: rename plan -> plan_code, tokenized so replay is safe.
    ledger.record("accounts.plan", "rename", token="b1-rename-1")
    # B3 rejected: compensator re-materializes plan AFTER the branch point.
    ledger.record("accounts.plan", "compensation")
    snapshot_cursor = 1  # S0 was taken before the compensation

    # B2's merge log touches accounts.plan with no idempotency token.
    winner_log = [Effect(cursor=2, target="accounts.plan", kind="rename", idempotency_token=None)]
    merge_winner(ledger, winner_log, snapshot_cursor)  # raises SpeculativeMergeError


if __name__ == "__main__":
    try:
        run_speculation()
    except SpeculativeMergeError as exc:
        print(f"merge aborted to reconciliation-required state: {exc}")
