# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-become-unsound-for-rollback-in-multi-agent-tool-call-caching.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-become-unsound-for-rollback-in-multi-agent-tool-call-caching.warrant.json
# Markdown SHA-256:   7413c8e4c0b0d3f1f57522d46a1ca16d1d4c8bb27b55924b26791b08daccacc4
# Code AST SHA-256:   44c24c96a7329adac071053f6c21d96095ac360c32ea4caab40b49650ecda67a
# Verified Classes:   UnsoundSpeculativeCacheError, CacheEntry, SpeculativeToolCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any


class UnsoundSpeculativeCacheError(RuntimeError):
    """Raised when a cached tool result is replayed across a divergent world state."""
    pass


@dataclass
class CacheEntry:
    tool: str
    args_hash: str
    state_fingerprint: str
    result: Any
    branch_id: str
    tombstoned: bool = False


class SpeculativeToolCache:
    def __init__(self) -> None:
        self._entries: dict[tuple[str, str, str], CacheEntry] = {}

    def _key(self, tool: str, args: Any, fingerprint: str) -> tuple[str, str, str]:
        args_hash = hashlib.sha256(repr(args).encode()).hexdigest()
        return (tool, args_hash, fingerprint)

    def put(self, tool: str, args: Any, fingerprint: str, result: Any, branch_id: str) -> None:
        self._entries[self._key(tool, args, fingerprint)] = CacheEntry(
            tool=tool, args_hash=self._key(tool, args, fingerprint)[1],
            state_fingerprint=fingerprint, result=result, branch_id=branch_id,
        )

    def get(self, tool: str, args: Any, current_fingerprint: str,
            tool_is_pure: bool | None) -> Any:
        if tool_is_pure is None:
            # Unknown purity: treat as impure, require fingerprint match.
            tool_is_pure = False
        if tool_is_pure:
            # Pure tools: fingerprint-insensitive lookup.
            for (t, ah, _fp), entry in self._entries.items():
                if t == tool and ah == self._key(tool, args, current_fingerprint)[1]:
                    if entry.tombstoned:
                        raise UnsoundSpeculativeCacheError(
                            f"tombstoned entry for pure tool {tool} on branch")
                    return entry.result
            return None
        entry = self._entries.get(self._key(tool, args, current_fingerprint))
        if entry is None:
            return None
        if entry.tombstoned:
            raise UnsoundSpeculativeCacheError(
                f"cache entry for {tool} was produced under a rolled-back branch "
                f"({entry.branch_id}) and cannot be replayed")
        return entry.result

    def rollback_branch(self, branch_id: str) -> int:
        """Tombstone all entries produced under a discarded branch's fingerprint."""
        count = 0
        for entry in self._entries.values():
            if entry.branch_id == branch_id:
                entry.tombstoned = True
                count += 1
        return count


def replay_tool(cache: SpeculativeToolCache, tool: str, args: Any,
                current_fingerprint: str, branch_id: str,
                tool_is_pure: bool | None, executor) -> Any:
    cached = cache.get(tool, args, current_fingerprint, tool_is_pure)
    if cached is not None:
        return cached
    result = executor(tool, args)
    cache.put(tool, args, current_fingerprint, result, branch_id)
    return result


def commit_with_verification(cache: SpeculativeToolCache, branch_id: str,
                              committed_fingerprint: str) -> None:
    # Any surviving entry from another branch whose fingerprint diverges from
    # the committed one is a cross-world artifact and must not be trusted.
    for entry in cache._entries.values():
        if entry.branch_id != branch_id and entry.state_fingerprint != committed_fingerprint:
            if not entry.tombstoned:
                raise UnsoundSpeculativeCacheError(
                    f"entry from branch {entry.branch_id} survived with divergent "
                    f"fingerprint {entry.state_fingerprint} != {committed_fingerprint}")
