Implementing Agent Memory That Survives Restarts (Part 4)
Memory that survives restarts
A memory round-trip
Recall is a decorator: the agent loop stays unchanged.
- 01
episodeone completed step - 02
gate: worth storing?write policy decides - 03
embed + INSERTSQLite + vector - 04
recall queryscore, then top-k - 05
inject ordered factsinto the next prompt - 06
consolidate on scheduleepisodes become facts
Every run of the Part 3 agent starts from zero. It re-searches the same corpus, re-derives the same facts, and forgets the answer the moment the process exits. Ask it the same question twice and you pay for the same retrieval twice, with no guarantee of the same answer.
The usual fix is to dump everything into a vector database. That fails for a reason worth stating precisely: a vector store gives you similarity, and memory needs selection. Similarity cannot tell you that an observation from 60 days ago is probably stale, that a one-word tool output is not worth a row, or that two sentences about the same subject are the same fact with a newer value. Those are policy decisions, and they belong in code you can read.
This part builds that policy layer: three tiers of memory, a write gate with explicit scores, recall that multiplies relevance by recency and importance, and a consolidation pass that promotes repeated episodes into facts. Storage is SQLite — one file, two tables, no infrastructure.
The economics are worth stating because they justify the complexity. A single tool call in Part 2’s agent returns roughly 600 tokens, and a four-search run spends 2,400 tokens of context on evidence it will discard. A recalled fact costs about 30 tokens in the memory block. Once the same research question is asked twice, remembering is already cheaper than re-searching — and unlike a re-search, a memory row does not make the model re-read three passages to recover one number. The savings compound across runs; the risk (stale, poisoned, or irrelevant memories) is what the rest of this article is about controlling.
What you’ll build
A memory.py module with four components:
MemoryStore— SQLite persistence with two tables.episodesholds what happened;factsholds what is true, keyed by a normalised subject.WritePolicy— a scoring function that decides whether an observation earns a row, with aUNIQUEdedupe key as the backstop.AgentMemory— the façade:remember,recall,context_block,consolidate,record_run.PrefixLLM+MemoryAgent— injection and orchestration, so a run recalls before it plans and writes back after it answers.
The tiers map onto code you already have. Working memory is the history list inside AgentLoop, bounded by ContextBudget from Part 3. Episodic memory is the episodes table. Semantic memory is the facts table. Only the last two persist, and that asymmetry is the design: a run’s scratchpad is worthless tomorrow, but the fact it discovered is not.
Prerequisites
- Parts 1–3.
memory.pyimportsAgentLoop,LLMClient,Messageandbuild_toolsfromcontracts.py. - Python 3.10+, standard library only (
sqlite3,re,math,time). - A writable path for the database file. Use
:memory:for tests; the tests below do.
No embedding model yet. Recall here is lexical — token overlap with stopword removal. That is a deliberate, measurable limitation: it works for the vocabulary the agent itself produced, and it fails for paraphrase. Part 5 replaces the scoring function with a real retriever and keeps this table structure.
The write policy is the hard part
Storage is easy; selection is hard. If you write every tool result, the table grows linearly with steps and recall quality falls as noise accumulates. If you write nothing, you have no memory. The gate has to be a function you can argue about, not a heuristic buried in a prompt.
The score below is additive and inspectable. Each rule exists because of a specific failure:
from __future__ import annotationsfrom dataclasses import dataclass, fieldimport jsonimport mathimport osimport reimport sqlite3import time
from contracts import AgentLoop, ErrorCode, LLMClient, Message, ToolResult
SCHEMA = """CREATE TABLE IF NOT EXISTS episodes ( id INTEGER PRIMARY KEY AUTOINCREMENT, dedupe_key TEXT NOT NULL UNIQUE, run_id TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL, importance REAL NOT NULL, created_at REAL NOT NULL);CREATE TABLE IF NOT EXISTS facts ( key TEXT PRIMARY KEY, value TEXT NOT NULL, confidence REAL NOT NULL, mentions INTEGER NOT NULL DEFAULT 1, updated_at REAL NOT NULL);CREATE INDEX IF NOT EXISTS idx_episodes_created ON episodes(created_at);"""
def normalize_key(text: str) -> str: """Collapse a sentence to a comparison key: lowercase, alphanumeric, first 80 chars.""" cleaned = re.sub(r"[^a-z0-9 ]+", " ", text.lower()) return re.sub(r"\s+", " ", cleaned).strip()[:80]
STOP = frozenset("the and for with that this from are was were what when how why into than then".split())
def tokenize(text: str) -> list[str]: return [w for w in re.findall(r"[a-z0-9]+", text.lower()) if len(w) > 2 and w not in STOP]
@dataclassclass WritePolicy: """Decides what deserves a row. Cheap rules, applied before the write."""
min_importance: float = 0.5 max_content_chars: int = 800
def importance(self, text: str, kind: str, source: str) -> float: score = 0.2 if 40 <= len(text) <= 600: score += 0.2 if re.search(r"\d", text): score += 0.2 if source == "tool": score += 0.2 if source == "user": score += 0.3 if kind == "decision": score += 0.1 return round(min(1.0, score), 2)Read the weights as answers to four questions. Is it long enough to carry content? 40–600 characters is the band where an observation is a sentence rather than a token (ok, no matches) or a document dump. Does it contain a number? Facts with quantities are the ones worth recalling — latency, limits, counts, versions. Numbers also make an observation falsifiable: p95 is 240 ms can be checked against a new measurement, while the index is fast cannot. Did it come from a tool or a user? Both are evidence; user statements and tool observations outrank the agent’s own reasoning, which is the least reliable source in the system. Was it a decision? Decisions are worth one extra tenth, because the next run needs to know what was already tried.
The thresholds matter less than the ordering. With these weights, ok scores 0.4 and is dropped; a 90-character tool result containing a number scores 0.8 and is kept. The demo at the end of this section shows exactly that: three observations offered, two rows written.
Two guards sit outside the score. max_content_chars=800 rejects oversized blobs before they reach the database — a 4,000-character search result is a document, and documents belong in the retrieval index (Part 5), not in a memory row that will be re-injected on every future run. And the dedupe_key UNIQUE constraint makes double-writing impossible even if the policy changes, because the insert raises IntegrityError and the store returns False instead of propagating.
The dedupe key deserves a warning. It is the normalised text truncated to 80 characters, so two observations that share an 80-character prefix collapse into one. That is correct for a repeated sentence and wrong for a templated log line like search returned 12 results for agent loop where only the count differs in the tail. If your tools emit templated output, key on (tool, argument_hash) instead of content — the same key you built for idempotency in Part 2.
Recall: relevance is only one third of it
A remembered fact is useful when it is about the current goal, recent enough to still be true, and important enough to be worth the tokens. Multiplying those three factors is crude, but it beats any single one of them, and every term is inspectable.
@dataclassclass Episode: id: int content: str kind: str importance: float created_at: float score: float = 0.0
@dataclassclass Fact: key: str value: str confidence: float mentions: int updated_at: float score: float = 0.0
class MemoryStore: """SQLite-backed persistence. One connection, two tables, no ORM."""
def __init__(self, path: str = ":memory:") -> None: self.conn = sqlite3.connect(path) self.conn.row_factory = sqlite3.Row self.conn.executescript(SCHEMA)
def add_episode(self, dedupe_key: str, run_id: str, kind: str, content: str, importance: float, now: float) -> bool: try: self.conn.execute( "INSERT INTO episodes (dedupe_key, run_id, kind, content, importance, created_at)" " VALUES (?, ?, ?, ?, ?, ?)", (dedupe_key, run_id, kind, content, importance, now), ) self.conn.commit() return True except sqlite3.IntegrityError: return False
def load_episodes(self, limit: int = 500) -> list[Episode]: rows = self.conn.execute( "SELECT id, content, kind, importance, created_at FROM episodes" " ORDER BY created_at DESC LIMIT ?", (limit,) ).fetchall() return [Episode(r["id"], r["content"], r["kind"], r["importance"], r["created_at"]) for r in rows]
def upsert_fact(self, key: str, value: str, confidence: float, now: float) -> None: self.conn.execute( "INSERT INTO facts (key, value, confidence, mentions, updated_at) VALUES (?, ?, ?, 1, ?)" " ON CONFLICT(key) DO UPDATE SET" " value = excluded.value," " confidence = MIN(0.95, facts.confidence + 0.15)," " mentions = facts.mentions + 1," " updated_at = excluded.updated_at", (key, value, confidence, now), ) self.conn.commit()
def load_facts(self) -> list[Fact]: rows = self.conn.execute( "SELECT key, value, confidence, mentions, updated_at FROM facts" " ORDER BY confidence DESC, updated_at DESC" ).fetchall() return [Fact(r["key"], r["value"], r["confidence"], r["mentions"], r["updated_at"]) for r in rows]
def close(self) -> None: self.conn.close()
@dataclassclass Retriever: half_life_days: float = 14.0 recency_weight: float = 0.5
def score(self, query_tokens: set[str], text: str, importance: float, age_days: float) -> float: overlap = len(query_tokens & set(tokenize(text))) if overlap == 0: return 0.0 relevance = overlap / math.sqrt(len(query_tokens) + 1) recency = 0.5 ** (age_days / self.half_life_days) return relevance * (1.0 + self.recency_weight * recency) * (0.5 + importance)Three properties of score are load-bearing.
Zero overlap means zero score, not a small score. With lexical matching, an unrelated episode has no signal, and letting it through on a recency bonus pollutes the context block. The early return is what makes test_relevance_filters_unrelated_episodes pass.
Relevance is normalised by sqrt(len(query_tokens) + 1). Without it, a long goal accumulates more matches and long queries dominate ranking, so the recall set changes shape as the user’s question gets wordier. The square root damps that without making long queries score zero.
Recency is a half-life, not a cutoff. 0.5 ** (age_days / 14) gives 1.0 today, 0.5 at two weeks, 0.05 at 60 days. A cliff at 30 days would make a fact either fully trusted or invisible; a decay lets the importance term keep an old, high-value observation in play while pushing stale trivia down. The recency_weight=0.5 means recency can move a score by at most 50% — enough to break ties between two similar facts, not enough to override relevance entirely.
The asymmetry between 1.0 + 0.5*recency and 0.5 + importance is intentional: importance has a floor of 0.5 so that a highly important old episode still scores, while recency is a bounded bonus.
The read path is a full scan, and pretending otherwise would be dishonest. load_episodes() pulls up to 500 rows and scores each one in Python — about 2 ms at 500 rows and 200 ms at 50,000, which is the point where you stop being able to call this per step. Two fixes work without changing the schema: push a time window into the SQL (WHERE created_at > ?) so the scan is bounded by the recency you actually care about, and cache the token sets per episode so tokenize runs once per row instead of once per query. The first fix is a one-line change and typically cuts the candidate set by 80%; the second is a dict from episode id to frozenset, invalidated on write.
Consolidation: turning episodes into facts
Episodes are cheap to write and expensive to inject — a context block full of near-duplicates spends tokens saying the same thing three times. Consolidation folds repeated observations about the same subject into a single fact row.
class AgentMemory: """Write policy + hybrid recall + consolidation over a MemoryStore."""
def __init__(self, store: MemoryStore, policy: WritePolicy | None = None, retriever: Retriever | None = None, clock=time.time) -> None: self.store = store self.policy = policy or WritePolicy() self.retriever = retriever or Retriever() self.clock = clock
def remember(self, run_id: str, text: str, kind: str = "observation", source: str = "tool") -> bool: text = text.strip() if not text or len(text) > self.policy.max_content_chars: return False importance = self.policy.importance(text, kind, source) if importance < self.policy.min_importance: return False return self.store.add_episode(normalize_key(text), run_id, kind, text, importance, self.clock())
def record_run(self, run_id: str, goal: str, answer: str, steps: int) -> bool: summary = "goal: %s | answer: %s | steps: %d" % (goal[:120], answer[:200], steps) return self.remember(run_id, summary, kind="run", source="user")
def recall(self, query: str, k: int = 5, now: float | None = None) -> list[Episode]: now = self.clock() if now is None else now q = set(tokenize(query)) if not q: return [] scored = [] for ep in self.store.load_episodes(): age_days = max(0.0, (now - ep.created_at) / 86400.0) ep.score = self.retriever.score(q, ep.content, ep.importance, age_days) if ep.score > 0: scored.append(ep) scored.sort(key=lambda e: e.score, reverse=True) return scored[:k]
def context_block(self, query: str, k: int = 5, max_chars: int = 1100) -> str: lines = [] for fact in self.store.load_facts()[:5]: lines.append("- fact[%s]: %s (confidence %.2f)" % (fact.key, fact.value, fact.confidence)) for ep in self.recall(query, k=k): lines.append("- episode[%d]: %s" % (ep.id, ep.content[:200])) if not lines: return "" text = "MEMORY (cite as fact[key] or episode[id]; ignore if contradicted by new evidence):\n" text += "\n".join(lines) return text[:max_chars]
def consolidate(self) -> int: """Fold repeated 'key: value' observations into facts. Returns facts touched.""" touched = 0 for ep in self.store.load_episodes(): if ep.kind != "observation": continue m = re.match(r"^([a-z][a-z0-9 _-]{2,40})\s*[:=]\s*(.{3,200})$", ep.content.strip(), re.I) if not m: continue key = normalize_key(m.group(1)) self.store.upsert_fact(key, m.group(2).strip(), 0.5, ep.created_at) touched += 1 return touchedupsert_fact is where the interesting semantics live. On conflict it overwrites the value, increments mentions, and raises confidence by 0.15 capped at 0.95. Overwriting is the right default: a newer measurement of the same key is usually a better one, and keeping both would force the model to arbitrate between two numbers with no way to know which is fresher. The mentions counter is the evidence: one mention is an anecdote, three is a pattern, and confidence reflects that. The 0.95 cap exists so that a fact repeated a hundred times never becomes unfalsifiable — a new observation should always be able to displace it.
consolidate is deliberately dumb: a regex for key: value or key = value, restricted to observations. It runs offline, costs nothing, and cannot hallucinate. The extraction rate is the honest caveat — on free-form prose it will miss most facts. That is acceptable because the facts it does extract are verbatim substrings of real observations, and Part 5 brings a retriever that makes per-query reasoning unnecessary.
The context_block header is a small but real piece of engineering. cite as fact[key] or episode[id] makes the memory traceable to a row, and ignore if contradicted by new evidence prevents the failure where a stale fact outranks a fresh tool result simply because it was injected earlier in the prompt.
Injection order, and why it is a decorator
PrefixLLM rewrites the first system message. It has to run before the context budget measures, or the memory block will be appended after the budget has already decided the context fits — and the request overflows.
class PrefixLLM(LLMClient): """Injects a memory block into the system message before anything else sees it."""
def __init__(self, inner: LLMClient, prefix: str) -> None: self.inner = inner self.prefix = prefix
def complete(self, messages: list[Message], tools: list[dict]) -> dict: if not self.prefix: return self.inner.complete(messages, tools) patched = [ Message(role=m.role, content=m.content + "\n\n" + self.prefix, name=m.name) if m.role == "system" and i == 0 else m for i, m in enumerate(messages) ] return self.inner.complete(patched, tools)
class MemoryAgent: """One run = recall, inject, execute, write back. Memories never outlive the loop silently."""
def __init__(self, llm: LLMClient, tools: list, memory: AgentMemory, max_steps: int = 8) -> None: self.llm = llm self.tools = tools self.memory = memory self.max_steps = max_steps self.last_trace: list[dict] = []
def run(self, goal: str, run_id: str = "run") -> str: block = self.memory.context_block(goal) loop = AgentLoop(PrefixLLM(self.llm, block), self.tools, self.max_steps) answer = loop.run(goal) self.last_trace = loop.trace self.memory.record_run(run_id, goal, answer, len(loop.trace)) return answerThe full stack is MemoryAgent → PrefixLLM → BudgetedLLM → RetryingLLM → HTTPClient. Read that right to left: HTTP first, retries around it, budget around the retries, memory prefix outside the budget. A memory block that is injected after the budget has measured the context is invisible to the budget and overflows the window — the same ordering mistake from Part 3, one layer up.
MemoryAgent creates a fresh AgentLoop per run so that history never leaks between runs. Working memory should be exactly one run long; if you reuse the loop, you get a history that grows across questions and a budget that starts compressing before the second question is even asked.
Run it as demo_memory.py and the write policy is visible in the output:
from memory import AgentMemory, MemoryStore
def demo() -> None: store = MemoryStore(":memory:") memory = AgentMemory(store, clock=lambda: 1_700_000_000.0) memory.remember("r0", "Agent loop: repeats observe decide act over 3 phases", source="tool") memory.remember("r0", "token budget: cap input at 6000 tokens per call", source="tool") memory.remember("r0", "ok", source="tool") print("consolidated facts:", memory.consolidate()) print(memory.context_block("how does the agent loop work?")) print("episodes stored:", len(store.load_episodes()))
if __name__ == "__main__": demo()consolidated facts: 2MEMORY (cite as fact[key] or episode[id]; ignore if contradicted by new evidence):- fact[token budget]: cap input at 6000 tokens per call (confidence 0.50)- fact[agent loop]: repeats observe decide act over 3 phases (confidence 0.50)- episode[1]: Agent loop: repeats observe decide act over 3 phasesepisodes stored: 2Three observations offered, two stored. ok scored 0.4 and never reached the table. The recall block contains the fact and the episode that produced it, because both match the query — that redundancy is fine at two rows and becomes the problem consolidation and max_chars exist to bound.
Failure modes and how to handle them
| Failure | What actually happens | Handling here | Still broken |
|---|---|---|---|
| Every tool result stored | Table grows with steps, recall fills with noise | Importance gate drops anything under 0.5 | A verbose but worthless tool still scores 0.8 |
| Same sentence written every run | Duplicate rows crowd recall | dedupe_key UNIQUE + IntegrityError → False |
Collides on 80-char prefixes of templated logs |
| Stale fact overrides new evidence | Old value wins because it was injected first | Recency decay + confidence cap + header instruction | No contradiction detection; last write wins |
| Memory grows forever | Table scan slows recall | load_episodes(limit=500) bounds the scan |
Old rows never pruned; needs a retention job |
| Poisoned memory | A tool result containing instructions becomes a “fact” | Nothing — stored verbatim | Prompt-injection defence arrives in Part 11 |
| Empty recall | Model behaves as if nothing is known | context_block returns "", PrefixLLM passes through |
No signal to the model that memory was consulted |
| Clock skew or imported rows | Negative age inflates recency | max(0.0, ...) clamps age |
Rows from the future are trusted fully |
The poisoning row is the one that should worry you. A memory store is a persistence mechanism for text that a model will later read as instructions. Anything an untrusted tool returns can become a fact and be re-injected on every future run. Until Part 11 adds provenance and sanitisation, treat source="tool" memories as untrusted and keep the ignore if contradicted instruction — it is a mitigation, not a defence.
Trade-offs
| Decision | Alternative | Why we chose it | Cost |
|---|---|---|---|
| SQLite file | Vector database | One file, transactional, no service | No semantic search; lexical only |
| Lexical overlap scoring | Embedding similarity | Deterministic, zero cost, debuggable | Fails on paraphrase and synonyms |
| Importance gate at write time | Store everything, filter at read | Keeps the table small and the scan fast | A dropped observation is unrecoverable |
| Overwrite facts on conflict | Append-only fact history | Latest value is usually correct; simple reads | Cannot answer “what did we believe last week” |
| Regex consolidation | LLM extraction | Offline, free, cannot invent a fact | Low recall on free-form prose |
Fresh AgentLoop per run |
Reuse one loop | Working memory stays one run long | Rebuilds trace and specs per run |
| 14-day half-life | No decay | Bounds staleness for technical facts | Wrong for stable facts like schema definitions |
The half-life is the parameter most worth revisiting per domain. Fourteen days fits latency and pricing measurements; a schema or a product name is stable for a year, and decaying it is pure loss. The honest fix is a per-kind half-life rather than one global number, which is a ten-line change to Retriever and a good first exercise.
Testing it
Eleven tests, in-memory database, under 20 ms. These six cover the invariants:
import osimport tempfileimport unittest
from contracts import Message, ScriptedLLM, build_toolsfrom memory import ( AgentMemory, MemoryAgent, MemoryStore, PrefixLLM, WritePolicy, normalize_key, tokenize,)
DAY = 86400.0NOW = 1_700_000_000.0
def fresh(clock=NOW): store = MemoryStore(":memory:") return AgentMemory(store, clock=lambda: clock), store
class TestMemory(unittest.TestCase): def test_trivial_text_is_dropped(self): memory, store = fresh() self.assertFalse(memory.remember("r1", "ok", source="tool")) self.assertEqual(store.load_episodes(), [])
def test_duplicate_content_is_stored_once(self): memory, store = fresh() text = "Retries are allowed only for rate_limited, timeout and upstream_error codes." self.assertTrue(memory.remember("r1", text, source="tool")) self.assertFalse(memory.remember("r2", text, source="tool")) self.assertEqual(len(store.load_episodes()), 1)
def test_recent_episode_outranks_older_identical_one(self): store = MemoryStore(":memory:") old = AgentMemory(store, clock=lambda: NOW - 60 * DAY) old.remember("r0", "Search index latency is 240 ms at p95 on the local corpus.") new = AgentMemory(store, clock=lambda: NOW) new.remember("r1", "Search index latency is 190 ms at p95 on the local corpus.") hits = new.recall("search index latency", now=NOW) self.assertGreater(hits[0].created_at, hits[1].created_at)
def test_repeated_observation_becomes_a_fact(self): memory, store = fresh() memory.remember("r1", "embedding dims: 768 for the base model", source="tool") memory.remember("r2", "embedding dims: 1024 for the large model", source="tool") memory.consolidate() facts = store.load_facts() self.assertEqual(len(facts), 1) self.assertEqual(facts[0].key, "embedding dims") self.assertEqual(facts[0].mentions, 2) self.assertGreater(facts[0].confidence, 0.5)
def test_memory_survives_reopen(self): path = os.path.join(tempfile.mkdtemp(), "memory.db") first = MemoryStore(path) AgentMemory(first, clock=lambda: NOW).remember( "r1", "The corpus has 412 documents and 9 topic clusters.") first.close() second = MemoryStore(path) self.assertEqual(len(second.load_episodes()), 1) second.close()
def test_prefix_lands_in_system_message_only(self): seen = {}
class Capture(ScriptedLLM): def complete(self, messages, tools): seen["messages"] = list(messages) return {"type": "final", "content": "done"}
llm = PrefixLLM(Capture([]), "MEMORY: fact[loop] repeats") llm.complete([Message("system", "sys"), Message("user", "goal")], []) self.assertIn("MEMORY", seen["messages"][0].content) self.assertEqual(seen["messages"][1].content, "goal")
if __name__ == "__main__": unittest.main()test_memory_survives_reopen is the one that justifies the whole design. An in-memory dict passes every other test and fails this one, and persistence is the entire point — an agent that forgets on restart is just an expensive cache.
test_recent_episode_outranks_older_identical_one encodes the 60-day case: 0.5 ** (60/14) = 0.051, so the old episode keeps a relevance score but loses the recency bonus. If this test fails after you tune half_life_days, the failure is informative rather than mysterious.
Exercises
- Per-kind half-life. A
schemafact is stable for a year; alatencymeasurement is stale in a week. Addhalf_life_by_kindtoRetriever, fall back to the default, and write a test showing a 200-day-old schema fact outranks a 2-day-old latency fact for the same query. - Contradiction detection. Before
upsert_factoverwrites, compare the new value to the old one. If both contain numbers and differ by more than 20%, store the new value but record aconflictsrow with both timestamps. What shouldcontext_blockshow when a conflict exists? - Retention with value. Add a
prune(max_rows=5000)method that deletes the lowest-scoring episodes — score, not age — keeping anything referenced by a fact. Measure how recall precision changes on a 5,000-row table before and after, using a hand-labelled query set of ten questions.
Exercise 2 is the one that separates memory from a database: storing facts is easy, deciding which of two contradicting facts to believe is the actual problem.
What’s next
You now have an agent that remembers across runs. What it cannot do is find a passage in a large corpus: search is a five-entry dictionary from Part 1, and lexical recall only works on text the agent itself wrote.
Part 5, Building a RAG retriever, replaces that stub with real retrieval: chunking strategies and their effect on answer quality, hybrid recall that combines BM25 with embeddings, and a reranker that trades latency for precision. The MemoryStore schema stays; the search tool gets a backend, and the Retriever interface you just built is reused for passages instead of episodes.
Get Ball — Ball
Get Ball