# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-fan-out-when-sub-agent-rollback-is-not-idempotent-across-a-shared-tool-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-fan-out-when-sub-agent-rollback-is-not-idempotent-across-a-shared-tool-ledger.warrant.json
# Markdown SHA-256:   edfaadfa30b4c910ce2220e287037eef04440f3f59afd749cfa20e6d2241a027
# Code AST SHA-256:   546d4e499c39d9df5ba398d61afbd0cbf99daf4af837b2026675d69939205a03
# Verified Classes:   SpeculationUnsoundError, ToolClass, Tool, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class SpeculationUnsoundError(RuntimeError):
    """Raised when speculative fan-out would grant non-idempotent write
    authority over a shared resource to more than one branch."""
    pass


class ToolClass(Enum):
    READ = "read"
    IDEMPOTENT_WRITE = "idempotent_write"   # keyed by task-derived token
    NON_IDEMPOTENT_WRITE = "non_idempotent_write"


@dataclass(frozen=True)
class Tool:
    name: str
    cls: ToolClass
    resource: str


@dataclass
class Branch:
    branch_id: str
    tools: FrozenSet[Tool]


def assert_speculation_sound(branches: list[Branch], gated_resources: FrozenSet[str]) -> None:
    """Enforce the write-authority partition invariant before fan-out.

    A resource may be reachable by multiple branches only if it is either
    (a) read-only, (b) idempotent-write, or (c) behind a commit-gate.
    Any shared NON_IDEMPOTENT_WRITE resource outside the gate is fatal.
    """
    holders: dict[str, list[str]] = {}
    for b in branches:
        for t in b.tools:
            if t.cls is ToolClass.NON_IDEMPOTENT_WRITE and t.resource not in gated_resources:
                holders.setdefault(t.resource, []).append(b.branch_id)

    for resource, branch_ids in holders.items():
        if len(branch_ids) > 1:
            raise SpeculationUnsoundError(
                f"resource '{resource}' is a shared non-idempotent write surface "
                f"reachable by branches {branch_ids}; rollback of loser branches "
                f"cannot retract emitted effects. Gate the resource or serialize."
            )


def dispatch_speculative(branches: list[Branch], gated_resources: FrozenSet[str]) -> None:
    assert_speculation_sound(branches, gated_resources)
    # only reached when the partition invariant holds
    for b in branches:
        _run(b)


def _run(branch: Branch) -> None:  # placeholder for actual sub-agent launch
    ...
