When must an instance invalidate a speculative tool-call cache shared across agents, and how does a stale-but-well-formed memoization entry silently corrupt a downstream agent's reasoning?

**Date of Record:** 2026 December 1

**Scope:** Applies to multi-agent systems that share a memoization/speculative-execution layer keyed on tool-call signatures and reuse cached results across agent instances or workflow steps. Does not apply to single-shot, stateless tool invocation where no cache is shared and no downstream agent consumes a prior agent's cached observation.

Core Distinction

The failure mode is not "cache returns a wrong value." It is that a *speculative* cache entry — computed by an upstream agent under a set of assumptions (input parameters, world state, caller identity, and a *reasoning context*) — is a well-formed, schema-valid, plausible-looking artifact that a downstream agent cannot distinguish from a freshly verified observation. The cache key almost always encodes the *tool name and arguments* but not the *epistemic preconditions* under which the result was valid. Therefore invalidation cannot be driven by argument equality alone; it must be driven by the conjunction of (a) argument identity, (b) world-state generation counters touched by the call, and (c) the provenance class of the entry (speculative vs. verified). The core distinction operational teams miss: a **speculative** entry is a *hypothesis about a future observation*, while a **verified** entry is a *record of a past observation*. They may share a key but never share an invalidation contract.

What Was Observed

A three-agent pipeline (planner → executor → auditor) shared a memoization layer for a `read_inventory(sku)` tool. The planner speculatively pre-warmed the cache for 400 SKUs at workflow start (t=0) to hide latency. The executor ran for ~90 seconds; mid-run, an external restock event mutated inventory for 37 SKUs. The executor's `read_inventory` calls for those SKUs hit the speculative entries, which were still schema-valid, returned `in_stock: true`, and the executor placed orders against phantom stock. The auditor — whose entire job was verification — replayed the *same cache key*, received the *same stale entry*, and *confirmed* the executor's decision. Verification collapsed because the auditor and the executor shared the poisoned cache; the auditor's replay was not independent.

The trace that mattered:

  1. t=0: planner calls `read_inventory(sku=A17)` → cache miss → tool returns `in_stock:true` → entry written with `provenance=speculative`, `world_gen=41`.
  2. t=45: external restock event increments `world_gen` to `42`; 37 SKUs now out of stock. **No cache listener is registered for `world_gen` on the inventory domain.**
  3. t=60: executor calls `read_inventory(sku=A17)` → cache hit on key `(read_inventory, A17)` → returns `in_stock:true` with `world_gen=41` embedded in the payload but *not checked against current `world_gen`*.
  4. t=61: executor issues `place_order(A17)`.
  5. t=75: auditor replays `read_inventory(A17)` → **same hit**, same stale entry → auditor signs off.
  6. t=80: order rejected by fulfillment system. Incident.

The non-obvious part: the auditor's replay *increased* confidence rather than catching the error, because replay through a shared cache is not an independent observation — it is a memoized echo of the executor's belief.

Condition of Validity

A speculative cache entry is valid for a consumer agent **iff all four hold simultaneously**:

  1. **Argument identity** — the full canonicalized tool signature matches (including defaults, not just supplied args).
  2. **World-generation monotonicity** — every generation counter in the entry's `read_set` is unchanged since the entry was written. If any counter advanced, the entry is invalid regardless of TTL.
  3. **Provenance sufficiency** — the consumer's `required_provenance` is ≤ the entry's provenance class. An auditor requiring `verified` must never accept a `speculative` entry; a planner may.
  4. **Caller-scope compatibility** — the entry was computed under a caller identity whose authorization scope is a superset of the consumer's requested scope (prevents cross-tenant leakage of a speculative result computed with broader privileges).

If any condition fails, the entry must be treated as a **miss**, not a **hit-with-warning**. A warning is insufficient because downstream agents routinely drop warnings from structured tool payloads.

The invariant to enforce architecturally: **no speculative entry may be served to a consumer whose `required_provenance` exceeds the entry's provenance, and no entry may be served when any generation counter in its `read_set` has advanced.** This is a hard gate at the cache boundary, not a policy in the agent's prompt.

Decision Boundary

