diff --git a/src/search-engines.ts b/src/search-engines.ts index f7e1a3b1..26fc53eb 100644 --- a/src/search-engines.ts +++ b/src/search-engines.ts @@ -14,11 +14,10 @@ * whose name matches (no file path carries it, so rg cannot see it; fd and * the walk both report it). * - * A runtime failure disables that engine for the rest of the process (a - * broken binary must not slow every later search); the caller falls back to - * the plain walk. A timeout is NOT a failure: it means this tree was too - * large, so it must not strip every other root of the engine. Hooks are - * swappable for tests (setEngineHooks). + * Repeated runtime failures disable that engine for the rest of the process + * (a broken binary must not slow every later search); a single bad query or a + * timeout only degrades THAT one search, so the next one retries the engine. + * Hooks are swappable for tests (setEngineHooks). */ import { spawn, type ChildProcess } from 'node:child_process' import { createInterface } from 'node:readline' @@ -204,7 +203,7 @@ function verify(binary: string): Promise { /** Escape glob metacharacters so a query matches literally inside -g. * Braces are metacharacters too ({a,b} alternation): an unbalanced '{' - * makes rg fail to parse the glob (exit 2 → the engine looks broken), and + * makes rg fail to parse the glob (exit 2 → the run fails), and * a balanced one silently matches a DIFFERENT literal ('a{b}' searches * 'ab'). Verified against rg 15: '\{' is a valid brace escape. */ export function escapeGlob(query: string): string { @@ -359,14 +358,16 @@ export function normalizeEnginePaths(lines: readonly string[], separator: string * pinned, and --max-results one ABOVE the stream sentinel (cap + 1) so a * full result set overflows into the same truncation detected for rg * (see runChild). Directory matches are read from a second invocation - * (`type: 'd'`, see runChild) because fd cannot label its matches. */ + * (`type: 'd'`, see runChild) because fd cannot label its matches. + * `--` ends option parsing BEFORE the query: a `-`-leading pattern must stay + * a positional, not become an fd option. */ export function fdArgv(cap: number, query: string, type?: 'd'): string[] { return [ '--hidden', '--no-ignore', ...SKIP_DIR_NAMES.flatMap(name => ['--exclude', name]), '--fixed-strings', '--ignore-case', ...(type === undefined ? [] : ['--type', type]), - '--path-separator', '/', '--max-results', String(cap + 1), query, '.', + '--path-separator', '/', '--max-results', String(cap + 1), '--', query, '.', ] } @@ -481,8 +482,8 @@ function runChild( return Promise.all([ streamLines(child, cap), // The directory run's failure is NOT swallowed (#883): a rejected dirs - // stream rejects the whole engine call, so runEngine marks the engine - // broken and this one search falls back to the plain walk — exactly + // stream rejects the whole engine call, so runEngine records the failure + // and this one search falls back to the plain walk — exactly // the main run's failure handling. The old swallow-catch degraded the // failure into "zero directories", invisible in every environment. streamLines(dirChild, cap), @@ -514,6 +515,10 @@ export type EngineSpawner = ( let spawner: EngineSpawner = spawn /** Engines failed at runtime: skipped for the rest of this process. */ const broken = new Set() +/** Consecutive runtime failures per engine. A single bad query (or a timeout) + * is not evidence of a dead binary, so only repeated failures disable it. */ +const BROKEN_AFTER = 3 +const failures = new Map() let probePromise: Promise | null = null /** Probe once per process (lazy): each engine's first working candidate. */ @@ -538,12 +543,10 @@ export function probeEngines(): Promise { return probePromise } -/** Run one engine and get capped, normalized matches; a runtime failure - * disables that engine for the rest of the process (a broken binary must - * not slow every later search) — but a TIMEOUT does not: a timeout means - * THIS tree was too big, while the broken-set is per-engine, so disabling - * here would strip every other (small) root of the engine over one huge - * directory. */ +/** Run one engine and get capped, normalized matches. A single runtime + * failure (bad query) or a timeout only degrades THIS search — the engine + * stays usable so the next one retries it; only repeated consecutive + * failures disable the engine for the rest of the process. */ export async function runEngine( probe: EngineProbe, root: string, @@ -551,13 +554,22 @@ export async function runEngine( maxMatches: number, ): Promise { try { - return await runner(probe, root, query, maxMatches) + const result = await runner(probe, root, query, maxMatches) + failures.delete(probe.engine) + return result } catch (error) { if (error instanceof EngineTimeoutError) { debugLog(`[dsh-search] engine ${probe.engine} timed out (tree too large), falling back`) } else { - broken.add(probe.engine) - debugLog(`[dsh-search] engine ${probe.engine} failed at runtime, disabled: ${error instanceof Error ? error.message : String(error)}`) + const count = (failures.get(probe.engine) ?? 0) + 1 + failures.set(probe.engine, count) + const why = error instanceof Error ? error.message : String(error) + if (count >= BROKEN_AFTER) { + broken.add(probe.engine) + debugLog(`[dsh-search] engine ${probe.engine} failed ${String(count)} times in a row, disabled: ${why}`) + } else { + debugLog(`[dsh-search] engine ${probe.engine} query failed (${String(count)}/${String(BROKEN_AFTER)}), will retry: ${why}`) + } } throw error } @@ -576,10 +588,11 @@ export function setEngineHooks(next: { prober?: typeof prober; runner?: typeof r if (next.spawner !== undefined) spawner = next.spawner } -/** Reset probe cache, broken-set and hooks (test isolation). */ +/** Reset probe cache, failure state and hooks (test isolation). */ export function resetEngines(): void { probePromise = null broken.clear() + failures.clear() prober = (): Promise => probeOnce() runner = runChild spawner = spawn diff --git a/tests/fs-search.spec.ts b/tests/fs-search.spec.ts index 9eeb115f..283fd80d 100644 --- a/tests/fs-search.spec.ts +++ b/tests/fs-search.spec.ts @@ -642,13 +642,14 @@ describe('fs-search dispatch', () => { runner: async () => { throw new Error('engine exploded') }, }) expect(await searchFiles(dir, 'util')).toEqual({ matches: ['src/util.ts'], dirs: [], truncated: false }) - // The failed engine is disabled for the rest of the process. + // A single failure must NOT disable the engine: the next search retries + // it instead of permanently degrading to the slow walk. let attempts = 0 setEngineHooks({ - runner: async () => { attempts += 1; return { paths: [], dirs: [], truncated: false } }, + runner: async () => { attempts += 1; throw new Error('engine exploded again') }, }) expect(await searchFiles(dir, 'util')).toEqual({ matches: ['src/util.ts'], dirs: [], truncated: false }) - expect(attempts).toBe(0) + expect(attempts).toBe(1) } finally { removeTree(dir) } diff --git a/tests/search-engines.spec.ts b/tests/search-engines.spec.ts index 40205ee4..4d99a04f 100644 --- a/tests/search-engines.spec.ts +++ b/tests/search-engines.spec.ts @@ -1,8 +1,9 @@ /** * search-engines: the native-engine probe and runner behind fs.search. - * The probe is process-cached (verified binaries only); a runtime failure - * disables one engine without disturbing the others, while a TIMEOUT only - * degrades that one search. `normalizeEnginePaths` re-bases raw stdout lines + * The probe is process-cached (verified binaries only); a single runtime + * failure (or a timeout) only degrades that one search, so the next one can + * retry the engine — only repeated consecutive failures disable it, without + * disturbing the others. `normalizeEnginePaths` re-bases raw stdout lines * onto the walk contract (root-relative, '/'-separated, no './' prefix) and * `deriveRgMatches` supplies the directory hits `rg --files` cannot report. * Child processes are exercised entirely through injected hooks — CI @@ -212,9 +213,9 @@ describe('escapeGlob', () => { }) // '{' is globset alternation syntax: unbalanced it breaks the glob parse - // (rg exits 2 → the engine looks broken and gets disabled process-wide), - // balanced 'a{b}' silently searches 'ab' instead of the literal. Both - // verified against real rg 15; '\{' is the accepted escape. + // (rg exits 2 → that engine run fails), balanced 'a{b}' silently searches + // 'ab' instead of the literal. Both verified against real rg 15; '\{' is the + // accepted escape. it('escapes braces so alternation syntax cannot hijack a literal query', () => { expect(escapeGlob('a{b}')).toBe('a\\{b\\}') expect(escapeGlob('{')).toBe('\\{') @@ -245,6 +246,32 @@ describe('engine argv symmetry', () => { expect(argv[argv.length - 1]).toBe('.') }) + // Regression: `fd ... -foo .` made fd parse the query as an option. `--` + // must sit AFTER all options (and their values) and BEFORE the query, with + // the trailing `.` path still a positional. + it('fd argv puts `--` immediately before the query', () => { + const argv = fdArgv(10, '-foo') + const dash = argv.indexOf('--') + expect(dash).toBe(argv.length - 3) + expect(argv[dash + 1]).toBe('-foo') // literal, unescaped + expect(argv[dash + 2]).toBe('.') + // The last option's value precedes the separator; nothing after it is an option. + expect(argv[dash - 1]).toBe('11') + expect(argv.slice(0, dash)).toContain('--fixed-strings') + }) + + it('a `--`-leading query stays positional too', () => { + const argv = fdArgv(10, '--hidden') + expect(argv[argv.indexOf('--') + 1]).toBe('--hidden') + expect(argv[argv.length - 1]).toBe('.') + }) + + it('the `--type d` invocation keeps `--` before the pattern', () => { + const argv = fdArgv(10, '-foo', 'd') + expect(argv[argv.indexOf('--') + 1]).toBe('-foo') + expect(argv.indexOf('--type')).toBeLessThan(argv.indexOf('--')) + }) + // fd cannot label its matches, so the directory subset comes from a second // invocation restricted to directories. The filter must not disturb the // sentinel/truncation contract of the main run. @@ -437,7 +464,7 @@ describe('bundledRgCandidates', () => { }) }) -describe('probe cache and broken-disable', () => { +describe('probe cache and failure handling', () => { afterEach(() => { resetEngines() }) @@ -449,16 +476,51 @@ describe('probe cache and broken-disable', () => { expect(calls).toBe(1) }) - it('usableEngines hides engines broken at runtime', async () => { + // Regression: one bad query used to add fd to the broken set forever, so + // every later search silently fell back to the slow plain walk. + it('a single runtime failure leaves the engine usable for the next search', async () => { setEngineHooks({ prober: async () => [fdProbe, rgProbe] }) + let calls = 0 setEngineHooks({ - runner: async () => { throw new Error('boom') }, + runner: async () => { calls += 1; throw new Error('boom') }, }) await runEngine(fdProbe, '/w', 'x', 10).catch(() => { /* the failing runner above */ }) - const usable = await usableEngines() - expect(usable.map(probe => probe.engine)).toEqual(['rg']) + expect((await usableEngines()).map(probe => probe.engine)).toEqual(['fd', 'rg']) + // The caller can actually try it again instead of being locked to the walk. + await runEngine(fdProbe, '/w', 'x', 10).catch(() => {}) + expect(calls).toBe(2) + }) + + it('repeated consecutive failures still disable the engine', async () => { + setEngineHooks({ prober: async () => [fdProbe, rgProbe] }) + setEngineHooks({ runner: async () => { throw new Error('boom') } }) + // BROKEN_AFTER = 3: a genuinely dead binary must not slow every search, + // while a single failure (above) must not disable one. + for (let i = 0; i < 3; i += 1) { + await runEngine(fdProbe, '/w', 'x', 10).catch(() => {}) + } + expect((await usableEngines()).map(probe => probe.engine)).toEqual(['rg']) + }) + + it('a successful run clears the consecutive-failure streak', async () => { + setEngineHooks({ prober: async () => [fdProbe] }) + let fail = true + setEngineHooks({ + runner: async () => { + if (fail) throw new Error('boom') + return { paths: [], dirs: [], truncated: false } + }, + }) + await runEngine(fdProbe, '/w', 'x', 10).catch(() => {}) + await runEngine(fdProbe, '/w', 'x', 10).catch(() => {}) + fail = false + await runEngine(fdProbe, '/w', 'x', 10) + // Two failures, a success, then one more: only one in a row, still usable. + fail = true + await runEngine(fdProbe, '/w', 'x', 10).catch(() => {}) + expect((await usableEngines()).map(probe => probe.engine)).toEqual(['fd']) }) // A timeout means THIS tree was too big — the broken-set is per-engine, @@ -519,7 +581,7 @@ describe('real engines (only when installed)', () => { // (verified against real rg 15.2.0: unescaped '*a[b]*' returns // 'ab.ts', escaped '*a\[b\]*' returns 'a[b].ts'). Deliberately NOT an // UNCLOSED 'a[b': rg refuses the glob outright ("unclosed character - // class", exit 2), the engine gets dropped as broken and the plain-walk + // class", exit 2), that engine run fails and the plain-walk // fallback satisfies the assertion by accident. const meta = process.platform === 'win32' ? { file: 'a[b].ts', decoy: 'ab.ts', query: 'a[b]' } @@ -652,9 +714,10 @@ describe('streamLines settles on close, not exit', () => { first.emit('exit', 0) first.emit('close', 0) // The --type d run dies: a rejection, which must reach runEngine's - // broken-marking instead of degrading into "zero directories". + // failure handling instead of degrading into "zero directories". second.emit('error', new Error('fd dirs stream exploded')) await expect(call).rejects.toThrow('fd dirs stream exploded') - expect((await usableEngines()).map(probe => probe.engine)).toEqual([]) + // One failed run must not permanently drop fd: the next search can retry. + expect((await usableEngines()).map(probe => probe.engine)).toEqual(['fd']) }) })