Skip to content

Commit ee677bc

Browse files
author
lichao
committed
memory-lancedb: isolate per-agent DB by agentId
1 parent 5dbf607 commit ee677bc

2 files changed

Lines changed: 295 additions & 34 deletions

File tree

‎extensions/memory-lancedb/index.test.ts‎

Lines changed: 239 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,9 @@ describe("memory plugin e2e", () => {
246246
debug: vi.fn(),
247247
},
248248
registerTool: (tool: any, opts: any) => {
249-
registeredTools.push({ tool, opts });
249+
// Tools are registered as OpenClawPluginToolFactory functions; resolve with a mock context.
250+
const resolved = typeof tool === "function" ? tool({ agentId: undefined }) : tool;
251+
registeredTools.push({ tool: resolved, opts });
250252
},
251253
registerCli: vi.fn(),
252254
registerService: vi.fn(),
@@ -330,6 +332,242 @@ describe("memory plugin e2e", () => {
330332
});
331333
});
332334

335+
describe("per-agent memory isolation", () => {
336+
const { getDbPath } = installTmpDirHarness({ prefix: "openclaw-memory-isolation-test-" });
337+
338+
/**
339+
* Returns a lancedb connect mock plus a minimal table stub.
340+
* Each connect() call returns the same stub so we can focus on
341+
* how many times connect was called and with which paths.
342+
*/
343+
function buildLanceDbMocks() {
344+
const openTable = vi.fn(async () => ({
345+
vectorSearch: vi.fn(() => ({
346+
limit: vi.fn(() => ({ toArray: vi.fn(async () => []) })),
347+
})),
348+
countRows: vi.fn(async () => 0),
349+
add: vi.fn(async () => undefined),
350+
delete: vi.fn(async () => undefined),
351+
}));
352+
const connect = vi.fn(async (_dbPath: string) => ({
353+
tableNames: vi.fn(async () => ["memories"]),
354+
openTable,
355+
}));
356+
return { connect, openTable };
357+
}
358+
359+
function buildMockApi(overrides: {
360+
dbPath: string;
361+
autoRecall?: boolean;
362+
autoCapture?: boolean;
363+
}) {
364+
const hookHandlers = new Map<string, (...args: unknown[]) => unknown>();
365+
const factories: Array<{ factory: unknown; opts: unknown }> = [];
366+
const mockApi = {
367+
id: "memory-lancedb",
368+
pluginConfig: {
369+
embedding: { apiKey: "test-key", model: "text-embedding-3-small" },
370+
dbPath: overrides.dbPath,
371+
autoCapture: overrides.autoCapture ?? false,
372+
autoRecall: overrides.autoRecall ?? false,
373+
},
374+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
375+
registerTool: (tool: unknown, opts: unknown) => {
376+
factories.push({ factory: tool, opts });
377+
},
378+
registerCli: vi.fn(),
379+
registerService: vi.fn(),
380+
on: (eventName: string, handler: (...args: unknown[]) => unknown) => {
381+
hookHandlers.set(eventName, handler);
382+
},
383+
resolvePath: (p: string) => p,
384+
};
385+
return { mockApi, hookHandlers, factories };
386+
}
387+
388+
test("tools with different agentIds connect to separate DB subdirectories", async () => {
389+
const { connect } = buildLanceDbMocks();
390+
vi.resetModules();
391+
vi.doMock("openclaw/plugin-sdk/runtime-env", () => ({
392+
ensureGlobalUndiciEnvProxyDispatcher: vi.fn(),
393+
}));
394+
vi.doMock("openai", () => ({
395+
default: class MockOpenAI {
396+
embeddings = { create: vi.fn(async () => ({ data: [{ embedding: [0.1, 0.2] }] })) };
397+
},
398+
}));
399+
vi.doMock("./lancedb-runtime.js", () => ({
400+
loadLanceDbModule: vi.fn(async () => ({ connect })),
401+
}));
402+
403+
try {
404+
const { default: plugin } = await import("./index.js");
405+
const baseDbPath = getDbPath();
406+
const { mockApi, factories } = buildMockApi({ dbPath: baseDbPath });
407+
408+
plugin.register(mockApi as never);
409+
410+
// Call the memory_recall factory with three different contexts
411+
const recallFactory = factories.find(
412+
(f) => (f.opts as { name?: string })?.name === "memory_recall",
413+
)!.factory as (ctx: { agentId?: string }) => {
414+
execute: (...a: unknown[]) => Promise<unknown>;
415+
};
416+
const toolA = recallFactory({ agentId: "agent-a" });
417+
const toolB = recallFactory({ agentId: "agent-b" });
418+
const toolLegacy = recallFactory({ agentId: undefined });
419+
420+
// Execute each to trigger DB initialization
421+
await toolA.execute("call-a", { query: "test" });
422+
await toolB.execute("call-b", { query: "test" });
423+
await toolLegacy.execute("call-legacy", { query: "test" });
424+
425+
const calledPaths = connect.mock.calls.map((c) => c[0]);
426+
expect(calledPaths).toHaveLength(3);
427+
428+
// Each agent gets a subdirectory; no-agentId falls back to the root dbPath
429+
expect(calledPaths.some((p) => p.endsWith("agent-a"))).toBe(true);
430+
expect(calledPaths.some((p) => p.endsWith("agent-b"))).toBe(true);
431+
expect(calledPaths.some((p) => p === baseDbPath)).toBe(true);
432+
433+
// All three paths are distinct
434+
expect(new Set(calledPaths).size).toBe(3);
435+
} finally {
436+
vi.doUnmock("openclaw/plugin-sdk/runtime-env");
437+
vi.doUnmock("openai");
438+
vi.doUnmock("./lancedb-runtime.js");
439+
vi.resetModules();
440+
}
441+
});
442+
443+
test("same agentId reuses a single DB instance across tool types", async () => {
444+
const { connect } = buildLanceDbMocks();
445+
vi.resetModules();
446+
vi.doMock("openclaw/plugin-sdk/runtime-env", () => ({
447+
ensureGlobalUndiciEnvProxyDispatcher: vi.fn(),
448+
}));
449+
vi.doMock("openai", () => ({
450+
default: class MockOpenAI {
451+
embeddings = { create: vi.fn(async () => ({ data: [{ embedding: [0.1, 0.2] }] })) };
452+
},
453+
}));
454+
vi.doMock("./lancedb-runtime.js", () => ({
455+
loadLanceDbModule: vi.fn(async () => ({ connect })),
456+
}));
457+
458+
try {
459+
const { default: plugin } = await import("./index.js");
460+
const { mockApi, factories } = buildMockApi({ dbPath: getDbPath() });
461+
462+
plugin.register(mockApi as never);
463+
464+
type ToolLike = { execute: (...a: unknown[]) => Promise<unknown> };
465+
type Factory = (ctx: { agentId?: string }) => ToolLike;
466+
const getFactory = (name: string) =>
467+
factories.find((f) => (f.opts as { name?: string })?.name === name)!.factory as Factory;
468+
469+
// Two different tool types, same agentId
470+
const recallTool = getFactory("memory_recall")({ agentId: "shared-agent" });
471+
const storeTool = getFactory("memory_store")({ agentId: "shared-agent" });
472+
473+
await recallTool.execute("r", { query: "test" });
474+
await storeTool.execute("s", {
475+
text: "I prefer TypeScript",
476+
importance: 0.8,
477+
category: "preference",
478+
});
479+
480+
// Only one connect call: both tools share the same MemoryDB instance
481+
expect(connect).toHaveBeenCalledTimes(1);
482+
expect(connect.mock.calls[0][0]).toMatch(/shared-agent$/);
483+
} finally {
484+
vi.doUnmock("openclaw/plugin-sdk/runtime-env");
485+
vi.doUnmock("openai");
486+
vi.doUnmock("./lancedb-runtime.js");
487+
vi.resetModules();
488+
}
489+
});
490+
491+
test("before_agent_start hook connects to agent-specific DB path", async () => {
492+
const { connect } = buildLanceDbMocks();
493+
vi.resetModules();
494+
vi.doMock("openclaw/plugin-sdk/runtime-env", () => ({
495+
ensureGlobalUndiciEnvProxyDispatcher: vi.fn(),
496+
}));
497+
vi.doMock("openai", () => ({
498+
default: class MockOpenAI {
499+
embeddings = { create: vi.fn(async () => ({ data: [{ embedding: [0.1, 0.2] }] })) };
500+
},
501+
}));
502+
vi.doMock("./lancedb-runtime.js", () => ({
503+
loadLanceDbModule: vi.fn(async () => ({ connect })),
504+
}));
505+
506+
try {
507+
const { default: plugin } = await import("./index.js");
508+
const { mockApi, hookHandlers } = buildMockApi({
509+
dbPath: getDbPath(),
510+
autoRecall: true,
511+
});
512+
513+
plugin.register(mockApi as never);
514+
515+
const hook = hookHandlers.get("before_agent_start")!;
516+
// Fire the hook for two agents
517+
await hook({ prompt: "what do I prefer?" }, { agentId: "hook-agent-1" });
518+
await hook({ prompt: "what do I prefer?" }, { agentId: "hook-agent-2" });
519+
520+
const calledPaths = connect.mock.calls.map((c) => c[0]);
521+
expect(calledPaths.some((p) => p.endsWith("hook-agent-1"))).toBe(true);
522+
expect(calledPaths.some((p) => p.endsWith("hook-agent-2"))).toBe(true);
523+
} finally {
524+
vi.doUnmock("openclaw/plugin-sdk/runtime-env");
525+
vi.doUnmock("openai");
526+
vi.doUnmock("./lancedb-runtime.js");
527+
vi.resetModules();
528+
}
529+
});
530+
531+
test("no agentId falls back to root dbPath (backward compat)", async () => {
532+
const { connect } = buildLanceDbMocks();
533+
vi.resetModules();
534+
vi.doMock("openclaw/plugin-sdk/runtime-env", () => ({
535+
ensureGlobalUndiciEnvProxyDispatcher: vi.fn(),
536+
}));
537+
vi.doMock("openai", () => ({
538+
default: class MockOpenAI {
539+
embeddings = { create: vi.fn(async () => ({ data: [{ embedding: [0.1, 0.2] }] })) };
540+
},
541+
}));
542+
vi.doMock("./lancedb-runtime.js", () => ({
543+
loadLanceDbModule: vi.fn(async () => ({ connect })),
544+
}));
545+
546+
try {
547+
const { default: plugin } = await import("./index.js");
548+
const baseDbPath = getDbPath();
549+
const { mockApi, factories } = buildMockApi({ dbPath: baseDbPath });
550+
551+
plugin.register(mockApi as never);
552+
553+
type ToolLike = { execute: (...a: unknown[]) => Promise<unknown> };
554+
const recallFactory = factories.find(
555+
(f) => (f.opts as { name?: string })?.name === "memory_recall",
556+
)!.factory as (ctx: { agentId?: string }) => ToolLike;
557+
await recallFactory({ agentId: undefined }).execute("c", { query: "test" });
558+
559+
// Must connect to exactly the root path, not a subdirectory
560+
expect(connect).toHaveBeenCalledTimes(1);
561+
expect(connect.mock.calls[0][0]).toBe(baseDbPath);
562+
} finally {
563+
vi.doUnmock("openclaw/plugin-sdk/runtime-env");
564+
vi.doUnmock("openai");
565+
vi.doUnmock("./lancedb-runtime.js");
566+
vi.resetModules();
567+
}
568+
});
569+
});
570+
333571
describe("lancedb runtime loader", () => {
334572
test("uses the bundled module when it is already available", async () => {
335573
const bundledModule = createMockModule();

0 commit comments

Comments
 (0)