diff --git a/packages/server/src/server/git-observation-paths.ts b/packages/server/src/server/git-observation-paths.ts index 1ef0a4e571..ded5bf0a46 100644 --- a/packages/server/src/server/git-observation-paths.ts +++ b/packages/server/src/server/git-observation-paths.ts @@ -13,6 +13,7 @@ const identityIo = pLimit(2); export class GitObservationPaths { private constructor( private readonly root: string, + readonly identity: string, private readonly aliases: string[], private readonly windows: boolean, ) {} @@ -23,11 +24,15 @@ export class GitObservationPaths { windows ? normalizePathPreservingCase(value, true).replaceAll("\\", "/").toLowerCase() : normalizePathPreservingCase(value, false); - const aliases = new Set([normalizePath(root)]); + const lexicalRoot = normalizePath(root); + const aliases = new Set([lexicalRoot]); + let identity: string | undefined; // Sequential: foreign paths must not fan out into the shared libuv pool. for (const resolve of [nativeRealpath, jsRealpath]) { try { - aliases.add(normalizePath(await identityIo(() => resolve(root)))); + const alias = normalizePath(await identityIo(() => resolve(root))); + identity ??= alias; + aliases.add(alias); } catch { /* Missing roots retain lexical identity. */ } @@ -48,7 +53,7 @@ export class GitObservationPaths { break; } } - return new GitObservationPaths(root, [...aliases], windows); + return new GitObservationPaths(root, identity ?? lexicalRoot, [...aliases], windows); } relative(candidate: string): string | null { diff --git a/packages/server/src/server/workspace-git-service.test.ts b/packages/server/src/server/workspace-git-service.test.ts index b8b3b508a3..9d2b3008d6 100644 --- a/packages/server/src/server/workspace-git-service.test.ts +++ b/packages/server/src/server/workspace-git-service.test.ts @@ -1757,6 +1757,74 @@ describe("WorkspaceGitServiceImpl", () => { 30_000, ); + test.each(["repository metadata", "working tree"])( + "keeps the %s watcher retry delay when the last observer reconnects", + async (kind) => { + const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD; + const setup = createStallingWatchSetup(watchPath); + const service = createService({ subscribe: setup.subscribe, now: () => new Date() }); + const first = service.registerWorkspace({ cwd: REPO_CWD }, () => {}); + try { + await settle(() => expect(setup.signals).toHaveLength(1)); + await setup.expectAttemptAbortedAtDeadline(); + await waitForObservationToSettle(service, 1); + await setup.expectNextAttemptAfter(30_000, service); + await setup.expectAttemptAbortedAtDeadline(); + first.unsubscribe(); + + await vi.advanceTimersByTimeAsync(15_000); + const second = service.registerWorkspace({ cwd: REPO_CWD }, () => {}); + try { + await settle(() => { + const metrics = service.getMetrics(); + const observationReady = + metrics.repositoryWorkspaceLinkCount === 1 && + metrics.workspaceObservationSetupInFlightCount === 0; + expect(observationReady || setup.signals.length > 2).toBe(true); + }); + expect(setup.signals).toHaveLength(2); + await setup.expectNextAttemptAfter(45_000, service); + await setup.expectAttemptAbortedAtDeadline(); + await setup.expectNextAttemptAfter(120_000, service); + } finally { + second.unsubscribe(); + } + } finally { + await service.dispose(); + } + }, + ); + + test.each(["repository metadata", "working tree"])( + "keeps the scheduled %s watcher retry after an error and a setup timeout", + async (kind) => { + const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD; + const setup = createStallingWatchSetup(watchPath); + setup.acceptNextAttempt(); + const service = createService({ subscribe: setup.subscribe, now: () => new Date() }); + const first = service.registerWorkspace({ cwd: REPO_CWD }, () => {}); + try { + await waitForObservationToSettle(service, 1); + expect(setup.signals).toHaveLength(1); + setup.failAcceptedWatcher(); + await setup.expectNextAttemptAfter(30_000, service); + await setup.expectAttemptAbortedAtDeadline(); + first.unsubscribe(); + + await vi.advanceTimersByTimeAsync(15_000); + const second = service.registerWorkspace({ cwd: REPO_CWD }, () => {}); + try { + await waitForObservationToSettle(service, 1); + await setup.expectNextAttemptAfter(45_000, service); + } finally { + second.unsubscribe(); + } + } finally { + await service.dispose(); + } + }, + ); + test.each(["repository metadata", "working tree"])( "an accepted %s watcher subscription resets the setup-timeout backoff", async (kind) => { diff --git a/packages/server/src/server/workspace-git-service.ts b/packages/server/src/server/workspace-git-service.ts index 2295adb557..dc369f69ba 100644 --- a/packages/server/src/server/workspace-git-service.ts +++ b/packages/server/src/server/workspace-git-service.ts @@ -132,7 +132,7 @@ const WATCH_RECOVERY_MAX_BACKOFF_STEPS = 4; // 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; +const WATCH_SETUP_TIMEOUT_CACHE_MAX = 1_024; // 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. @@ -593,10 +593,12 @@ 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; + setupKey: string; +} + +interface WatchSetupTimeout { + delayMs: number; + retryAtMs: number; } function setsEqual(left: ReadonlySet, right: ReadonlySet): boolean { @@ -695,6 +697,10 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { private readonly workingTreeWatchSetups = new Map>(); private readonly workingTreeWatchResolutions = new Map>(); private readonly workingTreeWatchAliases = new Map(); + // A timed-out scan stays expensive even when the last observer disconnects. + private readonly watchSetupTimeouts = new LRUCache({ + max: WATCH_SETUP_TIMEOUT_CACHE_MAX, + }); private readonly branchValidationCache = new LRUCache< string, WorkspaceGitAuxiliaryReadCacheEntry @@ -1187,6 +1193,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { this.workingTreeWatchSetups.clear(); this.workingTreeWatchResolutions.clear(); this.workingTreeWatchAliases.clear(); + this.watchSetupTimeouts.clear(); this.snapshotUpdatedListeners.clear(); // Unsubscribing can remove a target while its Git command still owns the cwd. // Stop admission first, then drain those refreshes and the parent lookups they start. @@ -1552,14 +1559,25 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { fallbackPolling: false, fallbackPollTimer: null, fallbackPollQuietTickCount: 0, - recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 }, + recovery: { + attemptCount: 0, + timer: null, + establishedAt: null, + setupKey: `working-tree:${paths.identity}`, + }, listeners: new Set(), closed: false, }; this.workingTreeWatchTargets.set(cwd, target); this.workingTreeWatchAliases.set(cwd, cwd); - await this.startWorkingTreeSubscription(target); + const retryInMs = this.watchSetupRetryInMs(target.recovery); + if (retryInMs > 0) { + this.startWorkingTreeWatchFallback(target, "watcher_setup_failed"); + this.scheduleWorkingTreeWatchRecovery(target, retryInMs); + } else { + await this.startWorkingTreeSubscription(target); + } this.assertNotDisposed(); if (repoRoot === null) { @@ -1749,7 +1767,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; + this.watchSetupTimeouts.delete(target.recovery.setupKey); if (options?.replaceFallback && target.repoRoot !== null) { target.fallbackPolling = false; if (target.fallbackPollTimer) { @@ -1998,28 +2016,60 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { 2 ** Math.min(recovery.attemptCount - 1, WATCH_RECOVERY_MAX_BACKOFF_STEPS), WATCH_RECOVERY_MAX_DELAY_MS, ); - if (recovery.setupTimeoutCount === 0) { + const timeout = this.getWatchSetupTimeout(recovery); + if (!timeout) { 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); + const delayMs = Math.max(ladderDelayMs, timeout.delayMs); + // Resume the retry that is actually scheduled, even if the ordinary + // recovery ladder asks for a longer wait than the setup-timeout ladder. + timeout.retryAtMs = this.deps.now().getTime() + delayMs; + return delayMs; + } + + private watchSetupRetryInMs(recovery: WatchRecoveryState): number { + const timeout = this.getWatchSetupTimeout(recovery); + return timeout ? timeout.retryAtMs - this.deps.now().getTime() : 0; + } + + private getWatchSetupTimeout(recovery: WatchRecoveryState): WatchSetupTimeout | undefined { + const timeout = this.watchSetupTimeouts.get(recovery.setupKey); + if ( + timeout && + timeout.retryAtMs + WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS <= this.deps.now().getTime() + ) { + this.watchSetupTimeouts.delete(recovery.setupKey); + return undefined; + } + return timeout; } private noteWatchSetupFailure(recovery: WatchRecoveryState, error: unknown): void { - if (error instanceof WorkspaceGitWatcherSubscriptionTimeoutError) { - recovery.setupTimeoutCount += 1; + if (!(error instanceof WorkspaceGitWatcherSubscriptionTimeoutError)) { + return; } + + const previous = this.getWatchSetupTimeout(recovery); + const delayMs = previous + ? Math.min(previous.delayMs * 2, WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS) + : WATCH_RECOVERY_BASE_DELAY_MS; + const retryAtMs = this.deps.now().getTime() + delayMs; + // Age out history after one hour beyond the pending retry. No timers + // remain active once the last listener releases the watcher. + this.watchSetupTimeouts.set(recovery.setupKey, { + delayMs, + retryAtMs, + }); } - private scheduleWorkingTreeWatchRecovery(target: WorkingTreeWatchTarget): void { + private scheduleWorkingTreeWatchRecovery( + target: WorkingTreeWatchTarget, + retryInMs?: number, + ): void { if (target.closed || target.subscription || target.recovery.timer) { return; } - const delayMs = this.advanceWatchRecoveryLadder(target.recovery); + const delayMs = retryInMs ?? this.advanceWatchRecoveryLadder(target.recovery); target.recovery.timer = setTimeout(() => { target.recovery.timer = null; void this.recoverWorkingTreeWatch(target).catch((error) => { @@ -2486,7 +2536,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { fallbackPolling: false, fallbackPollTimer: null, fallbackPollQuietTickCount: 0, - recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 }, + recovery: { + attemptCount: 0, + timer: null, + establishedAt: null, + setupKey: `repository-metadata:${paths.identity}`, + }, intervalId: null, fetchInFlight: false, bufferedFetchMetadataEvents: [], @@ -2495,7 +2550,13 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { closed: false, }; this.repoTargets.set(repoGitRoot, repoTarget); - await this.startRepoMetadataObservation(repoTarget); + const retryInMs = this.watchSetupRetryInMs(repoTarget.recovery); + if (retryInMs > 0) { + this.startRepoMetadataFallback(repoTarget); + this.scheduleRepoMetadataWatchRecovery(repoTarget, retryInMs); + } else { + await this.startRepoMetadataObservation(repoTarget); + } if (repoTarget.closed || this.repoTargets.get(repoGitRoot) !== repoTarget) { return; } @@ -2636,7 +2697,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; + this.watchSetupTimeouts.delete(target.recovery.setupKey); if (options?.replaceFallback) { target.fallbackPolling = false; if (target.fallbackPollTimer) { @@ -2679,11 +2740,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService { this.startRepoMetadataFallback(target); } - private scheduleRepoMetadataWatchRecovery(target: RepoGitTarget): void { + private scheduleRepoMetadataWatchRecovery(target: RepoGitTarget, retryInMs?: number): void { if (target.closed || target.subscription || target.recovery.timer) { return; } - const delayMs = this.advanceWatchRecoveryLadder(target.recovery); + const delayMs = retryInMs ?? this.advanceWatchRecoveryLadder(target.recovery); target.recovery.timer = setTimeout(() => { target.recovery.timer = null; void this.recoverRepoMetadataWatch(target).catch((error) => {