# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-effects-before-committing-a-shared-memory-write.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-effects-before-committing-a-shared-memory-write.warrant.json
# Markdown SHA-256:   3751a0575ae5031da00fe1961115e06ab9992c5625f4300f8e7ea2c29b5d2ae1
# Code AST SHA-256:   37eb767f4f23159f0ef56f2c8bb391b39f1ebb017c7839ae5a49ef1d9fdb23f2
# Verified Classes:   SpeculativeBleedError, Branch, SpeculativeStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class SpeculativeBleedError(RuntimeError):
    """Raised when a branch's committed lineage references state that only a
    discarded sibling established, or when a shared-key write escapes its
    branch version during the speculation window."""


@dataclass
class Branch:
    branch_id: str
    version: int
    written_keys: Set[str] = field(default_factory=set)
    action_entity_refs: Set[str] = field(default_factory=set)


class SpeculativeStore:
    def __init__(self) -> None:
        self._committed: Dict[str, str] = {}
        self._tentative: Dict[int, Dict[str, str]] = {}
        self._snapshot_version: int = 0

    def begin(self, branch_id: str) -> Branch:
        version = self._snapshot_version + 1
        self._tentative[version] = {}
        return Branch(branch_id=branch_id, version=version)

    def write(self, branch: Branch, key: str, value: str) -> None:
        # Writes land only in the branch's own version namespace.
        self._tentative[branch.version][key] = value
        branch.written_keys.add(key)

    def read(self, branch: Branch, key: str) -> str:
        # Snapshot isolation: a branch sees committed state at speculation
        # start plus its OWN tentative writes -- never a sibling's.
        if key in self._tentative[branch.version]:
            return self._tentative[branch.version][key]
        if key in self._committed:
            return self._committed[key]
        raise KeyError(key)

    def commit(self, winner: Branch, discarded: list[Branch]) -> None:
        # 1. Verify the winner's lineage does not depend on speculative facts.
        for ref in winner.action_entity_refs:
            resolved = ref in self._tentative[winner.version] or ref in self._committed
            if not resolved:
                raise SpeculativeBleedError(
                    f"branch {winner.branch_id} action references '{ref}' which "
                    f"exists only in a discarded sibling's version"
                )
        # 2. Detect cross-branch contamination: a discarded branch must not
        #    have written a key the winner read as committed.
        discarded_keys = set()
        for b in discarded:
            discarded_keys |= b.written_keys
        for key in winner.action_entity_refs & discarded_keys:
            if key not in self._tentative[winner.version]:
                raise SpeculativeBleedError(
                    f"winner read '{key}' from a sibling's tentative write; "
                    f"snapshot isolation was violated"
                )
        # 3. Atomic fold: winner's version becomes committed, others dropped.
        self._committed.update(self._tentative[winner.version])
        self._snapshot_version = winner.version
        for b in discarded:
            self._tentative.pop(b.version, None)
        self._tentative.pop(winner.version, None)


def reconcile(store: SpeculativeStore, winner: Branch, losers: list[Branch]) -> None:
    try:
        store.commit(winner, losers)
    except SpeculativeBleedError:
        raise
    except Exception as exc:  # defensive: never leave a half-folded cursor
        raise SpeculativeBleedError(f"non-atomic commit aborted: {exc}") from exc
