# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-subtree-scheduler-commit-a-cached-tool-result-that-was-produced-under-a-branch-that-was-later-pruned-and-how-do.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-subtree-scheduler-commit-a-cached-tool-result-that-was-produced-under-a-branch-that-was-later-pruned-and-how-do.warrant.json
# Markdown SHA-256:   6bc6f70673749af71f5582803a2d1a22d75f51c1394baa9a7b3a3aed02ea1ba5
# Code AST SHA-256:   90fad2578d99194727ca35a05f50d54cc449fedc36131f9bda5511660e115eb1
# Verified Classes:   SpecCacheViolation, CallKey, CacheEntry, SpecToolCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class SpecCacheViolation(RuntimeError):
    """Raised when a speculative cache serve would cross a branch precondition boundary."""


@dataclass(frozen=True)
class CallKey:
    tool: str
    args: dict[str, Any]
    precondition_hash: str  # hash of the branch's asserted preconditions for this call

    def digest(self) -> str:
        payload = json.dumps(
            {"tool": self.tool, "args": self.args, "pre": self.precondition_hash},
            sort_keys=True,
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class CacheEntry:
    value: Any
    purity: bool
    mutation_epoch: int
    origin_branch: str
    orphaned: bool = False


class SpecToolCache:
    def __init__(self) -> None:
        self._store: dict[str, CacheEntry] = {}
        self._epoch: int = 0

    def bump_epoch(self) -> None:
        self._epoch += 1

    def orphan_branch(self, branch_id: str) -> None:
        # Pruning orphans, never deletes: deletion would allow silent re-collision.
        for entry in self._store.values():
            if entry.origin_branch == branch_id:
                entry.orphaned = True
        self.bump_epoch()

    def lookup(
        self,
        key: CallKey,
        serving_branch: str,
        serving_preconditions: frozenset[str],
    ) -> CacheEntry | None:
        entry = self._store.get(key.digest())
        if entry is None:
            return None

        if entry.orphaned and entry.origin_branch != serving_branch:
            raise SpecCacheViolation(
                f"orphaned entry from pruned branch {entry.origin_branch} "
                f"cannot serve {serving_branch}"
            )

        if not entry.purity:
            # Mutating calls: only serve within the originating branch, same epoch.
            if entry.origin_branch != serving_branch:
                raise SpecCacheViolation(
                    f"mutating call {key.tool} cannot cross branch boundary "
                    f"{entry.origin_branch} -> {serving_branch}"
                )
            if entry.mutation_epoch != self._epoch:
                return None  # stale, force re-execution

        # Purity holds; still require precondition superset.
        origin_pre = frozenset(json.loads(key.precondition_hash))
        if not serving_preconditions.issuperset(origin_pre):
            raise SpecCacheViolation(
                f"precondition set for {serving_branch} is not a superset of "
                f"{entry.origin_branch}'s; refusing to serve"
            )

        return entry

    def store(
        self,
        key: CallKey,
        value: Any,
        purity: bool,
        origin_branch: str,
    ) -> None:
        self._store[key.digest()] = CacheEntry(
            value=value,
            purity=purity,
            mutation_epoch=self._epoch,
            origin_branch=origin_branch,
        )


def dispatch(
    cache: SpecToolCache,
    tool: str,
    args: dict[str, Any],
    preconditions: frozenset[str],
    branch_id: str,
    purity: bool,
    execute,
):
    key = CallKey(
        tool=tool,
        args=args,
        precondition_hash=json.dumps(sorted(preconditions)),
    )
    try:
        hit = cache.lookup(key, branch_id, preconditions)
    except SpecCacheViolation as exc:
        # Violation is a hard stop: the scheduler must re-execute, not serve.
        raise SpecCacheViolation(str(exc)) from exc

    if hit is not None:
        return hit.value

    value = execute()
    if not purity:
        cache.bump_epoch()  # mutating side effect advances the timeline
    cache.store(key, value, purity=purity, origin_branch=branch_id)
    return value
