# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-parallel-plans-and-the-rollback-of-a-losing-branch-corrupts-the-reconciliation-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-parallel-plans-and-the-rollback-of-a-losing-branch-corrupts-the-reconciliation-ledger.warrant.json
# Markdown SHA-256:   ddff67f3b971bf8f181c96395d91ebfc728853ca2ac8c5b4c1a9f352be51060b
# Code AST SHA-256:   ef0cb9740607dcdc9d625f38ab7c0724fee83bbf48169999b3bc272ea0bda9dd
# Verified Classes:   ReconciliationConflict, EffectEntry, Branch, SharedStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Optional


class ReconciliationConflict(RuntimeError):
    """Raised when a discarded branch's rollback or the join-time
    value-set assertion detects cross-branch state corruption."""
    pass


@dataclass
class EffectEntry:
    key: str
    written_value: Any          # value this branch wrote
    fork_value: Any             # value at the fork point (baseline)
    committed: bool = False


@dataclass
class Branch:
    name: str
    journal: list[EffectEntry] = field(default_factory=list)
    discarded: bool = False


class SharedStore:
    def __init__(self) -> None:
        self._data: dict[str, Any] = {}

    def read(self, key: str) -> Optional[Any]:
        return self._data.get(key)

    def cas_write(self, key: str, expected: Optional[Any], new: Any) -> bool:
        if self._data.get(key) != expected:
            return False
        self._data[key] = new
        return True

    def cas_delete(self, key: str, expected: Any) -> bool:
        if self._data.get(key) != expected:
            return False
        del self._data[key]
        return True


def rollback_branch(branch: Branch, store: SharedStore) -> None:
    """Reverse a discarded branch. Every inverse is CAS-guarded against the
    value THIS branch wrote. If the store no longer holds that value, a
    sibling has taken ownership; do not force the inverse — raise."""
    for entry in reversed(branch.journal):
        if entry.committed:
            continue
        ok = store.cas_delete(entry.key, expected=entry.written_value)
        if not ok:
            observed = store.read(entry.key)
            raise ReconciliationConflict(
                f"branch {branch.name!r} rollback of key {entry.key!r} aborted: "
                f"expected {entry.written_value!r}, store holds {observed!r}. "
                f"A sibling committed over this key; forcing the inverse would "
                f"destroy committed state."
            )


def reconcile(winner: Branch, losers: list[Branch], store: SharedStore) -> None:
    """Join-time invariant: for every key touched by any branch, the store
    must hold either the fork baseline or the winner's written value."""
    touched: dict[str, tuple[Any, Any]] = {}  # key -> (fork_value, winner_value)
    for entry in winner.journal:
        touched[entry.key] = (entry.fork_value, entry.written_value)
    for loser in losers:
        for entry in loser.journal:
            touched.setdefault(entry.key, (entry.fork_value, None))

    for key, (fork_value, winner_value) in touched.items():
        observed = store.read(key)
        allowed = {fork_value, winner_value}
        if observed not in allowed:
            raise ReconciliationConflict(
                f"join assertion failed for key {key!r}: observed {observed!r} "
                f"is neither fork baseline {fork_value!r} nor winner value "
                f"{winner_value!r}. Refusing to re-derive; halting merge."
            )


# Reproduction of the observed failure, now guarded:
store = SharedStore()
store.cas_write("customer_id", expected=None, new="fork_baseline")

a = Branch("A", [EffectEntry("customer_id", written_value="Y", fork_value="fork_baseline")])
b = Branch("B", [EffectEntry("customer_id", written_value="X", fork_value="fork_baseline")])

store.cas_write("customer_id", expected="fork_baseline", new="X")  # B at t+4
store.cas_write("customer_id", expected="X", new="Y")             # A at t+6 (winner)
a.journal[0].committed = True

try:
    rollback_branch(b, store)          # B's blind delete would have killed "Y"
except ReconciliationConflict as exc:
    print("guarded:", exc)             # conflict surfaced, Y preserved

reconcile(a, [b], store)               # join assertion passes: store holds "Y"
assert store.read("customer_id") == "Y"
