From 3f576d99c3e55f760f676932f57c2441e393afdb Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 26 Nov 2026 14:45:41 -0800 Subject: [PATCH] [node-core-library] Own Windows folder deletion retry policy Address #6230 with a whole-operation retry budget, compatible folder enumeration, and settled async child deletes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...der-deletion-retries_2026-11-26-22-39.json | 10 + libraries/node-core-library/src/FileSystem.ts | 169 ++++++--- .../src/test/FileSystem.test.ts | 343 +++++++++++++++++- 3 files changed, 475 insertions(+), 47 deletions(-) create mode 100644 common/changes/@rushstack/node-core-library/fix-windows-folder-deletion-retries_2026-11-26-22-39.json diff --git a/common/changes/@rushstack/node-core-library/fix-windows-folder-deletion-retries_2026-11-26-22-39.json b/common/changes/@rushstack/node-core-library/fix-windows-folder-deletion-retries_2026-11-26-22-39.json new file mode 100644 index 00000000000..06277346a78 --- /dev/null +++ b/common/changes/@rushstack/node-core-library/fix-windows-folder-deletion-retries_2026-11-26-22-39.json @@ -0,0 +1,10 @@ +{ + "changes": [ + { + "packageName": "@rushstack/node-core-library", + "comment": "Retry `FileSystem` folder deletion operations on Windows only for errors reported as `EBUSY`, `ENOTEMPTY` or `EPERM`, with a shared budget of three retries and delays of 100, 200 and 300 ms. Fix `FileSystem.ensureEmptyFolder` and `FileSystem.ensureEmptyFolderAsync` compatibility with Node.js 20.9 and unbound calls, and ensure async child deletions settle before retrying or rejecting. `FileSystem.ensureEmptyFolderAsync` deletes at most 10 top-level children concurrently; `FileSystem.ensureEmptyFolder` and `FileSystem.ensureEmptyFolderAsync` throw on folder read errors other than `ENOENT`.", + "type": "patch" + } + ], + "packageName": "@rushstack/node-core-library" +} diff --git a/libraries/node-core-library/src/FileSystem.ts b/libraries/node-core-library/src/FileSystem.ts index efcc1efd959..9450e963160 100644 --- a/libraries/node-core-library/src/FileSystem.ts +++ b/libraries/node-core-library/src/FileSystem.ts @@ -378,18 +378,12 @@ const DELETE_FILE_DEFAULT_OPTIONS: Partial = { throwIfNotExists: false }; -/** - * Default options for fs.rm / fsPromises.rm calls in this file. - * - * @remarks - * The retry settings mitigate transient EPERM/EBUSY/ENOTEMPTY errors on - * Windows (e.g. AV scanners holding a lock right after a delete). - */ const FS_RM_DEFAULT_OPTIONS: Partial = { recursive: true, force: true, - maxRetries: 3, - retryDelay: 100 + // Own the retry budget for the whole operation instead of letting Node retry each recursive entry. + maxRetries: 0, + retryDelay: 0 }; /** @@ -740,20 +734,29 @@ export class FileSystem { * Behind the scenes it uses `fs.rmSync()`. * @remarks * Does not throw if the folderPath does not exist. + * + * On Windows, if the operation fails with an error reported as `EBUSY`, `ENOTEMPTY` or `EPERM`, + * it is retried up to three times, with delays of 100, 200 and 300 milliseconds between attempts. * @param folderPath - The absolute or relative path to the folder which should be deleted. */ public static deleteFolder(folderPath: string): void { _wrapException(() => { - fs.rmSync(folderPath, FS_RM_DEFAULT_OPTIONS); + _retryFolderDeletion(() => { + fs.rmSync(folderPath, FS_RM_DEFAULT_OPTIONS); + }); }); } /** * An async version of {@link FileSystem.deleteFolder}. + * + * @remarks + * On Windows, if the operation fails with an error reported as `EBUSY`, `ENOTEMPTY` or `EPERM`, + * it is retried up to three times, with delays of 100, 200 and 300 milliseconds between attempts. */ public static async deleteFolderAsync(folderPath: string): Promise { await _wrapExceptionAsync(() => { - return fsPromises.rm(folderPath, FS_RM_DEFAULT_OPTIONS); + return _retryFolderDeletionAsync(() => fsPromises.rm(folderPath, FS_RM_DEFAULT_OPTIONS)); }); } @@ -763,50 +766,90 @@ export class FileSystem { * @remarks * This is a workaround for a common race condition, where the virus scanner holds a lock on the folder * for a brief period after it was deleted, causing EBUSY errors for any code that tries to recreate the folder. + * + * On Windows, if the operation fails with an error reported as `EBUSY`, `ENOTEMPTY` or `EPERM`, + * it is retried up to three times, with delays of 100, 200 and 300 milliseconds between attempts. + * + * Throws on folder read errors other than `ENOENT`. * @param folderPath - The absolute or relative path to the folder which should have its contents deleted. */ public static ensureEmptyFolder(folderPath: string): void { _wrapException(() => { - let items: FolderItem[]; - try { - items = this.readFolderItems(folderPath); - } catch (error) { - if (!FileSystem.isNotExistError(error as Error)) { - throw error; + _retryFolderDeletion(() => { + let names: string[]; + try { + names = fsx.readdirSync(folderPath); + } catch (error) { + if (!FileSystem.isFileDoesNotExistError(error as Error)) { + throw error; + } + + fsx.ensureDirSync(folderPath); + return; } - fsx.ensureDirSync(folderPath); - return; - } - for (const item of items) { - const itemPath: string = nodeJsPath.join(item.parentPath, item.name); - fs.rmSync(itemPath, FS_RM_DEFAULT_OPTIONS); - } + + for (const name of names) { + fs.rmSync(nodeJsPath.join(folderPath, name), FS_RM_DEFAULT_OPTIONS); + } + }); }); } /** * An async version of {@link FileSystem.ensureEmptyFolder}. + * + * @remarks + * On Windows, if the operation fails with an error reported as `EBUSY`, `ENOTEMPTY` or `EPERM`, + * it is retried up to three times, with delays of 100, 200 and 300 milliseconds between attempts. + * + * Deletes at most 10 top-level children concurrently and waits for started child deletes to settle + * before retrying or rejecting. Throws on folder read errors other than `ENOENT`. */ public static async ensureEmptyFolderAsync(folderPath: string): Promise { await _wrapExceptionAsync(async () => { - let items: FolderItem[]; - try { - items = await this.readFolderItemsAsync(folderPath); - } catch (error) { - if (!FileSystem.isNotExistError(error as Error)) { - throw error; + await _retryFolderDeletionAsync(async () => { + let names: string[]; + try { + names = await fsx.readdir(folderPath); + } catch (error) { + if (!FileSystem.isFileDoesNotExistError(error as Error)) { + throw error; + } + + await fsx.ensureDir(folderPath); + return; } - await fsx.ensureDir(folderPath); - return; - } - await Async.forEachAsync( - items, - (item) => { - const itemPath: string = nodeJsPath.join(item.parentPath, item.name); - return fsPromises.rm(itemPath, FS_RM_DEFAULT_OPTIONS); - }, - { concurrency: 10 } - ); + + let hasError: boolean = false; + let deletionError: unknown; + await Async.forEachAsync( + names, + async (name) => { + if (hasError) { + return; + } + + try { + await fsPromises.rm(nodeJsPath.join(folderPath, name), FS_RM_DEFAULT_OPTIONS); + } catch (error) { + // Keep callbacks fulfilled so every started delete settles before the retry decision. + if ( + !hasError || + (_isRetryableFolderDeletionError(deletionError) && !_isRetryableFolderDeletionError(error)) + ) { + deletionError = error; + } + + hasError = true; + } + }, + { concurrency: 10 } + ); + + if (hasError) { + throw deletionError; + } + }); }); } @@ -1758,6 +1801,50 @@ async function _handleLinkAsync( } } +function _isRetryableFolderDeletionError(error: unknown): boolean { + if (typeof error !== 'object' || error === null || !('code' in error)) { + return false; + } + + const { code } = error; + return code === 'EBUSY' || code === 'ENOTEMPTY' || code === 'EPERM'; +} + +function _shouldRetryFolderDeletion(error: unknown, retryCount: number): boolean { + // Retry transient deletion failures on Windows, where open file handles can + // temporarily prevent files and folders from being removed. Extend this + // policy to other platforms if the problem is reported there. + return process.platform === 'win32' && retryCount < 3 && _isRetryableFolderDeletionError(error); +} + +function _retryFolderDeletion(action: () => void): void { + for (let retryCount: number = 0; ; retryCount++) { + try { + return action(); + } catch (error) { + if (!_shouldRetryFolderDeletion(error, retryCount)) { + throw error; + } + + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, (retryCount + 1) * 100); + } + } +} + +async function _retryFolderDeletionAsync(action: () => Promise): Promise { + for (let retryCount: number = 0; ; retryCount++) { + try { + return await action(); + } catch (error) { + if (!_shouldRetryFolderDeletion(error, retryCount)) { + throw error; + } + + await Async.sleepAsync((retryCount + 1) * 100); + } + } +} + function _wrapException(fn: () => TResult): TResult { try { return fn(); diff --git a/libraries/node-core-library/src/test/FileSystem.test.ts b/libraries/node-core-library/src/test/FileSystem.test.ts index 80e0ef28fea..652e655d368 100644 --- a/libraries/node-core-library/src/test/FileSystem.test.ts +++ b/libraries/node-core-library/src/test/FileSystem.test.ts @@ -2,13 +2,26 @@ // See LICENSE in the project root for license information. import fs from 'node:fs'; +import fsPromises from 'node:fs/promises'; +import * as path from 'node:path'; +import fsx from 'fs-extra'; +import { Async } from '../Async'; import { FileSystem } from '../FileSystem'; import { PosixModeBits } from '../PosixModeBits'; // Use a deterministic path inside the project's output folder for temp files const testTempFolder: string = `${__dirname}/temp`; +function createDeletionError(code: string): NodeJS.ErrnoException { + return Object.assign(new Error(`${code}: deletion failed`), { + code, + errno: -1, + syscall: 'unlink', + path: 'mock-child' + }); +} + describe(FileSystem.name, () => { test(FileSystem.formatPosixModeBits.name, () => { // The PosixModeBits are intended to be used with bitwise operations. @@ -176,11 +189,11 @@ describe(FileSystem.name, () => { expect(fs.readdirSync(tempDir)).toEqual([]); }); - test('re-throws errors from readFolderItems that are not not-exist errors', () => { + test('re-throws folder read errors other than ENOENT', () => { const permError: NodeJS.ErrnoException = Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }); - const spy: jest.SpyInstance = jest.spyOn(FileSystem, 'readFolderItems').mockImplementationOnce(() => { + const spy: jest.SpyInstance = jest.spyOn(fsx, 'readdirSync').mockImplementationOnce(() => { throw permError; }); @@ -190,6 +203,24 @@ describe(FileSystem.name, () => { spy.mockRestore(); } }); + + test('supports an unbound call', () => { + FileSystem.ensureFolder(tempDir); + FileSystem.writeFile(`${tempDir}/a.txt`, 'a'); + const { ensureEmptyFolder } = FileSystem; + + ensureEmptyFolder(tempDir); + + expect(fs.readdirSync(tempDir)).toEqual([]); + }); + + test('does not delete or replace an existing file', () => { + FileSystem.ensureFolder(testTempFolder); + FileSystem.writeFile(tempDir, 'keep'); + + expect(() => FileSystem.ensureEmptyFolder(tempDir)).toThrow(/ENOTDIR/); + expect(FileSystem.readFile(tempDir)).toBe('keep'); + }); }); describe(FileSystem.ensureEmptyFolderAsync.name, () => { @@ -219,13 +250,11 @@ describe(FileSystem.name, () => { expect(fs.readdirSync(tempDir)).toEqual([]); }); - test('re-throws errors from readFolderItemsAsync that are not not-exist errors', async () => { + test('re-throws folder read errors other than ENOENT', async () => { const permError: NodeJS.ErrnoException = Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }); - const spy: jest.SpyInstance = jest - .spyOn(FileSystem, 'readFolderItemsAsync') - .mockRejectedValueOnce(permError); + const spy: jest.SpyInstance = jest.spyOn(fsx, 'readdir').mockRejectedValueOnce(permError); try { await expect(FileSystem.ensureEmptyFolderAsync(tempDir)).rejects.toThrow(/EACCES/); @@ -233,6 +262,308 @@ describe(FileSystem.name, () => { spy.mockRestore(); } }); + + test('supports an unbound call', async () => { + await FileSystem.ensureFolderAsync(tempDir); + await FileSystem.writeFileAsync(`${tempDir}/a.txt`, 'a'); + const { ensureEmptyFolderAsync } = FileSystem; + + await ensureEmptyFolderAsync(tempDir); + + expect(fs.readdirSync(tempDir)).toEqual([]); + }); + + test('does not delete or replace an existing file', async () => { + await FileSystem.ensureFolderAsync(testTempFolder); + await FileSystem.writeFileAsync(tempDir, 'keep'); + + await expect(FileSystem.ensureEmptyFolderAsync(tempDir)).rejects.toThrow(/ENOTDIR/); + expect(FileSystem.readFile(tempDir)).toBe('keep'); + }); + }); + + describe.each([ + { name: 'deleteFolder', run: FileSystem.deleteFolder, isAsync: false, emptiesFolder: false }, + { name: 'deleteFolderAsync', run: FileSystem.deleteFolderAsync, isAsync: true, emptiesFolder: false }, + { name: 'ensureEmptyFolder', run: FileSystem.ensureEmptyFolder, isAsync: false, emptiesFolder: true }, + { + name: 'ensureEmptyFolderAsync', + run: FileSystem.ensureEmptyFolderAsync, + isAsync: true, + emptiesFolder: true + } + ])('$name retry policy', ({ run, isAsync, emptiesFolder }) => { + const folderPath: string = path.join(testTempFolder, 'mock-deletion'); + const platformDescriptor: PropertyDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!; + let rmSpy: jest.SpyInstance; + let readSpy: jest.SpyInstance; + let sleeps: number[]; + + beforeEach(() => { + Object.defineProperty(process, 'platform', { value: 'win32' }); + sleeps = []; + jest.spyOn(Atomics, 'wait').mockImplementation((array, index, value, delay) => { + sleeps.push(delay!); + return 'timed-out'; + }); + jest.spyOn(Async, 'sleepAsync').mockImplementation(async (delay) => { + sleeps.push(delay); + }); + readSpy = isAsync ? jest.spyOn(fsx, 'readdir') : jest.spyOn(fsx, 'readdirSync'); + readSpy.mockImplementation(() => (isAsync ? Promise.resolve(['child']) : ['child'])); + rmSpy = isAsync ? jest.spyOn(fsPromises, 'rm') : jest.spyOn(fs, 'rmSync'); + rmSpy.mockImplementation(() => (isAsync ? Promise.resolve() : undefined)); + }); + + afterEach(() => { + jest.restoreAllMocks(); + Object.defineProperty(process, 'platform', platformDescriptor); + }); + + test.each(['EBUSY', 'ENOTEMPTY', 'EPERM'])( + 'retries %s then succeeds with native retries disabled', + async (code) => { + rmSpy.mockImplementationOnce(() => { + throw createDeletionError(code); + }); + + await run(folderPath); + + expect(sleeps).toEqual([100]); + expect(rmSpy).toHaveBeenCalledTimes(2); + for (const call of rmSpy.mock.calls) { + expect(call).toEqual([ + emptiesFolder ? path.join(folderPath, 'child') : folderPath, + { recursive: true, force: true, maxRetries: 0, retryDelay: 0 } + ]); + } + } + ); + + test('waits exactly 100, 200 and 300 ms and throws the last failed attempt', async () => { + const errors: NodeJS.ErrnoException[] = ['EBUSY', 'ENOTEMPTY', 'EPERM', 'EPERM'].map( + createDeletionError + ); + let attempt: number = 0; + rmSpy.mockImplementation(() => { + throw errors[attempt++]; + }); + + await expect(async () => run(folderPath)).rejects.toBe(errors[3]); + + expect(rmSpy).toHaveBeenCalledTimes(4); + expect(sleeps).toEqual([100, 200, 300]); + expect(errors[3].message).toContain('File or folder could not be deleted:'); + expect(errors[2].message).not.toContain('File or folder could not be deleted:'); + }); + + test.each(['EACCES', 'EMFILE', 'ENFILE', 'EIO', 'ENOTDIR', ''])( + 'does not retry a reported code of %j', + async (code) => { + const error: NodeJS.ErrnoException = createDeletionError(code); + rmSpy.mockImplementation(() => { + throw error; + }); + + await expect(async () => run(folderPath)).rejects.toBe(error); + + expect(rmSpy).toHaveBeenCalledTimes(1); + expect(sleeps).toEqual([]); + } + ); + + test('does not retry an error without a code', async () => { + const error: Error = new Error('unexpected failure'); + rmSpy.mockImplementation(() => { + throw error; + }); + + await expect(async () => run(folderPath)).rejects.toBe(error); + + expect(rmSpy).toHaveBeenCalledTimes(1); + expect(sleeps).toEqual([]); + }); + + test('stops retrying when a subsequent attempt fails with a non-retryable error', async () => { + const error: NodeJS.ErrnoException = createDeletionError('EACCES'); + rmSpy + .mockImplementationOnce(() => { + throw createDeletionError('EPERM'); + }) + .mockImplementationOnce(() => { + throw error; + }); + + await expect(async () => run(folderPath)).rejects.toBe(error); + + expect(rmSpy).toHaveBeenCalledTimes(2); + expect(sleeps).toEqual([100]); + }); + + test.each(['linux', 'darwin'])('does not retry on %s', async (platform) => { + Object.defineProperty(process, 'platform', { value: platform }); + const error: NodeJS.ErrnoException = createDeletionError('EPERM'); + rmSpy.mockImplementation(() => { + throw error; + }); + + await expect(async () => run(folderPath)).rejects.toBe(error); + + expect(rmSpy).toHaveBeenCalledTimes(1); + expect(sleeps).toEqual([]); + }); + + if (emptiesFolder) { + test('re-reads child names after a partially completed attempt', async () => { + readSpy + .mockImplementationOnce(() => + isAsync ? Promise.resolve(['first', 'second']) : ['first', 'second'] + ) + .mockImplementation(() => (isAsync ? Promise.resolve(['second']) : ['second'])); + let attempt: number = 0; + rmSpy.mockImplementation(() => { + if (++attempt === 2) { + throw createDeletionError('ENOTEMPTY'); + } + + return isAsync ? Promise.resolve() : undefined; + }); + + await run(folderPath); + + expect(rmSpy.mock.calls.map(([childPath]) => childPath)).toEqual( + ['first', 'second', 'second'].map((name) => path.join(folderPath, name)) + ); + expect(isAsync ? fsx.readdir : fsx.readdirSync).toHaveBeenCalledTimes(2); + expect(sleeps).toEqual([100]); + }); + + test('retries folder enumeration as part of the whole operation', async () => { + const error: NodeJS.ErrnoException = createDeletionError('EBUSY'); + if (isAsync) { + jest.spyOn(fsx, 'readdir').mockRejectedValueOnce(error); + } else { + jest.spyOn(fsx, 'readdirSync').mockImplementationOnce(() => { + throw error; + }); + } + + await run(folderPath); + + expect(isAsync ? fsx.readdir : fsx.readdirSync).toHaveBeenCalledTimes(2); + expect(rmSpy).toHaveBeenCalledTimes(1); + expect(sleeps).toEqual([100]); + }); + } + }); + + describe('ensureEmptyFolderAsync in-flight deletions', () => { + const platformDescriptor: PropertyDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!; + + beforeEach(() => { + Object.defineProperty(process, 'platform', { value: 'win32' }); + }); + + afterEach(() => { + jest.restoreAllMocks(); + Object.defineProperty(process, 'platform', platformDescriptor); + }); + + test.each([ + { name: 'before retrying', earlierFailures: 0, firstCode: 'EBUSY', secondCode: undefined }, + { + name: 'before rejecting after exhausting retries', + earlierFailures: 3, + firstCode: 'EPERM', + secondCode: undefined + }, + { + name: 'preferring a later non-retryable error', + earlierFailures: 0, + firstCode: 'EPERM', + secondCode: 'EACCES' + }, + { + name: 'preserving an earlier non-retryable error', + earlierFailures: 0, + firstCode: 'EACCES', + secondCode: 'EPERM' + }, + { + name: 'preserving the first retryable error', + earlierFailures: 3, + firstCode: 'EBUSY', + secondCode: 'EPERM' + } + ])( + 'settles started deletes and stops starting new ones $name', + async ({ earlierFailures, firstCode, secondCode }) => { + const firstError: NodeJS.ErrnoException = createDeletionError(firstCode); + const secondError: NodeJS.ErrnoException | undefined = secondCode + ? createDeletionError(secondCode) + : undefined; + const expectedError: NodeJS.ErrnoException = secondCode === 'EACCES' ? secondError! : firstError; + const shouldRetry: boolean = earlierFailures === 0 && firstCode !== 'EACCES' && !secondError; + const [started, signalStarted] = Async.getSignal(); + const [firstDelete, , rejectFirst] = Async.getSignal(); + const [otherDeletes, resolveOthers, rejectOthers] = Async.getSignal(); + const sleeps: number[] = []; + jest.spyOn(Async, 'sleepAsync').mockImplementation(async (delay) => { + sleeps.push(delay); + }); + let reads: number = 0; + const readSpy: jest.SpyInstance = jest.spyOn(fsx, 'readdir').mockImplementation(async () => { + if (++reads <= earlierFailures) { + throw createDeletionError('EBUSY'); + } + + return reads === earlierFailures + 1 ? Array.from({ length: 20 }, (value, i) => `child-${i}`) : []; + }); + let startedDeletes: number = 0; + const rmSpy: jest.SpyInstance = jest.spyOn(fsPromises, 'rm').mockImplementation(() => { + if (++startedDeletes === 10) { + signalStarted(); + } + + return startedDeletes === 1 ? firstDelete : otherDeletes; + }); + let settled: boolean = false; + const operation: Promise = FileSystem.ensureEmptyFolderAsync('mock-folder').then( + () => { + settled = true; + }, + (error) => { + settled = true; + throw error; + } + ); + const result: Promise = shouldRetry + ? expect(operation).resolves.toBeUndefined() + : expect(operation).rejects.toBe(expectedError); + + await started; + rejectFirst(firstError); + await new Promise((resolve) => setImmediate(resolve)); + + expect(rmSpy).toHaveBeenCalledTimes(10); + expect(readSpy).toHaveBeenCalledTimes(earlierFailures + 1); + expect(sleeps).toEqual(earlierFailures ? [100, 200, 300] : []); + expect(settled).toBe(false); + + if (secondError) { + rejectOthers(secondError); + } else { + resolveOthers(); + } + + await result; + + expect(settled).toBe(true); + expect(rmSpy).toHaveBeenCalledTimes(10); + expect(readSpy).toHaveBeenCalledTimes(earlierFailures + (shouldRetry ? 2 : 1)); + expect(sleeps).toEqual(shouldRetry ? [100] : earlierFailures ? [100, 200, 300] : []); + } + ); }); describe(FileSystem.createWriteStreamAsync.name, () => {