# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-branch-whose-read-set-was-invalidated-by-a-sibling-branch-s-tool-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-branch-whose-read-set-was-invalidated-by-a-sibling-branch-s-tool-side-effect.warrant.json
# Markdown SHA-256:   c354c9804254027a518ac3b25f78721993eadda6f7494e7f7b12d76e1408e804
# Code AST SHA-256:   255c6621c9cf7727066a02995049e8996b21eb9115e0947ee884f36f81d07f10
# Verified Classes:   SpeculativeReadContamination, ReadStamp, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpeculativeReadContamination(RuntimeError):
    """Raised when a branch attempts to commit a write-set whose read-set
    observed an uncommitted or aborted sibling's side effect."""
    pass


@dataclass
class ReadStamp:
    key: str
    value: object
    source_branch: Optional[str]  # None if read from committed prefix
    source_committed: bool


@dataclass
class Branch:
    branch_id: str
    read_set: list[ReadStamp] = field(default_factory=list)
    write_set: dict = field(default_factory=dict)
    status: str = "PENDING"  # PENDING | COMMITTED | ABORTED


def reconcile_commit(branch: Branch, siblings: dict[str, Branch]) -> dict:
    # Reject any commit whose derivation touched a phantom sibling effect.
    for stamp in branch.read_set:
        if stamp.source_branch is None:
            continue
        src = siblings.get(stamp.source_branch)
        if src is None:
            raise SpeculativeReadContamination(
                f"branch {branch.branch_id} read key {stamp.key!r} from "
                f"unknown source {stamp.source_branch!r}"
            )
        if src.status != "COMMITTED":
            raise SpeculativeReadContamination(
                f"branch {branch.branch_id} read key {stamp.key!r} from "
                f"sibling {src.branch_id!r} in state {src.status}; "
                f"commit is unsound and branch must be re-run from checkpoint"
            )
        if src.write_set.get(stamp.key) != stamp.value:
            raise SpeculativeReadContamination(
                f"branch {branch.branch_id} read stale speculative value "
                f"{stamp.value!r} for key {stamp.key!r}; committed value is "
                f"{src.write_set.get(stamp.key)!r}"
            )
    branch.status = "COMMITTED"
    return dict(branch.write_set)


def run_fanout(branches: list[Branch]) -> dict:
    by_id = {b.branch_id: b for b in branches}
    merged: dict = {}
    # Commit in dependency order: a branch whose read-set references a sibling
    # must wait for that sibling to resolve. Dependents of aborted siblings
    # are re-run, never merged.
    for b in sorted(branches, key=lambda x: len(x.read_set)):
        try:
            merged.update(reconcile_commit(b, by_id))
        except SpeculativeReadContamination:
            b.status = "ABORTED"
            raise
    return merged
