Practical technical guides / Architecture / evergreen

Revalidate Every Read Dependency Before Applying an Agent Plan

Keep planning outside transactions, then compare all recorded dependency versions atomically with the proposed state change.

By Sandeep Belgavi · Published 2026-11-25 · Prepared 2026-11-17

Planning evidence has a revision: Capture trusted reads, then Plan outside transaction, then Revalidate and apply
Original explanatory diagram by Sandeep Belgavi. Conceptual sequence; no measured performance is represented.

Keep planning outside transactions, then compare all recorded dependency versions atomically with the proposed state change.

Planning creates a long gap between reading and writing

An ordinary service often reads a few records, checks a rule and writes a result within a short transaction. An agent may read the same records, spend seconds constructing a plan, ask for clarification and return much later. The values that justified its decision can change during that interval. Checking only the version of the row being updated protects against one lost update; it does not prove that the other facts used by the planner still hold.

Consider a synthetic computation service. An agent reads a task record at version 7 and a policy record at version 3. The policy permits a memory setting of 512 units, so the agent proposes that setting for the task. Before the plan is applied, the policy changes to version 4 with a lower ceiling. The task itself remains at version 7. A conditional write that checks only the task version would accept a decision whose supporting policy has expired.

The architecture needs an explicit read-dependency contract. Planning stays outside the database transaction. The application captures the identities and versions of the facts supplied to the planner, then checks them again at the effect boundary. The check and the state change must be atomic with respect to the relevant writers. A successful revalidation confirms a particular snapshot dependency, not the general correctness of everything the model said.

Separate evidence capture from the agent's output

Do not ask the model to reconstruct which versions it read. The tool adapter already knows which records it returned. It should attach trusted metadata to an application-owned evidence record while returning the useful data to the planner. The model can propose a new setting, but it cannot remove an inconvenient policy dependency from the evidence set or lower the expected version to make a stale command pass.

A minimal evidence record contains a resource identifier, an incarnation identifier if resources can be recreated, and a monotonic version. The task and policy use separate version counters because an unrelated task update should not invalidate every proposal. Every write that changes decision-relevant content must advance the corresponding version. A writer that bypasses this rule creates a blind spot that no amount of model reasoning can repair.

Versions are preferable to comparing current values alone. A value can change from 512 to 256 and back to 512 while a plan is pending. Whether that intervening history matters is a domain decision. A monotonic revision makes the change visible, allowing the application to require replanning. A reused identifier with a reset version needs an incarnation token as well; otherwise a replacement resource can impersonate the evidence that was originally read.

Build a small atomic boundary

This original teaching model represents state as value/version pairs. The lock protects both validation and mutation. The example does not hold the lock while planning and does not perform remote effects inside it. Real adapters need the equivalent transactional guarantee from their storage system, including a plan for dependencies that live in different stores.

# Author: Sandeep Belgavi. In-memory read-dependency boundary.
from threading import Lock

class Store:
    def __init__(self):
        self.lock = Lock()
        self.rows = {"task": (128, 7), "policy": (512, 3)}

    def snapshot(self):
        with self.lock:
            return dict(self.rows)

    def apply(self, observed, proposed):
        if set(observed) != {"task", "policy"}:
            raise ValueError("incomplete evidence")
        if type(proposed) is not int or proposed < 0:
            raise ValueError("invalid proposed setting")
        with self.lock:
            if any(self.rows[k][1] != observed[k][1] for k in observed):
                return "replan"
            if proposed > self.rows["policy"][0]:
                return "policy-rejected"
            _, version = self.rows["task"]
            self.rows["task"] = (proposed, version + 1)
            return "applied"

store = Store()
evidence = store.snapshot()
with store.lock:
    store.rows["policy"] = (256, 4)
assert store.apply(evidence, 512) == "replan"
assert store.rows["task"] == (128, 7)

