From 89108013f9381b282ee5766e3537f3185e976ba4 Mon Sep 17 00:00:00 2001 From: Lakshmi Tanmay Date: Mon, 2 Nov 2026 15:33:48 +0530 Subject: [PATCH 1/6] perf(server): keep workspace content searches responsive --- .../workspace/WorkspaceSearchIndex.test.ts | 77 +++++++++++++++++++ .../src/workspace/WorkspaceSearchIndex.ts | 18 +++-- 2 files changed, 87 insertions(+), 8 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 8c42fcf52aabf..4e19dbf5f323c 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -718,6 +718,83 @@ it.effect("finds symlinks in folders past the first page of the index", () => ).pipe(Effect.provide(testLayer)), ); +it.effect.each([false, true])( + "resumes empty budget pages without losing results (hasMatch: %s)", + (hasMatch) => + Effect.scoped( + Effect.gen(function* () { + const clock = vi.spyOn(performance, "now").mockReturnValue(0); + const cursors = [1, 2].map( + (offset) => + ({ + __brand: "GrepCursor", + _offset: offset, + }) as GrepCursor, + ); + let eventLoopServiced = false; + let eventLoopTask: NodeJS.Immediate | undefined; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + if (eventLoopTask) clearImmediate(eventLoopTask); + }), + ); + const grep = vi.fn((_query: string, options?: GrepOptions) => { + const page = options?.cursor ? cursors.indexOf(options.cursor) + 1 : 0; + if (page === 0) { + clock.mockReturnValue(1_000); + eventLoopTask = setImmediate(() => { + eventLoopServiced = true; + }); + } else { + expect(eventLoopServiced).toBe(true); + } + expect(options?.enforceTimeBudget).toBe(true); + const value: GrepResult = { + items: + page === 2 && hasMatch + ? [ + { + ...fileItem("src/late.ts"), + isBinary: false, + lineNumber: 1, + col: 0, + byteOffset: 0, + lineContent: "needle", + matchRanges: [[0, 6]], + }, + ] + : [], + totalMatched: page === 2 && hasMatch ? 1 : 0, + totalFilesSearched: 1, + totalFiles: 3, + filteredFileCount: 3, + nextCursor: cursors[page] ?? null, + }; + return { ok: true as const, value }; + }); + const finder = { + destroy: vi.fn(), + waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), + grep, + } as unknown as FileFinder; + vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); + + const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content"); + const result = yield* searchIndex.searchContents({ + query: "needle", + limit: 10, + caseSensitive: true, + wholeWord: false, + useRegex: false, + }); + + expect(result.matches.map((match) => match.path)).toEqual(hasMatch ? ["src/late.ts"] : []); + expect(result.truncated).toBe(false); + expect(grep).toHaveBeenCalledTimes(3); + }), + ), +); + // fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there. it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "refuses to index a workspace rooted at the home directory", diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index b33ceade77fa5..eecabf60ccc81 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -1,6 +1,8 @@ // @effect-diagnostics nodeBuiltinImport:off - readdir with file types avoids an lstat per child import * as NodeFSP from "node:fs/promises"; import * as NodeModule from "node:module"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- Yield to Node I/O, not just the Effect scheduler. +import * as NodeTimersPromises from "node:timers/promises"; import type { DirItem, @@ -55,7 +57,7 @@ const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2; const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds"; const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000; const WORKSPACE_INDEX_IDLE_TTL = "15 minutes"; -const CONTENT_SEARCH_TIME_BUDGET_MS = 250; +const CONTENT_SEARCH_TIME_BUDGET_MS = 25; const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100; const GIT_GREP_MAX_OUTPUT_BYTES = 4 * 1024 * 1024; // fff's lineContent cap; matches past it are reported without ranges. @@ -1295,7 +1297,6 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( contentIndexPending = false; } let { searchQuery, regexMode } = buildContentSearchQuery(input); - const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS; // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing. const rawPageSize = input.wholeWord ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE) @@ -1306,7 +1307,6 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( let retryLiterally = false; do { - const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now())); const result = yield* runSearch(input.query, input.limit, "grep", () => finder.grepAsync(searchQuery, { mode: regexMode ? "regex" : "plain", @@ -1314,7 +1314,8 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize), pageSize: rawPageSize, cursor: nextCursor, - timeBudgetMs: remainingTimeBudgetMs, + timeBudgetMs: CONTENT_SEARCH_TIME_BUDGET_MS, + enforceTimeBudget: true, }), ); // fff searches an invalid pattern as a literal, which would keep the `(?i)` prefix. @@ -1341,10 +1342,11 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( } nextCursor = result.nextCursor; regexFallbackError ??= result.regexFallbackError; - } while ( - retryLiterally || - (matches.length < input.limit && nextCursor !== null && performance.now() < deadline) - ); + // The RPC has no resume cursor: finish paging internally, letting Node service I/O between pages. + if (matches.length < input.limit && nextCursor !== null) { + yield* Effect.promise((signal) => NodeTimersPromises.setImmediate(undefined, { signal })); + } + } while (retryLiterally || (matches.length < input.limit && nextCursor !== null)); return { matches: matches.slice(0, input.limit), From 90a70d68d18c5ed56311c770125b2454a4f70ad4 Mon Sep 17 00:00:00 2001 From: Lakshmi Tanmay Date: Mon, 2 Nov 2026 16:32:37 +0530 Subject: [PATCH 2/6] perf(server): yield between search pages without diagnostic suppression --- apps/server/src/workspace/WorkspaceSearchIndex.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index eecabf60ccc81..a19c7c61cb29b 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -1,8 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off - readdir with file types avoids an lstat per child import * as NodeFSP from "node:fs/promises"; import * as NodeModule from "node:module"; -// @effect-diagnostics-next-line nodeBuiltinImport:off -- Yield to Node I/O, not just the Effect scheduler. -import * as NodeTimersPromises from "node:timers/promises"; import type { DirItem, @@ -1344,7 +1342,10 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( regexFallbackError ??= result.regexFallbackError; // The RPC has no resume cursor: finish paging internally, letting Node service I/O between pages. if (matches.length < input.limit && nextCursor !== null) { - yield* Effect.promise((signal) => NodeTimersPromises.setImmediate(undefined, { signal })); + yield* Effect.callback((resume) => { + const immediate = setImmediate(() => resume(Effect.void)); + return Effect.sync(() => clearImmediate(immediate)); + }); } } while (retryLiterally || (matches.length < input.limit && nextCursor !== null)); From 4e5de040e1fef0d7afad49ab318942ae8c41b497 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Fri, 6 Nov 2026 08:38:23 +0000 Subject: [PATCH 3/6] fix(server): rerun content search pages that lose native fallback results --- .../workspace/WorkspaceSearchIndex.test.ts | 48 +++++++++++++++++++ .../src/workspace/WorkspaceSearchIndex.ts | 13 +++-- 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 4e19dbf5f323c..0a90554cdfaa8 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -795,6 +795,54 @@ it.effect.each([false, true])( ), ); +it.effect("reruns an enforced page whose path constraint filtered every file", () => + Effect.scoped( + Effect.gen(function* () { + const grep = vi.fn((_query: string, options?: GrepOptions) => { + const fellBack = options?.enforceTimeBudget === false; + const value: GrepResult = { + items: fellBack + ? [ + { + ...fileItem("arch/x86/kernel/head64.c"), + isBinary: false, + lineNumber: 1, + col: 0, + byteOffset: 0, + lineContent: "asmlinkage __visible void start_kernel(void)", + matchRanges: [[0, 44]], + }, + ] + : [], + totalMatched: fellBack ? 1 : 0, + totalFilesSearched: fellBack ? 3 : 0, + totalFiles: 3, + filteredFileCount: fellBack ? 3 : 0, + nextCursor: null, + }; + return { ok: true as const, value }; + }); + const finder = { + destroy: vi.fn(), + waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), + grep, + } as unknown as FileFinder; + vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); + + const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content"); + const result = yield* searchIndex.searchContents({ + query: "[a-z]{90}[-+*/]{5}|asmlinkage __visible.*start_kernel", + limit: 10, + caseSensitive: true, + wholeWord: false, + useRegex: true, + }); + + expect(result.matches.map((match) => match.path)).toEqual(["arch/x86/kernel/head64.c"]); + }), + ), +); + // fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there. it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "refuses to index a workspace rooted at the home directory", diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index a19c7c61cb29b..c16a4b4dd68e2 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -1304,8 +1304,8 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( let regexFallbackError: string | undefined; let retryLiterally = false; - do { - const result = yield* runSearch(input.query, input.limit, "grep", () => + const grepPage = (enforceTimeBudget: boolean) => + runSearch(input.query, input.limit, "grep", () => finder.grepAsync(searchQuery, { mode: regexMode ? "regex" : "plain", smartCase: !input.caseSensitive && !regexMode, @@ -1313,9 +1313,16 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( pageSize: rawPageSize, cursor: nextCursor, timeBudgetMs: CONTENT_SEARCH_TIME_BUDGET_MS, - enforceTimeBudget: true, + enforceTimeBudget, }), ); + + do { + let result = yield* grepPage(true); + // fff 0.11 drops an empty enforced raw-query fallback page's cursor when a parsed path constraint matches no files. + if (result.filteredFileCount === 0 && result.totalFiles > 0) { + result = yield* grepPage(false); + } // fff searches an invalid pattern as a literal, which would keep the `(?i)` prefix. retryLiterally = regexMode && !input.caseSensitive && result.regexFallbackError !== undefined; if (retryLiterally) { From 6684a4ff9a5707769d7165d6f08460c01a02533f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 12:07:04 +0000 Subject: [PATCH 4/6] fix(server): rerun content search fallback pages whose constraint matched files fff drops the cursor of an enforced raw-query fallback page that times out, whether or not the parsed path constraint matched any files. Rerun any empty enforced page that reports the scan ended without enforcement, instead of only those whose constraint matched nothing. Co-Authored-By: Claude Opus 5.5 --- .../workspace/WorkspaceSearchIndex.test.ts | 186 ++++++++---------- .../src/workspace/WorkspaceSearchIndex.ts | 13 +- 2 files changed, 85 insertions(+), 114 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 0a90554cdfaa8..550059d4f6557 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -718,129 +718,105 @@ it.effect("finds symlinks in folders past the first page of the index", () => ).pipe(Effect.provide(testLayer)), ); -it.effect.each([false, true])( - "resumes empty budget pages without losing results (hasMatch: %s)", - (hasMatch) => - Effect.scoped( - Effect.gen(function* () { - const clock = vi.spyOn(performance, "now").mockReturnValue(0); - const cursors = [1, 2].map( - (offset) => - ({ - __brand: "GrepCursor", - _offset: offset, - }) as GrepCursor, - ); - let eventLoopServiced = false; - let eventLoopTask: NodeJS.Immediate | undefined; - yield* Effect.addFinalizer(() => - Effect.sync(() => { - if (eventLoopTask) clearImmediate(eventLoopTask); - }), - ); - const grep = vi.fn((_query: string, options?: GrepOptions) => { - const page = options?.cursor ? cursors.indexOf(options.cursor) + 1 : 0; - if (page === 0) { - clock.mockReturnValue(1_000); - eventLoopTask = setImmediate(() => { - eventLoopServiced = true; - }); - } else { - expect(eventLoopServiced).toBe(true); - } - expect(options?.enforceTimeBudget).toBe(true); - const value: GrepResult = { - items: - page === 2 && hasMatch - ? [ - { - ...fileItem("src/late.ts"), - isBinary: false, - lineNumber: 1, - col: 0, - byteOffset: 0, - lineContent: "needle", - matchRanges: [[0, 6]], - }, - ] - : [], - totalMatched: page === 2 && hasMatch ? 1 : 0, - totalFilesSearched: 1, - totalFiles: 3, - filteredFileCount: 3, - nextCursor: cursors[page] ?? null, - }; - return { ok: true as const, value }; - }); - const finder = { - destroy: vi.fn(), - waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - grep, - } as unknown as FileFinder; - vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); - - const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content"); - const result = yield* searchIndex.searchContents({ - query: "needle", - limit: 10, - caseSensitive: true, - wholeWord: false, - useRegex: false, - }); +function grepMatch(relativePath: string, lineContent: string): GrepResult["items"][number] { + return { + ...fileItem(relativePath), + isBinary: false, + lineNumber: 1, + col: 0, + byteOffset: 0, + lineContent, + matchRanges: [[0, lineContent.length]], + }; +} - expect(result.matches.map((match) => match.path)).toEqual(hasMatch ? ["src/late.ts"] : []); - expect(result.truncated).toBe(false); - expect(grep).toHaveBeenCalledTimes(3); - }), - ), -); +function contentFinder(grepAsync: (query: string, options?: GrepOptions) => Promise) { + const finder = { + destroy: vi.fn(), + waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), + getScanProgressAsync: async () => ({ ok: true as const, value: { isScanning: false, isWarmupComplete: true } }), + watchAsync: async () => ({ ok: true as const, value: () => undefined }), + grepAsync, + } as unknown as FileFinder; + vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); +} -it.effect("reruns an enforced page whose path constraint filtered every file", () => +it.effect("pages past empty time-budget pages to a late match", () => Effect.scoped( Effect.gen(function* () { - const grep = vi.fn((_query: string, options?: GrepOptions) => { - const fellBack = options?.enforceTimeBudget === false; + const clock = vi.spyOn(performance, "now").mockReturnValue(0); + const cursors = [1, 2].map( + (offset) => ({ __brand: "GrepCursor", _offset: offset }) as GrepCursor, + ); + const grep = vi.fn(async (_query: string, options?: GrepOptions) => { + const page = options?.cursor ? cursors.indexOf(options.cursor) + 1 : 0; + // Each page outlasts any overall deadline; paging must still reach the end. + clock.mockReturnValue((page + 1) * 1_000); + const items = page === 2 ? [grepMatch("src/late.ts", "needle")] : []; const value: GrepResult = { - items: fellBack - ? [ - { - ...fileItem("arch/x86/kernel/head64.c"), - isBinary: false, - lineNumber: 1, - col: 0, - byteOffset: 0, - lineContent: "asmlinkage __visible void start_kernel(void)", - matchRanges: [[0, 44]], - }, - ] - : [], - totalMatched: fellBack ? 1 : 0, - totalFilesSearched: fellBack ? 3 : 0, + items, + totalMatched: items.length, + totalFilesSearched: 1, totalFiles: 3, - filteredFileCount: fellBack ? 3 : 0, - nextCursor: null, + filteredFileCount: 3, + nextCursor: cursors[page] ?? null, }; return { ok: true as const, value }; }); - const finder = { - destroy: vi.fn(), - waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - grep, - } as unknown as FileFinder; - vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); + contentFinder(grep); const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content"); const result = yield* searchIndex.searchContents({ - query: "[a-z]{90}[-+*/]{5}|asmlinkage __visible.*start_kernel", + query: "needle", limit: 10, caseSensitive: true, wholeWord: false, - useRegex: true, + useRegex: false, }); - expect(result.matches.map((match) => match.path)).toEqual(["arch/x86/kernel/head64.c"]); + expect(result.matches.map((match) => match.path)).toEqual(["src/late.ts"]); + expect(result.truncated).toBe(false); + expect(grep.mock.calls.map(([, options]) => options?.enforceTimeBudget)).toEqual([ + true, + true, + true, + ]); }), - ), + ).pipe(Effect.provide(testLayer)), +); + +it.effect.each([0, 1])( + "reruns an empty enforced fallback page whose constraint matched %i files", + (constrainedFileCount) => + Effect.scoped( + Effect.gen(function* () { + const grep = vi.fn(async (_query: string, options?: GrepOptions) => { + const fellBack = options?.enforceTimeBudget === false; + const items = fellBack ? [grepMatch("zzzz.txt", "*.ts needle")] : []; + const value: GrepResult = { + items, + totalMatched: items.length, + totalFilesSearched: fellBack ? 3 : constrainedFileCount, + totalFiles: 3, + filteredFileCount: fellBack ? 3 : constrainedFileCount, + nextCursor: null, + }; + return { ok: true as const, value }; + }); + contentFinder(grep); + + const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content"); + const result = yield* searchIndex.searchContents({ + query: "*.ts needle", + limit: 10, + caseSensitive: true, + wholeWord: false, + useRegex: false, + }); + + expect(result.matches.map((match) => match.path)).toEqual(["zzzz.txt"]); + }), + ).pipe(Effect.provide(testLayer)), ); // fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there. diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index c16a4b4dd68e2..1aa41a51add77 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -1319,8 +1319,9 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( do { let result = yield* grepPage(true); - // fff 0.11 drops an empty enforced raw-query fallback page's cursor when a parsed path constraint matches no files. - if (result.filteredFileCount === 0 && result.totalFiles > 0) { + // fff 0.11 drops the cursor when an enforced raw-query fallback page (after a constraint like `*.ts` finds nothing) + // times out, so an empty enforced page that claims the scan ended is rerun without enforcement. + if (result.items.length === 0 && result.nextCursor === null) { result = yield* grepPage(false); } // fff searches an invalid pattern as a literal, which would keep the `(?i)` prefix. @@ -1347,13 +1348,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( } nextCursor = result.nextCursor; regexFallbackError ??= result.regexFallbackError; - // The RPC has no resume cursor: finish paging internally, letting Node service I/O between pages. - if (matches.length < input.limit && nextCursor !== null) { - yield* Effect.callback((resume) => { - const immediate = setImmediate(() => resume(Effect.void)); - return Effect.sync(() => clearImmediate(immediate)); - }); - } + // The RPC has no resume cursor, so page to the limit; short enforced pages keep each native call brief. } while (retryLiterally || (matches.length < input.limit && nextCursor !== null)); return { From e92997fc960ed8db7e37eb2c255f5a02c127f8da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 13:18:21 +0000 Subject: [PATCH 5/6] perf(server): filter whole-word content searches in fff Whole-word searches sent fff the bare query and dropped substring hits in JS, so a repo full of needleSuffix lines pushed hundreds of thousands of candidates through fff before the five real matches arrived (12 s on 4,000 files). Plain ASCII whole-word queries now go to fff as a boundary regex, and JS still computes the exact ranges and applies the existing word rule. Co-Authored-By: Claude Opus 5.5 --- .../workspace/WorkspaceSearchIndex.test.ts | 1 + .../src/workspace/WorkspaceSearchIndex.ts | 53 +++++++++++++++++-- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 550059d4f6557..0f2bd58f5cf97 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -290,6 +290,7 @@ it.effect("continues whole-word searches after a filtered grep page", () => truncated: false, }); expect(grep).toHaveBeenCalledTimes(2); + expect(grep.mock.calls[0]?.[0]).toBe(String.raw`(?:^|\W)needle(?:\W|$)`); expect(grep.mock.calls[1]?.[1]?.cursor).toBe(nextCursor); }), ).pipe(Effect.provide(testLayer)), diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 1aa41a51add77..41bef5af23123 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -273,9 +273,33 @@ function codePointBefore(line: string, index: number): string | undefined { return codePointAt(line, previousIndex); } +function escapeRegex(text: string): string { + return text.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); +} + function buildContentSearchQuery(input: Omit): { readonly searchQuery: string; readonly regexMode: boolean; + readonly wholeWordPrefilter: boolean; +} { + // Without a native prefilter every substring hit crosses into JS, which takes seconds on large repos. + // fff compiles regexes bytewise, so `\W` also accepts non-ASCII and the JS check below stays authoritative; + // non-ASCII queries skip this because bytewise `(?i)` may not fold them. + if (input.wholeWord && !input.useRegex && /^[\x20-\x7e]+$/.test(input.query)) { + const left = /\w/.test(input.query[0] ?? "") ? String.raw`(?:^|\W)` : ""; + const right = /\w/.test(input.query.at(-1) ?? "") ? String.raw`(?:\W|$)` : ""; + return { + searchQuery: `${input.caseSensitive ? "" : "(?i)"}${left}${escapeRegex(input.query)}${right}`, + regexMode: true, + wholeWordPrefilter: true, + }; + } + return { ...buildPlainOrRegexQuery(input), wholeWordPrefilter: false }; +} + +function buildPlainOrRegexQuery(input: Omit): { + readonly searchQuery: string; + readonly regexMode: boolean; } { if (input.caseSensitive) { return { searchQuery: input.query, regexMode: input.useRegex }; @@ -338,6 +362,19 @@ function parseGitGrepRecords( return records; } +function findLiteralRanges( + line: string, + query: string, + caseSensitive: boolean, +): Array<{ readonly start: number; readonly end: number }> { + const pattern = new RegExp(escapeRegex(query), caseSensitive ? "gu" : "giu"); + return Array.from(line.matchAll(pattern), (match) => ({ + start: match.index, + end: match.index + match[0].length, + })); + +} + // Post-filter whole words: consuming boundary regexes swallow adjacent separators and widen ranges; \b misses punctuation edges. function isWholeWordRange( line: string, @@ -1294,7 +1331,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( ); contentIndexPending = false; } - let { searchQuery, regexMode } = buildContentSearchQuery(input); + let { searchQuery, regexMode, wholeWordPrefilter } = buildContentSearchQuery(input); // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing. const rawPageSize = input.wholeWord ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE) @@ -1328,15 +1365,21 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( retryLiterally = regexMode && !input.caseSensitive && result.regexFallbackError !== undefined; if (retryLiterally) { regexFallbackError = result.regexFallbackError; - ({ searchQuery, regexMode } = buildContentSearchQuery({ ...input, useRegex: false })); + ({ searchQuery, regexMode, wholeWordPrefilter } = buildContentSearchQuery({ + ...input, + useRegex: false, + wholeWord: false, + })); continue; } for (const match of result.items) { if (isIgnoredPath(ignoredPaths, match.relativePath, hostIsWindows)) continue; - const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter( - (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range), - ); + const matchRanges = ( + wholeWordPrefilter + ? findLiteralRanges(match.lineContent, input.query, input.caseSensitive) + : mapContentMatchRanges(match.lineContent, match.matchRanges) + ).filter((range) => !input.wholeWord || isWholeWordRange(match.lineContent, range)); // fff reports hits past its 512-char lineContent cap with no ranges, so whole words can't be verified there. if (input.wholeWord && matchRanges.length === 0) continue; matches.push({ From d1ffdba74b44f6ac4be078a5930cf2e72c19d894 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 13:34:15 +0000 Subject: [PATCH 6/6] fix(server): keep fff query parsing for whole-word searches fff rewrites glob and path syntax out of a query even in regex mode, so the escaped whole-word prefilter turned '*.ts needle' into an invalid regex and returned nothing. Only queries made of ASCII word characters, which fff leaves alone and need no escaping, now use the prefilter; everything else takes the previous path. Co-Authored-By: Claude Opus 5.5 --- .../workspace/WorkspaceSearchIndex.test.ts | 45 +++++++++++++++++-- .../src/workspace/WorkspaceSearchIndex.ts | 22 ++++----- 2 files changed, 49 insertions(+), 18 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 0f2bd58f5cf97..d7ef2aa8ca792 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -444,10 +444,10 @@ it.live("answers content searches with git grep while a slow content index build "fatal: cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE\n", ); expect((yield* noPcreIndex.searchContents(regexInput)).regexFallbackError).toBeUndefined(); - expect(grep).toHaveBeenCalledTimes(1); + expect(grep).toHaveBeenCalledTimes(2); const noRangesIndex = yield* failingGitIndex("-o", "fatal: unexpected failure\n"); yield* noRangesIndex.searchContents(regexInput); - expect(grep).toHaveBeenCalledTimes(2); + expect(grep).toHaveBeenCalledTimes(4); // Ranges output cut off after line 1: line 2 is left out and the result says so. const cutRangesIndex = yield* failingGitIndex("-o", "", { exitCode: 0, @@ -467,7 +467,7 @@ it.live("answers content searches with git grep while a slow content index build isWarmupComplete = true; yield* search({}); - expect(grep).toHaveBeenCalledTimes(3); + expect(grep).toHaveBeenCalledTimes(6); expect(finder.destroy).not.toHaveBeenCalled(); }).pipe(Effect.scoped, Effect.provide(testLayer)), ); @@ -735,7 +735,10 @@ function contentFinder(grepAsync: (query: string, options?: GrepOptions) => Prom const finder = { destroy: vi.fn(), waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - getScanProgressAsync: async () => ({ ok: true as const, value: { isScanning: false, isWarmupComplete: true } }), + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false, isWarmupComplete: true }, + }), watchAsync: async () => ({ ok: true as const, value: () => undefined }), grepAsync, } as unknown as FileFinder; @@ -850,3 +853,37 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( }), ).pipe(Effect.provide(testLayer)), ); + +// Real fff: it parses glob and path syntax out of the query, which a native whole-word prefilter must not break. +it.effect.each([ + { query: "*.ts needle", expected: ["words.ts:2"] }, + { query: "*.ts", expected: ["notes.md:1"] }, + { query: "needle", expected: ["notes.md:1", "words.ts:2"] }, +])("matches whole words in a real workspace for $query", ({ query, expected }) => + Effect.scoped( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-whole-word-" }); + yield* fileSystem.writeFileString( + path.join(cwd, "words.ts"), + "needleSuffix\nneedle\ntrailer\n", + ); + yield* fileSystem.writeFileString(path.join(cwd, "notes.md"), "needle *.ts\n"); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content"); + const result = yield* searchIndex.searchContents({ + query, + limit: 500, + caseSensitive: true, + wholeWord: true, + useRegex: false, + }); + + expect(result.regexFallbackError).toBeUndefined(); + expect(result.matches.map((match) => `${match.path}:${match.lineNumber}`).toSorted()).toEqual( + expected, + ); + }), + ).pipe(Effect.provide(testLayer)), +); diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 41bef5af23123..ae7562574106b 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -259,6 +259,7 @@ function mapMixedSearchResult( } const WORD_CHARACTER = /[\p{Letter}\p{Mark}\p{Number}_]/u; +const ASCII_WORD = /^\w+$/; function codePointAt(line: string, index: number): string | undefined { const codePoint = line.codePointAt(index); @@ -273,23 +274,17 @@ function codePointBefore(line: string, index: number): string | undefined { return codePointAt(line, previousIndex); } -function escapeRegex(text: string): string { - return text.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"); -} - function buildContentSearchQuery(input: Omit): { readonly searchQuery: string; readonly regexMode: boolean; readonly wholeWordPrefilter: boolean; } { // Without a native prefilter every substring hit crosses into JS, which takes seconds on large repos. - // fff compiles regexes bytewise, so `\W` also accepts non-ASCII and the JS check below stays authoritative; - // non-ASCII queries skip this because bytewise `(?i)` may not fold them. - if (input.wholeWord && !input.useRegex && /^[\x20-\x7e]+$/.test(input.query)) { - const left = /\w/.test(input.query[0] ?? "") ? String.raw`(?:^|\W)` : ""; - const right = /\w/.test(input.query.at(-1) ?? "") ? String.raw`(?:\W|$)` : ""; + // Only plain ASCII words qualify: fff rewrites queries with glob or path syntax even in regex mode, and its + // bytewise `\W` also accepts non-ASCII, so the JS whole-word check below stays authoritative. + if (input.wholeWord && !input.useRegex && ASCII_WORD.test(input.query)) { return { - searchQuery: `${input.caseSensitive ? "" : "(?i)"}${left}${escapeRegex(input.query)}${right}`, + searchQuery: `${input.caseSensitive ? "" : "(?i)"}(?:^|\\W)${input.query}(?:\\W|$)`, regexMode: true, wholeWordPrefilter: true, }; @@ -362,17 +357,16 @@ function parseGitGrepRecords( return records; } -function findLiteralRanges( +function findWordQueryRanges( line: string, query: string, caseSensitive: boolean, ): Array<{ readonly start: number; readonly end: number }> { - const pattern = new RegExp(escapeRegex(query), caseSensitive ? "gu" : "giu"); + const pattern = new RegExp(query, caseSensitive ? "gu" : "giu"); return Array.from(line.matchAll(pattern), (match) => ({ start: match.index, end: match.index + match[0].length, })); - } // Post-filter whole words: consuming boundary regexes swallow adjacent separators and widen ranges; \b misses punctuation edges. @@ -1377,7 +1371,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( if (isIgnoredPath(ignoredPaths, match.relativePath, hostIsWindows)) continue; const matchRanges = ( wholeWordPrefilter - ? findLiteralRanges(match.lineContent, input.query, input.caseSensitive) + ? findWordQueryRanges(match.lineContent, input.query, input.caseSensitive) : mapContentMatchRanges(match.lineContent, match.matchRanges) ).filter((range) => !input.wholeWord || isWholeWordRange(match.lineContent, range)); // fff reports hits past its 512-char lineContent cap with no ranges, so whole words can't be verified there.