New in Public Preview – PostgreSQL Support and TiDB Cloud Filesystem
Copy of Blog - Feature

Key Takeaways

  • Context compaction keeps an agent running when its window fills, but anything the summary leaves out drops out of the model’s active context unless another memory source holds it.
  • In the demo’s memory.md setup, the model decides what goes into the notes file, so a fact it never wrote down can’t be recovered from that file.
  • Saving every turn as a row in TiDB let the demo agent recover the lost launch date by pulling back 440 tokens instead of re-reading about 7,552.
  • Keyword and vector recall on the same table catch exact details like dates and questions phrased a new way.

Tell an AI agent your product ships on October 12, give it a few long tasks, then ask when you ship. There’s a good chance it no longer knows. Nothing broke when the date disappeared. It was summarized away.

That’s context compaction. Context compaction is what an agent does when its context window fills: it writes a short summary of older turns, keeps the most recent exchange, and drops the rest from the active context to make room. It keeps the conversation going, and it quietly decides which facts the model can still see.

A small open-source demo, tidb-agent-memory-demo on GitHub, makes this visible. It runs the same chat twice in your terminal, once with a typical memory setup and once with every turn stored in a TiDB table. This post walks through both runs, what the numbers show, and how to run it yourself.

What Is Context Compaction?

Context compaction is the step an LLM-based agent takes when its conversation history no longer fits in the model’s context window. The agent condenses older turns into a summary and drops the originals from the active context so there’s room for new input. Without it, a long session would simply stop.

The cost is what the summary leaves out. Summaries are written for the gist, so specific details (a date, an account number, a threshold someone mentioned once) can get left out. Once the originals leave the context, the model can’t tell what it lost unless it has another memory or history source to check.

A common safeguard is to pair compaction with a notes file the agent can write to. That’s the setup the demo tests first.

What an Agent Forgets When Its Context Window Fills

In the first run (python demo.py forget), the agent loses a launch date it was told directly, and neither its summary nor its notes file can bring it back. Here’s how that happens.

The Setup: A Small Window and a Notes File

The agent gets a deliberately small context window, 6,000 tokens, so compaction happens within a few messages instead of a few hours. Alongside it sits memory.md, a notes file where the agent writes down whatever it judges important.

The user, Maya, opens with her name and birthday (March 14). Next she says she’s a product manager prepping the Atlas launch, which ships on October 12. Then come two heavy requests: summarize a 30-page vendor report, and plan a three-day team offsite. Those replies are saved in full, about 3,890 and 3,190 tokens.

The chat is scripted, so every run is identical and you don’t need an LLM or an API key. The replies, the notes, the point where compaction happens, and the summary are all fixed, and the agent’s closing lines are templates. The long replies are saved in full in TiDB but shortened in the terminal output to keep it readable. The TiDB part is real: each message is inserted, TiDB embeds it on insert, and recall runs real vector and full-text queries against the table.

What Compaction Dropped

After the offsite reply, the chat has used 7,544 tokens of a 6,000-token window, so the agent compacts. It writes a short summary (“I prepped the Atlas launch; summarized the vendor report; planned the 3-day offsite.”), keeps the latest exchange word for word, and drops every older message from its context, including the one with the date.

The summary records the Atlas launch as a task. It doesn’t record the date.

Why the Notes File Didn’t Save It

The notes file survived compaction because it lives outside the context window. It holds a heading, Maya’s birthday, and her job title. The agent never wrote down the launch date, so neither the summary nor the notes file has it.

That’s the core limit of model-curated memory like memory.md: the agent decides what’s worth saving when it first hears something, before it knows what will matter later. When Maya asks, “Remind me, when do we ship Atlas?”, the agent checks its summary and notes, finds no date, and asks her for it again. A full transcript would still contain the date, but reading it back means pulling about 7,552 tokens into context for one question, if a transcript was kept at all.

How a TiDB Memory Table Changes the Outcome

The second run (python demo.py remember) keeps everything else the same: the same 6,000-token window, the same messages, and the same compaction. The agent’s context loses exactly what it lost in the first run. The difference is that every message also lives outside the context, in a table the agent can search.

Every Turn Becomes a Row

Saving a turn is a plain INSERT of the text into a TiDB table called agent_memory, and TiDB generates the embedding as part of the insert. There’s no judgment call: the agent doesn’t decide what to keep, so it can’t forget to keep something. Each row also records a rough token count, which the demo uses to show how much context each recall pulls back. The long replies are saved in full and only shortened in the terminal output, so the eight rows total about 7,544 tokens.

