# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-commitment-cannot-be-safely-rolled-back-in-multi-agent-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-commitment-cannot-be-safely-rolled-back-in-multi-agent-pipelines.warrant.json
# Markdown SHA-256:   7945acdafb02c118450a9f76ee4f2b101354389c2d48a05871ceae09773ad241
# Code AST SHA-256:   6dd027d998c6949b9d3e02fddf9daf546a86175a2719946d78fca0aff8bff100
# Verified Classes:   EffectClass, ToolSpec, BranchManifest, UnsafeSpeculativeRollback
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class EffectClass(Enum):
    READ = "read"
    MUTATING = "mutating"


@dataclass(frozen=True)
class ToolSpec:
    name: str
    effect_class: EffectClass
    routed_through_commit_gate: bool


@dataclass(frozen=True)
class BranchManifest:
    branch_id: str
    speculative: bool
    tool_schema: tuple[ToolSpec, ...]
    compensations: dict[str, str]  # tool_name -> compensating tool_name


class UnsafeSpeculativeRollback(RuntimeError):
    """Raised when a speculative branch can emit an unbuffered, non-compensable effect."""


def assert_rollback_safe(manifest: BranchManifest) -> None:
    if not manifest.speculative:
        return
    for tool in manifest.tool_schema:
        if tool.effect_class is EffectClass.READ:
            continue
        if tool.routed_through_commit_gate:
            continue
        # Ungated mutating tool reachable from a speculative branch.
        if tool.name not in manifest.compensations:
            raise UnsafeSpeculativeRollback(
                f"branch {manifest.branch_id!r} is speculative but tool "
                f"{tool.name!r} is mutating, ungated, and has no compensation; "
                f"discard would leave an unbuffered effect. Restrict the branch "
                f"schema to gated tools or serialize the fan-out."
            )
        # Compensation exists; it must itself be gate-checked or read-only.
        comp = manifest.compensations[tool.name]
        comp_spec = next((t for t in manifest.tool_schema if t.name == comp), None)
        if comp_spec is None or (
            comp_spec.effect_class is EffectClass.MUTATING
            and not comp_spec.routed_through_commit_gate
        ):
            raise UnsafeSpeculativeRollback(
                f"branch {manifest.branch_id!r}: compensation {comp!r} for "
                f"{tool.name!r} is itself an ungated mutating call; "
                f"compensation closure is not satisfied."
            )


def plan_fanout(manifests: list[BranchManifest]) -> str:
    for m in manifests:
        assert_rollback_safe(m)
    ungated = [
        t.name
        for m in manifests
        for t in m.tool_schema
        if t.effect_class is EffectClass.MUTATING and not t.routed_through_commit_gate
    ]
    if ungated:
        return "serialize"
    return "parallel"