The evidence dictionary in this snippet is trusted application state. A network endpoint must not accept it as an unsigned assertion from an arbitrary client. Bind it to a server-side proposal identifier or another authenticated representation of the recorded reads. The operation-specific rule also remains deterministic: even fresh evidence cannot authorize a value above the current policy ceiling.

Map the boundary onto database semantics

For a relational implementation, acquire or validate the relevant records inside a short transaction, evaluate the rule and update the task before committing. Choose one consistent ordering for locks when several dependencies are involved. An application that checks versions in separate autocommit queries and then writes has recreated the original race between the last check and the effect.

PostgreSQL documents that Read Committed uses a new statement snapshot and can expose different committed state across statements. Serializable provides stronger transaction-level guarantees but can require retries. Neither isolation level magically includes the agent's earlier, out-of-transaction reasoning. The final transaction must still compare the evidence supplied to that reasoning with the state it is about to act upon.

Predicate reads require additional thought. A planner may depend on the absence of any conflicting task, rather than on a fixed list of existing rows. Recording only the rows returned by an empty query records nothing to validate. Represent the predicate with a versioned aggregate, a suitable constraint, range protection or a serializable transaction that checks the invariant again. Do not claim that a dictionary of row versions solves arbitrary phantom-read problems.

Make stale evidence a visible outcome

Return a distinct replan outcome when evidence changed. Do not reinterpret it as a transport failure and replay the same proposal indefinitely. A retry can repeat a failed transmission; a replan needs fresh facts and may produce a different command. The audit record should retain the old evidence identity and the reason it was refused, without storing sensitive record contents unnecessarily.

An application can sometimes prove that a change is irrelevant. For example, a policy record's display label may change while its enforced ceiling remains identical. If that distinction matters, split cosmetic metadata from decision-relevant policy or maintain a separate semantic revision. Avoid embedding ad hoc field comparisons in every agent caller. The storage contract should define which mutations invalidate evidence consistently across deterministic and agent-driven clients.

Repeated conflicts need an operational policy. Bound the number of replans, add a queue or serialize updates to a hot aggregate, and surface a stable conflict explanation when progress is impossible. An agent loop that repeatedly reads and rewrites contested state can amplify load. Measure refusals by dependency type so a frequently changing policy can be distinguished from a task that several workers are modifying.

Migrate from target-only optimistic locking

Begin with one operation that already uses a target version. Inventory the extra facts its implementation uses to make a decision. Add evidence capture for those facts and run the broader validation in observation mode, recording when it would have rejected a target-only success. Review concrete cases before making the new gate mandatory. This reveals missing version increments and dependency records that are too broad.

Then make the gate authoritative at the existing service boundary. Keep it shared by agent callers and conventional clients so one path cannot bypass the invariant. The agent should propose intent through the service contract, not open a second direct-write path. Approval, when required, should refer to the same proposal and evidence revision; a materially revised plan needs a new approval decision rather than a recycled flag.

Verify the dependency you almost forgot

The central negative test changes only the policy version while leaving the task untouched. The expected outcome is refusal with no task mutation. Add cases for an unchanged snapshot, a changed target, an omitted dependency, an invalid proposal and a fresh proposal that violates the current rule. Check the final state independently of the returned status so an implementation cannot report refusal after already writing.

Also test the ABA case by changing a dependency away and back while increasing its version. A value-only comparator would accept; the revision comparator should refuse. These are offline behavioral tests of the boundary, not a distributed database benchmark. A deployment still needs integration tests with the actual transaction isolation, writer paths and resource-recreation rules.

A deterministic service is enough when the decision can be expressed directly as a stable rule. Agents can help interpret ambiguous intent or propose alternative configurations, but they do not replace atomic validation. The useful adaptation is modest: expose the facts that informed a proposal, retain them outside the model, and make their continued validity part of the service's commit decision.

Run the example yourself

The synthetic fixtures, expected output and tests behind this guide are in the companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.

Primary references and authorship

Sources read 17 November 2026. Original explanation and synthetic examples by Sandeep Belgavi. Views are my own and do not represent any employer, past or present.