# What structural signals indicate a speculative memory write has been invalidated by a divergent tool-call result **Date of Record:** 2026 November 19 **Scope:** Applies to agents that speculatively pre-execute tool calls and optimistically commit resulting memory mutations (episodic writes, semantic upserts, cache fills) before the tool's authoritative result is confirmed. Does not apply to strictly serialized read-then-write agents or to pure read-only tool invocations with no memory side effects. ## Core Distinction The failure here is not "the tool returned an error." It is that a *speculative* memory write derived from a *predicted* tool result survives into the committed store after the *actual* tool result diverges. Two distinct artifacts must be kept separate: - **Speculation provenance** — the fact that a memory record was written under a hypothesis `H_pred` about what a tool would return. - **Commit authority** — the fact that a tool result `R_actual` is now authoritative and either confirms or refutes `H_pred`. The invariant is: *no memory record whose provenance points to an unconfirmed hypothesis may be visible to subsequent reasoning steps.* A speculative write is not a slow write; it is a write with a conditional existence predicate. When the predicate flips to false, the record must be tombstoned, not merely overwritten, because overwriting loses the conflict evidence needed to detect downstream reasoning that already consumed the stale record. The subtle part: divergence is often *partial and structural*, not a clean inequality. A tool may return a superset, a reordered set, or an object that agrees on scalar fields but disagrees on a nested collection. Naive equality checks miss these, and the speculative write leaks. ## What Was Observed A retrieval agent speculatively pre-fetches `get_account_flags(account_id)` while the model is still emitting the surrounding reasoning, and optimistically upserts `account.flags = ["fraud_hold"]` into episodic memory tagged `provenance=speculative, hypothesis=tool_call_7`. The actual tool result arrives 340 ms later as `{"flags": ["fraud_hold", "kyc_pending"], "as_of": "2025-06-01"}`. The speculative record had truncated the list because the pre-execution path used a cached partial projection. A naive reconciliation compared only the first element or used set-membership in one direction and declared "confirmed." The record was promoted to `provenance=committed`. Three reasoning steps later, the agent asserted the account had no KYC hold and authorized a transfer. The conflict existed in the store — the authoritative result contained `kyc_pending` — but no mechanism surfaced it, because the speculative record had been *promoted* rather than *replaced*, and the promotion logic treated "predicted flags ⊆ actual flags" as confirmation. The structural signals that should have blocked promotion: 1. **Cardinality mismatch** between the speculative collection and the authoritative collection. 2. **As-of skew**: the speculative record carried no `as_of`, the authoritative one did — a temporal provenance gap. 3. **Directional subset trap**: `H_pred ⊆ R_actual` is *not* confirmation when the memory record is used to reason about *absence* (the agent inferred "no KYC hold" from a list that never claimed completeness). ## Condition of Validity Speculative pre-execution with optimistic memory writes is only sound under a conjunction that is almost never fully satisfied in practice: - The tool must be declared **idempotent and monotone** for the fields being speculated on — i.e., a predicted value that is a subset of the actual value must be a *safe* representation for every downstream consumer. - The speculation must carry a **completeness claim** or explicitly abstain from one. A record that says "flags observed: [fraud_hold]" is valid; a record that says "flags: [fraud_hold]" implies completeness and is invalid under partial projection. - Conflict detection must run on the **authoritative arrival**, not on the next read, and must compare with a **structural diff** (cardinality, key set, nested collection membership, temporal `as_of`), not scalar equality. When any of these fails — and partial projections, as-of skew, and absence-reasoning are the common cases — the speculative write must be treated as *provisionally invisible* until an explicit confirmation predicate passes. ## Decision Boundary The boundary is between **promote-on-subset** and **promote-on-exact-structural-match-with-completeness-attestation**. - Below the boundary (safe): the speculation declares `complete=True` and the authoritative result is structurally identical including `as_of`; promote in place. - At the boundary (ambiguous): the speculation declares `complete=False` or omits completeness; the authoritative result is a superset. Do **not** promote. Tombstone the speculative record, write the authoritative record fresh, and emit a `SpeculationDivergence` event so any reasoning step that already consumed the speculative record can be flagged for re-evaluation. - Above the boundary (unsafe): the authoritative result is a superset *and* the speculative record was already consumed by a downstream step that reasoned about absence. This is the poisoned-state case: the divergence must invalidate not just the record but the *derived conclusions* that referenced it, and the agent must checkpoint-rollback to before the speculative read. The decision must be made on the **first authoritative arrival**, before any subsequent read can observe the speculative record. A conflict detector that runs lazily on read is a detector that runs too late. ## Operational Effect Enforcing the invariant changes three things: 1. **Memory records gain a provenance lattice**: `speculative(hypothesis_id, complete: bool)` → `confirmed` or `tombstoned`. Promotion is a state transition gated on a structural predicate, not a default. 2. **Conflict detection becomes eager and structural**: it fires on authoritative arrival, computes a structural diff, and on divergence emits a divergence event carrying `hypothesis_id` and the set of downstream step-ids that read the speculative record. 3. **Downstream reasoning steps become re-evaluable**: any step that consumed a tombstoned record is marked `stale`, and if it reasoned about absence (a class of inference the agent must tag), the run rolls back to the checkpoint before the speculative read rather than attempting in-place repair. The cost is that speculative writes are no longer free — they carry a completeness obligation and a potential rollback. The benefit is that the agent cannot silently authorize an action on the strength of a truncated projection that the authoritative tool result already contradicted. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Any class SpeculationDivergenceError(RuntimeError): """Raised when a speculative memory write cannot be safely promoted because the authoritative tool result structurally diverges from the hypothesized result, or because the speculation lacked a completeness attestation required for the downstream inference that consumed it.""" class Provenance(str, Enum): SPECULATIVE = "speculative" CONFIRMED = "confirmed" TOMBSTONED = "tombstoned" @dataclass class MemoryRecord: key: str value: dict[str, Any] hypothesis_id: str complete: bool # did the speculation claim completeness? provenance: Provenance = Provenance.SPECULATIVE consumers: list[str] = field(default_factory=list) # step-ids that read it def _structural_diff(pred: dict[str, Any], actual: dict[str, Any]) -> dict[str, Any]: """Return a diff describing how pred and actual diverge structurally. Detects cardinality mismatch on collections, missing keys, and as_of skew — the signals a scalar-equality check would miss. """ diff: dict[str, Any] = {"missing_in_pred": [], "cardinality": {}, "as_of_skew": False} for k, av in actual.items(): if k not in pred: diff["missing_in_pred"].append(k) continue pv = pred[k] if isinstance(pv, (list, set, tuple)) and isinstance(av, (list, set, tuple)): if len(pv) != len(av): diff["cardinality"][k] = (len(pv), len(av)) if ("as_of" in actual) != ("as_of" in pred): diff["as_of_skew"] = True return diff def reconcile_speculative_write( record: MemoryRecord, actual_result: dict[str, Any], reasoned_about_absence: bool, ) -> MemoryRecord: """Gate promotion of a speculative record on a structural confirmation predicate. Promotion is permitted only when the speculation attested completeness and the authoritative result is structurally identical. A superset result is NOT confirmation when the record was consumed by an absence-reasoning step. """ diff = _structural_diff(record.value, actual_result) diverges = bool(diff["missing_in_pred"] or diff["cardinality"] or diff["as_of_skew"]) if not diverges: record.provenance = Provenance.CONFIRMED return record # Divergence detected. If a downstream step already reasoned about absence # using this record, in-place repair is unsound — force rollback. if reasoned_about_absence and record.consumers: raise SpeculationDivergenceError( f"speculative record {record.key!r} (hypothesis {record.hypothesis_id!r}) " f"diverged from authoritative result; consumers {record.consumers!r} " f"reasoned about absence and must be rolled back. diff={diff!r}" ) # Otherwise tombstone and let the caller write the authoritative record fresh. record.provenance = Provenance.TOMBSTONED return record def commit_or_rollback(record: MemoryRecord, actual_result: dict[str, Any]) -> MemoryRecord: """Convenience wrapper for the common path where the record was consumed by a step whose inference mode is tracked on the record itself.""" reasoned_about_absence = any(c.startswith("absence:") for c in record.consumers) return reconcile_speculative_write(record, actual_result, reasoned_about_absence) ```