The same rows serve every kind of access the agent needs. SQL reads them as a session log, vector search matches them by meaning, and a BM25 full-text index matches them by exact words. That one table covers the jobs a typical build splits across a database, a cache, a vector store, and a search index.

How the Agent Recovered the Launch Date

When Maya asks the same question, the message with the date is gone from the context window, just as in the first run. This time the agent searches agent_memory. The demo runs two queries against the same rows, one by meaning and one by keyword, and merges the results with reciprocal rank fusion (RRF). Maya’s original message ranks first in both lists.

The top three rows total 440 tokens, including the full launch plan reply, and the agent answers October 12, quoting the stored sentence.

Then python demo.py recall starts a brand-new process with no conversation, no summary, and no notes. It returns the same rows, the same answer, and the same token ratio, because the memory lives in the table rather than the session.

What the Table Looks Like

This is the demo’s schema, from schema.sql in the repo. The embedding column is generated inside the database from content, so every row is searchable by meaning as soon as it’s inserted.

Before you run it: full-text search and auto embedding currently require TiDB Cloud Starter on AWS in a supported region: Oregon (us-west-2), N. Virginia (us-east-1), Tokyo (ap-northeast-1), Frankfurt (eu-central-1), or Singapore (ap-southeast-1). Check the current list of regions before you start. Vector search on TiDB Cloud is also currently available on Starter. To skip signup, python demo.py zero creates a disposable TiDB Cloud Zero database that expires after 30 days.

sql

CREATE TABLE IF NOT EXISTS agent_memory (
  id          BIGINT PRIMARY KEY AUTO_RANDOM,
  user_id     VARCHAR(64)  NOT NULL,
  session_id  VARCHAR(64)  NOT NULL,
  speaker     VARCHAR(16)  NOT NULL,          -- 'user' or 'agent'
  content     TEXT         NOT NULL,
  tokens      INT          NOT NULL,          -- rough estimate: characters / 4
  created_at  TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  embedding   VECTOR(1024) GENERATED ALWAYS AS (
                EMBED_TEXT('tidbcloud_free/amazon/titan-embed-text-v2', content)
              ) STORED,
  KEY idx_scope (user_id, session_id),
  VECTOR INDEX idx_embedding ((VEC_COSINE_DISTANCE(embedding))),
  FULLTEXT INDEX idx_content (content) WITH PARSER MULTILINGUAL
);

Recall runs these two queries and fuses the results:

sql

-- By meaning: TiDB embeds the question text itself
SELECT id, content,
      VEC_EMBED_COSINE_DISTANCE(embedding, 'Remind me, when do we ship Atlas?') AS distance
FROM agent_memory
WHERE user_id = 'maya' AND session_id = 'blog-demo'
ORDER BY distance
LIMIT 10;

-- By keyword (BM25)
SELECT id, content
FROM agent_memory
WHERE user_id = 'maya' AND session_id = 'blog-demo'
  AND fts_match_word('Remind me, when do we ship Atlas?', content)
ORDER BY fts_match_word('Remind me, when do we ship Atlas?', content) DESC
LIMIT 10;

Keyword recall matches “Atlas” exactly. Vector search catches the same fact when the question is phrased differently. Because the user and session filter sits in the same query as the vector ordering, TiDB computes exact distances over just that user’s rows instead of using the vector index. That’s correct and fast for one user’s memory. When a filter keeps a large share of a big table, use the vector index with filters: fetch the nearest rows first, then filter.

For a fuller build, see our guide to building an agent memory database on TiDB.

What the Demo Shows

The demo compares the two setups on four points. Both token figures come from the tokens column of the saved rows. The other two rows describe how the setups differ.

MeasureResult with one TiDB tableCompared with
Systems to run for agent memoryOne TiDB tableFour in a typical build: a database, a cache, a vector store, and a search index
Tokens to answer a recall question440 recalled tokensAbout 7,552 tokens, the eight saved rows plus the question, which the agent would have to re-read
Token reduction per answerAbout 94% fewer, roughly 17xRe-reading the full transcript on every question
Facts lost to compactionZeroThe Atlas launch date, kept by neither the summary nor the notes file

