Skip to content

Commit fd44319

Browse files
committed
fix(memory-wiki): cancel compile work on stop
1 parent a77e3fb commit fd44319

10 files changed

Lines changed: 229 additions & 98 deletions

File tree

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

Lines changed: 52 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -298,59 +298,61 @@ describe("memory-wiki plugin", () => {
298298
await expect(loadMemoryWikiCompiledCache(config)).resolves.toBeNull();
299299
});
300300

301-
it("closes queued dashboard source sync before it can activate a vault", async () => {
302-
const rootDir = await createTempDir("memory-wiki-index-stop-sync-");
303-
const { api, registerGatewayMethod, registerService } = createPluginApi();
304-
api.pluginConfig = { vault: { path: rootDir } };
305-
plugin.register(api);
306-
const config = resolveMemoryWikiConfig(api.pluginConfig);
307-
const service = registerService.mock.calls[0]?.[0];
308-
await service?.start?.();
301+
it.each(["wiki.importInsights", "wiki.compile"])(
302+
"closes queued %s source sync before it can activate a vault",
303+
async (method) => {
304+
const rootDir = await createTempDir("memory-wiki-index-stop-sync-");
305+
const { api, registerGatewayMethod, registerService } = createPluginApi();
306+
api.pluginConfig = { vault: { path: rootDir } };
307+
plugin.register(api);
308+
const config = resolveMemoryWikiConfig(api.pluginConfig);
309+
const service = registerService.mock.calls[0]?.[0];
310+
await service?.start?.();
309311

310-
const mutationEntered = deferred();
311-
const releaseMutation = deferred();
312-
const mutation = withMemoryWikiVaultMutation(rootDir, async () => {
313-
mutationEntered.resolve();
314-
await releaseMutation.promise;
315-
});
316-
await mutationEntered.promise;
317-
const handler = registerGatewayMethod.mock.calls.find(
318-
([method]) => method === "wiki.importInsights",
319-
)?.[1];
320-
if (!handler) {
321-
throw new Error("Expected wiki.importInsights gateway handler");
322-
}
323-
await handler({ params: {}, respond: vi.fn() });
324-
await vi.waitFor(async () => {
325-
const drainState = await Promise.race([
326-
waitForMemoryWikiImportedSourceSyncs().then(() => "settled" as const),
327-
new Promise<"pending">((resolve) => {
328-
setImmediate(() => resolve("pending"));
329-
}),
330-
]);
331-
expect(drainState).toBe("pending");
332-
});
312+
const mutationEntered = deferred();
313+
const releaseMutation = deferred();
314+
const mutation = withMemoryWikiVaultMutation(rootDir, async () => {
315+
mutationEntered.resolve();
316+
await releaseMutation.promise;
317+
});
318+
await mutationEntered.promise;
319+
const handler = registerGatewayMethod.mock.calls.find(([name]) => name === method)?.[1];
320+
if (!handler) {
321+
throw new Error(`Expected ${method} gateway handler`);
322+
}
323+
const request = handler({ params: {}, respond: vi.fn() });
324+
await vi.waitFor(async () => {
325+
const drainState = await Promise.race([
326+
waitForMemoryWikiImportedSourceSyncs().then(() => "settled" as const),
327+
new Promise<"pending">((resolve) => {
328+
setImmediate(() => resolve("pending"));
329+
}),
330+
]);
331+
expect(drainState).toBe("pending");
332+
});
333333

334-
const stop = service?.stop?.();
335-
releaseMutation.resolve();
336-
await mutation;
337-
await stop;
334+
const stop = service?.stop?.();
335+
releaseMutation.resolve();
336+
await mutation;
337+
await request;
338+
await stop;
338339

339-
const snapshot = emptyCompiledSnapshot();
340-
await expect(
341-
writeMemoryWikiCompiledCache(
342-
config,
343-
snapshot,
344-
resolveMemoryWikiCompiledCacheGeneration(snapshot),
345-
createMemoryWikiCompiledCachePublicationId(),
346-
null,
347-
async () => {},
348-
async () => {},
349-
() => loadMemoryWikiValidatedVaultIdentity(rootDir),
350-
),
351-
).rejects.toThrow("vault is not active");
352-
await expect(loadMemoryWikiCompiledCache(config)).resolves.toBeNull();
353-
});
340+
const snapshot = emptyCompiledSnapshot();
341+
await expect(
342+
writeMemoryWikiCompiledCache(
343+
config,
344+
snapshot,
345+
resolveMemoryWikiCompiledCacheGeneration(snapshot),
346+
createMemoryWikiCompiledCachePublicationId(),
347+
null,
348+
async () => {},
349+
async () => {},
350+
() => loadMemoryWikiValidatedVaultIdentity(rootDir),
351+
),
352+
).rejects.toThrow("vault is not active");
353+
await expect(loadMemoryWikiCompiledCache(config)).resolves.toBeNull();
354+
},
355+
);
354356

