# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-tool-call-pre-execution-when-idempotency-keys-collide-across-divergent-reasoning-branches.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-tool-call-pre-execution-when-idempotency-keys-collide-across-divergent-reasoning-branches.warrant.json
# Markdown SHA-256:   37a26b01e3a93b05be4a459c3444c82ea17369d27a9f6b889212aea7de499a2b
# Code AST SHA-256:   cbb04e53b3b9c83760a95b9a9a23be8cc8e7cc9922dceb1a200fd97afafd9aa8
# Verified Classes:   SpeculativeKeyCollision, SpeculativeCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class SpeculativeKeyCollision(RuntimeError):
    """Raised when two divergent speculative branches resolve to the same idempotency key."""
    pass


@dataclass(frozen=True)
class SpeculativeCall:
    task_id: str
    step_index: int
    tool_name: str
    args: dict[str, Any]
    effectful_params: frozenset[str]

    def canonical_args(self) -> str:
        return json.dumps(self.args, sort_keys=True, separators=(",", ":"))

    def derive_key(self) -> str:
        # Argument-derived key: siblings with divergent args get distinct keys.
        payload = f"{self.task_id}:{self.step_index}:{self.tool_name}:{self.canonical_args()}"
        return "idem_" + hashlib.sha256(payload.encode()).hexdigest()[:16]

    def is_divergent_effect(self, other: "SpeculativeCall") -> bool:
        if self.tool_name != other.tool_name or self.step_index != other.step_index:
            return False
        for p in self.effectful_params:
            if self.args.get(p) != other.args.get(p):
                return True
        return False


def mint_speculative_keys(calls: list[SpeculativeCall]) -> dict[int, str]:
    """Mint per-branch keys, refusing to collapse divergent-effect siblings onto one key."""
    keys: dict[int, str] = {}
    for i, call in enumerate(calls):
        key = call.derive_key()
        for j, prev in enumerate(calls[:i]):
            if prev.derive_key() == key and call.is_divergent_effect(prev):
                # Should be unreachable with argument-derived keys, but guard anyway:
                # if a schema change ever reintroduces arg-excluding derivation, fail loud.
                raise SpeculativeKeyCollision(
                    f"branches {j} and {i} share key {key} but diverge on "
                    f"effectful params {sorted(call.effectful_params)}"
                )
        keys[i] = key
    return keys


def reconcile(branch_results: list[tuple[SpeculativeCall, dict[str, Any]]],
              expected: dict[int, dict[str, Any]]) -> int:
    """Return index of winning branch; raise if any result contradicts its branch intent."""
    for idx, (call, result) in enumerate(branch_results):
        for p, want in expected[idx].items():
            if result.get(p) != want:
                # A replayed body from a sibling branch shows up exactly here.
                raise SpeculativeKeyCollision(
                    f"branch {idx} result field {p!r}={result.get(p)!r} != intended {want!r}; "
                    "treating as key collision, not replication lag"
                )
    return 0  # arbitration policy: first branch satisfying intent wins
