# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-outrun-the-merge-barrier-in-optimistic-multi-agent-tool-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-outrun-the-merge-barrier-in-optimistic-multi-agent-tool-invocation.warrant.json
# Markdown SHA-256:   cacce4f0a77f2e8f1deb701375cddd538bf400f90b6de756c750beacec1bdd7d
# Code AST SHA-256:   95a2e18986b78579a1d1f9a2a133bd979d286de9c0fc5422994fe2df5aed997f
# Verified Classes:   SpeculativeMergeError, BranchPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SpeculativeMergeError(RuntimeError):
    """Raised when a speculative branch set cannot be safely merged."""
    pass


@dataclass(frozen=True)
class BranchPlan:
    branch_id: str
    read_version: str                      # version token of the base snapshot read
    write_keys: FrozenSet[str]             # resources this branch will optimistically write
    reads_sibling_overlay: bool            # True if any read targets another branch's overlay


def classify_merge_regime(branches: list[BranchPlan]) -> str:
    """
    Decide the merge regime at dispatch time, before any tool call fires.
    Returns one of: 'disjoint', 'serialized_revalidate', 'refused_contaminated'.
    """
    if any(b.reads_sibling_overlay for b in branches):
        # Derived-read contamination: independence is already lost.
        return "refused_contaminated"

    # Group branches by read_version; intersection only matters within a version.
    by_version: Dict[str, list[BranchPlan]] = {}
    for b in branches:
        by_version.setdefault(b.read_version, []).append(b)

    for version, group in by_version.items():
        seen: Set[str] = set()
        for b in group:
            overlap = seen & b.write_keys
            if overlap:
                # Intersecting write-set on equal read-version -> must serialize.
                return "serialized_revalidate"
            seen |= b.write_keys

    return "disjoint"


def commit_speculative(branches: list[BranchPlan], committed_state: dict) -> list[str]:
    """
    Commit a branch set. Refuses contaminated sets; serializes intersecting sets
    with deterministic ordering and read-set revalidation.
    """
    regime = classify_merge_regime(branches)

    if regime == "refused_contaminated":
        contaminated = [b.branch_id for b in branches if b.reads_sibling_overlay]
        raise SpeculativeMergeError(
            f"Speculative merge refused: branches {contaminated} read sibling overlays; "
            f"independence lost, collapse to serial execution from checkpoint."
        )

    if regime == "disjoint":
        return [b.branch_id for b in branches]

    # serialized_revalidate: deterministic order by (read_version, sorted write_keys),
    # never by dispatch order.
    ordered = sorted(
        branches,
        key=lambda b: (b.read_version, tuple(sorted(b.write_keys))),
    )
    committed: list[str] = []
    for b in ordered:
        # Revalidate read-set against committed state produced by prior commits.
        if b.read_version != committed_state.get("version", b.read_version):
            raise SpeculativeMergeError(
                f"Branch {b.branch_id} read version {b.read_version} but committed "
                f"state advanced to {committed_state.get('version')}; re-derive branch."
            )
        committed.append(b.branch_id)
        # Advance version after each commit so the next branch revalidates against it.
        committed_state["version"] = f"{b.read_version}+{b.branch_id}"
    return committed
