# When must an instance refuse a memory write because its namespace lease expired mid-transaction: TTL expiry as a torn-write hazard in scoped memory tool APIs **Date of Record:** 2026 November 29 **Scope:** Applies to agents that write to scoped, TTL-bearing memory namespaces through a tool API where the lease (TTL) is checked at write-commit time rather than at write-begin time, and where a single logical memory operation spans more than one tool call or an internal read-modify-write. Does not apply to append-only log memories with no expiry, nor to single-call atomic `put` primitives that validate and commit under one lock. ## Core Distinction The distinction that matters is between **TTL as a garbage-collection hint** and **TTL as a write-authorization lease**. Most memory tool APIs conflate them: the namespace carries an `expires_at`, the agent reads it at the start of a reasoning step, decides the namespace is live, performs several tool calls (a `get`, a merge in context, a `set`), and only on the final `set` does the server re-evaluate `expires_at`. If the lease lapsed between the `get` and the `set`, the server has two defensible behaviors and picks the wrong one by default: it either (a) silently re-creates the namespace with a fresh TTL and commits the write, resurrecting a namespace that another agent or a supervisor believed was dead, or (b) rejects the write but leaves the agent's in-context state believing the write succeeded, because the rejection arrives as a tool-result string the model may not treat as terminal. The non-obvious part: this is not a race between two writers. It is a race between **one writer and the clock**, mediated by the agent's own multi-call latency. The failure is a torn write across the TTL boundary — the read half of a read-modify-write executed against a live namespace, the write half executed against a namespace whose lease has expired, with the agent's context window holding an intermediate value that was never durably merged. ## What Was Observed A supervisor agent maintained a `task_state` namespace with a 900-second TTL, refreshed on every successful write. A worker agent, handed a subtask, performed the canonical read-modify-write: 1. `memory.get(namespace="task_state", key="plan")` → returns `{"steps": [A, B, C], "cursor": 0}`. 2. Worker reasons over the plan in-context, executes step A via a slow tool (a code sandbox run taking ~340s), appends `"A_done"` to its local copy. 3. `memory.set(namespace="task_state", key="plan", value={"steps":[A,B,C], "cursor":1, "done":["A"]})`. Between step 1 and step 3, 380 seconds elapsed. The namespace's `expires_at` had been set 900s before step 1 by the supervisor's last refresh, so at step 1 there were 520s of lease remaining — comfortably enough for the worker's reasoning. But the supervisor itself had a heartbeat that refreshed the lease on a 300s cadence, and the heartbeat was blocked behind the same slow sandbox call on a different worker. The lease expired at T+900. The worker's `set` arrived at T+900+ε. The server's default policy was **resurrect-on-write**: because the namespace record had been tombstoned but not yet physically purged (purge ran on a 3600s sweep), the `set` matched the tombstone, cleared the tombstone, assigned a fresh 900s TTL, and committed. The write succeeded. The worker received `{"ok": true}`. Three problems surfaced downstream: - The supervisor's heartbeat, recovering at T+905, read `task_state` and saw the worker's `cursor:1` write — but also saw that the namespace had been "renewed," so it did not re-derive the plan. It had no record that the lease had lapsed, and therefore no record that any concurrent writer could have touched the namespace during the gap. - A second worker, whose `get` had landed at T+880 (after the supervisor's lease expired, before the first worker's `set`), had received an **empty namespace** with `{"ok": true, "missing": true}` — the server's read path treated tombstoned-but-unpurged as absent. That worker initialized a fresh plan from scratch and wrote `cursor:0` at T+890. The resurrect-on-write from the first worker then overwrote it, or was overwritten by it, depending on commit ordering. The two workers diverged with no error raised to either. - The supervisor's final audit compared `done` lists and found a step recorded as complete that had, in fact, been re-executed by the second worker — a duplicate side effect invisible in the memory record. The trace that made this legible: the server logged `tombstone_cleared=true` on the first worker's `set`. That flag existed in the log but was not surfaced in the tool result. The agent had no way, from its own tool API, to learn that its write had crossed a lease boundary. ## Condition of Validity The resurrection hazard is bounded by three conditions, all of which must hold for the torn write to be silently accepted: 1. **Tombstone retention exceeds lease-check granularity.** The namespace is logically expired but physically retained (for purge batching, audit, or soft-delete). During this window, `get` and `set` disagree about liveness: `get` treats tombstoned as absent, `set` treats tombstoned as revivable. 2. **The agent's operation spans multiple tool calls with unbounded inter-call latency.** A single atomic `put_if_lease_valid` primitive would collapse the window. The hazard requires that the read and the write are separate calls, with model reasoning or tool execution (sandbox runs, retrieval, sub-agent dispatch) in between. 3. **Lease expiry is not propagated as a typed, terminal signal.** If the `set` returns `{"ok": true}` — even with a `renewed: true` field the model is not trained to treat as fatal — the agent's context state diverges from durable state. The invariant that must hold is: *a write whose lease was invalid at commit time must either fail closed or return a signal the agent is obligated to handle as a control-flow branch, not a data field.* When any condition fails, the hazard does not occur: atomic primitives close (2); immediate purge closes (1); a typed `LeaseExpiredError` closes (3). The interesting engineering fact is that most production memory APIs close none of the three by default, because each is individually a reasonable optimization (batching purges, letting agents do multi-step reasoning, returning structured results instead of exceptions). ## Decision Boundary The boundary the agent must enforce is: **before committing any write to a leased namespace, re-validate the lease and compare the namespace generation (a monotonic counter bumped on every tombstone-clear and every lease renewal) against the generation observed at read time.** If the generation advanced, or the lease is invalid, the agent must not commit; it must re-read, re-merge, and re-decide. This is a compare-and-swap on `(generation, lease_valid)`, not on the value. Value-level CAS does not help here because the second worker's write was a *legitimate* write to a namespace it believed was fresh — the conflict is at the namespace-lifetime level, not the key level. The decision boundary in operational terms: - **Generation unchanged and lease valid** → commit. Normal path. - **Generation advanced** → another writer or a tombstone-clear intervened. Do not commit the in-context merge; discard it, re-read, re-derive. The in-context value is stale by construction. - **Lease invalid** → the namespace is dead. Do not resurrect implicitly. Either fail the subtask upward (the supervisor owns namespace lifetime) or, if the agent holds an explicit `renew` capability, renew *first*, observe the new generation, then re-read and merge. Never `set` into a namespace whose lease the agent did not itself observe as valid at a generation it has seen. The guardrail the server must provide, and which the agent must consume: every `get` returns `(value, generation, lease_expires_at)`; every `set` takes `expected_generation` and fails closed with a typed error on mismatch or expired lease; tombstone-clearing requires an explicit `renew` call, never a side effect of `set`. ## Operational Effect With the generation-check invariant enforced, the observed failure class collapses: - The first worker's `set` at T+900+ε returns `LeaseExpiredError` (typed), not `{"ok": true}`. The worker's control flow branches to "re-request lease from supervisor," and the supervisor — which owns the heartbeat — either renews with a new generation or declares the task abandoned. No silent resurrection. - The second worker's `get` at T+880 returns `missing: true` with `generation: N`; its subsequent `set` with `expected_generation: N` fails when the first worker's renewal bumped to `N+1`. The second worker re-reads and sees the first worker's committed plan. Divergence is caught at commit, not at audit. - The duplicate side effect does not occur, because the second worker never commits a plan that re-executes step A. The cost is one extra field on every read and one extra check on every write, plus a hard rule that agents must treat `LeaseExpiredError` and `GenerationMismatchError` as terminal control-flow signals requiring re-read, not as retryable transient errors. The failure mode without the invariant is not data loss in the usual sense — every write was durably committed — it is **state divergence between agents that each hold a locally consistent but globally conflicting view of a namespace's lifetime**. That divergence is invisible to value-level consistency checks and only surfaces in duplicate side effects or contradictory audit records. The deeper operational lesson: TTL is a *lifetime* property, and lifetime changes are writes. Any mutation that changes a namespace's lifetime — expiry, renewal, tombstone-clear — must bump a generation counter that read-modify-write agents are required to observe, or the memory API is offering consistency guarantees it cannot keep across the multi-call latency that agentic reasoning inherently introduces. ```python from dataclasses import dataclass from typing import Any, Optional class LeaseExpiredError(RuntimeError): """Namespace lease lapsed before commit; write must not resurrect.""" class GenerationMismatchError(RuntimeError): """Namespace generation advanced between read and write; in-context merge is stale.""" @dataclass(frozen=True) class MemoryView: value: Any generation: int lease_expires_at: float missing: bool class ScopedMemoryClient: """Client enforcing the generation-check invariant on leased namespaces.""" def __init__(self, transport, clock): self._transport = transport self._clock = clock def get(self, namespace: str, key: str) -> MemoryView: raw = self._transport.get(namespace, key) return MemoryView( value=raw.get("value"), generation=raw["generation"], lease_expires_at=raw["lease_expires_at"], missing=raw.get("missing", False), ) def set_if_lease_valid( self, namespace: str, key: str, value: Any, expected_generation: int, ) -> int: now = self._clock() current = self._transport.get_meta(namespace) if current["lease_expires_at"] <= now: # Fail closed. Do NOT let the server resurrect-on-write. raise LeaseExpiredError( f"namespace {namespace!r} lease expired at " f"{current['lease_expires_at']:.3f} (now {now:.3f}); " f"refusing write to key {key!r}" ) if current["generation"] != expected_generation: # Another writer or tombstone-clear intervened; merge is stale. raise GenerationMismatchError( f"namespace {namespace!r} generation advanced " f"{expected_generation} -> {current['generation']}; " f"discard in-context merge for key {key!r} and re-read" ) result = self._transport.set_cas( namespace, key, value, expected_generation=expected_generation ) if not result["ok"]: # Lost a commit race despite the pre-check; treat as mismatch. raise GenerationMismatchError( f"CAS failed on {namespace!r}/{key!r}: " f"server generation is {result['generation']}" ) return result["generation"] def commit_step_result( client: ScopedMemoryClient, namespace: str, view: MemoryView, step_id: str, ) -> int: """Append a completed step to a plan under the generation invariant.""" if view.missing: # Namespace was absent at read time; agent has no authority to # initialize it implicitly — that is the supervisor's job. raise LeaseExpiredError( f"namespace {namespace!r} was absent at read; " f"cannot commit step {step_id!r} without explicit renewal" ) plan = dict(view.value or {}) done = list(plan.get("done", [])) if step_id in done: # Idempotent replay: do not re-execute, do not rewrite. return view.generation done.append(step_id) plan["done"] = done plan["cursor"] = len(done) return client.set_if_lease_valid( namespace=namespace, key="plan", value=plan, expected_generation=view.generation, ) ```