Skip to content

Commit 824d170

Browse files
authored
fix(memory): keep gateway RPCs responsive during startup (#119676)
* fix(memory): defer startup manager warmup * test(plugins): register memory stop hook contract
1 parent 462f8c4 commit 824d170

3 files changed

Lines changed: 186 additions & 24 deletions

File tree

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

Lines changed: 125 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
33
import type { OpenClawPluginApi, OpenClawPluginCommandDefinition } from "openclaw/plugin-sdk/core";
44
import type { MemoryPluginRuntime } from "openclaw/plugin-sdk/memory-core-host-runtime-core";
55
import { createTestPluginApi } from "openclaw/plugin-sdk/plugin-test-api";
6-
import { beforeEach, describe, expect, it, vi } from "vitest";
6+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
77
import { buildMemoryFlushPlan } from "./src/flush-plan.js";
88
import type { MemoryCoreRuntimeHost } from "./src/memory/runtime-host.js";
99
import { buildPromptSection } from "./src/prompt-section.js";
@@ -112,6 +112,10 @@ describe("memory-core plugin runtime registration", () => {
112112
vi.clearAllMocks();
113113
});
114114

115+
afterEach(() => {
116+
vi.useRealTimers();
117+
});
118+
115119
it("registers the dreaming runtime slash command", () => {
116120
let command: OpenClawPluginCommandDefinition | undefined;
117121
plugin.register(
@@ -196,6 +200,7 @@ describe("memory-core plugin runtime registration", () => {
196200
});
197201

198202
it("warms each configured memory manager at gateway start and logs failures at debug", async () => {
203+
vi.useFakeTimers();
199204
const gatewayStartHandlers: Array<(event: unknown, ctx: { config: OpenClawConfig }) => void> =
200205
[];
201206
const syncMain = vi.fn(async () => {});
@@ -229,6 +234,8 @@ describe("memory-core plugin runtime registration", () => {
229234
}
230235
warmup({}, { config });
231236

237+
expect(getMemorySearchManagerMock).not.toHaveBeenCalled();
238+
await vi.runOnlyPendingTimersAsync();
232239
await vi.waitFor(() => {
233240
expect(getMemorySearchManagerMock).toHaveBeenCalledTimes(2);
234241
expect(syncMain).toHaveBeenCalledWith({ reason: "startup-warmup" });
@@ -239,7 +246,123 @@ describe("memory-core plugin runtime registration", () => {
239246
});
240247
});
241248

249+
it("defers memory manager initialization until after the gateway start turn", async () => {
250+
vi.useFakeTimers();
251+
const gatewayStartHandlers: Array<(event: unknown, ctx: { config: OpenClawConfig }) => void> =
252+
[];
253+
getMemorySearchManagerMock.mockResolvedValue({ manager: null } as never);
254+
const config = {} as OpenClawConfig;
255+
plugin.register(
256+
createTestPluginApi({
257+
config,
258+
runtime: hostRuntime,
259+
on(hookName, handler) {
260+
if (hookName === "gateway_start") {
261+
gatewayStartHandlers.push(
262+
handler as unknown as (event: unknown, ctx: { config: OpenClawConfig }) => void,
263+
);
264+
}
265+
},
266+
}),
267+
);
268+
const warmup = gatewayStartHandlers.at(-1);
269+
if (!warmup) {
270+
throw new Error("expected memory warmup gateway_start hook");
271+
}
272+
273+
warmup({}, { config });
274+
275+
expect(getMemorySearchManagerMock).not.toHaveBeenCalled();
276+
await vi.runOnlyPendingTimersAsync();
277+
await vi.waitFor(() => expect(getMemorySearchManagerMock).toHaveBeenCalledTimes(1));
278+
});
279+
280+
it("cancels deferred memory warmup when the gateway stops", async () => {
281+
vi.useFakeTimers();
282+
const gatewayStartHandlers: Array<(event: unknown, ctx: { config: OpenClawConfig }) => void> =
283+
[];
284+
const gatewayStopHandlers: Array<() => void> = [];
285+
const config = {} as OpenClawConfig;
286+
plugin.register(
287+
createTestPluginApi({
288+
config,
289+
runtime: hostRuntime,
290+
on(hookName, handler) {
291+
if (hookName === "gateway_start") {
292+
gatewayStartHandlers.push(
293+
handler as unknown as (event: unknown, ctx: { config: OpenClawConfig }) => void,
294+
);
295+
}
296+
if (hookName === "gateway_stop") {
297+
gatewayStopHandlers.push(handler as unknown as () => void);
298+
}
299+
},
300+
}),
301+
);
302+
const warmup = gatewayStartHandlers.at(-1);
303+
const stop = gatewayStopHandlers.at(-1);
304+
if (!warmup || !stop) {
305+
throw new Error("expected memory warmup lifecycle hooks");
306+
}
307+
308+
warmup({}, { config });
309+
stop();
310+
await vi.runOnlyPendingTimersAsync();
311+
312+
expect(getMemorySearchManagerMock).not.toHaveBeenCalled();
313+
});
314+
315+
it("prevents a restarted gateway generation from syncing a stale manager", async () => {
316+
vi.useFakeTimers();
317+
const gatewayStartHandlers: Array<(event: unknown, ctx: { config: OpenClawConfig }) => void> =
318+
[];
319+
let resolveStaleManager:
320+
| ((value: { manager: { sync: () => Promise<void> } }) => void)
321+
| undefined;
322+
const staleManagerResult = new Promise<{ manager: { sync: () => Promise<void> } }>(
323+
(resolve) => {
324+
resolveStaleManager = resolve;
325+
},
326+
);
327+
const staleSync = vi.fn(async () => {});
328+
const currentSync = vi.fn(async () => {});
329+
getMemorySearchManagerMock
330+
.mockReturnValueOnce(staleManagerResult as never)
331+
.mockResolvedValueOnce({ manager: { sync: currentSync } } as never);
332+
const config = {} as OpenClawConfig;
333+
plugin.register(
334+
createTestPluginApi({
335+
config,
336+
runtime: hostRuntime,
337+
on(hookName, handler) {
338+
if (hookName === "gateway_start") {
339+
gatewayStartHandlers.push(
340+
handler as unknown as (event: unknown, ctx: { config: OpenClawConfig }) => void,
341+
);
342+
}
343+
},
344+
}),
345+
);
346+
const warmup = gatewayStartHandlers.at(-1);
347+
if (!warmup) {
348+
throw new Error("expected memory warmup gateway_start hook");
349+
}
350+
351+
warmup({}, { config });
352+
await vi.runOnlyPendingTimersAsync();
353+
await vi.waitFor(() => expect(getMemorySearchManagerMock).toHaveBeenCalledTimes(1));
354+
355+
warmup({}, { config });
356+
await vi.runOnlyPendingTimersAsync();
357+
await vi.waitFor(() => expect(currentSync).toHaveBeenCalledWith({ reason: "startup-warmup" }));
358+
359+
resolveStaleManager?.({ manager: { sync: staleSync } });
360+
await vi.waitFor(() => expect(getMemorySearchManagerMock).toHaveBeenCalledTimes(2));
361+
expect(staleSync).not.toHaveBeenCalled();
362+
});
363+
242364
it("leaves QMD startup synchronization to the backend boot policy", async () => {
365+
vi.useFakeTimers();
243366
const gatewayStartHandlers: Array<(event: unknown, ctx: { config: OpenClawConfig }) => void> =
244367
[];
245368
const sync = vi.fn(async () => {});
@@ -267,6 +390,7 @@ describe("memory-core plugin runtime registration", () => {
267390

268391
warmup({}, { config });
269392

393+
await vi.runOnlyPendingTimersAsync();
270394
await vi.waitFor(() => expect(getMemorySearchManagerMock).toHaveBeenCalledTimes(1));
271395
expect(sync).not.toHaveBeenCalled();
272396
});

‎extensions/memory-core/index.ts‎

Lines changed: 55 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ const loadRuntimeProviderModule = createLazyRuntimeModule(
5757
() => import("./src/runtime-provider.js"),
5858
);
5959

60+
const MEMORY_MANAGER_WARMUP_DELAY_MS = 5_000;
61+
6062
function getToolConfig(options: MemoryToolOptions): OpenClawConfig | undefined {
6163
return options.getConfig?.() ?? options.config;
6264
}
@@ -279,35 +281,66 @@ function registerMemoryManagerWarmup(
279281
api: OpenClawPluginApi,
280282
memoryRuntime: MemoryPluginRuntime,
281283
): void {
284+
let lifecycleGeneration = 0;
285+
let warmupTimer: ReturnType<typeof setTimeout> | null = null;
286+
287+
const cancelWarmup = () => {
288+
lifecycleGeneration += 1;
289+
if (warmupTimer) {
290+
clearTimeout(warmupTimer);
291+
warmupTimer = null;
292+
}
293+
};
294+
282295
api.on("gateway_start", (_event, ctx) => {
296+
cancelWarmup();
297+
const generation = lifecycleGeneration;
283298
const config = (api.runtime.config?.current?.() ?? ctx.config ?? api.config) as OpenClawConfig;
284299
if (normalizePluginsConfig(config.plugins).slots.memory !== "memory-core") {
285300
return;
286301
}
287-
for (const agentId of listAgentIds(config)) {
288-
const backend = memoryRuntime.resolveMemoryBackendConfig({ cfg: config, agentId });
289-
void memoryRuntime
290-
.getMemorySearchManager({ cfg: config, agentId })
291-
.then(async ({ manager, error }) => {
292-
if (!manager) {
293-
if (error) {
294-
api.logger.debug?.(`memory-core: startup index warmup unavailable: ${error}`);
302+
303+
// Leave a bounded idle window for initial post-ready RPCs before loading the manager.
304+
const timer = setTimeout(() => {
305+
if (warmupTimer !== timer || generation !== lifecycleGeneration) {
306+
return;
307+
}
308+
warmupTimer = null;
309+
for (const agentId of listAgentIds(config)) {
310+
const backend = memoryRuntime.resolveMemoryBackendConfig({ cfg: config, agentId });
311+
void memoryRuntime
312+
.getMemorySearchManager({ cfg: config, agentId })
313+
.then(async ({ manager, error }) => {
314+
if (generation !== lifecycleGeneration) {
315+
return;
295316
}
296-
return;
297-
}
298-
if (backend.backend === "builtin") {
299-
await manager.sync?.({ reason: "startup-warmup" });
300-
}
301-
})
302-
.catch((error: unknown) => {
303-
api.logger.debug?.(
304-
`memory-core: startup index warmup failed for ${agentId}: ${
305-
error instanceof Error ? error.message : String(error)
306-
}`,
307-
);
308-
});
309-
}
317+
if (!manager) {
318+
if (error) {
319+
api.logger.debug?.(`memory-core: startup index warmup unavailable: ${error}`);
320+
}
321+
return;
322+
}
323+
if (backend.backend === "builtin") {
324+
await manager.sync?.({ reason: "startup-warmup" });
325+
}
326+
})
327+
.catch((error: unknown) => {
328+
if (generation !== lifecycleGeneration) {
329+
return;
330+
}
331+
api.logger.debug?.(
332+
`memory-core: startup index warmup failed for ${agentId}: ${
333+
error instanceof Error ? error.message : String(error)
334+
}`,
335+
);
336+
});
337+
}
338+
}, MEMORY_MANAGER_WARMUP_DELAY_MS);
339+
warmupTimer = timer;
340+
warmupTimer.unref?.();
310341
});
342+
343+
api.on("gateway_stop", cancelWarmup);
311344
}
312345

313346
export default definePluginEntry({

‎src/plugins/contracts/boundary-invariants.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,12 @@ const BUNDLED_TYPED_HOOK_REGISTRATION_GUARDS = {
4242
"extensions/feishu/subagent-hooks-api.ts": ["subagent_delivery_target", "subagent_ended"],
4343
"extensions/matrix/subagent-hooks-api.ts": ["subagent_delivery_target", "subagent_ended"],
4444
"extensions/memory-core/src/dreaming.ts": ["before_agent_reply", "gateway_start", "gateway_stop"],
45-
"extensions/memory-core/index.ts": ["before_agent_reply", "before_prompt_build", "gateway_start"],
45+
"extensions/memory-core/index.ts": [
46+
"before_agent_reply",
47+
"before_prompt_build",
48+
"gateway_start",
49+
"gateway_stop",
50+
],
4651
"extensions/memory-lancedb/index.ts": ["agent_end", "before_prompt_build", "session_end"],
4752
"extensions/onepassword/index.ts": ["before_tool_call", "tool_result_persist"],
4853
"extensions/thread-ownership/index.ts": ["message_received", "message_sending"],

0 commit comments

Comments
 (0)