# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-speculative-branch-whose-write-set-intersects-a-committed-sibling-and-how-does-rollback-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-speculative-branch-whose-write-set-intersects-a-committed-sibling-and-how-does-rollback-reconciliation.warrant.json
# Markdown SHA-256:   62120d0381eccc4d3888affa21ee7194b0874f1192c42b7eb9f615862244fbb5
# Code AST SHA-256:   55604a2a3819672f0baa4e989ab0bf8681371e07b48c8ca9a813ba0e78b93366
# Verified Classes:   WriteSkewInvalidation, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class WriteSkewInvalidation(RuntimeError):
    """Raised when a speculative branch's read-set intersects a committed
    sibling's write-set, indicating write skew that cannot be merged soundly."""
    pass


@dataclass
class Branch:
    name: str
    read_set: Set[str] = field(default_factory=set)
    write_set: Set[str] = field(default_factory=set)
    committed: bool = False


def reconcile(branches: list[Branch]) -> Dict[str, Any]:
    committed_writes: Set[str] = set()
    merged: Dict[str, Any] = {}

    # Commit order matters; process in declaration order.
    for b in branches:
        # Anti-dependency check: does this branch's read-set intersect
        # any already-committed sibling's write-set?
        skew = b.read_set & committed_writes
        if skew:
            raise WriteSkewInvalidation(
                f"branch {b.name!r} read {sorted(skew)} which a committed "
                f"sibling has since written; re-fork required, merge unsound"
            )
        # Write-write overlap is a hard conflict handled elsewhere;
        # here we assume disjoint write-sets for the speculative case.
        committed_writes |= b.write_set
        b.committed = True
        merged[b.name] = "committed"

    return merged


if __name__ == "__main__":
    # Reproduces the observed failure: C reads `budget`, A writes `budget`.
    a = Branch("A", read_set={"constraints"}, write_set={"budget"})
    b = Branch("B", read_set={"calendar"}, write_set={"schedule"})
    c = Branch("C", read_set={"budget"}, write_set={"vendors"})

    try:
        reconcile([a, b, c])
    except WriteSkewInvalidation as e:
        print(f"MERGE REJECTED: {e}")