Read these as an illustration of the mechanism, not a benchmark for your workload. They come from one scripted conversation. Both sides use the same rough estimate (characters divided by four) on the text saved in TiDB. The eight saved rows total 7,544 tokens, and the question adds 8, for 7,552. Recall returned three rows totaling 440 tokens, including the full launch plan reply, so the ratio is about 17x. The dollar difference for your agent depends on your model’s pricing. The ratio also depends on which rows come back: here one of the three is the 402-token launch plan, and if a long reply like the vendor report ranked in the top results, recall could cost thousands of tokens.

Where the Four-Database Build Comes From

The usual way to give an agent memory is to assemble it from parts: a relational database for facts, a cache for recent turns, a vector store for search by meaning, and a search index for exact words. Each part is reasonable on its own. Together they create the memory wall, where every write has to reach several systems and every read has to stitch their answers back together.

The costs show up as sync lag, glue code, and four sets of credentials, backups, and access rules to maintain. A fact written a second ago may not be searchable yet. A message a user asked you to delete may linger in one of the indexes.

How to Apply the Pattern to Your Own Agent

A searchable memory table is a pattern you build on TiDB rather than a built-in feature. These practices follow directly from what the demo shows:

  • Log every turn automatically. Don’t ask the model to decide what to remember, because it can’t know what will matter later.
  • Let compaction manage the context window, and keep the originals in the table. The summary serves working memory, and the rows serve recall.
  • Recall with both keyword and vector search. Dates, IDs, and names need exact matches, and paraphrased questions need semantic ones. The demo merges the two with RRF, and the TiDB hybrid search docs show other ways to combine them in code.
  • Scope every recall query by user or tenant, so one person’s memory never reaches another person’s prompt.
  • Handle retention in the database. A TiDB TTL setting on created_at can expire old rows automatically. Deduplication and pruning still run as SQL jobs on whatever scheduler your app already uses.

Give Your Agent a Memory It Can Search

Context compaction will keep dropping details from context, because a summary can’t hold everything. When every original turn sits in a searchable table, a dropped detail is one query away instead of gone, and recalling it costs hundreds of tokens instead of thousands.

To see it yourself, clone tidb-agent-memory-demo on GitHub. After installing the requirements and connecting a database, the whole demo is five commands:

bash

python demo.py setup      # creates the table (safe to re-run)
python demo.py forget     # run 1: compaction loses the date
python demo.py remember   # run 2: TiDB recalls it
python demo.py recall     # new process, empty context: still recalled
python demo.py reset      # delete this demo's rows

To see which saved messages come back for a different question, pass your own, for example python demo.py recall “What date is Atlas shipping?”. TiDB runs the same hybrid search and prints how many tokens it read back. Only the default question gets a scripted answer line.

To build this for your own agents, see how TiDB supports persistent context for AI agents, with per-agent isolation and memory you can query in SQL.

Context Compaction and Agent Memory FAQs

What Is Context Compaction?

  • The step an agent takes when its conversation no longer fits in the model’s context window.
  • It summarizes older turns, keeps the latest exchange, and drops the originals from the active context.
  • It keeps long sessions running, but details the summary omits are no longer visible to the model.

Why Do AI Agents Forget What Users Told Them?

  • Compaction replaces original messages in the context with a summary that can miss specifics.
  • Model-curated notes files hold only what the model chose to write down.
  • New sessions start with an empty context window unless memory lives outside the model.

Is a memory.md Notes File Enough for Agent Memory?

  • It survives compaction because it lives outside the context window.
  • It holds only facts the model flagged as important when it first heard them.
  • In the demo, the launch date was never written down, so the notes file couldn’t recover it.

How Is Agent Memory Different From RAG?

  • RAG is a retrieval pattern: find relevant data and add it to the prompt.
  • The source is often a document collection, but it doesn’t have to be.
  • Agent memory is the data saved from the agent’s past conversations and actions.
  • Agent memory can use the same retrieval pattern to bring the right turns back when needed.

Do You Need a Separate Vector Database for Agent Memory?

  • Not necessarily. TiDB can store the text, embedding, and metadata for each turn in one table.
  • Vector search, full-text search, and SQL filters run against the same rows.
  • One system means one set of backups, access rules, and consistency guarantees.

Book a Demo


Experience modern data infrastructure firsthand.

Start for Free

Have questions? Let us know how we can help.

Contact Us

TiDB Cloud Dedicated

A fully-managed cloud DBaaS for predictable workloads

TiDB Cloud Starter

A fully-managed cloud DBaaS for auto-scaling workloads