# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-fence-speculative-branches-before-committing-a-merged-plan-write-skew-across-parallel-rollback-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-fence-speculative-branches-before-committing-a-merged-plan-write-skew-across-parallel-rollback-reconciliation.warrant.json
# Markdown SHA-256:   2da840f95f70810b9dfcde123b91158a3ea1cbb7e3bfb2777b256a112556bc41
# Code AST SHA-256:   6b1974b7c1e92c402eba063565f66973c807802c951ad4293dc799b99a8ca588
# Verified Classes:   SpeculativeCommitError, Branch, PlanInvariant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class SpeculativeCommitError(RuntimeError):
    """Raised when a merged speculative write-set violates a plan-level invariant
    that no individual branch violated (write-skew at the commit fence)."""


@dataclass
class Branch:
    name: str
    write_set: dict          # keys this branch would commit
    completion_ts: float


@dataclass
class PlanInvariant:
    name: str
    check: Callable[[dict], bool]   # evaluates against a full state dict


def merge_last_writer_wins(branches: list[Branch]) -> dict:
    merged: dict = {}
    for b in sorted(branches, key=lambda x: x.completion_ts):
        merged.update(b.write_set)
    return merged


def commit_speculative_plan(
    pre_state: dict,
    branches: list[Branch],
    invariants: list[PlanInvariant],
) -> dict:
    # Step 1: per-branch verification (necessary, NOT sufficient)
    for b in branches:
        candidate = {**pre_state, **b.write_set}
        for inv in invariants:
            if not inv.check(candidate):
                raise SpeculativeCommitError(
                    f"branch {b.name!r} individually violates {inv.name!r}"
                )

    # Step 2: the fence — verify the UNION, not the branches
    union_writes = merge_last_writer_wins(branches)
    committed = {**pre_state, **union_writes}
    for inv in invariants:
        if not inv.check(committed):
            # write-skew: each branch passed, the union did not
            raise SpeculativeCommitError(
                f"union write-set violates {inv.name!r}: "
                f"branches={[b.name for b in branches]} writes={union_writes} "
                f"state={committed} — write-skew at commit fence"
            )
    return committed


if __name__ == "__main__":
    pre = {"capacity": 10, "workers": 7, "reserved": 0}
    p = Branch("provision", {"workers": 10}, completion_ts=1.0)
    q = Branch("reserve", {"capacity": 7, "reserved": 3}, completion_ts=2.0)
    inv = PlanInvariant(
        "workers_plus_reserved_le_capacity",
        lambda s: s["workers"] + s["reserved"] <= s["capacity"],
    )
    commit_speculative_plan(pre, [p, q], [inv])  # raises SpeculativeCommitError
