diff --git a/src/web-search/parse.ts b/src/web-search/parse.ts index e8eee539483..b7db6a91033 100644 --- a/src/web-search/parse.ts +++ b/src/web-search/parse.ts @@ -1,6 +1,7 @@ import { sseFieldValue } from "../lib/sse-decoder"; import { appendSafeWebSearchSource, + fillMissingWebSearchSourceTitle, safeWebSearchSources, type SafeWebSearchSource, } from "./sources"; @@ -323,7 +324,7 @@ export const MAX_SIDECAR_DECODED_CHARS = 64 * 1024; function collectAnnotation(ann: AnnotationLike | undefined, sources: WebSearchSource[], seen: Set): void { if (!ann || ann.type !== "url_citation" || typeof ann.url !== "string") return; if (seen.has(ann.url)) { - fillMissingTitle(sources, ann.url, ann.title); + fillMissingWebSearchSourceTitle(sources, ann.url, ann.title); return; } if (appendSafeWebSearchSource(sources, { @@ -332,17 +333,6 @@ function collectAnnotation(ann: AnnotationLike | undefined, sources: WebSearchSo })) seen.add(ann.url); } -function fillMissingTitle(sources: WebSearchSource[], url: string, title: unknown): void { - if (title === undefined) return; - const index = sources.findIndex(source => source.url === url); - if (index < 0 || sources[index]!.title !== undefined) return; - const candidate = sources.map((source, at) => at === index ? { url, title } : source); - // Re-run the shared checks: an invalid title is dropped, and a title that would push the - // list past its byte cap drops a source, so either outcome leaves the list unchanged. - const checked = safeWebSearchSources(candidate); - if (checked.length === sources.length && checked[index]!.title !== undefined) sources[index] = checked[index]!; -} - /** * Hosted web_search (gpt-mini) rarely emits structured `url_citation` annotations; instead it ends * its answer with a markdown `Sources:` section. Extract sources from that TRAILING section only diff --git a/src/web-search/sources.ts b/src/web-search/sources.ts index 4b9d7abbb01..199dc77a35d 100644 --- a/src/web-search/sources.ts +++ b/src/web-search/sources.ts @@ -52,6 +52,19 @@ export function appendSafeWebSearchSource(target: SafeWebSearchSource[], source: return true; } +/** Fill one validated citation's missing title without rebuilding or revalidating its peers. */ +export function fillMissingWebSearchSourceTitle(target: SafeWebSearchSource[], url: string, value: unknown): void { + const title = safeTitle(value); + if (title === undefined) return; + const index = target.findIndex(source => source.url === url); + if (index < 0 || target[index]!.title !== undefined) return; + const previous = target[index]!; + const next = { url: previous.url, title }; + const delta = serializedSourceBytes(next) - serializedSourceBytes(previous); + const usedBytes = target.reduce((sum, source) => sum + serializedSourceBytes(source), 0); + if (usedBytes + delta <= MAX_WEB_SEARCH_SOURCE_BYTES) target[index] = next; +} + export function safeWebSearchSources(sources: unknown): SafeWebSearchSource[] { if (!Array.isArray(sources)) return []; const safe: SafeWebSearchSource[] = []; diff --git a/structure/data-planes/search.md b/structure/data-planes/search.md index 61b731fbf49..4d0e7f90050 100644 --- a/structure/data-planes/search.md +++ b/structure/data-planes/search.md @@ -79,6 +79,6 @@ Linking snapshots compare the accumulated content indexes of both candidate part Trailing source extraction in `src/web-search/parse.ts` pairs a pending title with a following URL only when the URL sits on an unmarked continuation line with no title of its own. A list item that cannot be paired, because another list item, a self-titled citation, or a URL that starts its own list item follows it, remains answer text, and extraction continues, so every later citation line, including one whose URL `appendSafeWebSearchSource` rejects, still leaves the answer. Non-HTTP URI-like text inside an inline code span of any backtick run, such as `mode:fast`, is not treated as a citation; an HTTP(S) URL is a citation even when code-formatted, and a closing code backtick is trimmed from it. Code spans are found by pairing backtick runs in one pass and the URI scheme length is bounded, so a long Sources line is scanned in linear time. -Completed-output citations are deduplicated independently of streaming annotations, so an earlier copy of a URL cannot hide its final title. A safe final title takes precedence, including one carried by a later completed annotation for a URL whose first completed annotation had no usable title; the upgraded entry keeps its first position and must still fit the byte limit. When no safe final title exists, a safe streamed title for that URL is retained. Final sources are merged before streaming-only sources, with the existing count and byte limits applied to the merged records. `tests/web-search/web-search-sources.test.ts` covers metadata precedence, fallback, ordering and sanitization. +Completed-output citations are deduplicated independently of streaming annotations, so an earlier copy of a URL cannot hide its final title. A safe final title takes precedence, including one carried by a later completed annotation for a URL whose first completed annotation had no usable title; the upgraded entry keeps its first position and must still fit the byte limit. `src/web-search/sources.ts` validates an offered title before inspecting the retained list, so invalid duplicates do not repeat source serialization. A valid replacement checks only its serialized UTF-8 byte delta against the retained list's aggregate size, without rebuilding or revalidating other sources. When no safe final title exists, a safe streamed title for that URL is retained. Final sources are merged before streaming-only sources, with the existing count and byte limits applied to the merged records. `tests/web-search/web-search-sources.test.ts` covers metadata precedence, fallback, ordering, sanitization, duplicate processing work and exact replacement-byte limits. Single-result query and answer truncation in `src/web-search/format-result.ts` uses the same surrogate-safe prefix as batched results. The existing UTF-16 limits and truncation markers remain unchanged. diff --git a/tests/responses/sse-untyped-credential-mask.test.ts b/tests/responses/sse-untyped-credential-mask.test.ts index f902ff185f4..982f0d28fa6 100644 --- a/tests/responses/sse-untyped-credential-mask.test.ts +++ b/tests/responses/sse-untyped-credential-mask.test.ts @@ -1,9 +1,11 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, spyOn, test } from "bun:test"; import { addFinalRequestLog, inspectResponseLogSsePayload, type RequestLogContext } from "../../src/server/request-log"; import { relaySseWithFailedTail } from "../../src/server"; import { relaySseEagerBounded, type EagerRelayHooks } from "../../src/server/relay-eager"; import { createForwardedEvidenceRedaction, createOutboundCredentialMask, createSynthesizedCopyMask, createTerminalErrorRedactionBlockRewrite } from "../../src/server/responses/terminal-error-redaction"; -import { OutboundCredentialRegistry, createSentValueGuard, maskSecretSpans, setOutboundCredentialRegistryForTests } from "../../src/lib/outbound-credential-registry"; +import { OutboundCredentialRegistry, createSentValueGuard, createSentValueMask, maskSecretSpans, setOutboundCredentialRegistryForTests } from "../../src/lib/outbound-credential-registry"; +import { REDACTED_SECRET } from "../../src/lib/redact"; +import { sseDataPayload } from "../../src/server/sse-payload-rewrite"; import { noteRelaySyntheticTail, noteRequestSentValueGuard } from "../../src/server/request-log-terminal-status"; import { reduceBareUpstreamEvidence } from "../../src/server/bare-upstream-error"; @@ -534,7 +536,8 @@ describe("untyped error envelopes never carry a value this request sent", () => test("excerpt masking of a large genuine terminal stays linear in the frame size", () => { // Every distinct matching window used to rescan the whole text: about 64k windows over a ~4 MB - // frame stalled the event loop for seconds. One marking pass keeps it to tens of milliseconds. + // frame stalled the event loop for seconds. Time that same excerpt masker directly; JSON/SSE + // serialization and the separate pattern masks are covered by the full rewrite checks below. const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const credentials = [1, 2, 3, 4].map(seed => { let state = seed; @@ -542,14 +545,44 @@ describe("untyped error envelopes never carry a value this request sent", () => for (let i = 0; i < 16_000; i++) { state = (state * 1103515245 + 12345) & 0x7fffffff; value += alphabet[state % 62]; } return value; }); - const rewrite = createTerminalErrorRedactionBlockRewrite(Object.fromEntries(credentials.map((value, i) => [`x-api-key-${i}`, value]))); + const headers = Object.fromEntries(credentials.map((value, i) => [`x-api-key-${i}`, value])); + const rewrite = createTerminalErrorRedactionBlockRewrite(headers); + const mask = createSentValueMask(headers, REDACTED_SECRET, { credentialOnly: true, wholeText: true }); const echoed = credentials.map(value => value.slice(0, -1)).join(" "); - const failed = { type: "response.failed", response: { status: "failed", error: { code: "server_error", message: echoed + " " + "z".repeat(3_900_000 - echoed.length) } } }; + const suffix = "z".repeat(3_900_000 - echoed.length); + const message = echoed + " " + suffix; const startedAt = performance.now(); - const out = rewrite(`event: response.failed\ndata: ${JSON.stringify(failed)}`).join("\n"); + const masked = mask(message); const elapsed = performance.now() - startedAt; - expect(credentials.some(value => out.includes(value.slice(100, 140)))).toBe(false); + expect(credentials.some(value => masked.includes(value.slice(100, 140)))).toBe(false); + expect(masked.endsWith(" " + suffix)).toBe(true); expect(elapsed).toBeLessThan(1_500); + + const failed = { type: "response.failed", response: { status: "failed", error: { code: "server_error", message } } }; + const out = rewrite(`event: response.failed\ndata: ${JSON.stringify(failed)}`).join("\n"); + expect(credentials.some(value => out.includes(value.slice(100, 140)))).toBe(false); + const payload = sseDataPayload(out); + expect(payload).not.toBeNull(); + expect(JSON.parse(payload!).response.error.message).toBe(masked); + }); + + test("excerpt masking does not restart a whole-text search for every matching window", () => { + const credential = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".repeat(4); + const suffix = "~".repeat(8192); + const text = credential.slice(0, -1) + " " + suffix; + const mask = createSentValueMask({ "x-api-key": credential }, REDACTED_SECRET, { credentialOnly: true, wholeText: true }); + const indexOf = String.prototype.indexOf; + let restarts = 0, masked = ""; + const scan = spyOn(String.prototype, "indexOf").mockImplementation(function (this: string, search: string, position?: number) { + if (String(this) === text && (position ?? 0) <= 0 && ++restarts > 8) { + throw new Error("excerpt masking repeatedly rescanned the whole input"); + } + return indexOf.call(this, search, position); + }); + try { masked = mask(text); } + finally { scan.mockRestore(); } + expect(masked).toBe(REDACTED_SECRET + " " + suffix); + expect(restarts).toBeLessThanOrEqual(8); }); test("exact masking of a self-overlapping credential stays linear in the frame size", () => { diff --git a/tests/web-search/web-search-sources.test.ts b/tests/web-search/web-search-sources.test.ts index 6a2ba2d9fb4..57e9345ffa7 100644 --- a/tests/web-search/web-search-sources.test.ts +++ b/tests/web-search/web-search-sources.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, spyOn, test } from "bun:test"; import { parseSidecarSSE } from "../../src/web-search/parse"; import { MAX_WEB_SEARCH_SOURCE_BYTES, @@ -103,6 +103,62 @@ describe("sidecar final citation metadata", () => { ]); }); + test("invalid duplicate titles do not reserialize the retained source list", async () => { + const initial = Array.from({ length: MAX_WEB_SEARCH_SOURCES }, (_, index) => ({ + type: "url_citation", url: `https://duplicate-title.test/${index}/${"a".repeat(400)}`, + })); + const invalid = ["", " ", "bad\u0001title", 42, "x".repeat(MAX_WEB_SEARCH_TITLE_BYTES + 1)]; + const duplicates = Array.from({ length: 40 }, (_, index) => ({ + type: "url_citation", url: initial[0]!.url, title: invalid[index % invalid.length], + })); + const measure = async (annotations: unknown[]) => { + const response = sourceResponse([completedSources(annotations)]); + const stringify = spyOn(JSON, "stringify"); + try { + const result = await parseSidecarSSE(response); + const serializations = stringify.mock.calls.filter(([value]) => value !== null + && typeof value === "object" && "url" in value).length; + return { result, serializations }; + } finally { stringify.mockRestore(); } + }; + const baseline = await measure(initial); + const repeated = await measure([...initial, ...duplicates]); + expect(repeated.result).toEqual(baseline.result); + expect(repeated.result.sources).toHaveLength(MAX_WEB_SEARCH_SOURCES); + expect(repeated.serializations).toBe(baseline.serializations); + const filled = await parseSidecarSSE(sourceResponse([completedSources([ + ...initial, ...duplicates, { type: "url_citation", url: initial[0]!.url, title: "Later valid title" }, + ])])); + expect(filled.sources[0]).toEqual({ url: initial[0]!.url, title: "Later valid title" }); + expect(filled.sources.slice(1)).toEqual(baseline.result.sources.slice(1)); + }); + + test("title replacement checks the exact UTF-8 byte delta without dropping other sources", async () => { + const first = { url: "https://title-delta.test/first" }; + const sources = [first, ...Array.from({ length: 7 }, (_, index) => ({ + url: `https://title-delta.test/${index}/${"a".repeat(2002)}`, + }))]; + const title = "😀"; + const delta = byteLength(JSON.stringify({ ...first, title })) - byteLength(JSON.stringify(first)); + const tail = { url: "https://title-delta.test/tail/" }; + const used = [...sources, tail].reduce((sum, source) => sum + byteLength(JSON.stringify(source)), 0); + tail.url += "a".repeat(MAX_WEB_SEARCH_SOURCE_BYTES - delta - used); + sources.push(tail); + expect(byteLength(tail.url)).toBeLessThanOrEqual(MAX_WEB_SEARCH_URL_BYTES); + const initial = sources.map(source => ({ type: "url_citation", ...source })); + const rejected = await parseSidecarSSE(sourceResponse([completedSources([ + ...initial, { type: "url_citation", url: first.url, title: `${title}a` }, + ])])); + expect(rejected.sources).toEqual(sources); + const accepted = await parseSidecarSSE(sourceResponse([completedSources([ + ...initial, { type: "url_citation", url: first.url, title: `${title}a` }, + { type: "url_citation", url: first.url, title }, + ])])); + expect(accepted.sources).toEqual([{ ...first, title }, ...sources.slice(1)]); + expect(accepted.sources.reduce((sum, source) => sum + byteLength(JSON.stringify(source)), 0)) + .toBe(MAX_WEB_SEARCH_SOURCE_BYTES); + }); + test("final citations retain their order without exceeding the source cap", async () => { const final = Array.from({ length: MAX_WEB_SEARCH_SOURCES }, (_, index) => ({ type: "url_citation", url: `https://example.test/${index}`, title: `Final ${index}`,