Skip to content

Commit 11bcc0e

Browse files
authored
fix(memory): stop cancelled searches before returning results (#124118)
* fix(memory): stop vector scan after search cancellation * fix(memory): preserve cancellation through hybrid search
1 parent c841845 commit 11bcc0e

4 files changed

Lines changed: 140 additions & 1 deletion

File tree

‎extensions/memory-core/src/memory/manager-search-orchestration.test.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Memory Core tests cover manager search orchestration behavior.
22
import fs from "node:fs/promises";
33
import path from "node:path";
4+
import type { DatabaseSync } from "node:sqlite";
45
import { describe, expect, it, vi } from "vitest";
56
import {
67
createManagerIndexFixture,
@@ -195,6 +196,81 @@ describe("memory index", () => {
195196
expect(close).not.toHaveBeenCalled();
196197
});
197198

199+
it("rejects caller cancellation during hybrid fallback scanning", async () => {
200+
const manager = await getPersistentManager(
201+
createCfg({
202+
minScore: 0,
203+
hybrid: { enabled: true, vectorWeight: 0.5, textWeight: 0.5 },
204+
}),
205+
);
206+
await manager.sync({ reason: "test" });
207+
208+
const fields = manager as unknown as {
209+
db: DatabaseSync;
210+
ensureVectorReady: (dimensions?: number) => Promise<boolean>;
211+
};
212+
fields.ensureVectorReady = async () => false;
213+
const insertChunk = fields.db.prepare(
214+
"INSERT INTO memory_index_chunks (id, path, source, start_line, end_line, hash, model, text, embedding, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
215+
);
216+
for (let index = 0; index < 4096; index += 1) {
217+
insertChunk.run(
218+
`cancel-scan-${index}`,
219+
`memory/cancel-scan-${index}.md`,
220+
"memory",
221+
1,
222+
1,
223+
`cancel-scan-hash-${index}`,
224+
"mock-embed",
225+
`fallback scan row ${index}`,
226+
JSON.stringify([0, 1, 0, 0]),
227+
index,
228+
);
229+
}
230+
231+
const originalPrepare = fields.db.prepare.bind(fields.db);
232+
let scannedBatches = 0;
233+
const prepareSpy = vi.spyOn(fields.db, "prepare").mockImplementation((sql: string) => {
234+
const statement = originalPrepare(sql);
235+
if (!sql.includes("SELECT rowid, id, path")) {
236+
return statement;
237+
}
238+
return {
239+
all: (...args: Parameters<typeof statement.all>) => {
240+
scannedBatches += 1;
241+
return statement.all(...args);
242+
},
243+
} as unknown as typeof statement;
244+
});
245+
246+
try {
247+
const caller = new AbortController();
248+
const abortReason = new Error("caller stopped hybrid memory search");
249+
const pending = manager.search("alpha", { signal: caller.signal });
250+
setImmediate(() => caller.abort(abortReason));
251+
252+
await expect(pending).rejects.toBe(abortReason);
253+
await new Promise<void>((resolve) => {
254+
setImmediate(resolve);
255+
});
256+
await new Promise<void>((resolve) => {
257+
setImmediate(resolve);
258+
});
259+
expect(scannedBatches).toBe(1);
260+
261+
const healthyResults = await manager.search("alpha");
262+
expect(healthyResults.some((result) => result.path === "memory/2026-01-12.md")).toBe(true);
263+
264+
fields.ensureVectorReady = async () => {
265+
throw new Error("vector store unavailable");
266+
};
267+
const degradedResults = await manager.search("alpha");
268+
expect(degradedResults.some((result) => result.path === "memory/2026-01-12.md")).toBe(true);
269+
} finally {
270+
prepareSpy.mockRestore();
271+
}
272+
});
273+
198274
it("supplements thin strict FTS results for conversational queries", async () => {
199275
const cases = [
200276
{

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,9 @@ export abstract class MemorySearchOrchestration extends MemoryKeywordRetrieval {
364364
candidates,
365365
sourceFilterList,
366366
vectorProviderIdentity,
367+
opts?.signal,
367368
).catch((err: unknown) => {
369+
opts?.signal?.throwIfAborted();
368370
log.warn(`memory search: vector query failed: ${formatErrorMessage(err)}`);
369371
return [];
370372
})
@@ -425,6 +427,7 @@ export abstract class MemorySearchOrchestration extends MemoryKeywordRetrieval {
425427
limit: number,
426428
sourceFilterList: MemorySource[],
427429
providerIdentity: { model: string; aliases: string[] },
430+
signal?: AbortSignal,
428431
): Promise<Array<MemorySearchResult & { id: string }>> {
429432
const results = await searchVector({
430433
db: this.db,
@@ -434,6 +437,7 @@ export abstract class MemorySearchOrchestration extends MemoryKeywordRetrieval {
434437
queryVec,
435438
limit,
436439
snippetMaxChars: SNIPPET_MAX_CHARS,
440+
signal,
437441
ensureVectorReady: async (dimensions) => await this.ensureVectorReady(dimensions),
438442
sourceFilterVec: this.buildSourceFilter("c", sourceFilterList),
439443
sourceFilterChunks: this.buildSourceFilter(undefined, sourceFilterList),

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

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
import { describe, expect, it, vi } from "vitest";
1010
import { bm25RankToScore, buildFtsQuery } from "./hybrid.js";
1111
import { searchKeyword, searchPathKeyword, searchVector } from "./manager-search.js";
12+
import { runMemorySearchWithDeadline } from "./search-deadline.js";
1213
import { vectorToBlob } from "./vector-blob.js";
1314

1415
function insertKeywordFixture(
@@ -1130,6 +1131,57 @@ describe("searchVector sqlite-vec KNN", () => {
11301131
}
11311132
});
11321133

1134+
it("stops fallback scanning when the caller aborts and keeps later searches healthy", async () => {
1135+
const db = createFallbackDb();
1136+
try {
1137+
for (let index = 0; index < 4096; index += 1) {
1138+
insertFallbackChunk(db, {
1139+
id: `chunk-${index}`,
1140+
model: "target-model",
1141+
vector: index === 4095 ? [1, 0] : [0, 1],
1142+
});
1143+
}
1144+
1145+
let scannedBatches = 0;
1146+
const countedDb = {
1147+
prepare: (sql: string) => {
1148+
const statement = db.prepare(sql);
1149+
if (!sql.includes("SELECT rowid, id, path")) {
1150+
return statement;
1151+
}
1152+
return {
1153+
all: (...args: Parameters<typeof statement.all>) => {
1154+
scannedBatches += 1;
1155+
return statement.all(...args);
1156+
},
1157+
};
1158+
},
1159+
} as unknown as DatabaseSync;
1160+
const caller = new AbortController();
1161+
const abortReason = new Error("caller stopped memory search");
1162+
const pending = runMemorySearchWithDeadline({
1163+
timeoutMs: 5_000,
1164+
parentSignal: caller.signal,
1165+
run: async (signal) => await searchVectorFixture(countedDb, { signal }),
1166+
});
1167+
setImmediate(() => caller.abort(abortReason));
1168+
1169+
await expect(pending).rejects.toBe(abortReason);
1170+
await new Promise<void>((resolve) => {
1171+
setImmediate(resolve);
1172+
});
1173+
await new Promise<void>((resolve) => {
1174+
setImmediate(resolve);
1175+
});
1176+
expect(scannedBatches).toBe(1);
1177+
1178+
const healthyResults = await searchVectorFixture(db, { limit: 1 });
1179+
expect(healthyResults.map((result) => result.id)).toEqual(["chunk-4095"]);
1180+
} finally {
1181+
db.close();
1182+
}
1183+
});
1184+
11331185
// ===== Fallback path boundary coverage (issue #81172 review diligence) =====
11341186

11351187
function createFallbackDb(): InstanceType<typeof DatabaseSync> {

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -449,13 +449,15 @@ export async function searchVector(params: {
449449
queryVec: number[];
450450
limit: number;
451451
snippetMaxChars: number;
452+
signal?: AbortSignal;
452453
ensureVectorReady: (dimensions: number) => Promise<boolean>;
453454
sourceFilterVec: { sql: string; params: SearchSource[] };
454455
sourceFilterChunks: { sql: string; params: SearchSource[] };
455456
}): Promise<SearchRowResult[]> {
456457
if (params.queryVec.length === 0 || params.limit <= 0) {
457458
return [];
458459
}
460+
params.signal?.throwIfAborted();
459461
const providerModels = resolveProviderModels(params.providerModel, params.providerModelAliases);
460462
const vectorModelFilter = buildModelFilter("c.model", providerModels);
461463
const searchFallback = () =>
@@ -467,8 +469,11 @@ export async function searchVector(params: {
467469
queryVec: params.queryVec,
468470
limit: params.limit,
469471
snippetMaxChars: params.snippetMaxChars,
472+
signal: params.signal,
470473
});
471-
if (await params.ensureVectorReady(params.queryVec.length)) {
474+
const vectorReady = await params.ensureVectorReady(params.queryVec.length);
475+
params.signal?.throwIfAborted();
476+
if (vectorReady) {
472477
// Use sqlite-vec's native KNN (MATCH ? AND k = ?) for candidate selection,
473478
// which runs in ~O(log N + k) via the vec0 index, instead of the previous
474479
// full-table scan over vec_distance_cosine(). Keep vec_distance_cosine() in
@@ -560,6 +565,7 @@ async function searchChunksByEmbedding(params: {
560565
queryVec: number[];
561566
limit: number;
562567
snippetMaxChars: number;
568+
signal?: AbortSignal;
563569
}): Promise<SearchRowResult[]> {
564570
if (params.limit <= 0) {
565571
return [];
@@ -634,6 +640,7 @@ async function searchChunksByEmbedding(params: {
634640
break;
635641
}
636642
await yieldToEventLoop();
643+
params.signal?.throwIfAborted();
637644
}
638645
topResults.sort((a, b) => b.score - a.score);
639646
// Read provenance once for the final retained set, not per scored candidate.

0 commit comments

Comments
 (0)