# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-reconciliation-from-corrupting-the-canonical-tool-effect-log.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-reconciliation-from-corrupting-the-canonical-tool-effect-log.warrant.json
# Markdown SHA-256:   46ebd9352ef33380ac0f8760fec1b95ef658ac9e02647a7964734eead3b85ba5
# Code AST SHA-256:   8ca2034221b8d61b487ce93b7ffb2f589d08ef7828625da776fbd8d8dc90ec5b
# Verified Classes:   SpeculativeEffectLeak, ToolSpec, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class SpeculativeEffectLeak(RuntimeError):
    """Raised when a speculative branch can reach a non-reversible tool
    without a branch-invariant idempotency key."""


@dataclass(frozen=True)
class ToolSpec:
    name: str
    supports_idempotency_key: bool
    speculation_allowed: bool
    reversible: bool


@dataclass
class Branch:
    branch_id: str            # provisional, e.g. "b-A"
    logical_op_id: str        # branch-invariant, e.g. "op-42"
    tool_calls: list[ToolSpec] = field(default_factory=list)


def assert_reconciliation_safe(
    branches: Iterable[Branch],
    registry: dict[str, ToolSpec],
) -> None:
    """Enforce: every externally observable effect is attributable to exactly
    one branch identity, resolvable at reconciliation time.

    A branch may invoke a tool speculatively only if the tool either supports
    an idempotency key (so duplicates collapse at the backend) or is reversible
    (so local rollback is a true rollback).
    """
    for branch in branches:
        for call in branch.tool_calls:
            spec = registry[call.name]
            if spec.reversible:
                continue
            if not spec.speculation_allowed:
                raise SpeculativeEffectLeak(
                    f"branch {branch.branch_id} invoked non-reversible tool "
                    f"{spec.name!r} but speculation_allowed=False"
                )
            if not spec.supports_idempotency_key:
                raise SpeculativeEffectLeak(
                    f"branch {branch.branch_id} invoked non-reversible tool "
                    f"{spec.name!r} without idempotency key support; "
                    f"loser branch would leak an external effect "
                    f"(logical_op={branch.logical_op_id!r})"
                )
            if not branch.logical_op_id:
                raise SpeculativeEffectLeak(
                    f"branch {branch.branch_id} has no branch-invariant "
                    f"logical_op_id; idempotency key cannot be derived"
                )


def derive_idempotency_key(branch: Branch, tool: ToolSpec) -> str:
    """Key MUST be branch-invariant: derived from logical op, not branch id."""
    if not branch.logical_op_id:
        raise SpeculativeEffectLeak(
            f"cannot derive idempotency key for branch {branch.branch_id}: "
            f"missing logical_op_id"
        )
    return f"{branch.logical_op_id}:{tool.name}"
