AI AgentsLangChain
How do you prevent stale or conflicting memories?
Question 316 of 324 · Updated
On this page
- Direct answer
- 1. Separate stale, expired, superseded and conflicting records
- 2. Model time explicitly
- Temporal validity is not a ranking preference
- 3. Define fact identity and source authority
- 4. Explicitly supersede a claim instead of rewriting history
- 5. Integrate resolution with LangChain and LangGraph Store
- 6. Invalidate caches, indexes and derived records
- Tombstones and replay
- Derived-memory dependencies
- 7. Tested Python: temporal resolution, supersession and version fencing
- Worked lifecycle trace
- Important limitations of the tested contract
- 8. Handle concurrent corrections and uncertain commits
- 9. Represent uncertainty to the agent and user
- 10. Production evaluation and release gates
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
Prevent stale and conflicting agent memories by treating every memory as a versioned, source-grounded claim with a defined scope, effective validity interval and retention policy. Resolve claims using domain-specific source authority and explicit supersession, not simply the newest timestamp or highest embedding similarity. When evidence cannot be reconciled, return an uncertain or conflicting result, retrieve authoritative current evidence where permitted, or request clarification.
In a LangChain agent, place these rules in an application-controlled memory service between the LangGraph Store and the model-facing projection. Use conditional updates for authoritative records, preserve deletion or supersession markers as required, and invalidate dependent summaries, search-index entries and cached context. A store search retrieves candidates; it does not certify that their facts remain current.
Earlier AI Agents #74 and #75 introduce the conceptual problems of stale and conflicting memories. #262–266 cover specialized cross-region tombstone and failback incidents. LangChain #30 and #32–35 (#310, #312–315) cover summarization, persistence, isolation, memory ingestion and retrieval. This lesson focuses on the single-agent application contract for temporal claims, authority-aware resolution, invalidation and version-consistent use of memory. It does not repeat distributed tombstone garbage-collection algorithms or general retrieval ranking.
1. Separate stale, expired, superseded and conflicting records#
A memory can become unusable for several different reasons. Consider a fictional support agent that remembers the status of case C-1. A verified service said pending yesterday. A user reports shipped today. Another verified service also reports shipped, but its effective timestamp and identity need to be checked.
| Condition | Meaning | Appropriate handling |
|---|---|---|
| Stale | A once-valid observation may no longer answer a current question | Revalidate with an approved source |
| Expired | The record is no longer eligible under a defined time or retention policy | Exclude, even if its historical content might be true |
| Superseded | An approved correction or replacement has retired the claim | Do not use it as an active fact |
| Conflicting | Eligible claims disagree about the same fact for the same applicable interval | Resolve by reviewed authority rules or report uncertainty |
| Deleted or revoked | Policy no longer permits use of the record | Prevent use and apply the required deletion lifecycle |
| Historical but valid | An observation accurately describes an earlier event | Retain and use only for its approved historical purpose |
A record saying "pending at 10:00" does not necessarily conflict with another saying "shipped at 12:00." Both may describe correct observations at different times. A conflict exists when the relevant claim identity, scope, applicability and effective time overlap in a way that makes the values incompatible.
Similarly, an old unsuccessful troubleshooting episode may remain correct as a historical event. It does not prove that the current system is still failing. Retain the distinction between past outcomes and current state.
This is an application resolution design. Neither similarity search nor a generic memory store guarantees that these checks occur automatically.
2. Model time explicitly#
Store several different time dimensions when the domain needs them. One timestamp named updated_at is rarely sufficient.
| Time field | Meaning |
|---|---|
| observed_at | When the source observed the event |
| recorded_at | When the application accepted the record |
| effective_from | Beginning of the claim's applicability |
| effective_until | End of applicability, preferably with an explicit boundary convention |
| expires_at | Deadline after which memory use is not permitted under the defined policy |
| verified_at | When the source or claim was last independently revalidated |
A late-arriving observation can have a recent recorded_at but an older observed_at. Sorting by database insertion time would incorrectly favor it over a newer source observation. A future-effective preference or configuration may be recorded today but should not control the current task until it becomes applicable.
Use a clearly defined interval convention such as inclusive start and exclusive end. A claim effective from 10 until 20 is applicable at 10 but not at 20. Store and compare timestamps under a consistent UTC representation in production. Establish a trusted clock, tolerable skew, source timestamp validation and policy for missing times.
Consider a hypothetical record with an effective interval from day 0 through, but not including, day 100, and a memory-use expiry at day 50. At day 49 it may be eligible. At day 50 it is no longer eligible even though the effective interval has not ended. The retention deadline is an independent constraint.
A current-status claim can also require revalidation before its expiry. A service may change a ticket's status between the last observation and the next request. For high-impact operations, do not rely solely on a remembered status or a long time-to-live; consult the authoritative domain service before acting.
Temporal validity is not a ranking preference#
The previous retrieval lesson used recency as a scoring signal for eligible episodes. That approach is unsuitable for mandatory eligibility checks. A superseded claim cannot become valid because its vector similarity is high. Conversely, an old historical episode need not become ineligible merely because it is old, provided its use and retention remain authorized.
3. Define fact identity and source authority#
Before comparing claims, identify what they refer to. A useful logical identity might include tenant, subject, entity, attribute and purpose. A claim about case C-1's status and a claim about case C-2's status do not conflict merely because both use the attribute name status.
The appropriate authority is domain-dependent:
| Claim | Appropriate authority |
|---|---|
| User's preferred answer style | Explicit authenticated user choice |
| External case status | Designated case-management system or verified domain event |
| User-supplied description of an event | User assertion, with attribution |
| Model-generated inference | Candidate interpretation, not verified fact |
| Executable procedure | Approved versioned procedure registry |
| Access permission | Current trusted authorization service |
A user is generally the best source of their own stated communication preference, but their statement is not automatically authoritative for an external transaction. A model's confidence does not make an inference more authoritative than a verified domain observation. Store source identifiers and evidence references that can be resolved under current policy.
A conservative resolution policy can:
- Identify eligible claims for one fact and time interval.
- Find the highest applicable source authority according to the reviewed domain policy.
- Check whether the claims at that level agree.
- Return the supported value if they agree.
- Return a conflict if equally authoritative eligible claims disagree.
- Revalidate or abstain when the policy requires additional evidence.
This is a useful baseline, not a universal truth-resolution algorithm. A formally lower-ranked source may reveal an important inconsistency requiring investigation. An authority hierarchy should be defined by the domain owner and separately tested for each field.
4. Explicitly supersede a claim instead of rewriting history#
Suppose a verified source originally reported pending, and a later authoritative correction explicitly states that the earlier observation was wrong. An accepted correction can create a new claim and identify the old claim it supersedes.
Record the reason, source, effective scope and approved revision. A supersession is different from merely adding another claim. It changes whether the original record remains active.
These are application lifecycle states, not built-in LangGraph Store states. Historical records may be retained or removed according to the product's documented privacy and audit policy. A logical retirement does not automatically imply permission to retain the original payload forever.
Validate supersession against the same fact identity and the authority required to correct the prior claim. Do not permit a low-authority inference to retire a verified fact merely because the inference arrived later. For scheduled changes, preserve the earlier record until the intended effective boundary or maintain valid-time history. An immediate retirement of the old claim combined with a future-effective replacement can otherwise create an availability gap.
When the application needs historical reconstruction, maintain versioned records or a suitable event history. A current-state snapshot that removes retired values cannot reconstruct every earlier answer. Keep the historical query semantics distinct from current resolution.
5. Integrate resolution with LangChain and LangGraph Store#
A compatible LangChain agent can access a configured store through ToolRuntime.store. The store is useful for candidates and exact-key records, but domain freshness, source authority and conflict resolution require explicit application logic.
The following illustrative SDK example uses a trusted memory resolver service. It does not expose namespace, source authority or arbitrary database filters as model-controlled arguments.
PYTHONfrom dataclasses import dataclass from typing import Literal, Protocol from langchain.tools import tool, ToolRuntime from langchain.agents import create_agent @dataclass(frozen=True) class FactResult: status: Literal["known", "conflict", "unavailable"] value: str | None source_ref: str | None class Resolver(Protocol): def current_case_status(self, tenant: str, subject: str, case_ref: str) -> FactResult: ... @dataclass(frozen=True) class RequestContext: tenant: str subject: str resolver: Resolver @tool def read_case_status(case_ref: str, runtime: ToolRuntime[RequestContext]) -> dict: """Read an eligible, verified fictional case status.""" ctx = runtime.context # Resolver independently validates case access and current source policy. result = ctx.resolver.current_case_status( ctx.tenant, ctx.subject, case_ref ) return { "status": result.status, "value": result.value if result.status == "known" else None, "source_ref": result.source_ref if result.status == "known" else None, } # Register on an approved agent configured with context_schema, # its thread checkpointer and store if needed.
SDK verification limitation: Python 3.13.5 is available locally, but langchain, langchain_core and langgraph are absent. The SDK illustration is unexecuted. The Resolver interface is an application dependency, not a built-in LangChain feature. The separate tested implementation in section 7 demonstrates a narrow resolution policy; it is not an implementation of this SDK service.
A production resolver should validate the requested case, construct the approved namespace, retrieve candidates from the store and check their authoritative metadata. If semantic indexing is used, fetch the current records by identity and version before using them. Check the exact framework and backend API against the pinned version.
A memory record's value may be JSON-compatible, with fields such as claim_id, record_version, schema_version, value, source_ref, effective_from, effective_until, expires_at and status. A simple store.put call should not be assumed to implement an atomic compare-and-set or coordinate all dependent projections. Use a reviewed backend-specific conditional-write mechanism or a transactional application-owned repository.
Do not construct a system instruction by concatenating raw recalled text. Use a bounded structured result with approved fields. The model's generated answer must still satisfy the application's independent evidence and authorization requirements.
6. Invalidate caches, indexes and derived records#
A memory subsystem often has several projections of the same fact. For example, the authoritative record may have version 12, while a vector index, cached summary or retrieved model context still refers to version 11. Updating the primary record does not automatically update those projections.
The sequence illustrates a recommended application protocol. It does not imply that a LangGraph Store provides a transactional outbox or these consistency guarantees by default.
Use an authoritative version as a read-path fence. Treat a vector-search result as a candidate reference, not an authoritative payload. A cache entry can include the fact identity, record revision, policy revision, permitted scope and a validity deadline. Before protected use, check that the cached entry still matches the relevant authoritative state.
If the store and index are eventually consistent, a stale index may miss newly added memories. That is a recall and availability issue. Returning a superseded or revoked value as current is a correctness or privacy failure. Protect the latter with authoritative revalidation while measuring index update lag and missing-record recall separately.
Tombstones and replay#
A tombstone is a marker that records a logical deletion or retirement without retaining the full deleted content. It can preserve a version fence against late or repeated writes. If a deleted fact at revision 14 receives a delayed update for revision 13, the service must reject that stale update rather than recreate the record.
A tombstone must not be treated as a searchable active memory. Retain only the minimal metadata required under the authorized lifecycle. Recreating a legitimately new record should follow an explicit authorized identity or generation policy, not silently reuse an old deleted record.
The earlier multi-agent lessons #262–266 cover cross-region replication and safe tombstone garbage collection. This lesson does not prescribe a new distributed GC algorithm. In a single-agent application, the practical rule is to keep the version fence for as long as the approved replay and reconciliation contract requires, and never use a retention period as proof that every delayed producer has stopped.
Derived-memory dependencies#
A summary or semantic observation can depend on several source facts. Record those dependencies as identities and revisions. If an input is retired, corrected, expires or becomes inaccessible, invalidate or rebuild the derived record according to the approved policy.
For example, a remembered observation that a checklist helped in two verified cases depends on both episodes. If one source is no longer eligible, the original derived claim may no longer have sufficient support. Do not keep displaying it merely because the derived record itself has a future expiry.
Maintain reverse dependency information when prompt or retrieval caches are materialized. Bound the invalidation work and prevent dependency cycles. For critical claims, check current source eligibility at read time even if asynchronous invalidation is delayed.
7. Tested Python: temporal resolution, supersession and version fencing#
The following standard-library implementation is a deliberately narrow in-process claim ledger. It models one fact identity at a time, an integer effective interval, an independent expiry, domain authority expressed as an integer, explicit supersession and permanent key tombstones. It rejects stale revision updates and checks derived projections against current source revisions and eligibility.
It is not a LangGraph Store backend, a distributed cache, a historical database or a production authentication service. The exact program was executed locally before publication.
PYTHONfrom dataclasses import dataclass from threading import RLock import sys, importlib.util @dataclass(frozen=True) class Claim: id: str value: str source: str authority: int start: int end: int expires: int @dataclass(frozen=True) class Snapshot: version: int = 0 claims: tuple[Claim, ...] = () retired: frozenset[str] = frozenset() deleted: bool = False class Conflict(Exception): pass class Ledger: def __init__(self): self.lock = RLock() self.rows = {} def read(self, key): with self.lock: return self.rows.get(key, Snapshot()) def update(self, key, expected, claim=None, *, supersedes=(), delete=False): with self.lock: old = self.read(key) if old.version != expected or old.deleted: raise Conflict('stale or deleted key') active = {c.id:c for c in old.claims} if delete: if claim is not None or supersedes: raise ValueError('ambiguous deletion') new = Snapshot(old.version+1, (), old.retired | frozenset(active), True) else: if (claim is None or not claim.source or claim.id in active or claim.id in old.retired or claim.start >= claim.end): raise ValueError('invalid claim') if any(i not in active or claim.authority < active[i].authority for i in supersedes): raise ValueError('invalid supersession') for i in supersedes: del active[i] active[claim.id] = claim new = Snapshot(old.version+1, tuple(sorted(active.values(),key=lambda c:c.id)), old.retired | frozenset(supersedes)) self.rows[key] = new return new def resolve(self, key, now): s = self.read(key) eligible = [c for c in s.claims if c.start <= now < c.end and now < c.expires] if s.deleted or not eligible: return ('unavailable', None) top = max(c.authority for c in eligible) values = {c.value for c in eligible if c.authority == top} return ('known', next(iter(values))) if len(values)==1 else ('conflict', None) def accepts_projection(self, deps, now): with self.lock: return bool(deps) and all(self.read(k).version == v and self.resolve(k,now)[0]=='known' for k,v in deps) def reject(exc, fn): try: fn() except exc: return raise AssertionError('expected rejection') l=Ledger(); key=('A','u','case-status') a=Claim('a','pending','service-1',2,0,100,50) b=Claim('b','shipped','user-1',1,0,100,100) c=Claim('c','shipped','service-2',2,0,100,100) d=Claim('d','shipped','service-3',2,10,100,100) assert l.resolve(key,0)==('unavailable',None) assert l.update(key,0,a).version==1 assert l.resolve(key,1)==('known','pending') assert l.accepts_projection(((key,1),),1) assert l.resolve(key,50)==('unavailable',None) assert not l.accepts_projection(((key,1),),50) l.update(key,1,b) assert l.resolve(key,2)==('known','pending') assert not l.accepts_projection(((key,1),),2) reject(ValueError,lambda:l.update(key,2,Claim('e','shipped','user-2',1,0,100,100),supersedes=('a',))) l.update(key,2,c) assert l.resolve(key,2)==('conflict',None) assert not l.accepts_projection(((key,3),),2) reject(Conflict,lambda:l.update(key,2,d)) l.update(key,3,d,supersedes=('a','b','c')) assert l.resolve(key,9)==('unavailable',None) assert l.resolve(key,10)==('known','shipped') reject(ValueError,lambda:l.update(key,4,a)) assert l.accepts_projection(((key,4),),10) l.update(key,4,delete=True) assert l.resolve(key,10)==('unavailable',None) assert not l.accepts_projection(((key,4),),10) reject(Conflict,lambda:l.update(key,5,c)) print('19 checks passed') print(sys.version.split()[0], {p:importlib.util.find_spec(p) is not None for p in ['langchain','langchain_core','langgraph']})
Actual local execution:
19 checks passed
3.13.5 {'langchain': False, 'langchain_core': False, 'langgraph': False}| Executed check | Result |
|---|---|
| Absent fact | Unavailable |
| First accepted claim | Version 1 |
| Eligible verified claim | Pending |
| Matching eligible dependency | Accepted |
| Exact expiry boundary | Unavailable |
| Dependency expired without version change | Rejected |
| Lower-authority disagreement | Higher-authority value remains |
| Old dependency revision | Rejected |
| Low-authority supersession attempt | Rejected |
| Equal-authority disagreement | Conflict |
| Projection depending on unresolved conflict | Rejected |
| Stale expected version | Rejected |
| Future-effective correction before start | Unavailable |
| Correction at effective start | Shipped |
| Retired claim identity replay | Rejected |
| New eligible dependency | Accepted |
| Deleted key resolution | Unavailable |
| Projection referencing pre-deletion version | Rejected |
| Write after tombstone | Rejected |
Worked lifecycle trace#
| Snapshot revision | Active claims | Resolution |
|---|---|---|
| 0 | None | Unavailable |
| 1 | A: authority 2, pending | Pending before expiry |
| 2 | A plus B: authority 1, shipped | Pending while A is eligible |
| 3 | A, B and C: authority 2, shipped | Conflict while A and C overlap |
| 4 | D supersedes A, B and C | Unavailable before time 10; shipped from time 10 while eligible |
| 5 | Tombstone | Unavailable |
The code checks both version and time. Expiration can occur without a database revision change, so version equality alone is insufficient. The synthetic query at time 9 after immediately retiring A, B and C deliberately demonstrates a gap before D becomes effective. A real scheduled transition that requires uninterrupted coverage would need a different retirement policy or a versioned valid-time history.
Important limitations of the tested contract#
The ledger assumes trusted, validated claim identities, source authority, timestamps and scope. A source string is not independently verified, and an arbitrary caller must not be able to invent authority 2. The example does not authenticate anyone, authorize keys, validate all field types, prove evidence support, or implement a durable database. The RLock makes each update coherent inside one process. The stale revision fixture is sequential, not a simultaneous contention or distributed consistency test.
The simplified policy immediately retires a claim on supersession and does not support historical reconstruction or later restoration of a tombstoned key. Its permanently deleted key policy is a deliberate choice for this fixture. A new legitimate record after deletion would require a separate approved identity or generation.
A dependency check validates only that the current version matches and resolution is known. It does not verify the derived text itself or bind the actual resolved value at every relevant time. For example, a fact's winning value can change at a time boundary even if its version remains constant. A production cache should bind the resolved claim identity/value, revision, policy and appropriate validity deadline, or recompute the projection. Test that time-driven value changes invalidate cached results even when the version does not change.
The program uses finite immutable snapshots but the in-process rows dictionary is visible to the teaching fixture. Encapsulate all mutation paths in production. It does not implement idempotent operation receipts, event propagation, real index invalidation or physical deletion. Those mechanisms require separate integration tests.
8. Handle concurrent corrections and uncertain commits#
Two conversations or background extraction workers can propose incompatible changes from the same record revision. A safe conditional-write service accepts an update only if the expected version still matches the current version, the caller is authorized and the proposed correction passes source policy.
When a conflict occurs, reload the current claim set and evaluate the proposal again. Do not automatically apply the old correction against the newest revision. If both observations remain independently eligible, preserve them and resolve according to the domain rule or report an unresolved conflict.
Use stable operation identities to handle a lost acknowledgement. A retry of the same accepted correction should not produce a second logically independent observation. Reconcile the committed operation before retrying. A retry with changed content under the same identity should be rejected.
Coordinate primary writes and invalidation event creation using a suitable transaction or durable outbox. An index worker should handle duplicates and delayed events using version-aware application rules. Invalidation lag can occur; the reader must enforce the authoritative fence at the moment it is needed. A single lock in a Python process does not provide this guarantee across worker processes, databases or external services.
9. Represent uncertainty to the agent and user#
The resolution layer should return a structured state, not only a string or a fabricated default.
| Resolver outcome | Appropriate response |
|---|---|
| known | Answer with the supported current value and relevant source or observation time |
| conflict | Explain that eligible sources disagree; obtain authoritative verification if allowed |
| unavailable | Do not guess; use a safe default only for optional settings |
| revalidation_required | Fetch authorized current evidence or report the limitation |
| policy_denied | Avoid disclosing the protected claim or existence details beyond approved policy |
For a fictional case with equally authoritative reports of pending and shipped, an agent should not answer "probably shipped" simply because one claim was retrieved first. A better response is that the current status cannot be confirmed from the available evidence and needs verification from the designated service.
For a low-impact user preference, the host may ask which preference should apply or follow an explicit current instruction for that turn without overwriting the stored preference. For an external business action, uncertainty must not be converted into permission. Treat the operation separately from the memory used to reason about it.
10. Production evaluation and release gates#
Evaluate facts and time transitions using synthetic fixtures with an independently defined expected outcome. Include temporal boundaries, conflicting sources, failed correction attempts, delayed events, index lag and concurrent updates.
| Test scenario | Required invariant |
|---|---|
| Recent insertion of older observation | Does not automatically override newer applicable evidence |
| Future-effective correction | Not used before its effective start |
| Expiry boundary | Ineligible at the defined deadline |
| Different effective intervals | Historical observations distinguished from actual conflicts |
| Lower-authority correction | Cannot retire a higher-authority claim without policy authorization |
| Equally authoritative disagreement | Explicit conflict; no arbitrary winner |
| Valid supersession | Retired value no longer supplied as current |
| Concurrent expected-version updates | Documented atomic conflict policy verified |
| Delayed pre-deletion update | Cannot resurrect deleted memory |
| Cache or index returns old revision | No stale model exposure |
| Time-driven winning-value change without a write | Cached projection invalidated or recomputed |
| Derived dependency becomes ineligible | Derived record retired or rebuilt |
| Source service unavailable | Truthful uncertainty or approved degraded path |
| Permission revoked mid-run | Recheck protected use and delivery under current policy |
| Model or framework upgrade | Actual resolver integration and evidence acceptance reverified |
Track stale-value acceptance rate, false conflict rate, unresolved conflict rate, supersession rejection reasons, invalidation propagation delay, index revision mismatch, cache eligibility violations, and downstream verified task success. Evaluate availability separately from correctness: rejecting every claim is not useful, and returning a plausible stale answer is not an acceptable way to improve availability.
For a hypothetical set of 100 correction fixtures, if the agent accepts two old values after they were superseded, the stale-value acceptance rate on that defined set is 2%. That is constructed arithmetic, not a measured benchmark. For sensitive actions or revoked private information, even one unauthorized acceptance is a serious failure. Set release gates according to the risk and evidence requirements.
Test actual SDK and database adapters with controlled fixtures, including concurrent workers and fault injection between commit and projection invalidation. Inspect provider-bound context to ensure retired or conflicting claims are never silently represented as current verified facts. Record safe fact aliases, revisions, source categories and normalized outcomes; avoid unnecessary raw memory payloads in logs.
Interview-ready answer#
I prevent stale or conflicting memories by treating each memory as a scoped, versioned claim with source provenance, effective validity and independent expiry. I resolve eligible claims using domain-specific authority and explicit supersession rather than similarity or insertion recency. Equal-authority disagreements produce an explicit conflict. I use conditional updates, tombstones and version-aware invalidation, check the current authoritative record before exposing cached or indexed candidates, and track dependencies for derived summaries. In LangChain I place this logic in a trusted memory resolver used by tools or middleware. I test time boundaries, competing corrections, delayed writes, revocation and actual cache/index integration, and return uncertainty rather than invent a current fact.
Official documentation research leads and verification status#
- LangChain long-term memory
- LangChain short-term memory
- LangChain tools
- LangChain runtime
- LangGraph persistence
- LangChain API reference
- Python dataclasses
- Python threading
Authorized offline research exception applied. These official documentation URLs are research leads, not live-accessed citations. The exact standalone program was executed on Python 3.13.5 and printed 19 checks passed. Package inspection confirmed langchain, langchain_core and langgraph were absent. The SDK example, actual durable store, live authorization, simultaneous distributed contention, real cache and vector-index invalidation, provider behavior, current documentation and public website rendering were not verified. The tests use synthetic claims, source-authority values and integer times. The limitations of version-only dependency checking and immediate retirement with future-effective replacement are documented above. All Mermaid diagrams use standard triple-backtick fences; rendering was not tested.
References
- 1.LangChain long-term memorydocs.langchain.com
- 2.LangChain short-term memorydocs.langchain.com
- 3.LangChain toolsdocs.langchain.com
- 4.LangChain runtimedocs.langchain.com
- 5.LangGraph persistencedocs.langchain.com
- 6.LangChain API referencereference.langchain.com
- 7.Python dataclassesdocs.python.org
- 8.Python threadingdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps