Stop timed-out watcher setups from rescanning large repos every 5 minutes (#9828)

* fix(server): abort timed-out watcher setups and back off their retries

A watcher subscription that missed WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS
was abandoned but its startup scan kept walking the tree to completion, and
recovery retried every five minutes forever, repeating the full scan each
time. On a CPU-starved host that kept dozens of directories rescanning.

- FileObserver.subscribe accepts an abort signal that stops the startup scan
  and rejects; WorkspaceGit aborts setups at the deadline and on dispose.
- Consecutive setup timeouts extend the recovery delay past the 5-minute
  ladder cap, doubling up to one hour; an accepted subscription resets it.
  Degraded polling keeps its 5-60 s cadence meanwhile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(file-observer): keep an aborted observation's backend from starting

Aborting a subscription closes its observation, which can happen while
start() is still reading the root. The backend then started after its close
had finished, and the native backend opened a root watcher that nothing
would close.

Co-authored-by: Spencer Shulem <1703265+Spshulem@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(file-observer): abort a subscription mid-scan in the abort test

The test aborted before the backend started, so it passed with the abort
listener removed. A tree past the Linux directory limit makes a scan that
keeps walking fail on the limit instead of rejecting with the reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Spencer Shulem <spshulem@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Spencer Shulem <1703265+Spshulem@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-11-16 09:10:01 +00:00
1 parent 41c294c785
commit 33259746db
8 files changed
+251 -7

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ Do not replace the Linux implementation with `fs.watch({ recursive: true })`. No
Closing an observation must remain safe after its root is renamed or removed. Workspace archive removes owned worktrees while releasing observation references, so teardown cannot assume the watched path still exists.
`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling.
`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling. `subscribe()` accepts an abort signal; aborting it before it resolves stops the startup scan and rejects. WorkspaceGit aborts every subscription that misses its setup deadline, because an abandoned scan otherwise keeps walking the tree. A timed-out directory retries on the recovery ladder (30 seconds doubling to five minutes), and each consecutive timeout keeps doubling the delay up to one hour. Under sustained CPU load the next scan misses the deadline too, and each attempt repeats the full scan. An accepted subscription resets the timeout streak. Degraded polling keeps its own cadence throughout.
Linux topology repair is trailing-debounced and scoped to the renamed path. A file rename needs one classification stat; a new or moved directory scans only its subtree. Full-tree scans are reserved for startup and ignore-set replacement. A subscription reports changes after `subscribe()` resolves, not the files that already existed. macOS FSEvents can still replay writes made moments before the stream started. Consumers read their initial state after `subscribe()` resolves; WorkspaceGit re-reads its checkout once observation setup completes, because its first refresh runs in parallel with setup. The Linux startup scan therefore emits nothing; only a scoped reconciliation of new topology reports files found before their directory's watcher was installed. Startup creates made every cold diff compute and discard a first revision. Benchmark startup cost with pre-populated trees.
@@ -327,6 +327,39 @@ test("unsubscribe cancels reconciliation queued by a write burst", async () => {
expect(callback).toHaveBeenCalledTimes(callsAtClose);
}, 20_000);
test("aborting a pending subscription stops its startup scan and rejects", async () => {
const root = await createRoot();
// More directories than the Linux backend watches: a scan that keeps walking after the abort
// fails on the directory limit instead of rejecting with the abort reason.
await Promise.all(
Array.from({ length: 80 }, (_, outer) =>
Promise.all(
Array.from({ length: 70 }, (__, inner) =>
mkdir(join(root, `dir-${outer}`, `nested-${inner}`), { recursive: true }),
),
),
),
);
const observer = createObserver();
const controller = new AbortController();
const reason = new Error("setup deadline passed");
const callback = vi.fn();
const subscription = observer.subscribe(root, callback, { signal: controller.signal });
await new Promise((resolve) => setTimeout(resolve, 10));
controller.abort(reason);
await expect(subscription).rejects.toBe(reason);
expect(observer.getDiagnostics()).toMatchObject({
activeObservationCount: 0,
nativeHandleCount: 0,
pendingReconciliationWorkCount: 0,
});
await writeFile(join(root, "dir-0", "after-abort.txt"), "late");
await new Promise((resolve) => setTimeout(resolve, 100));
expect(callback).not.toHaveBeenCalled();
}, 20_000);
test("aggregate diagnostics return to their lifecycle baseline", async () => {
const root = await createRoot();
const observer = createObserver();
@@ -14,6 +14,8 @@ export interface FileChange {
export interface FileObserverOptions {
ignore?: string[];
// Aborting before `subscribe()` resolves stops the startup scan and rejects with the reason.
signal?: AbortSignal;
}
export type FileObserverCallback = (error: Error | null, events: FileChange[]) => void;
@@ -105,7 +107,19 @@ class FileObserverService implements FileObserver {
createBackend: this.createBackend,
onClosed: () => state.observations.delete(observation),
});
await observation.start();
const { signal } = options;
signal?.throwIfAborted();
const abort = () => void observation.close();
signal?.addEventListener("abort", abort, { once: true });
try {
await observation.start();
} finally {
signal?.removeEventListener("abort", abort);
}
if (signal?.aborted) {
await observation.close();
throw signal.reason;
}
if (this.closePromise) {
await observation.close();
throw new Error("File observer is closed");
@@ -0,0 +1,46 @@
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, test } from "vitest";
import { createFileObserver } from "../index.js";
import { createNativeRecursiveBackend } from "./native-recursive.js";
import { createManagedObservation } from "./observation.js";
import { createObserverPaths } from "./paths.js";
// Aborting a subscription closes its observation while start() may still be
// reading the root, before the backend has started.
test("closing an observation before its backend starts leaves no native watcher open", async () => {
const root = await mkdtemp(join(tmpdir(), "observation-close-"));
const paths = createObserverPaths(process.platform);
let openWatchers = 0;
const observation = createManagedObservation({
root,
callback: () => {},
options: {},
paths,
metrics: createFileObserver().getDiagnostics(),
createBackend: (host) =>
createNativeRecursiveBackend(host, paths, () => {
openWatchers += 1;
let open = true;
return {
close: () => {
if (open) openWatchers -= 1;
open = false;
},
on: () => {},
};
}),
onClosed: () => {},
});
try {
const started = observation.start();
const closed = observation.close();
await started;
await closed;
expect(openWatchers).toBe(0);
} finally {
await rm(root, { recursive: true, force: true });
}
});
@@ -69,6 +69,9 @@ class Observation implements ManagedObservation, ObservationHost {
if (!rootStats.isDirectory()) {
throw new Error(`File observation requires a directory: ${this.root}`);
}
// An aborted subscription can close the observation while the root is being read; the backend
// must not start after its close has already finished.
if (!this.isActive()) return;
try {
await this.backend.start();
} catch (error) {
@@ -2195,6 +2195,7 @@ describe("WorkspaceGitServiceImpl D2 read methods", () => {
expect(subscribe).toHaveBeenCalledTimes(1);
expect(subscribe).toHaveBeenCalledWith(repoDir, expect.any(Function), {
ignore: [join(repoDir, ".git"), ignoredRoot],
signal: expect.any(AbortSignal),
});
subscription.unsubscribe();
@@ -477,6 +477,56 @@ async function advanceThroughWorkingTreeRecoveryAttempts(
}
}
// Stalls every subscription for `watchPath` the way a CPU-starved startup scan does, until the
// service aborts it at the subscribe deadline. Other paths subscribe immediately.
function createStallingWatchSetup(watchPath: string) {
const signals: AbortSignal[] = [];
let acceptNext = false;
let acceptedCallback: WatchCallback | null = null;
const subscribe = vi.fn(
async (directory: string, callback: WatchCallback, options?: { signal?: AbortSignal }) => {
if (directory !== watchPath) {
return createAsyncSubscription();
}
const signal = options?.signal ?? new AbortController().signal;
signals.push(signal);
if (acceptNext) {
acceptNext = false;
acceptedCallback = callback;
return createAsyncSubscription();
}
return new Promise<ReturnType<typeof createAsyncSubscription>>((_resolve, reject) => {
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
});
},
);
return {
subscribe,
signals,
acceptNextAttempt() {
acceptNext = true;
},
failAcceptedWatcher() {
acceptedCallback?.(new Error("accepted watcher stopped"), []);
},
async expectAttemptAbortedAtDeadline() {
const signal = signals.at(-1);
expect(signal?.aborted).toBe(false);
await vi.advanceTimersByTimeAsync(WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS);
expect(signal?.aborted).toBe(true);
expect(signal?.reason).toMatchObject({ name: "WorkspaceGitWatcherSubscriptionTimeoutError" });
},
async expectNextAttemptAfter(delayMs: number, service: WorkspaceGitServiceImpl) {
const attempts = signals.length;
await vi.advanceTimersByTimeAsync(delayMs - 1);
await waitForRefreshesToSettle(service);
expect(signals).toHaveLength(attempts);
await vi.advanceTimersByTimeAsync(1);
await settle(() => expect(signals).toHaveLength(attempts + 1));
},
};
}
describe("WorkspaceGitServiceImpl", () => {
beforeEach(() => {
vi.useFakeTimers();
@@ -1573,6 +1623,7 @@ describe("WorkspaceGitServiceImpl", () => {
expect(subscribe).toHaveBeenCalledTimes(1);
expect(subscribe).toHaveBeenCalledWith(REPO_CWD, expect.any(Function), {
ignore: [join(REPO_CWD, ".git")],
signal: expect.any(AbortSignal),
});
subscription.unsubscribe();
@@ -1648,6 +1699,67 @@ describe("WorkspaceGitServiceImpl", () => {
15_000,
);
test.each(["repository metadata", "working tree"])(
"aborts each timed-out %s watcher setup and backs retries off toward an hour",
async (kind) => {
const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD;
const setup = createStallingWatchSetup(watchPath);
const getCheckoutStatus = vi.fn(async (cwd: string) => createCheckoutStatus(cwd));
const service = createService({ subscribe: setup.subscribe, getCheckoutStatus });
const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn());
try {
await settle(() => expect(setup.signals).toHaveLength(1));
await setup.expectAttemptAbortedAtDeadline();
await waitForObservationToSettle(service, 1);
for (const delayMs of [
30_000, 60_000, 120_000, 240_000, 480_000, 960_000, 1_920_000, 3_600_000,
]) {
await setup.expectNextAttemptAfter(delayMs, service);
await setup.expectAttemptAbortedAtDeadline();
}
// Degraded polling keeps the checkout fresh while the watcher waits out an hour.
const readsBeforeCappedWait = getCheckoutStatus.mock.calls.length;
await setup.expectNextAttemptAfter(3_600_000, service);
expect(getCheckoutStatus.mock.calls.length).toBeGreaterThanOrEqual(
readsBeforeCappedWait + 59,
);
} finally {
subscription.unsubscribe();
await service.dispose();
}
},
30_000,
);
test.each(["repository metadata", "working tree"])(
"an accepted %s watcher subscription resets the setup-timeout backoff",
async (kind) => {
const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD;
const setup = createStallingWatchSetup(watchPath);
const service = createService({ subscribe: setup.subscribe });
const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn());
try {
await settle(() => expect(setup.signals).toHaveLength(1));
await setup.expectAttemptAbortedAtDeadline();
for (const delayMs of [30_000, 60_000, 120_000, 240_000, 480_000]) {
await setup.expectNextAttemptAfter(delayMs, service);
await setup.expectAttemptAbortedAtDeadline();
}
setup.acceptNextAttempt();
await setup.expectNextAttemptAfter(960_000, service);
setup.failAcceptedWatcher();
// The ordinary recovery ladder's ceiling applies again, not the 32-minute timeout step.
await setup.expectNextAttemptAfter(300_000, service);
await setup.expectAttemptAbortedAtDeadline();
await setup.expectNextAttemptAfter(300_000, service);
} finally {
subscription.unsubscribe();
await service.dispose();
}
},
30_000,
);
test.each(["repository metadata", "working tree"])(
"ignores expired %s watcher callbacks after recovery",
async (kind) => {
@@ -1873,6 +1985,7 @@ describe("WorkspaceGitServiceImpl", () => {
expect(subscription.repoRoot).toBeNull();
expect(subscribe).toHaveBeenCalledWith(plainCwd, expect.any(Function), {
ignore: [join(plainCwd, ".git")],
signal: expect.any(AbortSignal),
});
expect(vi.getTimerCount()).toBe(1);
@@ -123,6 +123,11 @@ const WATCH_RECOVERY_BASE_DELAY_MS = 30_000;
// restart, which kills running agents. Back off, but keep trying.
const WATCH_RECOVERY_MAX_DELAY_MS = 300_000;
const WATCH_RECOVERY_MAX_BACKOFF_STEPS = 4;
// A startup scan that missed the subscribe deadline on a CPU-starved host misses it again on the
// next attempt, and every attempt repeats the full scan. Consecutive setup timeouts therefore
// keep doubling the recovery delay past the ladder cap, up to an hour.
const WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS = 3_600_000;
const WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS = 7;
// Auxiliary reads may reuse cached values within this window; snapshots do not expire on read.
const WORKSPACE_GIT_AUXILIARY_READ_TTL_MS = 15_000;
// Non-forced refresh triggers share this minimum gap to absorb watcher/self-heal bursts; force bypasses it.
@@ -574,6 +579,10 @@ interface WatchRecoveryState {
// use (SMB/NFS, Docker virtiofs, some FUSE) resets the ladder on every
// attempt and the backoff never engages.
establishedAt: number | null;
// Setup attempts that hit WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS since the last accepted
// subscription. Reset on acceptance: finishing the startup scan in time is the proof that
// the next attempt is affordable.
setupTimeoutCount: number;
}
function setsEqual(left: ReadonlySet<string>, right: ReadonlySet<string>): boolean {
@@ -1519,7 +1528,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
fallbackPolling: false,
fallbackPollTimer: null,
fallbackPollQuietTickCount: 0,
recovery: { attemptCount: 0, timer: null, establishedAt: null },
recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 },
listeners: new Set(),
closed: false,
};
@@ -1549,9 +1558,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
let removeAbortListener = () => {};
let unsubscribePromise: Promise<void> | null = null;
let subscriptionPromise: Promise<FileObserverSubscription>;
// Abandoning the race is not enough: the observer's startup scan would keep walking the
// tree after the deadline. Abort it so a timed-out attempt stops costing CPU.
const setupController = new AbortController();
try {
subscriptionPromise = this.deps
.subscribe(watchPath, callback, options)
.subscribe(watchPath, callback, { ...options, signal: setupController.signal })
.finally(onSubscribeSettled);
} catch (error) {
onSubscribeSettled();
@@ -1570,12 +1582,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
const timeoutPromise = new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => {
outcome = "expired";
reject(new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath));
const error = new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath);
setupController.abort(error);
reject(error);
}, WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS);
});
const disposalPromise = new Promise<never>((_resolve, reject) => {
const rejectForDisposal = () => {
outcome = "expired";
setupController.abort(signal.reason);
reject(signal.reason);
};
if (signal.aborted) {
@@ -1710,6 +1725,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
// `scheduleWorkingTreeWatchRecovery` only resets the ladder once this
// one has survived long enough to prove itself durable.
target.recovery.establishedAt = this.deps.now().getTime();
target.recovery.setupTimeoutCount = 0;
if (options?.replaceFallback && target.repoRoot !== null) {
target.fallbackPolling = false;
if (target.fallbackPollTimer) {
@@ -1730,6 +1746,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
{ err: error, cwd: target.cwd },
"Failed to start working tree watcher; using degraded polling",
);
this.noteWatchSetupFailure(target.recovery, error);
if (!options?.replaceFallback) {
this.startWorkingTreeWatchFallback(target, "watcher_setup_failed");
}
@@ -1952,11 +1969,26 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
}
recovery.establishedAt = null;
recovery.attemptCount += 1;
return Math.min(
const ladderDelayMs = Math.min(
WATCH_RECOVERY_BASE_DELAY_MS *
2 ** Math.min(recovery.attemptCount - 1, WATCH_RECOVERY_MAX_BACKOFF_STEPS),
WATCH_RECOVERY_MAX_DELAY_MS,
);
if (recovery.setupTimeoutCount === 0) {
return ladderDelayMs;
}
const setupTimeoutDelayMs = Math.min(
WATCH_RECOVERY_BASE_DELAY_MS *
2 ** Math.min(recovery.setupTimeoutCount - 1, WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS),
WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS,
);
return Math.max(ladderDelayMs, setupTimeoutDelayMs);
}
private noteWatchSetupFailure(recovery: WatchRecoveryState, error: unknown): void {
if (error instanceof WorkspaceGitWatcherSubscriptionTimeoutError) {
recovery.setupTimeoutCount += 1;
}
}
private scheduleWorkingTreeWatchRecovery(target: WorkingTreeWatchTarget): void {
@@ -2430,7 +2462,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
fallbackPolling: false,
fallbackPollTimer: null,
fallbackPollQuietTickCount: 0,
recovery: { attemptCount: 0, timer: null, establishedAt: null },
recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 },
intervalId: null,
fetchInFlight: false,
bufferedFetchMetadataEvents: [],
@@ -2580,6 +2612,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
// subscribe success alone, only record when this subscription was
// established.
target.recovery.establishedAt = this.deps.now().getTime();
target.recovery.setupTimeoutCount = 0;
if (options?.replaceFallback) {
target.fallbackPolling = false;
if (target.fallbackPollTimer) {
@@ -2603,6 +2636,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
{ err: error, repoGitRoot: target.repoGitRoot },
"Failed to start repository metadata watcher; using degraded polling",
);
this.noteWatchSetupFailure(target.recovery, error);
if (!options?.replaceFallback) {
this.startRepoMetadataFallback(target);
}