agentic-flow icon indicating copy to clipboard operation
agentic-flow copied to clipboard

AgentDB persistence problem

Open wlwwt opened this issue 1 year ago • 9 comments

AgentDB runs as an MCP server and only stores the database temporarily in memory or in a temp directory. All data is lost each time Claude Code is restarted.

Already did this in .mcp.json "agentdb": { "command": "npx", "args": [ "agentdb@latest", "mcp", "start" ], "env": { "AGENTDB_PATH": "./agentdb/agentdb.db" }

But the database is not created in the project. after a claude code restart all learnings are gone. any idea?

Much appreciate

wlwwt avatar Nov 05 '25 22:11 wlwwt

I have the same issue. According to the code in the whole mcp flow the save() is never called.

stenebenau avatar Nov 30 '25 17:11 stenebenau

Taking a look

ruvnet avatar Dec 02 '25 14:12 ruvnet

Issue #48 - Root Cause Identified and Fixed ✅

Problem Analysis

The AgentDB MCP server was losing all data on restart because db.save() was never called during shutdown. @stenebenau was correct - the save mechanism exists but wasn't being triggered.

Root Cause

File: packages/agentdb/src/mcp/agentdb-mcp-server.ts (lines 2302-2309)

The shutdown handler only cleared intervals and exited immediately:

const shutdown = () => {
  clearInterval(keepAlive);
  process.exit(0);  // ❌ No db.save() call!
};

Even though:

  • ✅ AGENTDB_PATH environment variable was correctly read
  • ✅ db.save() method existed and worked in db-fallback.ts
  • ✅ The database path was properly configured

The data stayed in sql.js memory and was lost on process exit.

Solution Implemented

  1. Added periodic auto-save (every 5 minutes)
  2. Fixed shutdown handler to call db.save() before exit
  3. Added proper cleanup with db.close()
  4. Added error recovery for uncaught exceptions/rejections
  5. Enhanced logging for observability

Expected Behavior After Fix

When you restart Claude Code, you should see:

🔄 Shutting down AgentDB MCP Server...
💾 Saving database to ./agentdb/agentdb.db
✅ Database saved successfully
✅ Database connection closed

And your database file will be created at the path specified in AGENTDB_PATH.

Installation

The fix is now available in [email protected]:

# Update to latest alpha version
npm install -g agentdb@alpha

# Or use npx (auto-updates)
npx agentdb@alpha mcp start

Testing

To verify the fix works:

  1. Update agentdb to the latest alpha version
  2. Restart Claude Code
  3. Add some data via MCP tools (store episodes, skills, patterns)
  4. Press Ctrl+C or restart Claude Code
  5. Check logs for "Database saved successfully"
  6. Restart and verify data persists

You should see the database file created at your AGENTDB_PATH location, and data will persist across restarts.

Documentation

Full documentation available:

Auto-Save Feature

The fix includes automatic saving every 5 minutes during runtime, so even if the process crashes unexpectedly, you'll only lose at most 5 minutes of data.


@stenebenau Thanks for confirming the missing save() call - you were absolutely right!

Please test the fix and let me know if persistence works correctly now. The database should be created at the path you specified in your .mcp.json configuration.

ruvnet avatar Dec 02 '25 15:12 ruvnet

@ruvnet - Thanks for solving this problem. That's absolutely what I needed. I really would love to add the agentdb to my local project as an MCP server. but still with using the latest version It does not create the agentdb.db on the local file system.

That's my configuration in .mcp.json

"agentdb": {
      "command": "npx",
      "args": [
        "agentdb@latest",
        "mcp",
        "start"
      ],
      "env": {
        "AGENTDB_PATH": "./.claude/agentdb.db"
      }
    }

But when starting claude code and using the agentdb_init, it uses a different path. Image

But also at this path there is no database file. Any idea?

wlwwt avatar Dec 02 '25 16:12 wlwwt

@wlwwt The fix is only available in the alpha version, not in @latest. You're currently using agentdb@latest which is version 1.6.1 (without the fix).

Solution: Update to Alpha Version

Change your .mcp.json configuration to use the alpha tag:

"agentdb": {
  "command": "npx",
  "args": [
    "agentdb@alpha",  // ✅ Changed from @latest to @alpha
    "mcp",
    "start"
  ],
  "env": {
    "AGENTDB_PATH": "./.claude/agentdb.db"
  }
}

Why This Matters

  • agentdb@latest = 1.6.1 (stable, but has the persistence bug)
  • agentdb@alpha = 2.0.0-alpha.2.12 (alpha, with persistence fix)

After Updating

  1. Restart Claude Code to reload the MCP configuration
  2. When you run MCP tools, you should see:
    • 💾 Auto-saved database to ./.claude/agentdb.db (every 5 minutes)
    • On shutdown: ✅ Database saved successfully
  3. Verify the file exists: ls -la ./.claude/agentdb.db

About agentdb_init

The path shown in agentdb_init is the runtime working directory. The actual database path is controlled by AGENTDB_PATH environment variable. With the alpha version:

  • It will create the .claude directory if it doesn't exist
  • It will save the database to ./.claude/agentdb.db
  • You'll see confirmation logs when it saves

Verification Steps

After changing to @alpha:

# 1. Check which version is being used
npx agentdb@alpha --version
# Should show: 2.0.0-alpha.2.12

# 2. After Claude Code restart, check logs for:
# 🚀 AgentDB MCP Server v2.0.0 running on stdio
# (Look for v2.0.0, not v1.x)

# 3. Use some MCP tools, then check:
ls -la ./.claude/
# Should show agentdb.db file

# 4. Wait 5 minutes or restart Claude Code
# Should see: ✅ Database saved successfully

Let me know if you still have issues after switching to the alpha version!

ruvnet avatar Dec 02 '25 16:12 ruvnet

Perfect! Thank you for fixing, will test it the coming days. I'm not using Claude but OpenCode where i don't know how the mcp shutdown is handled. So is a database_persist mcp tool not a usefull addition so you can trigger it manually.

stenebenau avatar Dec 02 '25 18:12 stenebenau

@ruvnet my mistake. Didn't see i had to use alpha. Still kinda buggy in MacOS, but got it working. Pretty excited how this will improve my workflow :)

wlwwt avatar Dec 02 '25 19:12 wlwwt

Hmm, thought it would work now, but still seems to use the temporary database and not the locally created file. So file is created, but is not used.

⏺ I'll help you initialize AgentDB, verify the database creation, add a test entry, and verify the entries. Let me do this step by step.

⏺ agentdb - agentdb_init (MCP)(db_path: "./agentdb.db", reset: false) ⎿  ✅ AgentDB initialized successfully!
📍 Database: ./agentdb.db 📊 Tables created: 15 … +2 lines (ctrl+o to expand)

⏺ Great! Now let's check the database statistics to verify it was created properly:

⏺ agentdb - agentdb_stats (MCP)(detailed: true) ⎿  📊 AgentDB Comprehensive Statistics

 🧠 Memory & Learning:
 … +16 lines (ctrl+o to expand)

⏺ Perfect! The database is initialized. Now let's add a test entry:

⏺ agentdb - agentdb_insert (MCP)(text: "This is a test entry to verify AgentDB functionality in the project. The database initialization was successful.", session_id: "test-session-001", tags: ["test","ecommerce","initialization"], metadata: {"project":"ecommerce-test","purpose":"database verification","timestamp":"2025-12-02"}) ⎿  ✅ Vector inserted successfully!
🆔 ID: 1 📝 Text: This is a test entry to verify AgentDB functionality in the ecommerce project. The database initial... … +2 lines (ctrl+o to expand)

⏺ Excellent! Now let's verify the entry was created by checking the statistics again:

⏺ agentdb - agentdb_stats (MCP)(detailed: true) ⎿  📊 AgentDB Comprehensive Statistics

 🧠 Memory & Learning:
 … +19 lines (ctrl+o to expand)

⏺ Let me search for the test entry to verify it was stored correctly:

⏺ agentdb - agentdb_search (MCP)(query: "test entry AgentDB functionality Shopware", k: 5, min_similarity: 0) ⎿  🔍 Search completed!
📊 Found: 1 results 🎯 Query: test entry AgentDB functionality Shopware … +5 lines (ctrl+o to expand)

⏺ Perfect! Let me also check the database file directly to confirm it exists:

⏺ Bash(ls -lh agentdb.db) ⎿  -rw-r--r--@ 1 wlwwt staff 0B Dec 2 20:31 agentdb.db

⏺ I notice the file shows 0B. Let me check with sqlite3 to inspect the actual database:

⏺ Bash(sqlite3 agentdb.db ".tables") ⎿  Error: Exit code 1 Error: file is not a database

⏺ The local agentdb.db appears to be empty.

@ruvnet - any idea on this? Much appreciate

wlwwt avatar Dec 02 '25 19:12 wlwwt

Follow-up: Deeper persistence gap in reflexion.storeEpisode()

Hey @ruvnet — thanks for the shutdown save fix, that solved the sql.js flush-to-disk problem. While building a production learning pipeline on top of AgentDB v3.0.0-alpha.10 (ruvector backend, 384-dim), we discovered a second layer of the persistence issue that the save() fix doesn't cover.

What we found

reflexion.storeEpisode() writes to the in-memory HNSW vector index only. It does NOT insert rows into the episodes or episode_embeddings SQLite tables — even though those tables exist with the correct schema.

This means:

  1. db.save() correctly flushes the SQLite file to disk ✅
  2. But the episodes table is empty because storeEpisode never issued an INSERT ❌
  3. On restart, HNSW is rebuilt from an empty table → all episodes gone

Quick repro

const { AgentDB } = await import('agentdb');
const db = new AgentDB({ path: './test.db', vectorBackend: 'ruvector', dimensions: 384 });
await db.initialize();

await db.reflexion.storeEpisode({
  sessionId: 'test-1', task: 'test task', reward: 0.8,
  success: true, input: 'test', output: 'result'
});

// Check SQLite directly:
const Database = require('better-sqlite3');
const raw = new Database('./test.db', { readonly: true });
console.log(raw.prepare('SELECT COUNT(*) as c FROM episodes').get());
// → { c: 0 }  ← should be 1
raw.close();

Our workaround

We dual-write: call storeEpisode() for in-memory HNSW, then INSERT directly into episodes + episode_embeddings via better-sqlite3, generating embeddings with @xenova/transformers (all-MiniLM-L6-v2, 384-dim). On server startup, we rebuild HNSW from the SQLite tables. This has been running reliably with 86+ episodes in a permit intelligence pipeline.

Scope

Filing a separate issue (#128 or similar) with full details since this is a distinct root cause from the original #48. Just wanted to link back here since users following this thread may still hit this.

PogeystickJoe avatar Mar 13 '26 16:03 PogeystickJoe