Skip to content

memory-lancedb: isolate per-agent lancedb by agentId - #63726

Closed
LiChao-cy wants to merge 1 commit into
openclaw:mainfrom
LiChao-cy:dev_memory_agent_isolation
Closed

LiChao-cy wants to merge 1 commit into
openclaw:mainfrom
LiChao-cy:dev_memory_agent_isolation

Conversation

@LiChao-cy

@LiChao-cy LiChao-cy commented Apr 9, 2026 •

Copy link
Copy Markdown

Summary

  • Problem: In the memory-lancedb plugin, all configured agents in a single openclaw instance share one LanceDB instance. When multiple agents are defined via agents.list, agent A's stored memories are recalled by agent B, leaking context across agents.
  • Why it matters: Any user who runs two or more agents (e.g., a customer-facing Telegram bot and an internal Discord assistant) within one openclaw instance will have their agents' memories contaminated by each other silently — the model receives irrelevant context without any warning.
  • What changed: Replaced the single MemoryDB instance with a Map<string, MemoryDB> keyed by agentId. Each agent now gets an isolated subdirectory <dbPath>/<agentId>/. All three tools (memory_recall, memory_store, memory_forget) and both lifecycle hooks
    (before_agent_start, agent_end) are migrated to OpenClawPluginToolFactory so ctx.agentId is available at execution time.
  • What did NOT change: Single-agent installs (no agents.list) are fully backward compatible — when agentId is absent, the original dbPath is used unchanged. CLI commands (ltm list/search/stats) also fall back to the root path.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause (if applicable)

  • Root cause: The register() function constructed a single new MemoryDB(resolvedDbPath, vectorDim) at plugin load time and captured it in closure. All tool execute callbacks and lifecycle hooks referenced this shared instance regardless of which agent triggered
    them. The old AnyAgentTool pattern used by the tools had no access to agentId at call time; OpenClawPluginToolFactory was available but not used.
  • Missing detection / guardrail: No test existed for multi-agent DB isolation at the plugin level.
  • Contributing context: DEFAULT_AGENT_ID = "main" means single-agent users are never affected, which masked the bug in practice.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: extensions/memory-lancedb/index.test.ts
  • Scenario the test should lock in: Tools with different agentIds must call lancedb.connect() with distinct paths; same agentId must reuse a single instance; missing agentId must fall back to the root dbPath exactly.
  • Why this is the smallest reliable guardrail: The lancedb.connect call is the boundary — mocking it and asserting the path argument is sufficient to verify isolation without requiring a real LanceDB installation.
  • Existing test that already covers this: None — added 4 new tests in the per-agent memory isolation describe block.
  • If no new test is added, why not: N/A — tests were added.

User-visible / Behavior Changes

  • Users with a single agent (the majority): no change. DB path is identical to before.
  • Users with multiple agents configured (agents.list): each agent now writes to and reads from <dbPath>/<agentId>/ instead of the shared root. Existing memories in the root are not migrated automatically — users upgrading with a multi-agent setup should be
    aware their pre-existing data remains in the root path and is no longer visible to named agents.

Diagram (if applicable)

Before:
[agent-a recall] -> lancedb.connect(<dbPath>)  ← shared
[agent-b recall] -> lancedb.connect(<dbPath>)  ← shared                                                                                                                                                                                                                          
 
After:                                                                                                                                                                                                                                                                           
[agent-a recall] -> lancedb.connect(<dbPath>/agent-a/)  ← isolated
[agent-b recall] -> lancedb.connect(<dbPath>/agent-b/)  ← isolated                                                                                                                                                                                                               
[CLI / no agentId] -> lancedb.connect(<dbPath>)          ← backward compat                                                                                                                                                                                                       
 
Security Impact (required)                                                                                                                                                                                                                                                       
                                                          
- New permissions/capabilities? No                                                                                                                                                                                                                                               
- Secrets/tokens handling changed? No
- New/changed network calls? No                                                                                                                                                                                                                                                  
- Command/tool execution surface changed? No              
- Data access scope changed? Yes — agents that previously could read each other's memories can no longer do so. This is a reduction in data access scope and is intentional. No new cross-agent data access is introduced.                                                       
                                                                                                                                                                                                                                                                                 
