Sub topic 16
Testing whether memory helps
Memory adds code, storage, prompt tokens, and privacy risk. It earns its place only if the agent behaves better with it than without it. This chapter shows how to measure that. It assumes you have the buffer, the MemoryStore, and the retrieval step from earlier chapters, and that you can write basic Python tests.
What you are testing
A memory system can fail in four places, and a single end-to-end "does it feel smarter" check will not tell you which one broke.
| Layer | Question | Typical failure |
|---|---|---|
| Writing | Was the right fact saved? | Fact never stored, or stored in a garbled form |
| Retrieval | Did the right memory come back for this query? | Relevant memory ranked below `k`, or irrelevant ones fill the slots |
| Prompt assembly | Did the memory reach the model within budget? | Trimming drops the memory block |
| Behavior | Did the answer improve? | Model ignores or misuses the memory |
Test the layers separately, then test the whole loop. When the end-to-end score drops, the layer tests tell you where to look.
Test cases that matter
Write each case as a small record: the memories that exist, the user and question, and what a correct answer must contain. Cover these kinds of case:
- Recall. A fact was saved in an earlier session. Does the agent use it?
- Abstention. Nothing relevant is stored. The agent should say it does not know, not invent a fact from a loosely related memory.
- Update. A fact changed ("I moved to Porto"). The agent should use the new value.
- Distraction. Many unrelated memories exist. The right one must still win.
- Isolation. User B asks a question that user A's memory could answer. User A's data must never appear.
The isolation and abstention cases are the ones teams skip, and they are the ones that cause the most harm in production.
Measure retrieval without an LLM
Retrieval is deterministic once the embedding function is fixed, so you can test it cheaply and in CI. The standard metric is recall@k: the fraction of cases where the expected memory appears in the top k results. Measure it with k equal to the value you use in production, since a store that only finds the answer at rank 10 is no help when you inject three memories.
The script below is self-contained. It uses a crude hashed bag-of-words embedding so it runs without any API. Swap in your real embedding function to test the real system.
import math
import re
import zlib
DIM = 256
def embed(text):
vec = [0.0] * DIM
for word in re.findall(r"[a-z]+", text.lower()):
if len(word) > 3 and word.endswith("s"):
word = word[:-1] # crude plural/verb-ending handling
vec[zlib.crc32(word.encode()) % DIM] += 1.0
return vec
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb) if na and nb else 0.0
class MemoryStore:
def __init__(self):
self.items = []
def write(self, user_id, text):
self.items.append({"user_id": user_id, "text": text, "vec": embed(text)})
def search(self, user_id, query, k=3):
q = embed(query)
own = [m for m in self.items if m["user_id"] == user_id]
own.sort(key=lambda m: cosine(q, m["vec"]), reverse=True)
return own[:k]
store = MemoryStore()
store.write("alice", "Alice prefers the Python language for scripting")
store.write("alice", "Alice lives in Lisbon")
store.write("alice", "Alice is allergic to peanuts")
store.write("bob", "Bob prefers the Rust language for scripting")
# (user, question, text the correct answer must contain)
CASES = [
("alice", "Which language do I prefer for scripting?", "python"),
("alice", "Where do I live?", "lisbon"),
("alice", "What am I allergic to?", "peanut"),
("bob", "Which language do I prefer for scripting?", "rust"),
]
def recall_at_k(k):
hits = 0
for user, question, expected in CASES:
results = store.search(user, question, k=k)
if any(expected in m["text"].lower() for m in results):
hits += 1
return hits / len(CASES)
def leaks():
"""Count results that belong to a different user than the asker."""
bad = 0
for user, question, _ in CASES:
bad += sum(1 for m in store.search(user, question, k=5)
if m["user_id"] != user)
return bad
print("recall@1:", recall_at_k(1))
print("recall@3:", recall_at_k(3))
print("cross-user leaks:", leaks())Expected output is recall@1: 1.0, recall@3: 1.0, and cross-user leaks: 0. The leak count must always be exactly zero. Treat any other value as a failing test, not a metric to tune.
Measure behavior with an A/B comparison
Retrieval tests say the right memory was found. They do not say the agent used it. For that, run every case twice, once with memory injected and once without, and grade both answers the same way.
The model below is a deterministic stand-in so the script runs offline. It answers from the first bullet line in its system prompt, or says it does not know. In a real test, replace fake_model with your chat API call. This block continues the previous one and reuses its store and CASES.
def fake_model(system_prompt, question):
for line in system_prompt.splitlines():
if line.startswith("- "):
return line[2:]
return "I don't know."
def agent_answer(user, question, use_memory):
system = "You are a helpful assistant."
if use_memory:
recalled = store.search(user, question, k=2)
system += "\n\nKnown facts about the user:\n"
system += "\n".join("- " + m["text"] for m in recalled)
return fake_model(system, question)
def score(use_memory):
passed = 0
for user, question, expected in CASES:
answer = agent_answer(user, question, use_memory)
if expected in answer.lower():
passed += 1
return passed, len(CASES)
print("memory on :", score(True))
print("memory off:", score(False))This prints memory on : (4, 4) and memory off: (0, 4). The number you report is the difference between the two runs. A high score with memory on means little if the score with memory off is also high, because the case may be answerable from the question alone.
Grading real model output
Substring checks work for facts with a clear answer, such as a city or a language. For open-ended answers you have two options:
- Rubric check by an LLM judge. Give a second model the question, the reference answer, and the agent's answer, and ask for pass or fail. Spot-check its verdicts by hand, since judges make mistakes.
- Structured outputs. Ask the agent to answer in a fixed format so that a program can compare fields.
Real models vary between runs. Run each case several times, with the temperature set low, and report the pass rate instead of a single pass or fail.
Costs and side effects to track
Memory can raise accuracy and still be a bad trade. Record these next to the accuracy numbers:
- Prompt tokens added by the memory block, per turn.
- Latency of the embedding call and the search.
- Precision of recalled memories. If two of three injected memories are irrelevant, you pay tokens and risk distraction.
- Regressions. Cases that passed without memory and fail with it. A stale or wrong memory causes these.
Common mistakes
- Testing only the happy path. A suite of recall cases cannot catch leaks, stale facts, or hallucinated "memories".
- Cases too easy for the model. If the question already contains the answer, memory off scores the same as memory on.
- A single run. One pass of a stochastic model proves little.
- Ignoring trimming. Test with a small
max_tokenstoo. The memory block sits in the system message, and a trim bug that drops it makes the whole memory system silently useless. - No test for deletion. After you delete a memory, a search must not return it, and the agent must not repeat it.
Exercise
Your A/B test shows 9 of 10 cases pass with memory on and 8 of 10 pass with memory off. List two things you should check before concluding that memory helps.
Show answer
First, find the two cases that differ and any case that regressed (passed with memory off, failed with memory on), since a regression can hide behind a net gain. Second, check whether the cases are answerable without memory, because 8 of 10 passing with memory off suggests the questions are too easy. Add harder recall cases, rerun each case several times to account for model variance, and compare again.
Exercise
Write down one test case that checks abstention. What are the stored memories, the question, and the pass condition?
Show answer
Stored memory for the user: "Alice lives in Lisbon". Question: "What is my favorite color?" Pass condition: the answer says it does not know, or asks the user, and does not name a color or claim that Lisbon is relevant. The case fails if the agent invents a color or treats the unrelated memory as an answer.