# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-of-a-speculative-multi-agent-planner-abandon-parallel-branch-execution-and-collapse-to-serialized-merge.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-of-a-speculative-multi-agent-planner-abandon-parallel-branch-execution-and-collapse-to-serialized-merge.warrant.json
# Markdown SHA-256:   11961af08d009970d2ae76a77f7bf7e666ba07c7ae763948ea12e8fa126eae70
# Code AST SHA-256:   4c424a9e3ecb73a3792d4f7212145a770a12ae24846c0729893b754f454de07b
# Verified Classes:   PhantomReadMergeError, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Hashable


class PhantomReadMergeError(RuntimeError):
    """Raised when a conflict-free write-set merge would admit a cross-branch phantom read."""
    pass


@dataclass
class Branch:
    branch_id: str
    read_set: set[Hashable] = field(default_factory=set)
    write_set: set[Hashable] = field(default_factory=set)


NON_COMMUTATIVE = {"budget_remaining", "rate_limit_tokens", "exclusive_lock", "monotonic_counter"}


def merge_branches(branches: list[Branch]) -> dict:
    # Static check: write-write disjointness (the cheap, standard check).
    for i, a in enumerate(branches):
        for b in branches[i + 1:]:
            overlap = a.write_set & b.write_set
            if overlap:
                raise PhantomReadMergeError(
                    f"write-write conflict between {a.branch_id} and {b.branch_id} on {overlap}"
                )

    # Temporal check: read-write overlap on non-commutative keys.
    for i, a in enumerate(branches):
        for b in branches[i + 1:]:
            for reader, writer in ((a, b), (b, a)):
                rw = reader.read_set & writer.write_set
                fatal = rw & NON_COMMUTATIVE
                if fatal:
                    raise PhantomReadMergeError(
                        f"phantom read: branch {reader.branch_id} read {fatal} "
                        f"which branch {writer.branch_id} wrote; "
                        f"collapse to serialized merge for these branches"
                    )

    merged: dict = {}
    for b in branches:
        merged.update({k: b.branch_id for k in b.write_set})
    return merged


def plan_fork(branches: list[Branch]) -> dict:
    try:
        return merge_branches(branches)
    except PhantomReadMergeError:
        # Selective re-speculation or serialization is the caller's responsibility;
        # we re-raise so the planner does not silently produce an inconsistent plan.
        raise
