From 6497046c9e6726bd418f55bd999b3d7a83105b0d Mon Sep 17 00:00:00 2001 From: NolanHo Date: Tue, 6 Oct 2026 10:50:51 -0700 Subject: [PATCH] fix(search-engines): settle streamLines on close, propagate fd dirs-run failures (#883) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit streamLines settled its promise on the child's 'exit' event. Node fires 'exit' the moment the process dies, while the stdout pipe may still hold undrained data — under host load the exit event can win that race and the promise resolved with a still-empty lines array. fd's second --type d run was the common victim (both children race, the match run usually drains first), so the observable signature was matches intact with dirs: [] — directory hits silently degraded into open-as-file errors, the exact error surface #801 fixed, now intermittent. Settlement moves to 'close' (process dead AND stdio drained, so every readline line event has fired). The truncation kill, the timeout and the spawn-error paths keep their semantics: whichever finish() ran first sets the closed flag and the close handler is idempotent. The --version probe keeps 'exit' — its stdio is 'ignore', the exit code is the only signal it reads. The fd branch also no longer swallows the directory run's failure: the .catch(() => empty dir list) is deleted, so a rejection now reaches runEngine's existing broken-marking and this one search falls back to the plain walk — symmetric with the main run, where the old catch degraded every failure into an invisible "zero directories". Evidence: on an fd-equipped Linux host the real-engine suite reproduced 7/30 runs on clean dev (signature constant), 0/30 after the one-line close change; upstream CI never saw it (ubuntu lane has no fd; ci-windows runs serially). Two deterministic cases now pin the contracts through the new spawner hook (scripted PassThrough children replay the racy event order directly); each was verified red by temporarily reverting the corresponding half of the fix. --- CHANGELOG.md | 3 + src/search-engines.ts | 45 ++++++++++--- tests/search-engines.spec.ts | 118 +++++++++++++++++++++++++++++++++++ 3 files changed, 157 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ee1b14a..6a2c5568 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ ### Unreleased +- 🐞 **修掉 `streamLines` 以 `exit` 结算子进程输出、负载下 fd 目录结果偶发静默清空**([#883](https://github.com/omdsh-dev/DSH-better-sidebar/issues/883)):Node 的 `exit` 在进程死亡**瞬间**触发,stdout 管道可能还有未排空的数据;正确信号是 **`close`**(进程结束**且 stdio 全部关闭**,stdout 读到 EOF、readline 的全部 `line` 事件已发出)。宿主负载高时 `exit` 抢在管道排空前到达,`lines` 数组还是空就 resolve——fd 双调用的第二路(`--type d`)最常受害,签名恒为 **`matches` 完好、`dirs: []`**,目录命中行退化为按文件打开(报 `is a directory`,正是 #801 修的错误面被偶发化)。实证(装 fd 的 Linux 宿主,`tests/search-engines.spec.ts` 单文件连跑):干净 dev 基线 **7/30 复现**、签名恒一;`exit`→`close` 一行后 **0/30**。截断 / 超时 / spawn-error 三条既有结算路径换事件后语义不变(`finish` 幂等守卫 + `if (truncated)` 分支照旧);探测函数的 `--version` 调用是 `stdio: 'ignore'`、只读退出码,`exit` 即正确信号,不改。上游 CI 从未暴露的原因:ubuntu lane 无 fd(真引擎用例自跳过,双 spawn 路径不存在)、ci-windows 串行跑撞不进竞态窗口——#872 记录的「慢机/负载才暴露」类隐患。 +- 🧹 **`runChild` 的 fd 分支不再吞掉第二路的失败**:删除 `streamLines(dirChild, cap).catch(() => ({ lines: [], truncated: false }))`——rejection 现在流进 `runEngine` 既有的 broken 标记 + 本次回退 JS 遍历(与主路对称;旧 catch 把失败降级成「目录恰好为零」,在所有环境都不可见)。 +- 🧪 测试:`setEngineHooks` 新增 `spawner` 缝隙(类型收窄为 `EngineSpawner`),两条**确定性**用例用脚本化 PassThrough 子进程直接钉住契约——「`exit` 先于 stdout 排空时零行丢失」(复放竞态的真实次序:先 exit、数据在途、close 后至;exit 版代码在「close 前仍未结算」断言即红)与「fd 目录路失败整路 reject 并标记 broken」(swallow-catch 版代码红在「以空 dirs resolve 而非 reject」)。判别性均已临时还原对应实现验证:还原 `exit` → 用例 1 红;还原 catch → 用例 2 红。真引擎用例('matches literals…')此前正是该竞态的偶发受害者,负载机器上 ~23% 概率红。 - 🪟 **修掉 CRLF 行尾文件在预览里的三层 `\r` 误判与「预览渲染两遍」(ci-windows 上暴露)**:Windows 检出下 README 的锚点用例全红,根因不是 slug 而是① `markdown-html.ts` 的 `isBlank`、`mermaid-blocks.ts` 的 `CLOSE_FENCE_RE`、`markdown-code.ts` 的 `closesFence` 都把行尾的 `\r` 当内容——于是 **HTML 段永不终止**(实测 `splitHtmlBlocks(README.md)`:LF 36 段 vs CRLF **4 段**,`# b` 被当原始 HTML 文字渲染)、**mermaid 围栏吞掉文件余下部分**、**链接改写从第一个围栏起全部失效**(首个分歧在第 16883 字节);② `TextEditor` 的 draft 快照把 CodeMirror 归一化后的 LF 文档在挂载后一个 commit 发布出去,`previewMdText` 从 CRLF 翻成 LF,宿主 `MarkdownText` 于是重建了文本变化的标题节点——挂载那一趟写入的 **26/26 个 id 被丢弃**(断言时只剩 7/26、13/15 个 TOC 锚点 `id=missing`),MutationObserver 一个微任务后才自愈。现已把 draft 定义成「编辑」:与已加载正文逐字节相等(或行尾归一后相等)时不发布。 - 🧪 测试:新增 `tests/markdown-crlf.spec.ts`(7 条 **CRLF ≡ LF** 不变式,覆盖分段器 / mask / 两个改写器 / mermaid 分段器)与两条真实渲染器用例(含把 `README.md` **在内存里**转成 CRLF,让 ubuntu / macOS lane 也跑 Windows 的拼写);测试脚手架 `scanDocumentAnchors` 改为 CRLF 安全(实测 CRLF 标题 0 → 26)。判别性:还原三个扫描文件 → 9 条红;还原 `TextEditor` → CRLF 检出下 2 条红(即 CI 原症状)。 - 📝 **已知未修(另立 [#871](https://github.com/omdsh-dev/DSH-better-sidebar/issues/871))**:同一归一化意味着**保存会把 CRLF 文件写成 LF**(一次内容修改变成整文件 diff),需要产品取舍;本轮只修读取侧。 diff --git a/src/search-engines.ts b/src/search-engines.ts index dffe37e5..931d5673 100644 --- a/src/search-engines.ts +++ b/src/search-engines.ts @@ -270,7 +270,16 @@ function streamLines( } const timer = setTimeout(() => { finish(new EngineTimeoutError('search engine timed out')) }, ENGINE_TIMEOUT_MS) child.once('error', (error) => { finish(error) }) - child.once('exit', (code) => { + // `close`, not `exit` (#883): `exit` fires the moment the process dies, + // while the stdout pipe may still hold undrained data — under host load + // the exit event can win the race and resolve this promise with a still + // EMPTY `lines` array (fd's second `--type d` run was the common victim: + // matches intact, dirs silently empty). `close` fires only after every + // stdio stream has ended, so every readline `line` event has fired + // before the settlement. The truncation kill and the timeout/error + // finishes below are unaffected: whichever finish ran first sets + // `closed`, and this handler is idempotent. + child.once('close', (code) => { if (truncated) { finish(undefined) } else if (code !== 0 && code !== 1) { @@ -449,19 +458,22 @@ function runChild( ): Promise { const cap = maxMatches + 1 if (probe.engine === 'rg') { - const child = spawn(probe.binary, rgArgv(query), { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }) + const child = spawner(probe.binary, rgArgv(query), { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }) return streamLines(child, cap).then(({ lines, truncated }) => { const derived = deriveRgMatches(normalizeEnginePaths(lines), query, maxMatches) return { paths: derived.paths, dirs: derived.dirs, truncated: truncated || derived.truncated } }) } - const child = spawn(probe.binary, fdArgv(cap, query), { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }) - const dirChild = spawn(probe.binary, fdArgv(cap, query, 'd'), { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }) + const child = spawner(probe.binary, fdArgv(cap, query), { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }) + const dirChild = spawner(probe.binary, fdArgv(cap, query, 'd'), { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }) return Promise.all([ streamLines(child, cap), - // Only the directory subset is kept: fd already labels it, and its - // truncation must not affect the match list's own sentinel. - streamLines(dirChild, cap).catch(() => ({ lines: [], truncated: false })), + // 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 + // the main run's failure handling. The old swallow-catch degraded the + // failure into "zero directories", invisible in every environment. + streamLines(dirChild, cap), ]).then(([matches, dirs]) => { const paths = normalizeEnginePaths(matches.lines) const dirSet = new Set(normalizeEnginePaths(dirs.lines)) @@ -475,6 +487,19 @@ function runChild( let prober = (): Promise => probeOnce() let runner = runChild +/** + * The spawn signature runChild uses, narrowed from `typeof spawn` so a test + * spawner returning a scripted `ChildProcess` satisfies the hook without + * matching spawn's full overload surface. + */ +export type EngineSpawner = ( + binary: string, + argv: readonly string[], + options: { cwd: string; stdio: ['ignore', 'pipe', 'ignore'] }, +) => ChildProcess +/** Child spawn behind runChild — injectable so tests can drive the real + * orchestration with scripted children (event order, stream timing). */ +let spawner: EngineSpawner = spawn /** Engines failed at runtime: skipped for the rest of this process. */ const broken = new Set() let probePromise: Promise | null = null @@ -532,10 +557,11 @@ export async function usableEngines(): Promise { return probes.filter((probe) => !broken.has(probe.engine)) } -/** Test seam: replace the probe / child-runner implementations. */ -export function setEngineHooks(next: { prober?: typeof prober; runner?: typeof runner }): void { +/** Test seam: replace the probe / child-runner / spawn implementations. */ +export function setEngineHooks(next: { prober?: typeof prober; runner?: typeof runner; spawner?: typeof spawner }): void { if (next.prober !== undefined) prober = next.prober if (next.runner !== undefined) runner = next.runner + if (next.spawner !== undefined) spawner = next.spawner } /** Reset probe cache, broken-set and hooks (test isolation). */ @@ -544,4 +570,5 @@ export function resetEngines(): void { broken.clear() prober = (): Promise => probeOnce() runner = runChild + spawner = spawn } diff --git a/tests/search-engines.spec.ts b/tests/search-engines.spec.ts index 81864633..01b6798b 100644 --- a/tests/search-engines.spec.ts +++ b/tests/search-engines.spec.ts @@ -12,6 +12,8 @@ import { afterEach, describe, expect, it } from 'vitest' import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' +import type { ChildProcess } from 'node:child_process' +import { PassThrough } from 'node:stream' import { join, posix, win32 } from 'node:path' import { searchFiles } from '../src/fs-search.ts' import { @@ -519,3 +521,119 @@ describe('real engines (only when installed)', () => { } }) }) + +/** + * streamLines settlement (#883): the promise must settle on the child's + * `close` event (process dead AND stdio drained), never on `exit` (process + * dead, stdout may still hold data — under host load the exit event wins + * the race and an exit-based settlement resolved with a still-empty lines + * array). The children below are scripted PassThrough streams driven through + * the `spawner` hook, so the racy ORDER itself — exit first, data still in + * flight, drained close later — is replayed deterministically. + */ +describe('streamLines settles on close, not exit', () => { + afterEach(() => { + resetEngines() + }) + + /** + * A scripted child: a PassThrough stdout plus a hand-rolled once-event + * registry, so the test chooses WHICH event fires and WHEN. The surface + * is exactly what streamLines touches (stdout, once, kill). + */ + function fakeChild(): { child: ChildProcess; stdout: PassThrough; emit: (event: string, arg?: unknown) => void } { + const stdout = new PassThrough() + const listeners = new Map void>>() + const child = { + stdout, + once(event: string, listener: (arg?: unknown) => void): ChildProcess { + const list = listeners.get(event) ?? [] + list.push(listener) + listeners.set(event, list) + return child as unknown as ChildProcess + }, + kill(): boolean { return true }, + } + const emit = (event: string, arg?: unknown): void => { + for (const listener of listeners.get(event) ?? []) listener(arg) + } + return { child: child as unknown as ChildProcess, stdout, emit } + } + + /** Feed lines into the fake stdout and wait until readline consumed them + * all (the stream's `end` fires after the last data chunk) — the state a + * real child is in right before `close` fires. */ + async function feed(stdout: PassThrough, lines: string): Promise { + const ended = new Promise(resolve => { stdout.once('end', resolve) }) + stdout.write(lines) + stdout.end() + await ended + } + + /** Whether `promise` is still pending after a short sample window. */ + async function stillPending(promise: Promise): Promise { + let settled = false + void promise.then(() => { settled = true }, () => { settled = true }) + await new Promise(resolve => { setTimeout(resolve, 20) }) + return !settled + } + + /** Reject with `why` when the promise does not settle within `ms`. */ + function withTimeout(promise: Promise, ms: number, why: string): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(why)), ms) + promise.then( + value => { clearTimeout(timer); resolve(value) }, + error => { clearTimeout(timer); reject(error) }, + ) + }) + } + + /** Two queued fake children for runChild's fd pair (main run, then --type d). */ + function fdPair(): [{ child: ChildProcess; stdout: PassThrough; emit: (e: string, a?: unknown) => void }, { child: ChildProcess; stdout: PassThrough; emit: (e: string, a?: unknown) => void }] { + const first = fakeChild() + const second = fakeChild() + const queue = [first, second] + setEngineHooks({ + prober: async () => [fdProbe], + spawner: () => (queue.shift() ?? first).child, + }) + return [first, second] + } + + it('loses no line when exit fires while stdout still holds data', async () => { + const [first, second] = fdPair() + const call = runEngine(fdProbe, '/workspace', 'util', 10) + // The losing order of the real race, replayed: both processes die + // (exit) BEFORE their stdout has drained. + first.emit('exit', 0) + second.emit('exit', 0) + // Data is still in flight at exit time; it only reaches readline after. + await feed(first.stdout, 'src/util.ts\nsrc\n') + await feed(second.stdout, 'src\n') + // close has not fired yet, so nothing may have settled: an exit-based + // settlement has already resolved here with the still-empty lines (the + // bug this case pins — it made the pending probe fail first). + expect(await stillPending(call)).toBe(true) + first.emit('close', 0) + second.emit('close', 0) + await expect(withTimeout(call, 1_000, 'engine settled on exit instead of close (regression of #883)')) + .resolves.toEqual({ paths: ['src/util.ts', 'src'], dirs: ['src'], truncated: false }) + }) + + it('a failed fd directory run rejects the whole engine call instead of reporting empty dirs', async () => { + const [first, second] = fdPair() + const call = runEngine(fdProbe, '/workspace', 'util', 10) + // The main run completes normally (both settlement events — the exit one + // keeps this case red under the old swallow-catch: the engine resolves + // with silently empty dirs there). + await feed(first.stdout, 'src/util.ts\n') + 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". + 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([]) + }) +})