Skip to content

Commit 184c9c3

Browse files
committed
fix: reduce retained Gateway and Activity memory
1 parent 2a920ab commit 184c9c3

30 files changed

Lines changed: 943 additions & 248 deletions

‎extensions/memory-core/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import type { OpenKeyedStoreOptions } from "openclaw/plugin-sdk/plugin-state-run
1616
import { configureMemoryCoreDreamingState } from "./src/dreaming-state.js";
1717
import { registerShortTermPromotionDreaming } from "./src/dreaming.js";
1818
import { buildMemoryFlushPlan } from "./src/flush-plan.js";
19+
import "./src/memory/background-context.js";
1920
import {
2021
buildMemoryPromptSection,
2122
MEMORY_GET_TOOL_CONTRACT,
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { AsyncLocalStorage } from "node:async_hooks";
2+
3+
// The plugin entry loads this before Gateway turns are admitted, while managers
4+
// load lazily. Background resources must not retain the turn that opens a
5+
// manager or publishes a transcript update.
6+
export const runInMemoryBackgroundContext = AsyncLocalStorage.snapshot();

‎extensions/memory-core/src/memory/manager-session-sync-ops.ts‎

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
import { normalizeAgentId } from "openclaw/plugin-sdk/routing";
2323
import { resolveStorePath } from "openclaw/plugin-sdk/session-store-paths";
2424
import { listMemorySessionTombstones } from "../memory-entry-origins.js";
25+
import { runInMemoryBackgroundContext } from "./background-context.js";
2526
import { shouldSyncSessionsForReindex } from "./manager-session-reindex.js";
2627
import {
2728
isMemorySessionIndexable,
@@ -131,21 +132,23 @@ export abstract class MemoryManagerSessionSyncOps extends MemoryManagerWatchOps
131132
if (!this.sources.has("sessions") || this.sessionUnsubscribe) {
132133
return;
133134
}
134-
this.sessionUnsubscribe = this.subscribeSessionTranscriptUpdates((update) => {
135-
if (this.closed) {
136-
return;
137-
}
138-
const target = this.resolveSessionTranscriptUpdateSyncTarget(update);
139-
if (target) {
140-
this.scheduleSessionDirty(target);
141-
return;
142-
}
143-
if (update.sessionFile) {
144-
void this.scheduleCorpusSessionFileDirty(update.sessionFile).catch((err: unknown) => {
145-
log.warn(`memory session corpus update failed: ${String(err)}`);
146-
});
147-
}
148-
});
135+
this.sessionUnsubscribe = this.subscribeSessionTranscriptUpdates((update) =>
136+
runInMemoryBackgroundContext(() => {
137+
if (this.closed) {
138+
return;
139+
}
140+
const target = this.resolveSessionTranscriptUpdateSyncTarget(update);
141+
if (target) {
142+
this.scheduleSessionDirty(target);
143+
return;
144+
}
145+
if (update.sessionFile) {
146+
void this.scheduleCorpusSessionFileDirty(update.sessionFile).catch((err: unknown) => {
147+
log.warn(`memory session corpus update failed: ${String(err)}`);
148+
});
149+
}
150+
}),
151+
);
149152
}
150153

151154
protected subscribeSessionTranscriptUpdates(

‎extensions/memory-core/src/memory/manager-sync-ops.startup-catchup.test-support.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
// Shared harness and fixtures for manager sync-ops startup catch-up tests.
2+
import path from "node:path";
23
import { DatabaseSync } from "node:sqlite";
3-
import type {
4-
OpenClawConfig,
5-
ResolvedMemorySearchConfig,
4+
import {
5+
resolveStateDir,
6+
type OpenClawConfig,
7+
type ResolvedMemorySearchConfig,
68
} from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
79
import {
810
MEMORY_CHUNKING_VERSION,
@@ -133,6 +135,7 @@ export class SessionStartupCatchupHarness extends MemoryManagerSyncOps {
133135
},
134136
provider: "none",
135137
store: {
138+
databasePath: path.join(resolveStateDir(), "memory-index.sqlite"),
136139
fts: {
137140
tokenizer: "unicode61",
138141
},

‎extensions/memory-core/src/memory/manager-sync-ops.startup-catchup.test.ts‎

Lines changed: 32 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Memory Core tests cover manager sync ops.startup-catchup plugin behavior.
2+
import { AsyncLocalStorage } from "node:async_hooks";
23
import fsSync from "node:fs";
34
import fs from "node:fs/promises";
45
import os from "node:os";
@@ -647,18 +648,38 @@ describe("session startup catch-up", () => {
647648
vi.useFakeTimers();
648649
const session = await writeSqliteSession();
649650
const harness = new SessionStartupCatchupHarness([], true, true);
650-
harness.startTranscriptListener();
651+
const turnContext = new AsyncLocalStorage<string>();
652+
const pendingInputContext = new AsyncLocalStorage<string>();
653+
turnContext.run("opening turn", () => harness.startTranscriptListener());
654+
const timerContexts: Array<{ turn?: string; pendingInput?: string }> = [];
655+
const originalSetTimeout = globalThis.setTimeout;
656+
const timerObserver = vi.spyOn(globalThis, "setTimeout").mockImplementation((...args) => {
657+
if (args[1] === 5000) {
658+
timerContexts.push({
659+
turn: turnContext.getStore(),
660+
pendingInput: pendingInputContext.getStore(),
661+
});
662+
}
663+
return originalSetTimeout(...args);
664+
});
651665

652666
try {
653-
await appendSessionTranscriptMessageByIdentity({
654-
agentId: "main",
655-
sessionId: session.sessionId,
656-
sessionKey: session.sessionKey,
657-
storePath: session.storePath,
658-
cwd: stateDir,
659-
message: { role: "assistant", content: "persisted listener update" },
660-
});
661-
await publishSessionTranscriptUpdateByIdentity(session);
667+
await turnContext.run("later turn", () =>
668+
pendingInputContext.run("later input", async () => {
669+
await appendSessionTranscriptMessageByIdentity({
670+
agentId: "main",
671+
sessionId: session.sessionId,
672+
sessionKey: session.sessionKey,
673+
storePath: session.storePath,
674+
cwd: stateDir,
675+
message: { role: "assistant", content: "persisted listener update" },
676+
});
677+
await publishSessionTranscriptUpdateByIdentity(session);
678+
expect(turnContext.getStore()).toBe("later turn");
679+
expect(pendingInputContext.getStore()).toBe("later input");
680+
}),
681+
);
682+
expect(timerContexts).toEqual([{ turn: undefined, pendingInput: undefined }]);
662683

663684
await vi.advanceTimersByTimeAsync(6000);
664685
await harness.waitForSessionSync();
@@ -669,6 +690,7 @@ describe("session startup catch-up", () => {
669690
]);
670691
} finally {
671692
harness.stopTranscriptListener();
693+
timerObserver.mockRestore();
672694
}
673695
});
674696

‎extensions/memory-core/src/memory/manager.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
type MemorySyncParams,
2020
} from "openclaw/plugin-sdk/memory-core-host-engine-storage";
2121
import { normalizeAgentId } from "openclaw/plugin-sdk/routing";
22+
import { runInMemoryBackgroundContext } from "./background-context.js";
2223
import type { MemoryCoreAcquireLocalService } from "./embedding-local-service.js";
2324
import type { EmbeddingProvider, EmbeddingProviderRequest } from "./embeddings.js";
2425
import { awaitPendingManagerWork } from "./manager-async-state.js";
@@ -235,11 +236,6 @@ export class MemoryIndexManager extends MemorySearchOrchestration implements Mem
235236
(initialIndexIdentity.status === "missing" && this.sources.has("memory"));
236237
const transient =
237238
params.purpose === "status" || params.purpose === "cli" || params.purpose === "maintenance";
238-
if (!transient) {
239-
this.ensureWatcher();
240-
this.ensureSessionListener();
241-
this.ensureIntervalSync();
242-
}
243239
const invalidatedSources = new Set(
244240
(
245241
this.db
@@ -266,7 +262,12 @@ export class MemoryIndexManager extends MemorySearchOrchestration implements Mem
266262
}
267263
this.batch = this.resolveBatchConfig();
268264
if (!transient) {
269-
this.ensureSessionStartupCatchup();
265+
runInMemoryBackgroundContext(() => {
266+
this.ensureWatcher();
267+
this.ensureSessionListener();
268+
this.ensureIntervalSync();
269+
this.ensureSessionStartupCatchup();
270+
});
270271
}
271272
} catch (err) {
272273
closeMemoryDatabase(this.db);

‎extensions/memory-core/src/memory/manager.watcher-filesystem.test.ts‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
import { AsyncLocalStorage } from "node:async_hooks";
2+
import nativeFs from "node:fs";
13
import fs from "node:fs/promises";
4+
import { syncBuiltinESMExports } from "node:module";
25
import path from "node:path";
36
import { DatabaseSync } from "node:sqlite";
47
import type { OpenClawConfig } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
58
import { MEMORY_INDEX_CHUNKS_TABLE } from "openclaw/plugin-sdk/memory-core-host-engine-storage";
69
import { createOpenClawTestState } from "openclaw/plugin-sdk/test-state";
7-
import { describe, expect, it } from "vitest";
10+
import { describe, expect, it, vi } from "vitest";
811
import {
912
configureMemoryCoreDreamingStateForTests,
1013
resetMemoryCoreDreamingStateForTests,
@@ -21,6 +24,30 @@ describe("memory watchers on the real filesystem", () => {
2124
async (operation) => {
2225
const state = await createOpenClawTestState({ label: "memory-watch-filesystem" });
2326
const initialWatchers = activeFilesystemWatchers();
27+
const turnContext = new AsyncLocalStorage<string>();
28+
const pendingInputContext = new AsyncLocalStorage<string>();
29+
const watcherContexts: Array<{ turn?: string; pendingInput?: string }> = [];
30+
const timerContexts: typeof watcherContexts = [];
31+
const originalWatch = nativeFs.watch;
32+
const watchObserver = vi.spyOn(nativeFs, "watch").mockImplementation((...args) => {
33+
watcherContexts.push({
34+
turn: turnContext.getStore(),
35+
pendingInput: pendingInputContext.getStore(),
36+
});
37+
return originalWatch(...args);
38+
});
39+
syncBuiltinESMExports();
40+
const originalSetTimeout = globalThis.setTimeout;
41+
const timerObserver = vi.spyOn(globalThis, "setTimeout").mockImplementation((...args) => {
42+
// Observe the real startup pressure check and filesystem debounce timers.
43+
if (args[1] === 10_000 || args[1] === 1500) {
44+
timerContexts.push({
45+
turn: turnContext.getStore(),
46+
pendingInput: pendingInputContext.getStore(),
47+
});
48+
}
49+
return originalSetTimeout(...args);
50+
});
2451
let manager: MemoryIndexManager | null = null;
2552
let index: DatabaseSync | undefined;
2653
try {
@@ -42,7 +69,14 @@ describe("memory watchers on the real filesystem", () => {
4269
},
4370
},
4471
};
45-
manager = await MemoryIndexManager.get({ cfg, agentId: "main" });
72+
manager = await turnContext.run("opening turn", () =>
73+
pendingInputContext.run("accepted input", async () => {
74+
const opened = await MemoryIndexManager.get({ cfg, agentId: "main" });
75+
expect(turnContext.getStore()).toBe("opening turn");
76+
expect(pendingInputContext.getStore()).toBe("accepted input");
77+
return opened;
78+
}),
79+
);
4680
if (!manager) {
4781
throw new Error("memory manager unavailable");
4882
}
@@ -93,6 +127,11 @@ describe("memory watchers on the real filesystem", () => {
93127
]);
94128
expect(await activeManager.search("Amethyst")).toEqual([]);
95129
expect(await activeManager.search("Cobalt")).toEqual([]);
130+
expect(watcherContexts.length).toBeGreaterThan(0);
131+
expect(timerContexts.length).toBeGreaterThan(0);
132+
for (const context of [...watcherContexts, ...timerContexts]) {
133+
expect(context).toEqual({ turn: undefined, pendingInput: undefined });
134+
}
96135

97136
index.close();
98137
index = undefined;
@@ -101,6 +140,9 @@ describe("memory watchers on the real filesystem", () => {
101140
} finally {
102141
index?.close();
103142
await manager?.close();
143+
timerObserver.mockRestore();
144+
watchObserver.mockRestore();
145+
syncBuiltinESMExports();
104146
resetMemoryCoreDreamingStateForTests();
105147
await state.cleanup();
106148
}

‎src/agents/agent-bundle-mcp-manager-lifecycle.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/** Session MCP runtime manager lifecycle: maps, idle sweep, dispose, advertised catalog. */
2+
import { AsyncLocalStorage } from "node:async_hooks";
23
import { logWarn } from "../logger.js";
34
import {
45
DEFAULT_SESSION_MCP_RUNTIME_IDLE_TTL_MS,
@@ -14,6 +15,10 @@ import type {
1415
SessionMcpRuntime,
1516
} from "./agent-bundle-mcp-types.js";
1617

18+
// Gateway shutdown preparation and CLI command imports load this before turns.
19+
// The process-owned sweep must not retain its first requesting turn.
20+
const runInMcpManagerContext = AsyncLocalStorage.snapshot();
21+
1722
type ManagerCreateInFlight = {
1823
promise: Promise<SessionMcpRuntime>;
1924
workspaceDir: string;
@@ -279,7 +284,9 @@ export function createSessionMcpRuntimeManagerLifecycle(
279284
if (!store.enableIdleSweepTimer || store.idleSweepIntervalMs <= 0 || store.idleSweepTimer) {
280285
return;
281286
}
282-
store.idleSweepTimer = setInterval(queueIdleSweep, store.idleSweepIntervalMs);
287+
store.idleSweepTimer = runInMcpManagerContext(() =>
288+
setInterval(queueIdleSweep, store.idleSweepIntervalMs),
289+
);
283290
store.idleSweepTimer.unref?.();
284291
};
285292

‎src/agents/agent-bundle-mcp-manager.lifecycle.test.ts‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1+
import { AsyncLocalStorage } from "node:async_hooks";
12
import { expectDefined } from "@openclaw/normalization-core";
23
import { afterEach, describe, expect, it, vi } from "vitest";
34
import { createDeferred } from "../../test/helpers/promise.js";
45
import { createSessionMcpRuntimeManager } from "./agent-bundle-mcp-manager.js";
5-
import type { CreateSessionMcpRuntime } from "./agent-bundle-mcp-runtime-shared.js";
6+
import {
7+
SESSION_MCP_RUNTIME_SWEEP_INTERVAL_MS,
8+
type CreateSessionMcpRuntime,
9+
} from "./agent-bundle-mcp-runtime-shared.js";
610
import type { SessionMcpRuntime, SessionMcpRuntimeManager } from "./agent-bundle-mcp-types.js";
711
import { testing as resolverTesting } from "./mcp-connection-resolver.js";
812

@@ -109,6 +113,63 @@ describe("MCP manager creation ownership", () => {
109113
expect(manager.listRuntimeKeys()).toEqual([]);
110114
});
111115

116+
it.each(["static", "requester"] as const)(
117+
"keeps the native idle timer outside %s requesting turns across disposal",
118+
async (entrypoint) => {
119+
const turnContext = new AsyncLocalStorage<string>();
120+
const pendingInputContext = new AsyncLocalStorage<string>();
121+
const readContext = () => ({
122+
turn: turnContext.getStore(),
123+
pendingInput: pendingInputContext.getStore(),
124+
});
125+
const timerContexts: ReturnType<typeof readContext>[] = [];
126+
const factoryContexts: ReturnType<typeof readContext>[] = [];
127+
const nativeSetInterval = globalThis.setInterval;
128+
const intervalSpy = vi.spyOn(globalThis, "setInterval").mockImplementation((...args) => {
129+
if (args[1] === SESSION_MCP_RUNTIME_SWEEP_INTERVAL_MS) {
130+
timerContexts.push(readContext());
131+
}
132+
return nativeSetInterval(...args);
133+
});
134+
const manager = createSessionMcpRuntimeManager({
135+
createRuntime(input) {
136+
factoryContexts.push(readContext());
137+
return createRuntimeFixture(input);
138+
},
139+
});
140+
managers.push(manager);
141+
resolverTesting.setMcpServerConnectionResolversForTest([
142+
{ serverName: "scoped", resolve: async () => ({ url: "https://mcp.example.test/scoped" }) },
143+
]);
144+
145+
try {
146+
for (const turn of ["first turn", "later turn"]) {
147+
const pendingInput = `${turn} input`;
148+
await turnContext.run(turn, () =>
149+
pendingInputContext.run(pendingInput, async () => {
150+
if (entrypoint === "static") {
151+
await manager.getOrCreate(params);
152+
} else {
153+
await manager.getOrCreateRequesterScoped({
154+
...params,
155+
requesterSenderId: "sender",
156+
cfg: { mcp: { servers: { scoped: { transport: "streamable-http" } } } },
157+
});
158+
}
159+
expect(readContext()).toEqual({ turn, pendingInput });
160+
}),
161+
);
162+
expect(factoryContexts.splice(0)).toEqual([{ turn, pendingInput }]);
163+
expect(timerContexts.splice(0)).toEqual([{ turn: undefined, pendingInput: undefined }]);
164+
await manager.disposeAll();
165+
}
166+
} finally {
167+
await manager.disposeAll();
168+
intervalSpy.mockRestore();
169+
}
170+
},
171+
);
172+
112173
it.each(["session", "all"] as const)(
113174
"drains late creation during %s disposal without publishing or clearing a successor",
114175
async (scope) => {

0 commit comments

Comments
 (0)