Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

fix(search): route highlights beta through indexed chain (#4038)

Gergő Móriczdc3977bc2737
diff --git a/apps/api/src/search/execute.ts b/apps/api/src/search/execute.ts
index 74c43cdc9..0fd58c123 100644
--- a/apps/api/src/search/execute.ts
+++ b/apps/api/src/search/execute.ts
@@ -13,7 +13,7 @@ import {
mergeScrapedContent,
calculateScrapeCredits,
} from "./scrape";
-import { applySearchHighlights, highlightsEnvReady } from "./highlights";
+import { applyIndexedSearchHighlights, highlightsEnvReady } from "./highlights";
import { runSearchHighlightsShadow } from "./highlights-shadow";
import { trackSearchResults, trackSearchRequest } from "../lib/tracking";
import type { BillingMetadata } from "../services/billing/types";
@@ -253,7 +253,12 @@ export async function executeSearch(
flags?.highlightsBeta === true &&
highlightsEnvReady();
if (shouldApplyHighlights) {
- await applySearchHighlights(searchResponse, query, logger);
+ await applyIndexedSearchHighlights(
+ searchResponse,
+ query,
+ logger,
+ context.requestId,
+ );
} else {
runSearchHighlightsShadow({
response: searchResponse,
diff --git a/apps/api/src/search/highlights.test.ts b/apps/api/src/search/highlights.test.ts
index 5162e6f6a..2f6c11976 100644
--- a/apps/api/src/search/highlights.test.ts
+++ b/apps/api/src/search/highlights.test.ts
@@ -45,6 +45,7 @@ import {
import { config } from "../config";
import { indexGetRecent5 } from "../db/rpc";
import {
+ applyIndexedSearchHighlights,
applySearchHighlights,
highlightsEnvReady,
runIndexedSearchHighlightsShadow,
@@ -114,6 +115,84 @@ describe("runIndexedSearchHighlightsShadow", () => {
});
});
+describe("applyIndexedSearchHighlights", () => {
+ it("uses the shadow indexed request path and applies web and news responses by ID", async () => {
+ vi.mocked(generateHighlightsIndexedBatch).mockResolvedValue(
+ new Map([
+ ["0", { highlights: [], markdown: "first highlight" }],
+ ["1", { highlights: [], markdown: "second highlight" }],
+ ]),
+ );
+ const response = {
+ web: [{ url: "https://first.test", description: "first fallback" }],
+ news: [{ url: "https://second.test", snippet: "second fallback" }],
+ } as any;
+
+ const result = await applyIndexedSearchHighlights(
+ response,
+ "query",
+ logger,
+ "request-1",
+ );
+
+ expect(generateHighlightsIndexedBatch).toHaveBeenCalledWith(
+ "query",
+ [
+ {
+ id: "0",
+ url: "https://first.test",
+ indexObject: "index:https://first.test.json",
+ },
+ {
+ id: "1",
+ url: "https://second.test",
+ indexObject: "index:https://second.test.json",
+ },
+ ],
+ {
+ logger,
+ logPayload: false,
+ requestId: "request-1",
+ timeoutMs: null,
+ onFailure: expect.any(Function),
+ },
+ );
+ expect(generateHighlightsBatch).not.toHaveBeenCalled();
+ expect(response.web[0].description).toBe("first highlight");
+ expect(response.news[0].snippet).toBe("second highlight");
+ expect(result).toEqual({
+ attempted: 2,
+ indexHits: 2,
+ replaced: 2,
+ succeeded: true,
+ });
+ });
+
+ it("preserves provider snippets when the indexed Chain request fails", async () => {
+ vi.mocked(generateHighlightsIndexedBatch).mockResolvedValue(null);
+ const response = {
+ web: [{ url: "https://first.test", description: "first fallback" }],
+ news: [{ url: "https://second.test", snippet: "second fallback" }],
+ } as any;
+
+ const result = await applyIndexedSearchHighlights(
+ response,
+ "query",
+ logger,
+ "request-1",
+ );
+
+ expect(response.web[0].description).toBe("first fallback");
+ expect(response.news[0].snippet).toBe("second fallback");
+ expect(result).toEqual({
+ attempted: 2,
+ indexHits: 2,
+ replaced: 0,
+ succeeded: false,
+ });
+ });
+});
+
describe("applySearchHighlights", () => {
it("enables the in-cluster service without requiring a bearer token", () => {
const token = config.HIGHLIGHT_MODEL_TOKEN;
diff --git a/apps/api/src/search/highlights.ts b/apps/api/src/search/highlights.ts
index d61bc0a3c..a8448c7c1 100644
--- a/apps/api/src/search/highlights.ts
+++ b/apps/api/src/search/highlights.ts
@@ -146,17 +146,42 @@ async function getIndexObjectForURL(
}
}
+interface IndexedSearchHighlightTarget {
+ url: string;
+ apply?: (highlight: string) => void;
+}
+
+function indexedSearchHighlightTargets(
+ response: SearchV2Response,
+): IndexedSearchHighlightTarget[] {
+ const targets: IndexedSearchHighlightTarget[] = [];
+ for (const result of response.web ?? []) {
+ if (!result.url) continue;
+ targets.push({
+ url: result.url,
+ apply: highlight => {
+ result.description = highlight;
+ },
+ });
+ }
+ for (const result of response.news ?? []) {
+ if (!result.url) continue;
+ targets.push({
+ url: result.url,
+ apply: highlight => {
+ result.snippet = highlight;
+ },
+ });
+ }
+ return targets;
+}
+
export function searchHighlightURLs(response: SearchV2Response): string[] {
- return [
- ...(response.web ?? []).flatMap(result => (result.url ? [result.url] : [])),
- ...(response.news ?? []).flatMap(result =>
- result.url ? [result.url] : [],
- ),
- ];
+ return indexedSearchHighlightTargets(response).map(target => target.url);
}
-export async function runIndexedSearchHighlightsShadow(
- urls: string[],
+async function runIndexedSearchHighlights(
+ targets: IndexedSearchHighlightTarget[],
query: string,
logger: Logger,
requestId: string,
@@ -167,16 +192,16 @@ export async function runIndexedSearchHighlightsShadow(
succeeded: boolean;
failureReason?: HighlightFailureReason;
}> {
- const attempted = urls.length;
+ const attempted = targets.length;
const resolved = await Promise.all(
- urls.map(url => getIndexObjectForURL(url, logger, false)),
+ targets.map(target => getIndexObjectForURL(target.url, logger, false)),
);
const pages: HighlightIndexedPage[] = [];
resolved.forEach((indexRef, index) => {
if (!indexRef) return;
pages.push({
id: String(index),
- url: urls[index],
+ url: targets[index].url,
indexObject: indexRef.name,
});
});
@@ -191,10 +216,15 @@ export async function runIndexedSearchHighlightsShadow(
failureReason = reason;
},
});
- const replaced = results
- ? Array.from(results.values()).filter(result => result.markdown.trim())
- .length
- : 0;
+ let replaced = 0;
+ if (results) {
+ for (const page of pages) {
+ const highlight = results.get(page.id)?.markdown;
+ if (!highlight?.trim()) continue;
+ targets[Number(page.id)].apply?.(highlight);
+ replaced++;
+ }
+ }
return {
attempted,
@@ -205,6 +235,42 @@ export async function runIndexedSearchHighlightsShadow(
};
}
+export async function applyIndexedSearchHighlights(
+ response: SearchV2Response,
+ query: string,
+ logger: Logger,
+ requestId: string,
+): ReturnType<typeof runIndexedSearchHighlights> {
+ const start = Date.now();
+ const result = await runIndexedSearchHighlights(
+ indexedSearchHighlightTargets(response),
+ query,
+ logger,
+ requestId,
+ );
+ logger.info("Search highlights applied", {
+ attempted: result.attempted,
+ indexHits: result.indexHits,
+ replaced: result.replaced,
+ timeTakenMs: Date.now() - start,
+ });
+ return result;
+}
+
+export function runIndexedSearchHighlightsShadow(
+ urls: string[],
+ query: string,
+ logger: Logger,
+ requestId: string,
+): ReturnType<typeof runIndexedSearchHighlights> {
+ return runIndexedSearchHighlights(
+ urls.map(url => ({ url })),
+ query,
+ logger,
+ requestId,
+ );
+}
+
/**
* For each search result: look up the URL in our index (last 30 days), and if
* present, replace the provider snippet with query-relevant highlights generated