# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-discard-prefetched-tool-results-after-speculative-plan-decoding-diverges-from-the-committed-plan.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-discard-prefetched-tool-results-after-speculative-plan-decoding-diverges-from-the-committed-plan.warrant.json
# Markdown SHA-256:   7b168ea130b100c2459c54710317dcb2eca5bbfdee432e2643d1666a04591d9f
# Code AST SHA-256:   6ef5153c5168a323871f34df89b65cfc492bc9ddc8285ed2cdafad5ea2ff7cf2
# Verified Classes:   PrefetchCommitDivergence, ToolCall, PrefetchedResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Any


class PrefetchCommitDivergence(RuntimeError):
    """Raised when a prefetched tool result is bound to a committed step whose
    full canonical argument tuple does not match the tuple used at prefetch time."""


@dataclass(frozen=True)
class ToolCall:
    tool: str
    args: tuple[tuple[str, Any], ...]  # canonicalized: sorted keys, normalized values

    def canonical_bytes(self) -> bytes:
        h = hashlib.sha256()
        h.update(self.tool.encode())
        for k, v in self.args:
            h.update(k.encode())
            h.update(repr(v).encode())
        return h.digest()


@dataclass(frozen=True)
class PrefetchedResult:
    call: ToolCall
    plan_version: int
    result: dict
    produced_fields: frozenset[str]  # fields the call *produced* (hashes, ids), not observed


def bind_prefetch_to_commit(
    prefetched: PrefetchedResult,
    committed_call: ToolCall,
    committed_version: int,
    *,
    tool_is_idempotent: bool,
) -> dict:
    # 1. Version gate: never bind across plan decode attempts.
    if prefetched.plan_version != committed_version:
        raise PrefetchCommitDivergence(
            f"prefetch from draft v{prefetched.plan_version} cannot bind to committed v{committed_version}"
        )

    # 2. Full-tuple identity gate. Prefix/subset matching is forbidden because
    #    speculative decoding accepts a prefix and resamples the remainder.
    if prefetched.call.canonical_bytes() != committed_call.canonical_bytes():
        raise PrefetchCommitDivergence(
            f"argument tuple diverged for tool {committed_call.tool!r}: "
            f"prefetch={prefetched.call.args!r} commit={committed_call.args!r}"
        )

    # 3. Produced-field gate: if the result carries fields the committed plan
    #    will trust, and the tool is not idempotent, re-execution is required.
    if prefetched.produced_fields and not tool_is_idempotent:
        raise PrefetchCommitDivergence(
            f"prefetched result for {committed_call.tool!r} carries produced fields "
            f"{sorted(prefetched.produced_fields)}; must re-execute at commit"
        )

    return prefetched.result