355357
it("clears active owners before a fallible lifecycle identity refresh", async () => {
356358
const rootDir = await createTempDir("memory-wiki-index-refresh-failure-");

‎extensions/memory-wiki/index.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,11 @@ export default definePluginEntry({
9696
// Context-free tool discovery cannot safely choose one agent's vault.
9797
return null;
9898
}
99-
return { appConfig, config: resolveConfig(agentId, appConfig) };
99+
return {
100+
appConfig,
101+
config: resolveConfig(agentId, appConfig),
102+
...(sourceSyncAbortController ? { signal: sourceSyncAbortController.signal } : {}),
103+
};
100104
};
101105
configureMemoryWikiSourceSyncStateStore(
102106
createMemoryWikiSourceSyncStateStore(api.runtime.state.openKeyedStore),
@@ -190,6 +194,7 @@ export default definePluginEntry({
190194
return resolved
191195
? createWikiStatusTool(resolved.config, resolved.appConfig, {
192196
agentId: resolved.config.agentId ?? ctx.agentId,
197+
...(resolved.signal ? { signal: resolved.signal } : {}),
193198
})
194199
: null;
195200
},
@@ -198,14 +203,18 @@ export default definePluginEntry({
198203
api.registerTool(
199204
(ctx) => {
200205
const resolved = resolveToolContext(ctx.agentId);
201-
return resolved ? createWikiLintTool(resolved.config, resolved.appConfig) : null;
206+
return resolved
207+
? createWikiLintTool(resolved.config, resolved.appConfig, resolved.signal)
208+
: null;
202209
},
203210
{ name: "wiki_lint" },
204211
);
205212
api.registerTool(
206213
(ctx) => {
207214
const resolved = resolveToolContext(ctx.agentId);
208-
return resolved ? createWikiApplyTool(resolved.config, resolved.appConfig) : null;
215+
return resolved
216+
? createWikiApplyTool(resolved.config, resolved.appConfig, resolved.signal)
217+
: null;
209218
},
210219
{ name: "wiki_apply" },
211220
);
@@ -220,6 +229,7 @@ export default definePluginEntry({
220229
agentSessionKey: ctx.sessionKey,
221230
sandboxed: ctx.sandboxed,
222231
conversationRecall: ctx.conversationRecall,
232+
...(resolved.signal ? { signal: resolved.signal } : {}),
223233
});
224234
},
225235
{ name: "wiki_search" },
@@ -235,6 +245,7 @@ export default definePluginEntry({
235245
agentSessionKey: ctx.sessionKey,
236246
sandboxed: ctx.sandboxed,
237247
conversationRecall: ctx.conversationRecall,
248+
...(resolved.signal ? { signal: resolved.signal } : {}),
238249
});
239250
},
240251
{ name: "wiki_get" },

‎extensions/memory-wiki/src/apply.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -365,8 +365,13 @@ async function applyUpdateMetadataMutation(params: {
365365
async function applyMemoryWikiMutationUnlocked(params: {
366366
config: ResolvedMemoryWikiConfig;
367367
mutation: ApplyMemoryWikiMutation;
368+
signal?: AbortSignal;
368369
}): Promise<ApplyMemoryWikiMutationResult> {
369-
await initializeMemoryWikiVault(params.config);
370+
await initializeMemoryWikiVault(
371+
params.config,
372+
params.signal ? { signal: params.signal } : undefined,
373+
);
374+
params.signal?.throwIfAborted();
370375
const result =
371376
params.mutation.op === "create_synthesis"
372377
? await applyCreateSynthesisMutation({
@@ -377,7 +382,11 @@ async function applyMemoryWikiMutationUnlocked(params: {
377382
config: params.config,
378383
mutation: params.mutation,
379384
});
380-
const compile = await compileMemoryWikiVault(params.config);
385+
params.signal?.throwIfAborted();
386+
const compile = await compileMemoryWikiVault(
387+
params.config,
388+
params.signal ? { signal: params.signal } : undefined,
389+
);
381390
return {
382391
changed: result.changed,
383392
operation: params.mutation.op,
@@ -390,6 +399,7 @@ async function applyMemoryWikiMutationUnlocked(params: {
390399
export async function applyMemoryWikiMutation(params: {
391400
config: ResolvedMemoryWikiConfig;
392401
mutation: ApplyMemoryWikiMutation;
402+
signal?: AbortSignal;
393403
}): Promise<ApplyMemoryWikiMutationResult> {
394404
return await withMemoryWikiVaultMutation(params.config.vault.path, () =>
395405
applyMemoryWikiMutationUnlocked(params),

‎extensions/memory-wiki/src/compile.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ describe("compileMemoryWikiVault", () => {
415415
).resolves.toContain("[Alpha Synthesis](alpha-synthesis.md)");
416416
});
417417

418-
it("bounds concurrent page reads while compiling", async () => {
418+
it("bounds concurrent page reads and stops the queue after abort", async () => {
419419
const { rootDir, config } = await createVault({
420420
rootDir: nextCaseRoot(),
421421
initialize: true,
@@ -437,6 +437,8 @@ describe("compileMemoryWikiVault", () => {
437437
}
438438

439439
const originalReadFile = fs.readFile.bind(fs);
440+
const abortController = new AbortController();
441+
let pageReads = 0;
440442
let activePageReads = 0;
441443
let maxActivePageReads = 0;
442444
const readFileSpy = vi
@@ -451,7 +453,11 @@ describe("compileMemoryWikiVault", () => {
451453
}
452454

453455
activePageReads += 1;
456+
pageReads += 1;
454457
maxActivePageReads = Math.max(maxActivePageReads, activePageReads);
458+
if (pageReads === 16) {
459+
abortController.abort();
460+
}
455461
try {
456462
await Promise.resolve();
457463
return await originalReadFile(...args);
@@ -461,12 +467,14 @@ describe("compileMemoryWikiVault", () => {
461467
});
462468

463469
try {
464-
await compileMemoryWikiVault(config);
470+
await expect(
471+
compileMemoryWikiVault(config, { signal: abortController.signal }),
472+
).rejects.toThrow();
465473
} finally {
466474
readFileSpy.mockRestore();
467475
}
468476

469-
expect(maxActivePageReads).toBeGreaterThan(0);
477+
expect(pageReads).toBe(16);
470478
expect(maxActivePageReads).toBeLessThanOrEqual(16);
471479
});
472480

0 commit comments

Comments
 (0)