Compare commits

...
Author SHA1 Message Date
Mohamed Boudra d419c7d964 Stop a stalled folder read from emptying Add Project search
A read that never returns (a dead NFS/SMB/FUSE mount) kept directory search waiting
until the 60s request timeout. Each filesystem call now gives up after 2s, the path is
skipped by later searches until the OS call settles, and a search answers with what it
found after 5s. A timed-out call keeps its slot in the two-call limiter, so search can
never hold more than two of libuv's four threads.
2026-12-02 06:50:55 +01:00
2 changed files with 280 additions and 26 deletions
@@ -10,6 +10,8 @@ import {
unlinkSync,
writeFileSync,
} from "node:fs";
import type { Dirent } from "node:fs";
import * as fsPromises from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
@@ -1326,3 +1328,125 @@ describe("filesystem threads held by concurrent searches", () => {
expect(peak).toBe(1);
});
});
// A read on a dead network mount never returns, and a JS timeout cannot free the thread it holds.
// A stalled read therefore keeps its slot until the OS call settles, the folder is skipped in the
// meantime, and a search answers with what it found instead of hanging.
describe("stalled folder reads", () => {
const READ_TIMEOUT_MS = 150;
const DEADLINE_MS = 2_000;
let scanRoot: string;
let stalledReads: Array<() => void>;
let mountRecovered: boolean;
let startedReads: string[];
let inFlightReads: number;
let peakInFlightReads: number;
beforeEach(() => {
scanRoot = realpathSync.native(mkdtempSync(path.join(tmpdir(), "directory-scan-stalled-")));
stalledReads = [];
mountRecovered = false;
startedReads = [];
inFlightReads = 0;
peakInFlightReads = 0;
});
afterEach(async () => {
// Settle every stalled read so its slot returns to the other tests in this file.
await recoverMount();
rmSync(scanRoot, { recursive: true, force: true });
});
function makeFolders(names: string[]): void {
for (const name of names)
mkdirSync(path.join(scanRoot, name, "inner-match"), { recursive: true });
}
// The real filesystem, except that folders in `stalled` never answer until the test settles them.
// After the mount recovers, they answer like any other folder.
function recoverMount(): Promise<void> {
mountRecovered = true;
stalledReads.forEach((settle) => settle());
return new Promise((resolve) => setImmediate(resolve));
}
function readDirectoryStallingOn(stalled: string[]) {
const stalledPaths = new Set(stalled.map((name) => path.join(scanRoot, name)));
return async function readDirectory(directory: string): Promise<Dirent[]> {
startedReads.push(path.basename(directory));
inFlightReads += 1;
peakInFlightReads = Math.max(peakInFlightReads, inFlightReads);
try {
if (mountRecovered || !stalledPaths.has(directory))
return await fsPromises.readdir(directory, { withFileTypes: true });
return await new Promise<Dirent[]>((resolve) => {
stalledReads.push(() => resolve([]));
});
} finally {
inFlightReads -= 1;
}
};
}
function search(options: {
readDirectory: (directory: string) => Promise<Dirent[]>;
deadlineMs?: number;
}) {
return searchDirectoryEntries({
root: scanRoot,
query: "match",
pathFormat: "relative",
pathQueryPolicy: "slashes",
blankQueryBehavior: "children",
readTimeoutMs: READ_TIMEOUT_MS,
deadlineMs: options.deadlineMs ?? DEADLINE_MS,
readDirectory: options.readDirectory,
}).then((entries) => entries.map((entry) => entry.path));
}
it("skips a stalled folder, keeps its healthy siblings, and reads it again once it settles", async () => {
makeFolders(["a-stalled", "b-healthy"]);
const readDirectory = readDirectoryStallingOn(["a-stalled"]);
const first = await search({ readDirectory });
const stalledStartsAfterFirst = startedReads.filter((name) => name === "a-stalled").length;
const second = await search({ readDirectory });
const stalledStartsAfterSecond = startedReads.filter((name) => name === "a-stalled").length;
await recoverMount();
const third = await search({ readDirectory });
expect({
first,
second,
stalledStartsAfterFirst,
stalledStartsAfterSecond,
stalledStartsAfterThird: startedReads.filter((name) => name === "a-stalled").length,
third,
}).toEqual({
first: ["b-healthy/inner-match"],
second: ["b-healthy/inner-match"],
stalledStartsAfterFirst: 1,
stalledStartsAfterSecond: 1,
stalledStartsAfterThird: 2,
third: ["a-stalled/inner-match", "b-healthy/inner-match"],
});
});
it("never runs more than two reads at once and answers with partial results at the deadline", async () => {
makeFolders(["a-stalled", "b-stalled", "c-match", "d-match"]);
const readDirectory = readDirectoryStallingOn(["a-stalled", "b-stalled"]);
const found = await search({ readDirectory, deadlineMs: 1_000 });
expect({
found,
peakInFlightReads,
startedStalled: startedReads.filter((name) => name.endsWith("stalled")),
}).toEqual({
found: ["c-match", "d-match"],
peakInFlightReads: 2,
startedStalled: ["a-stalled", "b-stalled"],
});
});
});
@@ -36,8 +36,17 @@ export interface SearchDirectoryEntriesOptions {
// Absolute paths that discovery never walks into. A path the caller types explicitly still
// resolves, and browsing inside one lists a single level at a time.
excludedDiscoveryPaths?: readonly string[];
// A search answers with what it found once this long has passed. Defaults to 5 seconds.
deadlineMs?: number;
// A folder read that takes this long is treated as unreadable for the search. Defaults to 2
// seconds.
readTimeoutMs?: number;
// Lists a folder. Defaults to the filesystem.
readDirectory?: ReadDirectory;
}
export type ReadDirectory = (directory: string) => Promise<Dirent[]>;
interface QueryPlan {
isPathQuery: boolean;
parentPart: string;
@@ -124,29 +133,76 @@ const NO_MATCH_TIER = 5;
// share two threads and leave the rest of the pool to the daemon. Searches over one tree walk it
// in the same order and stop at the same stuck folder, so they share its pending call and hold one
// thread between them instead of both.
//
// A timeout cannot free the thread of a read that never returns, so a stalled call keeps its slot
// until the OS call settles. Callers stop waiting for it, and later calls for the same path fail
// at once instead of queueing behind it.
const DEFAULT_READ_TIMEOUT_MS = 2_000;
const DEFAULT_SEARCH_DEADLINE_MS = 5_000;
const filesystemCalls = pLimit(2);
const pendingFilesystemCalls = new Map<string, Promise<unknown>>();
const stalledFilesystemCalls = new Set<string>();
function sharedFilesystemCall<T>(key: string, call: () => Promise<T>): Promise<T> {
class StalledFilesystemCallError extends Error {
constructor(public readonly key: string) {
super(`Filesystem call ${key} is stalled`);
this.name = "StalledFilesystemCallError";
}
}
interface SharedFilesystemCallOptions<T> {
key: string;
call: () => Promise<T>;
timeoutMs?: number;
}
function sharedFilesystemCall<T>({
key,
call,
timeoutMs = DEFAULT_READ_TIMEOUT_MS,
}: SharedFilesystemCallOptions<T>): Promise<T> {
if (stalledFilesystemCalls.has(key)) return Promise.reject(new StalledFilesystemCallError(key));
const pending = pendingFilesystemCalls.get(key);
if (pending) return pending as Promise<T>;
const started = filesystemCalls(call).finally(() => pendingFilesystemCalls.delete(key));
const started = new Promise<T>((resolve, reject) => {
void filesystemCalls(async () => {
const stallTimer = setTimeout(() => {
stalledFilesystemCalls.add(key);
reject(new StalledFilesystemCallError(key));
}, timeoutMs);
try {
resolve(await call());
} catch (error) {
reject(error);
} finally {
clearTimeout(stallTimer);
stalledFilesystemCalls.delete(key);
pendingFilesystemCalls.delete(key);
}
});
});
pendingFilesystemCalls.set(key, started);
return started;
}
function readdir(directory: string): Promise<Dirent[]> {
return sharedFilesystemCall(`readdir:${directory}`, () =>
fs.readdir(directory, { withFileTypes: true }),
);
function readdir(directory: string, input: SearchInput): Promise<Dirent[]> {
return sharedFilesystemCall({
key: `readdir:${directory}`,
call: () => input.readDirectory(directory),
timeoutMs: input.readTimeoutMs,
});
}
function defaultReadDirectory(directory: string): Promise<Dirent[]> {
return fs.readdir(directory, { withFileTypes: true });
}
function realpath(target: string): Promise<string> {
return sharedFilesystemCall(`realpath:${target}`, () => fs.realpath(target));
return sharedFilesystemCall({ key: `realpath:${target}`, call: () => fs.realpath(target) });
}
function stat(target: string): Promise<Stats> {
return sharedFilesystemCall(`stat:${target}`, () => fs.stat(target));
return sharedFilesystemCall({ key: `stat:${target}`, call: () => fs.stat(target) });
}
export const WORKSPACE_SEARCH_HIDDEN_DIRECTORIES = [
@@ -184,6 +240,42 @@ const gitIgnoredPathsCache = new Map<string, GitIgnoredPathsCacheEntry>();
export async function searchDirectoryEntries(
options: SearchDirectoryEntriesOptions,
): Promise<DirectorySuggestionEntry[]> {
const deadline = new AbortController();
const deadlineTimer = setTimeout(
() => deadline.abort(),
options.deadlineMs ?? DEFAULT_SEARCH_DEADLINE_MS,
);
const progress: SearchProgress = { input: null, exact: null };
const expired = new Promise<null>((resolve) =>
deadline.signal.addEventListener("abort", () => resolve(null), { once: true }),
);
const search = runSearch({ options, progress, signal: deadline.signal });
try {
// A read queued behind stalled reads never starts, so the search itself may never come back.
// Whatever it found by the deadline is the answer.
return (await Promise.race([search, expired])) ?? collectResults(progress);
} finally {
clearTimeout(deadlineTimer);
deadline.abort();
// An abandoned search finishes or fails on its own; nobody is left to report it to.
search.catch(() => undefined);
}
}
interface SearchProgress {
input: SearchInput | null;
exact: DirectorySuggestionEntry | null;
}
async function runSearch({
options,
progress,
signal,
}: {
options: SearchDirectoryEntriesOptions;
progress: SearchProgress;
signal: AbortSignal;
}): Promise<DirectorySuggestionEntry[]> {
const root = await resolveDirectory(options.root);
if (!root) return [];
@@ -191,8 +283,15 @@ export async function searchDirectoryEntries(
? await loadGitIgnoredPaths(root)
: new Set<string>();
const excludedDiscoveryPaths = await resolveExistingPaths(options.excludedDiscoveryPaths ?? []);
const input = buildSearchInput(options, root, gitIgnoredPaths, excludedDiscoveryPaths);
const input = buildSearchInput({
options,
root,
gitIgnoredPaths,
excludedDiscoveryPaths,
signal,
});
if (!input) return [];
progress.input = input;
const exact =
input.plan.browseExactPath ||
@@ -200,9 +299,15 @@ export async function searchDirectoryEntries(
? await findExactEntry(input)
: null;
if (exact && input.limit === 1) return [exact];
progress.exact = exact;
const ranked = await searchCandidates(input);
const results = sortAndFormat(ranked, input.root, input.pathFormat).slice(0, input.limit);
await searchCandidates(input);
return collectResults(progress);
}
function collectResults({ input, exact }: SearchProgress): DirectorySuggestionEntry[] {
if (!input) return [];
const results = sortAndFormat(input.found, input.root, input.pathFormat).slice(0, input.limit);
return exact
? [exact, ...results.filter((entry) => !sameEntry(entry, exact))].slice(0, input.limit)
: results;
@@ -249,9 +354,10 @@ async function withResolvedSpelling(visiblePath: string, resolvedPath: string):
let resolved = resolvedPath;
while (visible !== resolved && visible !== path.parse(visible).root) {
const entryPath = visible;
const entry = await sharedFilesystemCall(`lstat:${entryPath}`, () => fs.lstat(entryPath)).catch(
() => null,
);
const entry = await sharedFilesystemCall({
key: `lstat:${entryPath}`,
call: () => fs.lstat(entryPath),
}).catch(() => null);
if (!entry || entry.isSymbolicLink()) return visiblePath;
visible = path.dirname(visible);
resolved = path.dirname(resolved);
@@ -266,12 +372,19 @@ async function resolveExistingPaths(paths: readonly string[]): Promise<Set<strin
return new Set(resolved.filter((candidate): candidate is string => candidate !== null));
}
function buildSearchInput(
options: SearchDirectoryEntriesOptions,
root: string,
gitIgnoredPaths: Set<string>,
excludedDiscoveryPaths: Set<string>,
): SearchInput | null {
function buildSearchInput({
options,
root,
gitIgnoredPaths,
excludedDiscoveryPaths,
signal,
}: {
options: SearchDirectoryEntriesOptions;
root: string;
gitIgnoredPaths: Set<string>;
excludedDiscoveryPaths: Set<string>;
signal: AbortSignal;
}): SearchInput | null {
const includeDirectories = options.includeDirectories ?? true;
const includeFiles = options.includeFiles ?? false;
if (!includeDirectories && !includeFiles) return null;
@@ -301,6 +414,10 @@ function buildSearchInput(
confidentResultScanThreshold: options.confidentResultScanThreshold,
gitIgnoredPaths,
excludedDiscoveryPaths,
readDirectory: options.readDirectory ?? defaultReadDirectory,
readTimeoutMs: options.readTimeoutMs ?? DEFAULT_READ_TIMEOUT_MS,
signal,
found: [],
};
}
@@ -338,6 +455,12 @@ interface SearchInput {
confidentResultScanThreshold: number | undefined;
gitIgnoredPaths: Set<string>;
excludedDiscoveryPaths: Set<string>;
readDirectory: ReadDirectory;
readTimeoutMs: number;
// Aborts when the search deadline passes; walks stop and leave `found` as the answer.
signal: AbortSignal;
// Matches ranked so far, so a search cut off at its deadline still has them.
found: RankedEntry[];
}
async function searchChildren(input: SearchInput): Promise<RankedEntry[]> {
@@ -350,8 +473,9 @@ async function searchChildren(input: SearchInput): Promise<RankedEntry[]> {
const discoveryInput = isInsideExcludedPath(parent, input)
? { ...input, excludedDiscoveryPaths: new Set<string>() }
: input;
const ranked: RankedEntry[] = [];
for await (const entry of readChildren(parent)) {
const ranked = input.found;
for await (const entry of readChildren(parent, input)) {
if (input.signal.aborted) break;
if (!isPathInsideRoot(input.root, entry.resolvedPath) || !shouldDiscover(entry, discoveryInput))
continue;
const candidate: TraversedEntry = {
@@ -371,13 +495,14 @@ async function searchTree(
if (!(input.maxEntriesScanned > 0)) return [];
const visited = new Set<string>([start.resolvedPath]);
const branches = walkChildren({ parent: start, depth: 1, input, visited });
const ranked: RankedEntry[] = [];
const ranked = input.found;
let scanned = 0;
const threshold = input.confidentResultScanThreshold;
for await (const entry of roundRobin(branches)) {
scanned += 1;
if (shouldSuggest(entry, input)) ranked.push(rank(entry, input));
if (
input.signal.aborted ||
scanned >= input.maxEntriesScanned ||
(threshold &&
scanned >= threshold &&
@@ -412,7 +537,7 @@ async function* walkChildren({
input,
visited,
}: WalkChildrenOptions): AsyncGenerator<AsyncGenerator<TraversedEntry>> {
for await (const child of readChildren(parent.resolvedPath)) {
for await (const child of readChildren(parent.resolvedPath, input)) {
if (!staysInsideRoot(child, input.root) || !shouldDiscover(child, input)) continue;
yield walkBranch(
{ ...child, visiblePath: path.join(parent.visiblePath, child.name), depth },
@@ -763,7 +888,7 @@ async function resolveDirectory(inputPath: string): Promise<string | null> {
return info?.isDirectory() ? resolved : null;
}
async function* readChildren(directory: string): AsyncGenerator<ChildEntry> {
async function* readChildren(directory: string, input: SearchInput): AsyncGenerator<ChildEntry> {
const directoryInfo = await stat(directory).catch(() => null);
if (!directoryInfo?.isDirectory()) return;
@@ -779,7 +904,12 @@ async function* readChildren(directory: string): AsyncGenerator<ChildEntry> {
) {
rawEntries = cached.entries;
} else {
const dirents = await readdir(directory).catch(() => [] as Dirent[]);
// A stalled listing is unknown, not empty, so it is not cached and the folder is read again
// once the stalled call settles.
const dirents = await readdir(directory, input).catch((error: unknown) =>
error instanceof StalledFilesystemCallError ? null : ([] as Dirent[]),
);
if (!dirents) return;
rawEntries = dirents
.map(toRawChildEntry)
.filter((entry): entry is RawChildEntry => entry !== null)