Skip to content

Commit c0775c7

Browse files
authored
fix(search): preserve provider cache hits across equivalent queries (#126798)
1 parent 701b576 commit c0775c7

4 files changed

Lines changed: 116 additions & 30 deletions

File tree

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

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import {
88
import {
99
buildSearchCacheKey,
1010
buildUnsupportedSearchFilterResponse,
11-
DEFAULT_SEARCH_COUNT,
1211
MAX_SEARCH_COUNT,
1312
parseWebSearchTimeFilters,
1413
readCachedSearchPayload,
@@ -18,7 +17,6 @@ import {
1817
readStringParam,
1918
resolveCitationRedirectUrl,
2019
resolveSearchCacheTtlMs,
21-
resolveSearchCount,
2220
resolveSearchTimeoutSeconds,
2321
type SearchConfigRecord,
2422
withTrustedWebSearchEndpoint,
@@ -126,7 +124,7 @@ function freshnessStartTime(freshness: GeminiFreshness, now: Date): string {
126124
return toGeminiTimeRangeTimestamp(start);
127125
}
128126

129-
function queryWithSoftFreshness(query: string, freshness?: "day"): string {
127+
function queryWithSoftFreshness(query: string, freshness?: GeminiFreshness): string {
130128
if (freshness !== "day") {
131129
return query;
132130
}
@@ -137,7 +135,12 @@ function resolveGeminiTimeRangeFilter(
137135
args: Record<string, unknown>,
138136
now = new Date(),
139137
):
140-
| { timeRangeFilter?: GeminiTimeRangeFilter; freshness?: "day" }
138+
| {
139+
timeRangeFilter?: GeminiTimeRangeFilter;
140+
freshness?: GeminiFreshness;
141+
dateAfter?: string;
142+
dateBefore?: string;
143+
}
141144
| {
142145
error:
143146
| "invalid_freshness"
@@ -175,6 +178,7 @@ function resolveGeminiTimeRangeFilter(
175178
};
176179
}
177180
return {
181+
freshness,
178182
timeRangeFilter: {
179183
startTime: freshnessStartTime(freshness, now),
180184
endTime: toGeminiTimeRangeTimestamp(now),
@@ -187,6 +191,8 @@ function resolveGeminiTimeRangeFilter(
187191
}
188192

189193
return {
194+
dateAfter,
195+
dateBefore,
190196
timeRangeFilter: {
191197
startTime: dateAfter ? isoDateStart(dateAfter) : "1970-01-01T00:00:00Z",
192198
endTime: dateBefore ? isoDateExclusiveEnd(dateBefore) : toGeminiTimeRangeTimestamp(now),
@@ -413,13 +419,10 @@ export async function executeGeminiSearch(
413419
}
414420

415421
const query = readStringParam(args, "query", { required: true });
416-
const count =
417-
readPositiveIntegerParam(args, "count", {
418-
max: MAX_SEARCH_COUNT,
419-
message: `count must be an integer from 1 to ${MAX_SEARCH_COUNT}.`,
420-
}) ??
421-
searchConfig?.maxResults ??
422-
undefined;
422+
void readPositiveIntegerParam(args, "count", {
423+
max: MAX_SEARCH_COUNT,
424+
message: `count must be an integer from 1 to ${MAX_SEARCH_COUNT}.`,
425+
});
423426
const model = resolveGeminiModel(geminiConfig);
424427
const baseUrl = resolveGeminiBaseUrl(geminiConfig);
425428
const headers = resolveGeminiWebSearchHeaders(geminiConfig);
@@ -435,12 +438,11 @@ export async function executeGeminiSearch(
435438
const cacheKey = buildSearchCacheKey([
436439
"gemini",
437440
query,
438-
resolveSearchCount(count, DEFAULT_SEARCH_COUNT),
439441
baseUrl,
440442
model,
441443
timeRange.freshness,
442-
timeRange.timeRangeFilter?.startTime,
443-
timeRange.timeRangeFilter?.endTime,
444+
timeRange.dateAfter,
445+
timeRange.dateBefore,
444446
headersCacheKey,
445447
]);
446448
const cached = readCachedSearchPayload(cacheKey);

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

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,22 @@ describe("google web search provider", () => {
194194
expect(postCalls).toHaveLength(2);
195195
});
196196

197+
it("reuses cached Gemini answers across ignored result counts while rejecting invalid counts", async () => {
198+
const mockFetch = installGeminiFetch();
199+
const tool = createGeminiToolWithHeaders({});
200+
const query = "unique Gemini ignored result count cache regression";
201+
202+
await tool?.execute({ query, count: 1 });
203+
await tool?.execute({ query, count: 10 });
204+
await tool?.execute({ query });
205+
206+
await expect(tool?.execute({ query, count: 0 })).rejects.toThrow(
207+
"count must be an integer from 1 to 10.",
208+
);
209+
const postCalls = mockFetch.mock.calls.filter(([, init]) => typeof init?.body === "string");
210+
expect(postCalls).toHaveLength(1);
211+
});
212+
197213
it("does not partition cached results by overwritten provider-owned headers", async () => {
198214
const mockFetch = installGeminiFetch();
199215

@@ -720,6 +736,51 @@ describe("google web search provider", () => {
720736
expect(thirdBody.contents?.[0]?.parts?.[0]?.text).toBe("same query cache partition");
721737
});
722738

739+
it.each([
740+
{
741+
label: "relative freshness",
742+
filter: { freshness: "week" },
743+
equivalentFilter: { freshness: "pw" },
744+
distinctFilter: { freshness: "month" },
745+
initialTimeRange: {
746+
startTime: "2026-04-08T12:00:00Z",
747+
endTime: "2026-04-15T12:00:00Z",
748+
},
749+
},
750+
{
751+
label: "open-ended date ranges",
752+
filter: { date_after: "2026-04-01" },
753+
equivalentFilter: { date_after: "2026-04-01" },
754+
distinctFilter: { date_after: "2026-04-02" },
755+
initialTimeRange: {
756+
startTime: "2026-04-01T00:00:00Z",
757+
endTime: "2026-04-15T12:00:00Z",
758+
},
759+
},
760+
])(
761+
"reuses Gemini $label cache entries as the clock advances without merging distinct filters",
762+
async ({ label, filter, equivalentFilter, distinctFilter, initialTimeRange }) => {
763+
vi.useFakeTimers({ toFake: ["Date"] });
764+
vi.setSystemTime(new Date("2026-04-15T12:00:00.123Z"));
765+
const mockFetch = installGeminiFetch();
766+
const tool = createGeminiToolWithHeaders({});
767+
const query = `unique Gemini ${label} moving-clock cache regression`;
768+
769+
await tool?.execute({ query, ...filter });
770+
vi.setSystemTime(new Date("2026-04-15T12:00:02.123Z"));
771+
const cached = await tool?.execute({ query, ...equivalentFilter });
772+
773+
expect(cached).toMatchObject({ cached: true });
774+
expect(parseGeminiFetchBody(mockFetch).tools?.[0]?.google_search?.timeRangeFilter).toEqual(
775+
initialTimeRange,
776+
);
777+
778+
await tool?.execute({ query, ...distinctFilter });
779+
const postCalls = mockFetch.mock.calls.filter(([, init]) => typeof init?.body === "string");
780+
expect(postCalls).toHaveLength(2);
781+
},
782+
);
783+
723784
it("strips sub-second precision from date-range timestamps so Gemini accepts them", async () => {
724785
vi.useFakeTimers({ toFake: ["Date"] });
725786
// "now" with non-zero milliseconds. Without stripping, toISOString() emits

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

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import type { OpenClawConfig } from "openclaw/plugin-sdk/provider-onboard";
77
import {
88
buildSearchCacheKey,
99
buildUnsupportedSearchFilterResponse,
10-
DEFAULT_SEARCH_COUNT,
1110
MAX_SEARCH_COUNT,
1211
mergeScopedSearchConfig,
1312
readCachedSearchPayload,
@@ -17,7 +16,6 @@ import {
1716
readStringParam,
1817
resolveProviderWebSearchPluginConfig,
1918
resolveSearchCacheTtlMs,
20-
resolveSearchCount,
2119
resolveSearchTimeoutSeconds,
2220
setProviderWebSearchPluginConfigValue,
2321
type SearchConfigRecord,
@@ -366,22 +364,13 @@ export async function executeKimiWebSearchProviderTool(
366364
}
367365

368366
const query = readStringParam(args, "query", { required: true });
369-
const count =
370-
readPositiveIntegerParam(args, "count", {
371-
max: MAX_SEARCH_COUNT,
372-
message: `count must be an integer from 1 to ${MAX_SEARCH_COUNT}.`,
373-
}) ??
374-
searchConfig?.maxResults ??
375-
undefined;
367+
void readPositiveIntegerParam(args, "count", {
368+
max: MAX_SEARCH_COUNT,
369+
message: `count must be an integer from 1 to ${MAX_SEARCH_COUNT}.`,
370+
});
376371
const model = resolveKimiModel(kimiConfig);
377372
const baseUrl = resolveKimiBaseUrl(kimiConfig, ctx.config);
378-
const cacheKey = buildSearchCacheKey([
379-
"kimi",
380-
query,
381-
resolveSearchCount(count, DEFAULT_SEARCH_COUNT),
382-
baseUrl,
383-
model,
384-
]);
373+
const cacheKey = buildSearchCacheKey(["kimi", query, baseUrl, model]);
385374
const cached = readCachedSearchPayload(cacheKey);
386375
if (cached) {
387376
return cached;

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,40 @@ describe("kimi web search provider", () => {
298298
});
299299
});
300300

301+
it("reuses cached Kimi answers across ignored result counts while rejecting invalid counts", async () => {
302+
const fetchMock = vi.fn(() =>
303+
Promise.resolve(
304+
jsonResponse({
305+
search_results: [{ title: "OpenClaw", url: "https://github.com/openclaw/openclaw" }],
306+
choices: [
307+
{
308+
finish_reason: "stop",
309+
message: { content: "OpenClaw is on GitHub." },
310+
},
311+
],
312+
}),
313+
),
314+
);
315+
vi.stubGlobal("fetch", fetchMock);
316+
317+
await withEnvAsync({ KIMI_API_KEY: "kimi-test-key" }, async () => {
318+
const tool = createKimiWebSearchProvider().createTool({ config: {}, searchConfig: {} });
319+
if (!tool) {
320+
throw new Error("Expected tool definition");
321+
}
322+
const query = "unique Kimi ignored result count cache regression";
323+
324+
await tool.execute({ query, count: 1 });
325+
await tool.execute({ query, count: 10 });
326+
await tool.execute({ query });
327+
328+
await expect(tool.execute({ query, count: 0 })).rejects.toThrow(
329+
"count must be an integer from 1 to 10.",
330+
);
331+
expect(fetchMock).toHaveBeenCalledOnce();
332+
});
333+
});
334+
301335
it("returns original tool arguments as tool content", () => {
302336
const rawArguments = ' {"query":"MacBook Neo","usage":{"total_tokens":123}} ';
303337

0 commit comments

Comments
 (0)