Repro + Verification                                                                                                                                                                                                                                                             
                                                                                                                                                                                                                                                                                 
Environment                                                                                                                                                                                                                                                                      
 
- OS: Linux                                                                                                                                                                                                                                                                      
- Runtime/container: Node 22 / Bun                        
- Model/provider: any
- Integration/channel: any (bug is at the storage layer)
- Relevant config: agents.list with two or more agents, both with memory-lancedb enabled
                                                                                                                                                                                                                                                                                 
Steps
                                                                                                                                                                                                                                                                                 
1. Configure two agents (id: work, id: personal) in openclaw.yaml, both using memory-lancedb.                                                                                                                                                                                    
2. With agent work, store a memory: memory_store("My work API key prefix is sk-work").
3. Switch to agent personal and recall: memory_recall("API key").                                                                                                                                                                                                                
                                                          
Expected                                                                                                                                                                                                                                                                         
                                                          
- Agent personal finds no results (isolated DB).

Actual (before fix)

- Agent personal recalls the work API key memory — cross-agent leak.                                                                                                                                                                                                             
 
Evidence                                                                                                                                                                                                                                                                         
                                                          
- Failing test/log before + passing after — 4 new unit tests in index.test.ts (20/20 pass)

Human Verification (required)                                                                                                                                                                                                                                                    
 
- Verified scenarios: Single-agent fallback path (no agentId) produces the original dbPath unchanged; two distinct agentId values produce two distinct connect paths; same agentId called twice reuses one MemoryDB instance (no duplicate connections).                         
- Edge cases checked: agentId = undefined, agentId = "" (both map to root path key ""); before_agent_start hook with and without ctx.
- What you did not verify: Live multi-agent end-to-end with a real LanceDB installation; data migration path for existing multi-agent deployments.                                                                                                                               
                                                                                                                                                                                                                                                                                 
Review Conversations                                                                                                                                                                                                                                                             
                                                                                                                                                                                                                                                                                 
- I replied to or resolved every bot review conversation I addressed in this PR.
- I left unresolved only the conversations that still need reviewer or maintainer judgment.
                                                                                                                                                                                                                                                                                 
Compatibility / Migration
                                                                                                                                                                                                                                                                                 
- Backward compatible? Yes — single-agent users see no change. Multi-agent users will have isolated DBs going forward; pre-existing data in the shared root is not auto-migrated (documented above). 

@openclaw-barnacle openclaw-barnacle Bot added extensions: memory-lancedb Extension: memory-lancedb size: M labels Apr 9, 2026
@greptile-apps

greptile-apps Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes cross-agent memory contamination in memory-lancedb by replacing the single shared MemoryDB instance with a Map<string, MemoryDB> keyed by agentId, giving each agent an isolated subdirectory <dbPath>/<agentId>/. Single-agent installs are unaffected because an absent agentId falls back to the original resolvedDbPath. All three tools and both lifecycle hooks are migrated to the OpenClawPluginToolFactory pattern to carry ctx.agentId at execution time, and four targeted unit tests lock in the isolation contract.

Confidence Score: 5/5

Safe to merge; the isolation logic is correct and backward compatible.

All findings are P2: path sanitization for agentId and missing cleanup of dbMap on service stop. Neither blocks correctness for normal usage. The core fix is clean, the backward-compat fallback is correctly handled, and the new tests provide meaningful coverage of the isolation contract.

extensions/memory-lancedb/index.ts — getAgentDb path construction and service stop handler.

Vulnerabilities

  • agentId is passed directly to path.join without validation; a value containing .. segments could resolve outside resolvedDbPath. Risk is limited to operator-controlled config, but defensive sanitization is recommended (extensions/memory-lancedb/index.ts, getAgentDb).
  • No new network calls, no secrets handling changes, no new permissions introduced.

