# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-tool-call-fan-out-when-compensating-rollback-actions-are-non-commutative-with-concurrent-side-eff.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-tool-call-fan-out-when-compensating-rollback-actions-are-non-commutative-with-concurrent-side-eff.warrant.json
# Markdown SHA-256:   592a8bc03344e05651d7c1722e0a4092398c27565e7adaa4b5b3a5e38ed1b627
# Code AST SHA-256:   f55fbc303ba452e9427cd11481381317e142d9d1e3a9adbd46c2012620b8cee6
# Verified Classes:   NonCommutativeRollbackError, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class NonCommutativeRollbackError(RuntimeError):
    """Raised when a compensating action's write set intersects a sibling's
    read/write set, making optimistic rollback unsound."""


@dataclass(frozen=True)
class Branch:
    name: str
    forward_write_set: FrozenSet[str]
    read_set: FrozenSet[str]
    compensation_write_set: FrozenSet[str]


def assert_speculation_sound(branches: list[Branch]) -> None:
    """Enforce C1 (compensation isolation) across a speculative fan-out.

    Two branches may run concurrently only if neither branch's compensation
    write set intersects the other's read or write set. This is stricter than
    forward-write disjointness because compensations typically write to a
    superset (shared pricing pools, inventory counters, demand decay buckets).
    """
    for i, bi in enumerate(branches):
        for j, bj in enumerate(branches):
            if i == j:
                continue
            sibling_touch = bj.read_set | bj.forward_write_set | bj.compensation_write_set
            collision = bi.compensation_write_set & sibling_touch
            if collision:
                raise NonCommutativeRollbackError(
                    f"Branch {bi.name!r} compensation writes {sorted(collision)} "
                    f"which branch {bj.name!r} touches; fan-out is unsound. "
                    f"Serialize {bi.name!r} behind {bj.name!r} or abort speculation."
                )


def plan_fanout(branches: list[Branch]) -> list[Branch]:
    """Return the maximal sound parallel group; demote the rest to serial."""
    parallel: list[Branch] = []
    serial: list[Branch] = []
    for b in branches:
        trial = parallel + [b]
        try:
            assert_speculation_sound(trial)
            parallel.append(b)
        except NonCommutativeRollbackError:
            serial.append(b)
    if serial:
        # Caller must confirm-then-execute serial branches, never speculate.
        return parallel + serial  # order preserved; caller inspects grouping
    return parallel


# Reproduction of the observed incident:
t1 = Branch("reserve_seat", frozenset({"seat_14A"}), frozenset({"seat_14A"}), frozenset({"seat_14A"}))
t2 = Branch("hold_hotel_H9", frozenset({"inv_H9"}), frozenset({"inv_H9", "price_H9"}), frozenset({"inv_H9", "price_pool"}))
t3 = Branch("price_check", frozenset(), frozenset({"price_H9", "price_pool"}), frozenset())
t4 = Branch("hold_hotel_H11", frozenset({"inv_H11"}), frozenset({"inv_H11", "price_pool"}), frozenset({"inv_H11", "price_pool"}))

try:
    assert_speculation_sound([t1, t2, t3, t4])
except NonCommutativeRollbackError as exc:
    # Expected: t2's compensation touches price_pool, which t3 and t4 read.
    print(f"ABORT fan-out: {exc}")
