Skip to content

Commit 8e79622

Browse files
authored
fix(web-search): fence cancelled provider cache writes (#123951)
1 parent 6ef6d4d commit 8e79622

10 files changed

Lines changed: 151 additions & 6 deletions

‎extensions/google/src/gemini-web-search-provider.runtime.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,7 @@ export async function executeGeminiSearch(
384384
searchConfig?: SearchConfigRecord,
385385
context?: { signal?: AbortSignal },
386386
): Promise<Record<string, unknown>> {
387+
context?.signal?.throwIfAborted();
387388
const unsupportedResponse = buildUnsupportedSearchFilterResponse(
388389
{
389390
country: args.country,
@@ -458,6 +459,7 @@ export async function executeGeminiSearch(
458459
timeRangeFilter: timeRange.timeRangeFilter,
459460
headers,
460461
});
462+
context?.signal?.throwIfAborted();
461463
const payload = {
462464
query,
463465
provider: "gemini",

‎extensions/google/web-search-provider.test.ts‎

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -422,10 +422,11 @@ describe("google web search provider", () => {
422422
);
423423
});
424424

425-
it("passes provider execution abort signals into the Gemini fetch", async () => {
425+
it("does not contact Gemini for an already-cancelled search", async () => {
426426
const mockFetch = installGeminiFetch();
427427
const controller = new AbortController();
428-
controller.abort();
428+
const reason = new Error("Gemini search cancelled before billing");
429+
controller.abort(reason);
429430
const provider = createGeminiWebSearchProvider();
430431
const tool = provider.createTool({
431432
config: {
@@ -444,10 +445,46 @@ describe("google web search provider", () => {
444445
searchConfig: { provider: "gemini" },
445446
});
446447

447-
await tool?.execute({ query: "OpenClaw docs" }, { signal: controller.signal });
448+
await expect(
449+
tool?.execute({ query: "OpenClaw cancelled docs" }, { signal: controller.signal }),
450+
).rejects.toBe(reason);
451+
expect(mockFetch).not.toHaveBeenCalled();
452+
});
453+
454+
it("does not cache a Gemini result completed after caller cancellation", async () => {
455+
const controller = new AbortController();
456+
const reason = new Error("Gemini search cancelled after response");
457+
const mockFetch = installGeminiFetch();
458+
mockFetch.mockImplementationOnce(async () => {
459+
controller.abort(reason);
460+
return new Response(
461+
JSON.stringify({
462+
candidates: [
463+
{
464+
content: { parts: [{ text: "Cancelled grounded answer" }] },
465+
groundingMetadata: {},
466+
},
467+
],
468+
}),
469+
);
470+
});
471+
const tool = createGeminiWebSearchProvider().createTool({
472+
config: {
473+
plugins: {
474+
entries: {
475+
google: { config: { webSearch: { apiKey: "AIza-plugin-test" } } },
476+
},
477+
},
478+
},
479+
searchConfig: { provider: "gemini" },
480+
});
481+
const query = "OpenClaw late-cancel Gemini cache";
448482

449-
const [, init] = requireFirstGeminiFetchCall(mockFetch);
450-
expect(init?.signal?.aborted).toBe(true);
483+
await expect(tool?.execute({ query }, { signal: controller.signal })).rejects.toBe(reason);
484+
await tool?.execute({ query });
485+
486+
const postCalls = mockFetch.mock.calls.filter(([, init]) => typeof init?.body === "string");
487+
expect(postCalls).toHaveLength(2);
451488
});
452489

453490
it("reuses the Google model provider key when no web search key or env key is set", async () => {

‎extensions/moonshot/src/kimi-web-search-provider.runtime.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,7 @@ export async function executeKimiWebSearchProviderTool(
345345
args: Record<string, unknown>,
346346
opts?: { signal?: AbortSignal },
347347
): Promise<Record<string, unknown>> {
348+
opts?.signal?.throwIfAborted();
348349
const searchConfig = mergeScopedSearchConfig(
349350
ctx.searchConfig,
350351
"kimi",
@@ -397,6 +398,7 @@ export async function executeKimiWebSearchProviderTool(
397398
timeoutSeconds: resolveSearchTimeoutSeconds(searchConfig),
398399
signal: opts?.signal,
399400
});
401+
opts?.signal?.throwIfAborted();
400402
if (!result.grounded) {
401403
return {
402404
error: "kimi_web_search_ungrounded",

‎extensions/moonshot/src/kimi-web-search-provider.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,36 @@ describe("kimi web search provider", () => {
303303
});
304304
});
305305

306+
it("does not cache a grounded Kimi result completed after caller cancellation", async () => {
307+
const controller = new AbortController();
308+
const reason = new Error("Kimi search cancelled after response");
309+
const grounded = {
310+
search_results: [{ title: "OpenClaw", url: "https://github.com/openclaw/openclaw" }],
311+
choices: [{ finish_reason: "stop", message: { content: "OpenClaw is on GitHub." } }],
312+
};
313+
const fetchMock = vi
314+
.fn()
315+
.mockImplementationOnce(async () => {
316+
controller.abort(reason);
317+
return jsonResponse(grounded);
318+
})
319+
.mockResolvedValueOnce(jsonResponse(grounded));
320+
vi.stubGlobal("fetch", fetchMock);
321+
322+
await withEnvAsync({ KIMI_API_KEY: "kimi-test-key" }, async () => {
323+
const tool = createKimiWebSearchProvider().createTool({ config: {}, searchConfig: {} });
324+
if (!tool) {
325+
throw new Error("Expected tool definition");
326+
}
327+
const query = "unique Kimi late-cancel cache regression";
328+
329+
await expect(tool.execute({ query }, { signal: controller.signal })).rejects.toBe(reason);
330+
await tool.execute({ query });
331+
332+
expect(fetchMock).toHaveBeenCalledTimes(2);
333+
});
334+
});
335+
306336
it("uses config apiKey when provided", () => {
307337
expect(testing.resolveKimiApiKey({ apiKey: "kimi-test-key" })).toBe("kimi-test-key");
308338
});

‎extensions/parallel/src/parallel-free-web-search-provider.runtime.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ export async function executeParallelFreeWebSearchProviderTool(
2121
args: Record<string, unknown>,
2222
signal?: AbortSignal,
2323
): Promise<Record<string, unknown>> {
24+
signal?.throwIfAborted();
2425
const searchConfig = mergeScopedSearchConfig(
2526
ctx.searchConfig,
2627
"parallel-free",
@@ -59,6 +60,7 @@ export async function executeParallelFreeWebSearchProviderTool(
5960
timeoutSeconds: resolveSearchTimeoutSeconds(searchConfig),
6061
signal,
6162
});
63+
signal?.throwIfAborted();
6264
const payload = buildParallelSearchPayload({
6365
provider: "parallel-free",
6466
objective,

‎extensions/parallel/src/parallel-web-search-provider.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ type ToolParameters = {
1616
};
1717
const endpointMockState = vi.hoisted(() => ({
1818
calls: [] as EndpointCall[],
19+
effects: [] as Array<(() => void) | undefined>,
1920
responses: [] as Response[],
2021
}));
2122
vi.mock("openclaw/plugin-sdk/provider-web-search", async (importOriginal) => {
@@ -29,6 +30,7 @@ vi.mock("openclaw/plugin-sdk/provider-web-search", async (importOriginal) => {
2930
if (!response) {
3031
throw new Error("Missing mocked Parallel response.");
3132
}
33+
endpointMockState.effects.shift()?.();
3234
return await run(response);
3335
},
3436
),
@@ -120,6 +122,7 @@ const cacheKey = (overrides: Partial<CacheKeyParams> = {}) =>
120122
testing.buildParallelCacheKey({ ...CACHE_KEY_BASE, ...overrides });
121123
beforeEach(() => {
122124
endpointMockState.calls = [];
125+
endpointMockState.effects = [];
123126
endpointMockState.responses = [];
124127
});
125128
describe("parallel web search provider", () => {
@@ -711,6 +714,24 @@ describe("parallel-free web search provider", () => {
711714
expect(endpointMockState.calls.every((call) => call.signal === controller.signal)).toBe(true);
712715
});
713716

717+
it("does not cache a free MCP result completed after caller cancellation", async () => {
718+
const controller = new AbortController();
719+
const reason = new Error("Parallel free search cancelled after response");
720+
pushMcpHandshake({ search_id: "cancelled-free", results: [] });
721+
pushMcpHandshake({ search_id: "recovered-free", results: [] });
722+
endpointMockState.effects.push(undefined, undefined, () => controller.abort(reason));
723+
const args = {
724+
objective: "verify Parallel cancellation cache ownership",
725+
search_queries: ["parallel cancellation cache"],
726+
};
727+
728+
await expect(freeTool().execute(args, { signal: controller.signal })).rejects.toBe(reason);
729+
const recovered = await freeTool().execute(args);
730+
731+
expect(endpointMockState.calls).toHaveLength(6);
732+
expect(recovered.searchId).toBe("recovered-free");
733+
});
734+
714735
it("exposes keyless metadata without claiming auto-detect fallback", () => {
715736
const provider = createParallelFreeWebSearchProvider();
716737
expect(provider.id).toBe("parallel-free");

‎extensions/tavily/src/tavily-client.test.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { createStreamingResponse } from "../../test-support/streaming-error-resp
44

55
// Capture every call to postTrustedWebToolsJson so we can assert on extraHeaders.
66
const postTrustedWebToolsJson = vi.fn();
7+
const writeCache = vi.fn();
78

89
vi.mock("openclaw/plugin-sdk/provider-web-search", async (importOriginal) => ({
910
...(await importOriginal<typeof import("openclaw/plugin-sdk/provider-web-search")>()),
@@ -12,7 +13,7 @@ vi.mock("openclaw/plugin-sdk/provider-web-search", async (importOriginal) => ({
1213
postTrustedWebToolsJson,
1314
readCache: () => undefined,
1415
resolveCacheTtlMs: () => 300_000,
15-
writeCache: vi.fn(),
16+
writeCache,
1617
}));
1718

1819
vi.mock("./config.js", () => ({
@@ -33,6 +34,7 @@ describe("tavily client X-Client-Source header", () => {
3334

3435
beforeEach(() => {
3536
postTrustedWebToolsJson.mockReset();
37+
writeCache.mockReset();
3638
postTrustedWebToolsJson.mockImplementation(
3739
async (_params: unknown, parse: (r: Response) => Promise<unknown>) =>
3840
parse(Response.json({ results: [] })),
@@ -294,4 +296,27 @@ describe("tavily client X-Client-Source header", () => {
294296
expect(postTrustedWebToolsJson.mock.calls[0]?.[0]?.signal).toBe(controller.signal);
295297
},
296298
);
299+
300+
it.each(["search", "extract"] as const)(
301+
"does not cache a %s result completed after caller cancellation",
302+
async (kind) => {
303+
const controller = new AbortController();
304+
const reason = new Error(`${kind} cancelled after response`);
305+
postTrustedWebToolsJson.mockImplementationOnce(async () => {
306+
controller.abort(reason);
307+
return { results: [] };
308+
});
309+
310+
const operation =
311+
kind === "search"
312+
? runTavilySearch({ query: "late cancel", signal: controller.signal })
313+
: runTavilyExtract({
314+
urls: ["https://example.com/late-cancel"],
315+
signal: controller.signal,
316+
});
317+
318+
await expect(operation).rejects.toBe(reason);
319+
expect(writeCache).not.toHaveBeenCalled();
320+
},
321+
);
297322
});

‎extensions/tavily/src/tavily-client.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@ export async function runTavilySearch(
203203
errorLabel: "Tavily Search",
204204
...(params.signal ? { signal: params.signal } : {}),
205205
});
206+
params.signal?.throwIfAborted();
206207

207208
const rawResults = Array.isArray(payload.results) ? payload.results : [];
208209
let remainingSearchContentChars = TAVILY_SEARCH_MAX_CONTENT_CHARS;
@@ -321,6 +322,7 @@ export async function runTavilyExtract(
321322
responseMaxBytes: TAVILY_EXTRACT_RESPONSE_MAX_BYTES,
322323
...(params.signal ? { signal: params.signal } : {}),
323324
});
325+
params.signal?.throwIfAborted();
324326

325327
const rawResults = Array.isArray(payload.results) ? payload.results : [];
326328
let remainingContentChars = TAVILY_EXTRACT_MAX_CONTENT_CHARS;

‎extensions/xai/src/web-search-provider.runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@ function runXaiWebSearch(params: {
153153
inlineCitations: params.inlineCitations,
154154
...(params.signal ? { signal: params.signal } : {}),
155155
});
156+
params.signal?.throwIfAborted();
156157
const payload = buildXaiWebSearchPayload({
157158
query: params.query,
158159
provider: "grok",

‎extensions/xai/web-search.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -840,6 +840,29 @@ describe("xai web search config resolution", () => {
840840
expect(transportSignal?.reason).toBe(reason);
841841
});
842842

843+
it("does not cache a Grok result completed after caller cancellation", async () => {
844+
const controller = new AbortController();
845+
const reason = new Error("Grok search cancelled after response");
846+
const mockFetch = vi
847+
.fn()
848+
.mockImplementationOnce(async () => {
849+
controller.abort(reason);
850+
return xaiAnswerResponse("Cancelled Grok answer");
851+
})
852+
.mockResolvedValueOnce(xaiAnswerResponse("Recovered Grok answer"));
853+
global.fetch = withFetchPreconnect(mockFetch);
854+
const tool = requireXaiWebSearchTool({
855+
config: xaiPluginConfig({ webSearch: { apiKey: "xai-cancel-cache-key" } }),
856+
});
857+
const query = "unique Grok late-cancel cache regression";
858+
859+
await expect(tool.execute({ query }, { signal: controller.signal })).rejects.toBe(reason);
860+
const recovered = await tool.execute({ query });
861+
862+
expect(mockFetch).toHaveBeenCalledTimes(2);
863+
expect(recovered.content).toContain("Recovered Grok answer");
864+
});
865+
843866
it("does not contact the generic xAI provider when the caller is already cancelled", async () => {
844867
const mockFetch = installXaiWebSearchFetch();
845868
const controller = new AbortController();

0 commit comments

Comments
 (0)