# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculatively-decoded-tool-plan-before-merge-rather-than-after-the-pre-merge-divergence-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculatively-decoded-tool-plan-before-merge-rather-than-after-the-pre-merge-divergence-invariant.warrant.json
# Markdown SHA-256:   237c90bd9d798597998c17feee95c183661b38b22f79664f056b2d6b5606ff56
# Code AST SHA-256:   0376d59c7a4546a2f463202fbe3e394e370d3c7b74bffbee990b8b1e77ae7b9f
# Verified Classes:   PreMergeDivergenceError, ToolCall, Branch, MergeResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class PreMergeDivergenceError(RuntimeError):
    """Raised when a merged speculative plan violates a joint precondition
    that no constituent branch violated individually."""


@dataclass
class ToolCall:
    name: str
    precondition: Callable[[dict], bool]
    effect: Callable[[dict], dict]  # returns state delta
    irreversible: bool = False


@dataclass
class Branch:
    calls: list[ToolCall]
    verified: bool = False


@dataclass
class MergeResult:
    calls: list[ToolCall] = field(default_factory=list)
    poisoned: bool = False


def merge_branches(branches: list[Branch], shared_input: dict) -> MergeResult:
    for b in branches:
        if not b.verified:
            raise PreMergeDivergenceError(
                f"branch with calls {[c.name for c in b.calls]} was not verified; "
                "merge requires per-branch verification"
            )

    # field-level union over a typed schema (simplified: dedupe by name+args)
    merged: list[ToolCall] = []
    seen: set[str] = set()
    for b in branches:
        for call in b.calls:
            key = f"{call.name}:{id(call)}"
            if key not in seen:
                seen.add(key)
                merged.append(call)

    # CRITICAL: re-verify the JOINT precondition chain against shared inputs.
    state = dict(shared_input)
    for call in merged:
        if not call.precondition(state):
            raise PreMergeDivergenceError(
                f"joint precondition failed at {call.name!r}: merged plan is "
                f"locally valid per-branch but globally illegal against "
                f"shared input {shared_input!r}"
            )
        state.update(call.effect(state))

    # commit horizon check: if any irreversible call precedes a later
    # divergence, the merge must be aborted, not reordered.
    for i, call in enumerate(merged):
        if call.irreversible and i < len(merged) - 1:
            # irreversible call is not last; ensure no later precondition
            # depends on state it may corrupt
            later = merged[i + 1:]
            probe = dict(state)
            for nxt in later:
                if not nxt.precondition(probe):
                    raise PreMergeDivergenceError(
                        f"commit horizon crossed: irreversible {call.name!r} "
                        f"precedes {nxt.name!r} whose precondition fails "
                        "post-effect; abort before dispatch"
                    )
                probe.update(nxt.effect(probe))

    return MergeResult(calls=merged, poisoned=False)


def dispatch(merged: MergeResult) -> None:
    if merged.poisoned:
        raise PreMergeDivergenceError("refusing to dispatch poisoned merge")
    for call in merged.calls:
        # actual tool invocation would occur here
        pass