Comments Outside Diff (1)

  1. extensions/memory-lancedb/index.ts, line 685-688 (link)

    P2 dbMap and open LanceDB connections not cleaned up on service stop

    Each MemoryDB in dbMap holds a LanceDB.Connection that is never explicitly closed. With the new per-agent map this concern multiplies: a long-running gateway with many agents will accumulate open connections that are never released when the service is stopped. The stop handler currently only logs.

    Consider clearing dbMap (and optionally closing each connection if the LanceDB API exposes a close() method) in the stop callback:

    stop: () => {
      dbMap.clear();
      api.logger.info("memory-lancedb: stopped");
    },
    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: extensions/memory-lancedb/index.ts
    Line: 685-688
    
    Comment:
    **`dbMap` and open LanceDB connections not cleaned up on service stop**
    
    Each `MemoryDB` in `dbMap` holds a `LanceDB.Connection` that is never explicitly closed. With the new per-agent map this concern multiplies: a long-running gateway with many agents will accumulate open connections that are never released when the service is stopped. The `stop` handler currently only logs.
    
    Consider clearing `dbMap` (and optionally closing each connection if the LanceDB API exposes a `close()` method) in the `stop` callback:
    
    ```ts
    stop: () => {
      dbMap.clear();
      api.logger.info("memory-lancedb: stopped");
    },
    ```
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/memory-lancedb/index.ts
Line: 307

Comment:
**Unsanitized `agentId` used as path component**

`agentId` is passed directly to `path.join`, so a value containing `..` segments (e.g. `"../other"`) would silently produce a DB path that escapes `resolvedDbPath`. `path.join("/base/db", "../evil")` resolves to `/base/evil`. Because `agentId` comes from the operator's config file the attack surface is low, but defensive validation is still worth adding.

```suggestion
        const agentDbPath = agentId ? join(resolvedDbPath, agentId.replace(/[/\\]/g, "_").replace(/\.\./g, "_")) : resolvedDbPath;
```

Alternatively, reject any `agentId` that contains path-separator or `..` characters and surface a clear error at registration time.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: extensions/memory-lancedb/index.ts
Line: 685-688

Comment:
**`dbMap` and open LanceDB connections not cleaned up on service stop**

Each `MemoryDB` in `dbMap` holds a `LanceDB.Connection` that is never explicitly closed. With the new per-agent map this concern multiplies: a long-running gateway with many agents will accumulate open connections that are never released when the service is stopped. The `stop` handler currently only logs.

Consider clearing `dbMap` (and optionally closing each connection if the LanceDB API exposes a `close()` method) in the `stop` callback:

```ts
stop: () => {
  dbMap.clear();
  api.logger.info("memory-lancedb: stopped");
},
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "memory-lancedb: isolate per-agent DB by ..." | Re-trigger Greptile

function getAgentDb(agentId: string | undefined): MemoryDB {
const key = agentId ?? "";
if (!dbMap.has(key)) {
const agentDbPath = agentId ? join(resolvedDbPath, agentId) : resolvedDbPath;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 security Unsanitized agentId used as path component

agentId is passed directly to path.join, so a value containing .. segments (e.g. "../other") would silently produce a DB path that escapes resolvedDbPath. path.join("/base/db", "../evil") resolves to /base/evil. Because agentId comes from the operator's config file the attack surface is low, but defensive validation is still worth adding.

Suggested change
const agentDbPath = agentId ? join(resolvedDbPath, agentId) : resolvedDbPath;
const agentDbPath = agentId ? join(resolvedDbPath, agentId.replace(/[/\\]/g, "_").replace(/\.\./g, "_")) : resolvedDbPath;

Alternatively, reject any agentId that contains path-separator or .. characters and surface a clear error at registration time.

Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/memory-lancedb/index.ts
Line: 307

Comment:
**Unsanitized `agentId` used as path component**

`agentId` is passed directly to `path.join`, so a value containing `..` segments (e.g. `"../other"`) would silently produce a DB path that escapes `resolvedDbPath`. `path.join("/base/db", "../evil")` resolves to `/base/evil`. Because `agentId` comes from the operator's config file the attack surface is low, but defensive validation is still worth adding.

```suggestion
        const agentDbPath = agentId ? join(resolvedDbPath, agentId.replace(/[/\\]/g, "_").replace(/\.\./g, "_")) : resolvedDbPath;
