Skip to main content
Back to all articles
AI Engineering 6 min readUpdated August 31, 2026

Stale Context Is a State-Versioning Bug

An agent can fit comfortably inside its context window and still act on obsolete facts. This design keys observations by resource identity and version so current state replaces stale context instead of accumulating beside it.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#context-engineering#stale-context#ai-agents#optimistic-concurrency#distributed-systems#typescript#python
On this page

An agent can have plenty of context space and still make a bad decision because the context is old.

That is a different failure from context overflow.

Imagine a deployment assistant reads a Kubernetes deployment and sees six replicas. A few steps later an autoscaling change is applied and the live deployment now reports ten. If both observations remain in the prompt, the model has to infer which one is current. Sometimes it will. Sometimes an older, more detailed observation will win its attention.

This is not primarily a summarization problem. It is a state-versioning problem.

I prefer to treat observations about mutable resources as cache entries: each fact has a resource identity, a version or freshness marker, and a replacement rule. The prompt should render the current view rather than replay every historical read as if all of them are equally true.

The example here is an operations assistant that reads Kubernetes-like resources, deployment status, and incident state. The same pattern works for code files, CRM records, tickets, invoices, database rows, and any tool result whose value can change during a run.

A tool result needs resource identity

Raw tool messages are usually modeled like this:

Text
Tool: get_deploymentResult: { ...large JSON... }

That tells the conversation what happened, but not how the result relates to future observations.

I would rather normalize it into an observation:

TypeScript
type ResourceObservation<T> = {  resourceKey: string;  version: string;  observedAt: string;  value: T;  sourceToolCallId: string;};​type DeploymentState = {  namespace: string;  name: string;  replicas: number;  readyReplicas: number;  image: string;};

A resource key might be deployment:payments/prod-api. The version might be a Kubernetes resource version, an ETag, a database row version, a Git commit SHA, or a monotonically increasing revision supplied by your own service.

If the underlying system has no version, observedAt is still better than nothing, but timestamps alone do not guarantee ordering across every distributed source.

Python:

Python
from dataclasses import dataclassfrom datetime import datetimefrom typing import Generic, TypeVar​T = TypeVar("T")​@dataclass(frozen=True)class ResourceObservation(Generic[T]):    resource_key: str    version: str    observed_at: datetime    value: T    source_tool_call_id: str

The key makes replacement possible. Without it, every tool result is just another paragraph in history.

Keep a current-state map beside the event log

I still want an append-only event log for audit and replay. I just do not want to send the full log back to the model every turn.

TypeScript
class ObservationStore {  private readonly current = new Map<string, ResourceObservation<unknown>>();​  put<T>(observation: ResourceObservation<T>): void {    const existing = this.current.get(observation.resourceKey);​    if (!existing || isNewer(observation, existing)) {      this.current.set(observation.resourceKey, observation);    }  }​  get<T>(resourceKey: string): ResourceObservation<T> | undefined {    return this.current.get(resourceKey) as ResourceObservation<T> | undefined;  }​  values(): ResourceObservation<unknown>[] {    return [...this.current.values()];  }}

isNewer should use a meaningful version comparison for the resource type. I would not blindly compare arbitrary version strings lexicographically.

For a numeric revision:

TypeScript
function isNewer(  incoming: ResourceObservation<unknown>,  existing: ResourceObservation<unknown>,): boolean {  return Number(incoming.version) > Number(existing.version);}

For Git, equality against the expected commit may be more useful than ordering. For HTTP resources, ETags tell you whether content changed but not necessarily which tag is “larger.” The replacement policy belongs to the adapter that understands that resource.

Render current state, not the history of state

Suppose the agent read the same deployment three times:

  • revision 41: 6 replicas;
  • revision 42: 8 replicas;
  • revision 43: 10 replicas.

The event log should keep all three. The next prompt usually needs only revision 43.

TypeScript
function renderCurrentObservations(  observations: ResourceObservation<unknown>[],): string {  return observations    .map(      (item) =>        `[${item.resourceKey} @ version ${item.version}]\n` +        JSON.stringify(item.value),    )    .join("\n\n");}

That removes contradictory state without asking a summarizer to decide which copy to keep.

It also makes the prompt easier to inspect. If a bad action occurred, I can see exactly which resource version the model was given.

Writes should invalidate or refresh observations

A stale cache becomes especially dangerous after the agent itself changes a resource.

If the tool updates a deployment image, the old deployment observation should not remain “current.”

There are two reasonable strategies:

Invalidate after write. Remove the cached observation and force a read before the next decision that needs it.

Write-through refresh. If the mutation response contains the authoritative new resource and version, insert that immediately.

TypeScript
async function updateDeploymentImage(  input: { resourceKey: string; image: string },): Promise<DeploymentState> {  observationStore.delete(input.resourceKey);​  const updated = await deploymentApi.setImage(input.resourceKey, input.image);​  observationStore.put({    resourceKey: input.resourceKey,    version: updated.version,    observedAt: new Date().toISOString(),    value: updated.state,    sourceToolCallId: updated.operationId,  });​  return updated.state;}

