# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fork-speculative-branches-that-individually-pass-but-merge-into-an-inconsistent-state-the-cross-branch-invariant-gap-in-fan-out-o.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fork-speculative-branches-that-individually-pass-but-merge-into-an-inconsistent-state-the-cross-branch-invariant-gap-in-fan-out-o.warrant.json
# Markdown SHA-256:   68ac528fd98f2ef888e02f2a07e9a87777f0359d00d35cb290f2ed55b4331ee2
# Code AST SHA-256:   ebffb54442a3e32dc48254a62d243262995c0938da63bb19683c78d86be420e0
# Verified Classes:   CrossBranchMergeError, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Callable, Iterable


class CrossBranchMergeError(RuntimeError):
    """Raised when speculative branches cannot be soundly merged."""


@dataclass(frozen=True)
class Branch:
    name: str
    writes: frozenset[str]          # state keys this branch wrote
    read_depends: frozenset[str]    # keys it read-and-depended on
    opaque_tool: bool = False       # if True, treat as touching all keys
    verified: bool = True           # per-branch PASS, valid only against S0


def _effect_keys(b: Branch) -> frozenset[str]:
    if b.opaque_tool:
        return frozenset({"*"})     # conservative: touches everything
    return b.writes | b.read_depends


def _interferes(a: Branch, b: Branch) -> bool:
    ea, eb = _effect_keys(a), _effect_keys(b)
    if "*" in ea or "*" in eb:
        return True
    # write-write on a shared key with no total reconciliation
    if a.writes & b.writes:
        return True
    # write-read / read-write dependency across branches
    if a.writes & b.read_depends or b.writes & a.read_depends:
        return True
    return False


def build_dependency_graph(branches: Iterable[Branch]) -> dict[str, set[str]]:
    bs = list(branches)
    g: dict[str, set[str]] = {b.name: set() for b in bs}
    for i, a in enumerate(bs):
        for b in bs[i + 1:]:
            if _interferes(a, b):
                g[a.name].add(b.name)
                g[b.name].add(a.name)
    return g


def _has_cycle(g: dict[str, set[str]]) -> bool:
    WHITE, GRAY, BLACK = 0, 1, 2
    color = {n: WHITE for n in g}

    def dfs(n: str) -> bool:
        color[n] = GRAY
        for m in g[n]:
            if color[m] == GRAY:
                return True
            if color[m] == WHITE and dfs(m):
                return True
        color[n] = BLACK
        return False

    return any(color[n] == WHITE and dfs(n) for n in g)


def plan_merge(
    branches: list[Branch],
    verify_accumulated: Callable[[frozenset[str]], bool],
) -> list[str]:
    """
    Return a sound merge order, or raise CrossBranchMergeError.
    Per-branch `verified` is NOT trusted as a merge certificate; the
    accumulated state is re-verified after every replay step.
    """
    g = build_dependency_graph(branches)
    if _has_cycle(g):
        # No merge order is sound; caller must collapse the cycle into
        # a single joint branch and re-execute.
        raise CrossBranchMergeError(
            "dependency cycle among branches; merge order undefined — "
            "collapse the cycle and re-run jointly"
        )

    by_name = {b.name: b for b in branches}
    # topological order by interference degree (deterministic tiebreak)
    order: list[str] = []
    remaining = set(g)
    accumulated_writes: set[str] = set()
    while remaining:
        ready = sorted(
            (n for n in remaining if not (g[n] & remaining)),
            key=lambda n: (len(g[n]), n),
        )
        if not ready:
            raise CrossBranchMergeError(
                "topological sort stalled; graph not a forest"
            )
        for n in ready:
            b = by_name[n]
            accumulated_writes |= set(_effect_keys(b))
            if not verify_accumulated(frozenset(accumulated_writes)):
                # branch PASS does not survive merge with its siblings
                raise CrossBranchMergeError(
                    f"branch {n!r} passed in isolation but accumulated "
                    f"state fails verification after replay"
                )
            order.append(n)
            remaining.discard(n)
    return order