```

Alternatively, reject any `agentId` that contains path-separator or `..` characters and surface a clear error at registration time.

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ee677bc305

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +305 to +307
const key = agentId ?? "";
if (!dbMap.has(key)) {
const agentDbPath = agentId ? join(resolvedDbPath, agentId) : resolvedDbPath;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve root DB path for default single-agent runs

This logic routes any truthy agentId into a subdirectory, but runtime tool contexts always include an agent id (defaulting to "main" even when agents.list is unset). resolveOpenClawPluginToolInputs sets context.agentId from resolveSessionAgentId, and that resolver falls back to main by default, so single-agent runs now use <dbPath>/main instead of the historical root <dbPath>. As a result, existing single-agent memories become invisible after upgrade, which is a backwards-compatibility regression introduced by this commit.

Useful? React with 👍 / 👎.

@clawsweeper

clawsweeper Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Closing this as duplicate or superseded after Codex automated review.

Close PR #63726 as duplicate/superseded by the earlier open memory-lancedb agent-scoping implementation track in PR #40578. Current main still has the shared LanceDB memory behavior, so this is not implemented-on-main; the remaining fix and review should be consolidated on the canonical PR.

Best possible solution:

Close #63726 as duplicate/superseded and keep memory-lancedb agent isolation work consolidated on PR #40578. The eventual fix should scope recall/store/forget and auto hooks by agent, preserve legacy single-agent root DB behavior, validate or normalize agent IDs before storage/filter use, add regression tests for multi-agent isolation and default-agent compatibility, and update plugin config docs/changelog if a user-visible option or migration is introduced.

What I checked:

  • Current main still uses one shared MemoryDB: register() creates a single MemoryDB from resolvedDbPath, and MemoryEntry has no agentId field, so the stored rows have no agent namespace on current main. (extensions/memory-lancedb/index.ts:312, d54d2d6b9b8a)
  • Tools and hooks close over the same shared DB: memory_recall searches the shared db, and auto-recall in before_prompt_build also searches the same db; store/forget/auto-capture use the same captured instance too. (extensions/memory-lancedb/index.ts:363, d54d2d6b9b8a)
  • No current memory-lancedb agent-scoping config: memoryConfigSchema allows memory-lancedb keys for embedding, dbPath, autoCapture, autoRecall, captureMaxChars, and storageOptions, but no agentScoping or equivalent current-main setting exists. (extensions/memory-lancedb/config.ts:100, d54d2d6b9b8a)
  • Plugin API has the needed agent context seam: The current plugin tool context includes agentId, and resolveOpenClawPluginToolInputs() always resolves and passes agentId: sessionAgentId, so the fix can be implemented through existing plugin tool factory/context APIs. (src/agents/openclaw-tools.plugin-context.ts:33, d54d2d6b9b8a)
  • Canonical related PR is earlier and still the same implementation track: Provided GitHub context identifies PR Feature(memory-lancedb): Agent Scoping #38797 #40578 (Feature(memory-lancedb): Agent Scoping #38797) as open/draft and targeting the same memory-lancedb cross-agent memory contamination problem with an opt-in agentScoping config and migration path. git ls-remote also confirms the referenced PR head SHA exists. (5cf0acbfb35d)
  • This PR has unresolved correctness feedback: The provided PR review discussion flags that PR memory-lancedb: isolate per-agent lancedb by agentId #63726's subdirectory-by-agentId approach can route default single-agent runtime contexts from the historical root DB into <dbPath>/main, and Greptile also flagged direct agentId path use plus DB-map cleanup concerns. (extensions/memory-lancedb/index.ts:307, ee677bc30552)

So I’m closing this here and keeping the remaining discussion on the canonical linked item.

Codex Review notes: model gpt-5.5, reasoning high; reviewed against d54d2d6b9b8a.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: memory-lancedb Extension: memory-lancedb size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

memory-lancedb: Add agent-level namespace isolation

1 participant