If the write response is not authoritative, invalidate and re-read instead of manufacturing a new state locally.

Use optimistic preconditions for important writes

Fresh context does not guarantee the resource stays unchanged between read and write.

That is the ordinary time-of-check/time-of-use problem.

If a tool is going to modify a mutable resource, pass the version it reasoned about as a precondition where the API supports it.

TypeScript
type UpdateRequest = {  deploymentId: string;  expectedVersion: string;  replicas: number;};​async function changeReplicaCount(input: UpdateRequest) {  return deploymentApi.updateReplicas({    id: input.deploymentId,    replicas: input.replicas,    ifVersion: input.expectedVersion,  });}

If another actor changed the deployment meanwhile, the tool should fail with a conflict, refresh the resource, and return the new state to the agent.

The alternative—silently overwriting newer state because the agent had an old observation—is exactly the kind of race condition backend APIs have spent years learning to avoid.

Python implementation with explicit invalidation

Python
from collections.abc import Callable​class ObservationStore:    def __init__(self, newer: Callable[[str, str], bool]) -> None:        self._current: dict[str, ResourceObservation[object]] = {}        self._newer = newer​    def put(self, observation: ResourceObservation[object]) -> None:        existing = self._current.get(observation.resource_key)        if existing is None or self._newer(observation.version, existing.version):            self._current[observation.resource_key] = observation​    def invalidate(self, resource_key: str) -> None:        self._current.pop(resource_key, None)​    def get(self, resource_key: str) -> ResourceObservation[object] | None:        return self._current.get(resource_key)​    def values(self) -> list[ResourceObservation[object]]:        return list(self._current.values())

The store itself does not know how versions work. The adapter supplies that logic.

For a database row with integer revisions:

Python
def numeric_revision_is_newer(incoming: str, existing: str) -> bool:    return int(incoming) > int(existing)

For an immutable Git blob identified by SHA, there may be no “newer” relation at all; the application may simply replace the current observation when the branch head changes.

Freshness can be time-based when no version exists

Some external APIs expose neither ETags nor revisions.

Then I use an explicit freshness policy rather than pretending the observation is timeless.

TypeScript
type FreshnessPolicy = {  maxAgeMs: number;};​function isFresh(  observation: ResourceObservation<unknown>,  policy: FreshnessPolicy,  now = Date.now(),): boolean {  return now - Date.parse(observation.observedAt) <= policy.maxAgeMs;}

A weather reading might expire in minutes. A static project configuration may remain useful for hours. A bank balance may need to be re-read immediately before an action.

TTL is a domain property, not a universal agent setting.

Do not refresh everything every turn

Freshness can turn into a latency problem if the agent reloads every resource before every model call.

I prefer lazy refresh:

  1. the planner identifies which resources matter for the next decision;
  2. the application checks whether those observations are missing or expired;
  3. only those resources are refreshed;
  4. the current-state projection is rebuilt.

That gives you a cache-like tradeoff between freshness and cost without leaving the decision implicit in conversation history.

For especially critical actions, the tool itself should revalidate state regardless of what the prompt contains.

Summaries should point to resource state, not duplicate it

Long-running agents often combine compaction with current-state tracking.

The summary can say:

Text
We are investigating deployment:payments/prod-api. Current deployment state is provided separately in the live-resource section.

It should avoid embedding mutable details such as “replicas=6” if those details are already represented by the observation store.

That prevents the summary from becoming a second stale cache.

This is a useful general rule: a piece of state should have one canonical representation in the prompt whenever possible.

Tool-output IDs make freshness easier to debug

I keep the tool call or operation ID that produced each observation.

When a trace shows the agent decided to scale to twelve replicas based on deployment:payments/prod-api@43, I can follow that observation to the exact read call. If the API already had revision 44 at that moment, the problem is in our fetch/cache path. If revision 44 appeared afterward, the conflict-handling path should have protected the write.

That is far more actionable than reading a transcript and guessing which JSON blob the model paid attention to.

Test stale-state behavior deliberately

A useful evaluation changes the resource *between* agent steps.

For example:

  1. agent reads invoice status open, version 7;
  2. external actor marks it paid, version 8;
  3. agent proposes a reminder email based on the old observation;
  4. executor must refresh or reject the stale precondition;
  5. no reminder is sent.

Another case:

  1. coding agent reads package.json at commit A;
  2. a tool edits dependencies and commits B;
  3. old package metadata must not remain the current resource state.

These are concurrency tests, not prompt tests.

When this machinery is unnecessary

If the resources an agent reads are immutable during a run, ordinary event history may be enough. A document-analysis task over fixed PDFs does not need version-aware replacement for every chunk.

The pattern becomes valuable when the agent or other actors can change the same resources while the run is active.

At that point, more context is not safer context.

The correct abstraction is the one we already use for caches and distributed state: identity, version, freshness, invalidation, and preconditions on writes. Once mutable observations follow those rules, stale context stops being an invisible language-model quirk and becomes an ordinary state-consistency problem we know how to test.

KEEP READING

Related engineering notes