Sub topic 14
Updating, deduplicating, and forgetting
This chapter covers what happens to a long-term memory store after the first few writes. It assumes you have read the earlier chapters on writing and retrieving memories, and that you can read basic Python and understand cosine similarity between vectors.
Why a memory store needs maintenance
A store that only appends will go wrong in three ways:
- Stale facts. The user said "I live in Berlin" in March and "I moved to Paris" in June. Both records match a question about where they live, and the agent may quote the wrong one.
- Duplicates. Users repeat themselves. Ten copies of "likes tea" fill the top-k retrieval slots and crowd out other useful memories.
- Unbounded growth. Every memory adds storage cost, retrieval noise, and privacy exposure. Old one-off details rarely earn their place.
Maintenance has three operations: update a memory whose fact changed, deduplicate memories that say the same thing, and forget memories that are old, unused, or requested for deletion.
The write decision
Run the same decision on every candidate memory before you store it.
Updating changed facts
An update replaces a fact whose value changed. You must first recognize that the new memory and the old one describe the same slot. There are two common ways to do this:
- Explicit keys. Facts that fill a known slot (
home_city,preferred_language,timezone) get a key. Writing the same key again replaces the value. This is predictable and cheap, but you need to know the slots in advance. - Similarity plus a judge. For free-text memories, retrieve the nearest existing memories and ask an LLM whether the new one contradicts, repeats, or is unrelated to each. This is flexible but costs a model call per write and can misjudge.
Prefer soft updates. Mark the old record inactive and keep it with a superseded_at time, instead of overwriting it. You keep an audit trail, you can undo a wrong update, and retrieval still ignores the old record.
Deduplicating
Exact matching catches only identical strings. Real duplicates differ in wording: "Priya likes tea" and "Priya likes tea." are one case, "Priya enjoys tea" is another. To catch these, compare the embedding of the new memory with existing memories from the same user, and treat any pair above a threshold as the same memory. On a match, refresh the existing record instead of adding a new one.
Choosing the threshold involves a trade-off:
- Too low, and you merge different facts. "Priya is allergic to peanuts" and "Priya likes peanut butter" may sit close together in embedding space.
- Too high, and paraphrases slip through as separate records.
Start high (0.90 to 0.95 for most embedding models, but check yours on real examples) and tune it against a labeled sample of pairs.
A store that updates, dedupes, and forgets
The following code is self-contained. It uses a toy bag-of-words embedding so you can run it without an API. In practice, replace toy_embed with a real embedding function.
import itertools
import math
DAY = 86400
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0
VOCAB = ["lives", "berlin", "paris", "likes", "tea", "coffee", "priya"]
def toy_embed(text):
words = text.lower().replace(".", "").split()
return [float(words.count(w)) for w in VOCAB]
class MaintainedStore:
def __init__(self, embed, dup_threshold=0.95):
self.embed = embed
self.dup_threshold = dup_threshold
self.items = []
self._ids = itertools.count(1)
def _add(self, user_id, text, key, vec, now):
record = {
"id": next(self._ids), "user_id": user_id, "text": text,
"key": key, "vec": vec, "created": now, "last_seen": now,
"active": True, "superseded_at": None,
}
self.items.append(record)
return record["id"]
def write(self, user_id, text, key=None, now=0.0):
vec = self.embed(text)
live = [m for m in self.items
if m["user_id"] == user_id and m["active"]]
for m in live:
if key is not None and m["key"] == key:
if m["text"] == text:
m["last_seen"] = now
return m["id"], "duplicate"
m["active"] = False # soft update: keep the old row
m["superseded_at"] = now
return self._add(user_id, text, key, vec, now), "updated"
for m in live:
if cosine(vec, m["vec"]) >= self.dup_threshold:
m["last_seen"] = now
return m["id"], "duplicate"
return self._add(user_id, text, key, vec, now), "added"
def search(self, user_id, query, k=3):
q = self.embed(query)
own = [m for m in self.items
if m["user_id"] == user_id and m["active"]]
own.sort(key=lambda m: cosine(q, m["vec"]), reverse=True)
return own[:k]
def expire(self, now, max_age):
count = 0
for m in self.items:
if m["active"] and now - m["last_seen"] > max_age:
m["active"] = False
count += 1
return count
def purge_inactive(self):
before = len(self.items)
self.items = [m for m in self.items if m["active"]]
return before - len(self.items)
def delete_user(self, user_id):
self.items = [m for m in self.items if m["user_id"] != user_id]
s = MaintainedStore(toy_embed)
print(s.write("u1", "Priya lives in Berlin.", key="home_city", now=0))
print(s.write("u1", "Priya lives in Berlin.", key="home_city", now=1 * DAY))
print(s.write("u1", "Priya lives in Paris.", key="home_city", now=2 * DAY))
print(s.write("u1", "Priya likes tea.", now=3 * DAY))
print(s.write("u1", "Priya likes tea", now=50 * DAY))
print([m["text"] for m in s.search("u1", "Priya lives where", k=1)])
print(s.expire(now=60 * DAY, max_age=30 * DAY))
print(s.purge_inactive())
print(len(s.items))Running it prints:
(1, 'added')
(1, 'duplicate')
(2, 'updated')
(3, 'added')
(3, 'duplicate')
['Priya lives in Paris.']
1
2
1Here is what happened. The Berlin fact was repeated and then superseded by Paris. The two tea writes collapsed into one record, because their embeddings are identical. At day 60 the Paris record had not been confirmed for 58 days, so expire deactivated it. The purge then removed both inactive rows, the Berlin one superseded and the Paris one expired. Only the tea record remains.
Forgetting
Forgetting is a policy decision, and there are several policies to choose from.
| Policy | Rule | Good for | Risk |
|---|---|---|---|
| Time to live (TTL) | Drop memories not confirmed in N days | Episodic details, temporary context | Loses rare but important facts |
| Decay score | Rank by relevance, recency, and use count, and drop the lowest | Large stores with a size cap | Needs tuning, harder to explain |
| Capacity cap | Keep at most N per user, evict lowest score | Predictable storage cost | Evicts silently when full |
| Explicit deletion | User asks to forget something | Privacy, corrections | Copies may remain elsewhere |
| Supersession | Newer fact replaces older fact | Changing preferences, locations | Wrong match overwrites a good fact |
Do not apply one TTL to everything. A user's name and allergies should live far longer than "is debugging a failing test today". One approach is to give each memory a kind and a per-kind lifetime. Episodic memories get short lifetimes, and semantic memories get long ones or none.
Soft delete versus hard delete
Marking a record inactive hides it from retrieval but leaves the data on disk. That is enough for supersession and TTL expiry, where you may want to inspect or restore the record. It is not enough for a deletion request. For those, remove the record and its embedding, and remember the other places a copy can live: backups, logs, caches, and any summaries that quoted the memory.
Edge cases
- Negation. Embeddings often place "Priya likes tea" and "Priya no longer likes tea" very close together. A similarity threshold alone may treat them as duplicates and silently discard the change. Use keys, or send near-matches through an LLM judge that checks for contradiction.
- Wrong merges. If an update replaces the wrong record, a correct fact is lost. The soft-update pattern above makes this recoverable.
- Refreshing on repeat. Refreshing
last_seenwhen a duplicate arrives keeps frequently confirmed facts alive. Consider also refreshing when a memory is retrieved and used, so useful memories do not expire. - Scope. Run deduplication and updates only within one user's records, as
writedoes. A match across users would leak or corrupt data. - Concurrency. Two writes processed in parallel can both find no match and both add a record. Serialize writes per user, or run a periodic cleanup job.
- Summaries. A summary that absorbed a stale fact keeps repeating it after the original memory is gone. Rebuild or edit summaries when you supersede or delete the facts behind them.
Exercise
A user first says "I prefer email notifications" and later says "Please stop emailing me, use SMS". A similarity-only deduplicator with a threshold of 0.9 keeps the first memory and treats the second as a duplicate. Give two ways to fix this.
Show answer
First, give notification preference a key such as notification_channel, so the second write replaces the first by key regardless of similarity. Second, when a new memory is similar to an existing one but not identical, ask an LLM whether it repeats, contradicts, or is unrelated to the old one, and supersede the old record on a contradiction. You could also raise the threshold, but that only reduces the problem and does not fix it, because a contradiction can still embed very close to the original.
Exercise
Using the MaintainedStore above, write three lines that add the memory "Priya likes coffee." for user "u2" at time 0, then expire it at day 40 with a 30-day limit, then purge. What does purge_inactive return?
Show answer
s.write("u2", "Priya likes coffee.", now=0), then s.expire(now=40 * DAY, max_age=30 * DAY), then s.purge_inactive(). The expire call returns 1, and the purge returns 1 for a fresh store (the one expired row). If the store already holds other inactive rows, the purge count includes them as well.