The boundary between "serve the memoized entry" and "force a fresh observation" is *not* a TTL and *not* a simple key match. It is a predicate over `(entry.read_set, current_generations, consumer.required_provenance, entry.provenance, caller_scope)`. Concretely:

The subtle boundary case: a *partially* stale entry. If `read_inventory` reads SKU A17 and the warehouse-level `world_gen` but the mutation only touched SKU B09, a correct invalidation must be **per-key**, not per-domain. Over-broad invalidation (flush the whole domain on any mutation) destroys the latency benefit that motivated speculative caching; under-broad invalidation (flush only on exact-key mutation) misses the case where the tool's result depends on a *derived* aggregate (e.g., `total_stock`) that the mutation changed. The resolution is that the tool must declare its `read_set` explicitly, and the cache invalidates on the *declared* read set — never on the tool's arguments.

Operational Effect

When this invariant is enforced, the observable effect is a **latency cliff** at the first generation-counter advance after a speculative pre-warm: the executor's hit rate drops from ~95% to the fraction of SKUs whose read sets are untouched, and the auditor's replay forces a genuine fresh observation — which is exactly what verification requires. Teams that skip the invariant see the opposite: a *verification collapse* where auditor and executor agree because they share a memoized belief, producing high-confidence incorrect decisions that pass all schema checks and are undetectable without an external ground-truth reconciliation.

The guardrail is a cache-boundary predicate that fails closed, plus a provenance ladder (`speculative < verified < independently_verified`) that consumers declare and the cache enforces. Replay-based verification is only meaningful when the replay path is cache-bypassing or cache-isolated per consumer; sharing a memoization layer between executor and auditor silently converts an independent check into a correlated one. Treat the cache as a *shared belief store*, not a *shared result store* — and invalidate on world-generation, not on TTL.

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Dict, Set


class Provenance(IntEnum):
    SPECULATIVE = 0
    VERIFIED = 1
    INDEPENDENTLY_VERIFIED = 2


class StaleSpeculativeEntryError(RuntimeError):
    """Raised when a consumer requires verified provenance but the cache
    can only offer a speculative entry, or when a generation counter in the
    entry's read_set advanced. Fails closed: the workflow must not proceed
    on a verification path that was never independent."""


@dataclass
class CacheEntry:
    key: str
    payload: dict
    provenance: Provenance
    read_set: Set[str]          # generation-counter names this result depends on
    gens_at_write: Dict[str, int]
    caller_scope: frozenset


@dataclass
class Cache:
    entries: Dict[str, CacheEntry] = field(default_factory=dict)
    generations: Dict[str, int] = field(default_factory=dict)

    def bump(self, counter: str) -> None:
        self.generations[counter] = self.generations.get(counter, 0) + 1

    def lookup(
        self,
        key: str,
        required_provenance: Provenance,
        consumer_scope: frozenset,
    ) -> dict:
        entry = self.entries.get(key)
        if entry is None:
            raise StaleSpeculativeEntryError(f"cache miss for {key}")

        # Invariant 1: world-generation monotonicity over declared read_set.
        for counter in entry.read_set:
            if self.generations.get(counter, 0) != entry.gens_at_write.get(counter, 0):
                raise StaleSpeculativeEntryError(
                    f"entry {key} invalidated: counter {counter!r} advanced "
                    f"{entry.gens_at_write.get(counter, 0)} -> "
                    f"{self.generations.get(counter, 0)}"
                )

        # Invariant 2: provenance sufficiency. Fail closed, do not downgrade.
        if entry.provenance < required_provenance:
            raise StaleSpeculativeEntryError(
                f"entry {key} has provenance {entry.provenance.name} but "
                f"consumer requires {required_provenance.name}; "
                f"refusing to serve a speculative echo as verification"
            )

        # Invariant 3: caller-scope compatibility.
        if not consumer_scope.issubset(entry.caller_scope):
            raise StaleSpeculativeEntryError(
                f"entry {key} computed under narrower scope than consumer"
            )

        return entry.payload


def auditor_replay(cache: Cache, key: str, consumer_scope: frozenset) -> dict:
    # The auditor MUST require independently_verified provenance; sharing a
    # speculative entry with the executor collapses verification.
    return cache.lookup(
        key,
        required_provenance=Provenance.INDEPENDENTLY_VERIFIED,
        consumer_scope=consumer_scope,
    )