From f00009b2b135f2b11a7d553b61d03fb9f6a91b6a Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 26 Nov 2026 15:39:19 -0800 Subject: [PATCH 1/5] [node-core-library] Specify folder deletion retry behavior Record the spec approved independently by Claude Opus 5.5 and GPT-5.3 Codex, including the user's changelog and error-priority decisions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...-26-file-system-folder-deletion-retries.md | 217 ++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 specs/2026-11-26-file-system-folder-deletion-retries.md diff --git a/specs/2026-11-26-file-system-folder-deletion-retries.md b/specs/2026-11-26-file-system-folder-deletion-retries.md new file mode 100644 index 00000000000..e720ad2b198 --- /dev/null +++ b/specs/2026-11-26-file-system-folder-deletion-retries.md @@ -0,0 +1,217 @@ +# FileSystem folder-deletion retry specification + +## Problem and scope + +Implement the feedback in +[microsoft/rushstack#6230](https://github.com/microsoft/rushstack/issues/6230) +on [microsoft/rushstack#5836](https://github.com/microsoft/rushstack/pull/5836). +This specification supersedes the implementation proposed in +[microsoft/rushstack#6231](https://github.com/microsoft/rushstack/pull/6231). + +Windows users of Rush, Heft, and other `FileSystem` consumers can encounter +transient deletion failures while another process holds a file handle. Native +Node.js retries do not provide a consistent, whole-operation budget across +Node.js versions and synchronous/asynchronous implementations. + +The affected methods in +[`FileSystem.ts`](../libraries/node-core-library/src/FileSystem.ts) are: + +- `FileSystem.deleteFolder` +- `FileSystem.deleteFolderAsync` +- `FileSystem.ensureEmptyFolder` +- `FileSystem.ensureEmptyFolderAsync` + +Additionally, the current emptying implementation uses `Dirent.parentPath`, +which is unavailable on Node.js 20.9-20.11, and calls another static method +through `this`, which breaks unbound calls. Its asynchronous parallel loop +can reject before other started child deletions settle. + +No public signatures, dependencies, package engine requirements, or other +filesystem methods will change. `move`, `moveAsync`, resource-exhaustion +recovery, custom recursive traversal, and new caller-configurable options are +out of scope. + +## Required retry behavior + +1. A public invocation has one initial attempt and at most three retries. + Successful attempts return immediately, without waiting. +2. Retry only when `process.platform === 'win32'` and the error's `code` is + exactly `EBUSY`, `ENOTEMPTY`, or `EPERM`. Code classification does not require + additional `errno`, `syscall`, or `path` properties. +3. Wait 100 ms before attempt 2, 200 ms before attempt 3, and 300 ms before + attempt 4. Do not wait after attempt 4 fails. +4. Other errors, including `EACCES`, `EMFILE`, `ENFILE`, missing codes, and + unrecognized/empty codes, end the operation without further retries. + On non-Windows platforms, any failure ends the operation immediately. +5. Retry the whole deletion or emptying operation, not individual children. + All children and all stages of one emptying invocation share the budget. +6. Every underlying removal uses `fs.rmSync` or `fs.promises.rm` with + `{ recursive: true, force: true, maxRetries: 0, retryDelay: 0 }`. + Explicitly disabling both native retry settings avoids additional native + retries and native waits after the last failure. +7. Preserve the selected error object. Apply the existing `_wrapException` + or `_wrapExceptionAsync` decoration once, outside the retry loop, only when + the public invocation ultimately fails. + +The delays describe the wait schedule, not a maximum total duration. Timers +can run late, and retries repeat filesystem work. Separate locked children +can consume the shared budget on different attempts; this is an accepted +tradeoff to avoid depth-dependent budgets and a new recursive-delete engine. + +## Folder-emptying behavior + +Each attempt reads child names using `fsx.readdirSync` or `fsx.readdir`, +joins each name with the caller's `folderPath`, and removes the children +without deleting the parent. Do not use `Dirent.parentPath` or rely on a +bound `this`. Re-read the directory after a partial failure so already-removed +children are not scheduled again. + +If enumeration fails with `ENOENT`, create the folder using the existing +`fs-extra` directory-creation operation. Propagate every other enumeration +error, including `ENOTDIR`; do not remove or replace a file occupying the +requested path. Errors during creation are part of the same attempt and +follow the same retry policy. + +Keep existing successful behavior for missing, empty, and non-empty folders, +relative paths, nested contents, and child entries removed concurrently by +another process (`force: true`). Retrying does not make these operations +transactional or guarantee the folder remains empty if another process adds +children after enumeration. + +### Asynchronous draining and error selection + +Retain the limit of 10 concurrent top-level child-removal calls: + +1. Before starting a child-removal call, check whether a failure has already + been observed in this attempt. If so, skip starting that call. +2. Catch and record each started child's failure locally, allowing its + callback to fulfill so `Async.forEachAsync` waits for all started callbacks. + A separate failure flag must distinguish "no failure" from the value thrown. +3. Preserve the first observed error unless a later error has a non-transient + code and the preserved error has a transient code. Here, "transient" means + exactly `EBUSY`, `ENOTEMPTY`, or `EPERM`, irrespective of platform. Prefer + the first non-transient error on every platform; the decision to retry + remains Windows-only. Missing and unknown codes count as non-transient. +4. After all started calls settle, throw the selected error, if any. Only then + may the outer helper decide to retry or reject. + +This prevents retries from overlapping top-level removals from the preceding +attempt and prevents the public method from rejecting while those removal +promises are still pending. The limit and draining guarantee apply to calls +owned by node-core-library, not recursive work inside Node.js. Node's own +recursive implementation may reject while its internal work remains in +flight; redesigning that implementation is out of scope. + +## Implementation constraints + +- Use small, private synchronous and asynchronous retry helpers in the + existing `FileSystem.ts`, sharing the error/budget predicate. +- Synchronous waits use `Atomics.wait` on an `Int32Array` backed by a + `SharedArrayBuffer`. Asynchronous waits use `Async.sleepAsync`. +- Keep the sleep calls mockable without exporting test-only APIs; spies on + `Atomics.wait` and `Async.sleepAsync` are sufficient if verified by tests. +- Keep the retry predicate platform check dynamic so deterministic tests + can substitute the platform. Include the issue's explanatory comment about + Windows open-handle semantics and extending the policy only if needed. +- Replace the existing `FS_RM_DEFAULT_OPTIONS` comment with an explanation + that native retries and waits are deliberately disabled. +- Reuse `Async.forEachAsync` without changing its semantics for other callers. + Do not use `Async.runWithRetriesAsync`, which retries arbitrary errors with + a constant delay. + +## Documentation and release notes + +All four methods' TSDoc will include: + +> 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. + +"Reported as" is intentional: native synchronous error-code reporting varies +by Node.js version, and unknown codes must not be inferred or retried. +Document the folder read-error behavior and clarify that asynchronous +draining and concurrency apply to top-level calls. + +The release notes must address the +[changelog review comment](https://github.com/microsoft/rushstack/pull/6231#discussion_r4714037958): +state the benefit and impacted callers concisely, not the implementation. +Use Markdown code quotes for code references. + +The user approved consolidating the still-unreleased change file from +microsoft/rushstack#5836: +[`bartvandenende-wm-5373_2026-06-16-19-03.json`](https://github.com/microsoft/rushstack/blob/020c60a7bee6e6a673eab453c2b324bf9810b7ea/common/changes/%40rushstack/node-core-library/bartvandenende-wm-5373_2026-06-16-19-03.json). +Delete that pending file and add a new patch change file with two short entries: + +1. The Windows reliability benefit for callers of all four deletion methods + when another process temporarily holds a file open. +2. The user-visible emptying behavior changes relative to the last published + package: at most 10 concurrent top-level deletions in + `FileSystem.ensureEmptyFolderAsync`, and propagation of folder read errors + other than `ENOENT` by both emptying methods instead of silently leaving + an unreadable folder unemptied. + +Do not retain the earlier file's contradictory claim that native retries +implement the fix, or duplicate the same feature across change files. A newly +added file is required for `rush change --verify`, which detects added change +files rather than edits to existing pending files. + +The Node.js 20.9-20.11 and unbound-call regressions were introduced only on +unreleased `main`. Explain these fixes in the spec and PR description, not as +regressions affecting a published package in the release notes. + +The replacement PR description will correct the earlier PR's history: +`fs-extra` 7 used vendored rimraf, not a `rimraf@2` dependency. Its three-retry +policy applied to asynchronous removal on all platforms with per-recursion +budgets. Synchronous removal used a Windows-only final-`rmdir` spin of up to +500 ms and could silently leave a folder behind when that spin expired. + +## Verification and acceptance criteria + +Extend the existing `FileSystem.test.ts` tests, retaining their existing +behavioral coverage while updating mocks to the new enumeration primitive. + +Use mocked failures and mockable waits, not OS file locking, for deterministic +retry tests. Restore platform descriptors and mocks after every test. +Asynchronous cases must exercise actual promise rejection and pending +promises, not only synchronously thrown mocks. + +Required cases: + +- Each public method retries a recognized Windows failure and succeeds, + passing both disabled native retry settings to each removal. +- Both helper paths exhaust four failed attempts with exactly + `[100, 200, 300]` waits, propagate the final attempt's selected error by + identity, and decorate only that selected error. +- Non-retryable/missing/unknown codes, a retryable failure followed by a + non-retryable failure, and non-Windows failures cause no further retries. +- Emptying re-enumerates after partial deletion and handles enumeration and + directory-creation failures using the same budget. +- Real filesystem cases cover existing/missing/empty folders, relative and + unbound calls, nested contents, and preserving an existing file on failure. +- Async emptying never exceeds 10 started, pending top-level calls; stops + starting new removals after observing a failure; and drains pending calls + before both retries and final rejection. +- Mixed failures choose the first non-retryable error regardless of whether + it occurs before or after a retryable failure, including on non-Windows + platforms using code-only classification. All-transient failures preserve + the first observed error within the final attempt. +- Async tests complete without unhandled rejections or leaked work. + +Run the smallest combined Heft selection covering `FileSystem.test` and +`Async.test`, including compilation, linting, and API extraction. Verify +formatting and Rush change-file coverage. Use existing upstream CI for its +supported Linux/Windows Node.js matrix; investigate failures and distinguish +introduced failures from unrelated baseline failures. + +## Review gates + +1. Claude Opus 5.5 and GPT-5.3 Codex independently review this specification. + Incorporate actionable feedback; present conflicting requirements or + material design/scope decisions to the user. Obtain explicit approval + from both reviewers on the same spec revision before implementation. +2. Open a replacement PR against `microsoft/rushstack` and close microsoft/rushstack#6231 with + a link to its replacement, preserving the original commits. +3. Have both models independently review the complete replacement PR branch + against this specification. Address findings and repeat review until both + explicitly approve the same final commit. Ask the user to resolve genuine + judgement calls rather than silently choosing between conflicting reviews. From 93d1bc2fa3de06ff684188b3a4a520901d9b7a1a Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 26 Nov 2026 15:39:55 -0800 Subject: [PATCH 2/5] [node-core-library] Implement reviewed Windows deletion retries Apply the independently approved spec: own the retry budget, preserve compatible folder enumeration, drain started async removals, and consolidate unreleased user-facing change notes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...rtvandenende-wm-5373_2026-06-16-19-03.json | 10 - ...der-deletion-retries_2026-11-26-23-15.json | 15 + libraries/node-core-library/src/FileSystem.ts | 170 +++++-- .../src/test/FileSystem.test.ts | 426 +++++++++++++++++- 4 files changed, 564 insertions(+), 57 deletions(-) delete mode 100644 common/changes/@rushstack/node-core-library/bartvandenende-wm-5373_2026-06-16-19-03.json create mode 100644 common/changes/@rushstack/node-core-library/windows-folder-deletion-retries_2026-11-26-23-15.json diff --git a/common/changes/@rushstack/node-core-library/bartvandenende-wm-5373_2026-06-16-19-03.json b/common/changes/@rushstack/node-core-library/bartvandenende-wm-5373_2026-06-16-19-03.json deleted file mode 100644 index 839e9826eac..00000000000 --- a/common/changes/@rushstack/node-core-library/bartvandenende-wm-5373_2026-06-16-19-03.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "changes": [ - { - "packageName": "@rushstack/node-core-library", - "comment": "Make `FileSystem.deleteFolder`, `FileSystem.deleteFolderAsync`, `FileSystem.ensureEmptyFolder`, and `FileSystem.ensureEmptyFolderAsync` resilient to transient Windows `EPERM`/`EBUSY`/`ENOTEMPTY` errors by using native `fs.rm` with retries.", - "type": "patch" - } - ], - "packageName": "@rushstack/node-core-library" -} \ No newline at end of file diff --git a/common/changes/@rushstack/node-core-library/windows-folder-deletion-retries_2026-11-26-23-15.json b/common/changes/@rushstack/node-core-library/windows-folder-deletion-retries_2026-11-26-23-15.json new file mode 100644 index 00000000000..2a0f6cf3a6d --- /dev/null +++ b/common/changes/@rushstack/node-core-library/windows-folder-deletion-retries_2026-11-26-23-15.json @@ -0,0 +1,15 @@ +{ + "changes": [ + { + "packageName": "@rushstack/node-core-library", + "comment": "Fix intermittent folder-deletion failures for Windows users of `FileSystem.deleteFolder`, `FileSystem.deleteFolderAsync`, `FileSystem.ensureEmptyFolder`, and `FileSystem.ensureEmptyFolderAsync` when another process briefly holds a file open.", + "type": "patch" + }, + { + "packageName": "@rushstack/node-core-library", + "comment": "`FileSystem.ensureEmptyFolderAsync` now limits deletion to 10 concurrent top-level entries. Both folder-emptying methods now throw on read errors other than `ENOENT` instead of silently leaving an unreadable folder unemptied.", + "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..32bf2e48b9b 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 + // Disable native retries and waits so the whole operation shares one retry budget. + 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,91 @@ 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-removal calls to + * settle before retrying or rejecting. These guarantees do not cover Node.js's internal recursive work. + * 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) { + // Fulfilled callbacks let the parallel loop drain every started removal before we throw. + if ( + !hasError || + (_isTransientFolderDeletionError(deletionError) && !_isTransientFolderDeletionError(error)) + ) { + deletionError = error; + } + + hasError = true; + } + }, + { concurrency: 10 } + ); + + if (hasError) { + throw deletionError; + } + }); }); } @@ -1758,6 +1802,50 @@ async function _handleLinkAsync( } } +function _isTransientFolderDeletionError(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 && _isTransientFolderDeletionError(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..f1179e8b03f 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,34 @@ describe(FileSystem.name, () => { spy.mockRestore(); } }); + + test('supports an unbound call with a relative path', () => { + FileSystem.ensureFolder(`${tempDir}/sub`); + FileSystem.writeFile(`${tempDir}/sub/a.txt`, 'a'); + const { ensureEmptyFolder } = FileSystem; + + ensureEmptyFolder(path.relative(process.cwd(), tempDir)); + + expect(fs.existsSync(tempDir)).toBe(true); + expect(fs.readdirSync(tempDir)).toEqual([]); + }); + + test('keeps an already-empty folder', () => { + FileSystem.ensureFolder(tempDir); + + FileSystem.ensureEmptyFolder(tempDir); + + expect(fs.existsSync(tempDir)).toBe(true); + 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 +260,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 +272,381 @@ describe(FileSystem.name, () => { spy.mockRestore(); } }); + + test('supports an unbound call with a relative path', async () => { + await FileSystem.ensureFolderAsync(`${tempDir}/sub`); + await FileSystem.writeFileAsync(`${tempDir}/sub/a.txt`, 'a'); + const { ensureEmptyFolderAsync } = FileSystem; + + await ensureEmptyFolderAsync(path.relative(process.cwd(), tempDir)); + + expect(fs.existsSync(tempDir)).toBe(true); + expect(fs.readdirSync(tempDir)).toEqual([]); + }); + + test('keeps an already-empty folder', async () => { + await FileSystem.ensureFolderAsync(tempDir); + + await FileSystem.ensureEmptyFolderAsync(tempDir); + + expect(fs.existsSync(tempDir)).toBe(true); + 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[]; + + function failOperation(error: Error): Promise | void { + if (isAsync) { + return Promise.reject(error); + } + + throw error; + } + + 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('returns immediately on success', async () => { + await run(folderPath); + + expect(rmSpy).toHaveBeenCalledTimes(1); + expect(sleeps).toEqual([]); + }); + + test.each(['EBUSY', 'ENOTEMPTY', 'EPERM'])( + 'retries %s then succeeds with native retries disabled', + async (code) => { + rmSpy.mockImplementationOnce(() => failOperation(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('classifies transient errors without requiring errno or syscall properties', async () => { + rmSpy.mockImplementationOnce(() => failOperation(Object.assign(new Error('busy'), { code: 'EBUSY' }))); + + await run(folderPath); + + expect(rmSpy).toHaveBeenCalledTimes(2); + expect(sleeps).toEqual([100]); + }); + + test('waits exactly 100, 200 and 300 ms and decorates only the final selected error', async () => { + const errors: NodeJS.ErrnoException[] = ['EBUSY', 'ENOTEMPTY', 'EPERM', 'EPERM'].map( + createDeletionError + ); + let attempt: number = 0; + rmSpy.mockImplementation(() => failOperation(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.match(/File or folder could not be deleted:/g)).toHaveLength(1); + expect(errors.slice(0, 3).map(({ message }) => message)).toEqual([ + 'EBUSY: deletion failed', + 'ENOTEMPTY: deletion failed', + 'EPERM: deletion failed' + ]); + }); + + 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(() => failOperation(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(() => failOperation(error)); + + await expect(async () => run(folderPath)).rejects.toBe(error); + + expect(rmSpy).toHaveBeenCalledTimes(1); + expect(sleeps).toEqual([]); + }); + + test('stops when a subsequent attempt fails with a non-transient error', async () => { + const error: NodeJS.ErrnoException = createDeletionError('EACCES'); + rmSpy + .mockImplementationOnce(() => failOperation(createDeletionError('EPERM'))) + .mockImplementationOnce(() => failOperation(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(() => failOperation(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) { + return failOperation(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(readSpy).toHaveBeenCalledTimes(2); + expect(sleeps).toEqual([100]); + }); + + test('shares the retry budget between enumeration and child deletion', async () => { + readSpy.mockImplementationOnce(() => failOperation(createDeletionError('EBUSY'))); + rmSpy.mockImplementation(() => failOperation(createDeletionError('EPERM'))); + + await expect(async () => run(folderPath)).rejects.toThrow(/EPERM/); + + expect(readSpy).toHaveBeenCalledTimes(4); + expect(rmSpy).toHaveBeenCalledTimes(3); + expect(sleeps).toEqual([100, 200, 300]); + }); + + test('retries folder creation only within the same whole-operation budget', async () => { + readSpy.mockImplementation(() => failOperation(createDeletionError('ENOENT'))); + const ensureSpy: jest.SpyInstance = isAsync + ? jest.spyOn(fsx, 'ensureDir') + : jest.spyOn(fsx, 'ensureDirSync'); + ensureSpy + .mockImplementationOnce(() => failOperation(createDeletionError('EPERM'))) + .mockImplementation(() => (isAsync ? Promise.resolve() : undefined)); + + await run(folderPath); + + expect(readSpy).toHaveBeenCalledTimes(2); + expect(ensureSpy).toHaveBeenCalledTimes(2); + expect(rmSpy).not.toHaveBeenCalled(); + expect(sleeps).toEqual([100]); + }); + + test('propagates non-transient folder creation errors', async () => { + readSpy.mockImplementation(() => failOperation(createDeletionError('ENOENT'))); + const ensureSpy: jest.SpyInstance = isAsync + ? jest.spyOn(fsx, 'ensureDir') + : jest.spyOn(fsx, 'ensureDirSync'); + const error: NodeJS.ErrnoException = createDeletionError('EACCES'); + ensureSpy.mockImplementation(() => failOperation(error)); + + await expect(async () => run(folderPath)).rejects.toBe(error); + + expect(readSpy).toHaveBeenCalledTimes(1); + expect(ensureSpy).toHaveBeenCalledTimes(1); + expect(rmSpy).not.toHaveBeenCalled(); + expect(sleeps).toEqual([]); + }); + } + }); + + describe('ensureEmptyFolderAsync in-flight deletions', () => { + const platformDescriptor: PropertyDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!; + + afterEach(() => { + jest.restoreAllMocks(); + Object.defineProperty(process, 'platform', platformDescriptor); + }); + + test.each([ + { + name: 'before retrying', + earlierFailures: 0, + firstCode: 'EBUSY', + secondCode: undefined, + platform: 'win32' + }, + { + name: 'before rejecting after exhausting retries', + earlierFailures: 3, + firstCode: 'EPERM', + secondCode: undefined, + platform: 'win32' + }, + { + name: 'preferring a later non-transient error', + earlierFailures: 0, + firstCode: 'EPERM', + secondCode: 'EACCES', + platform: 'win32' + }, + { + name: 'preserving an earlier non-transient error', + earlierFailures: 0, + firstCode: 'EACCES', + secondCode: 'EPERM', + platform: 'win32' + }, + { + name: 'preserving the first transient error', + earlierFailures: 3, + firstCode: 'EBUSY', + secondCode: 'EPERM', + platform: 'win32' + }, + { + name: 'preferring a non-transient error on Linux', + earlierFailures: 0, + firstCode: 'EPERM', + secondCode: 'EACCES', + platform: 'linux' + }, + { + name: 'preserving a non-transient error on macOS', + earlierFailures: 0, + firstCode: 'EACCES', + secondCode: 'EPERM', + platform: 'darwin' + } + ])( + 'settles started deletes and stops starting new ones $name', + async ({ earlierFailures, firstCode, secondCode, platform }) => { + Object.defineProperty(process, 'platform', { value: platform }); + 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 && platform === 'win32'; + 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, () => { From 2c082a058827282ad1e7475a2765bfde8a1a0087 Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 26 Nov 2026 15:47:31 -0800 Subject: [PATCH 3/5] fixup! [node-core-library] Implement reviewed Windows deletion retries Keep the upstream specification technical-only, removing session-specific review and PR-management text as requested. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...-26-file-system-folder-deletion-retries.md | 42 ++++--------------- 1 file changed, 8 insertions(+), 34 deletions(-) diff --git a/specs/2026-11-26-file-system-folder-deletion-retries.md b/specs/2026-11-26-file-system-folder-deletion-retries.md index e720ad2b198..256092dde05 100644 --- a/specs/2026-11-26-file-system-folder-deletion-retries.md +++ b/specs/2026-11-26-file-system-folder-deletion-retries.md @@ -5,9 +5,6 @@ Implement the feedback in [microsoft/rushstack#6230](https://github.com/microsoft/rushstack/issues/6230) on [microsoft/rushstack#5836](https://github.com/microsoft/rushstack/pull/5836). -This specification supersedes the implementation proposed in -[microsoft/rushstack#6231](https://github.com/microsoft/rushstack/pull/6231). - Windows users of Rush, Heft, and other `FileSystem` consumers can encounter transient deletion failures while another process holds a file handle. Native Node.js retries do not provide a consistent, whole-operation budget across @@ -21,7 +18,7 @@ The affected methods in - `FileSystem.ensureEmptyFolder` - `FileSystem.ensureEmptyFolderAsync` -Additionally, the current emptying implementation uses `Dirent.parentPath`, +Additionally, the emptying implementation introduced by that PR uses `Dirent.parentPath`, which is unavailable on Node.js 20.9-20.11, and calls another static method through `this`, which breaks unbound calls. Its asynchronous parallel loop can reject before other started child deletions settle. @@ -132,15 +129,10 @@ by Node.js version, and unknown codes must not be inferred or retried. Document the folder read-error behavior and clarify that asynchronous draining and concurrency apply to top-level calls. -The release notes must address the -[changelog review comment](https://github.com/microsoft/rushstack/pull/6231#discussion_r4714037958): -state the benefit and impacted callers concisely, not the implementation. -Use Markdown code quotes for code references. - -The user approved consolidating the still-unreleased change file from -microsoft/rushstack#5836: -[`bartvandenende-wm-5373_2026-06-16-19-03.json`](https://github.com/microsoft/rushstack/blob/020c60a7bee6e6a673eab453c2b324bf9810b7ea/common/changes/%40rushstack/node-core-library/bartvandenende-wm-5373_2026-06-16-19-03.json). -Delete that pending file and add a new patch change file with two short entries: +Release notes state the benefit and impacted callers concisely, not the +implementation. Use Markdown code quotes for code references and describe +changes relative to the last published package, rather than intermediate +unreleased implementations. The two user-visible changes are: 1. The Windows reliability benefit for callers of all four deletion methods when another process temporarily holds a file open. @@ -150,16 +142,11 @@ Delete that pending file and add a new patch change file with two short entries: other than `ENOENT` by both emptying methods instead of silently leaving an unreadable folder unemptied. -Do not retain the earlier file's contradictory claim that native retries -implement the fix, or duplicate the same feature across change files. A newly -added file is required for `rush change --verify`, which detects added change -files rather than edits to existing pending files. +The Node.js 20.9-20.11 and unbound-call regressions were introduced only by the +unreleased implementation in microsoft/rushstack#5836, not a published package. -The Node.js 20.9-20.11 and unbound-call regressions were introduced only on -unreleased `main`. Explain these fixes in the spec and PR description, not as -regressions affecting a published package in the release notes. +### Historical context -The replacement PR description will correct the earlier PR's history: `fs-extra` 7 used vendored rimraf, not a `rimraf@2` dependency. Its three-retry policy applied to asynchronous removal on all platforms with per-recursion budgets. Synchronous removal used a Windows-only final-`rmdir` spin of up to @@ -202,16 +189,3 @@ Run the smallest combined Heft selection covering `FileSystem.test` and formatting and Rush change-file coverage. Use existing upstream CI for its supported Linux/Windows Node.js matrix; investigate failures and distinguish introduced failures from unrelated baseline failures. - -## Review gates - -1. Claude Opus 5.5 and GPT-5.3 Codex independently review this specification. - Incorporate actionable feedback; present conflicting requirements or - material design/scope decisions to the user. Obtain explicit approval - from both reviewers on the same spec revision before implementation. -2. Open a replacement PR against `microsoft/rushstack` and close microsoft/rushstack#6231 with - a link to its replacement, preserving the original commits. -3. Have both models independently review the complete replacement PR branch - against this specification. Address findings and repeat review until both - explicitly approve the same final commit. Ask the user to resolve genuine - judgement calls rather than silently choosing between conflicting reviews. From 022d80e82a811647891eefbcb17c46dc57408d20 Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 26 Nov 2026 17:15:04 -0800 Subject: [PATCH 4/5] fixup! [node-core-library] Implement reviewed Windows deletion retries Remove the specification from the upstream PR as requested in review; preserve the requested design deliverable outside the repository. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...-26-file-system-folder-deletion-retries.md | 191 ------------------ 1 file changed, 191 deletions(-) delete mode 100644 specs/2026-11-26-file-system-folder-deletion-retries.md diff --git a/specs/2026-11-26-file-system-folder-deletion-retries.md b/specs/2026-11-26-file-system-folder-deletion-retries.md deleted file mode 100644 index 256092dde05..00000000000 --- a/specs/2026-11-26-file-system-folder-deletion-retries.md +++ /dev/null @@ -1,191 +0,0 @@ -# FileSystem folder-deletion retry specification - -## Problem and scope - -Implement the feedback in -[microsoft/rushstack#6230](https://github.com/microsoft/rushstack/issues/6230) -on [microsoft/rushstack#5836](https://github.com/microsoft/rushstack/pull/5836). -Windows users of Rush, Heft, and other `FileSystem` consumers can encounter -transient deletion failures while another process holds a file handle. Native -Node.js retries do not provide a consistent, whole-operation budget across -Node.js versions and synchronous/asynchronous implementations. - -The affected methods in -[`FileSystem.ts`](../libraries/node-core-library/src/FileSystem.ts) are: - -- `FileSystem.deleteFolder` -- `FileSystem.deleteFolderAsync` -- `FileSystem.ensureEmptyFolder` -- `FileSystem.ensureEmptyFolderAsync` - -Additionally, the emptying implementation introduced by that PR uses `Dirent.parentPath`, -which is unavailable on Node.js 20.9-20.11, and calls another static method -through `this`, which breaks unbound calls. Its asynchronous parallel loop -can reject before other started child deletions settle. - -No public signatures, dependencies, package engine requirements, or other -filesystem methods will change. `move`, `moveAsync`, resource-exhaustion -recovery, custom recursive traversal, and new caller-configurable options are -out of scope. - -## Required retry behavior - -1. A public invocation has one initial attempt and at most three retries. - Successful attempts return immediately, without waiting. -2. Retry only when `process.platform === 'win32'` and the error's `code` is - exactly `EBUSY`, `ENOTEMPTY`, or `EPERM`. Code classification does not require - additional `errno`, `syscall`, or `path` properties. -3. Wait 100 ms before attempt 2, 200 ms before attempt 3, and 300 ms before - attempt 4. Do not wait after attempt 4 fails. -4. Other errors, including `EACCES`, `EMFILE`, `ENFILE`, missing codes, and - unrecognized/empty codes, end the operation without further retries. - On non-Windows platforms, any failure ends the operation immediately. -5. Retry the whole deletion or emptying operation, not individual children. - All children and all stages of one emptying invocation share the budget. -6. Every underlying removal uses `fs.rmSync` or `fs.promises.rm` with - `{ recursive: true, force: true, maxRetries: 0, retryDelay: 0 }`. - Explicitly disabling both native retry settings avoids additional native - retries and native waits after the last failure. -7. Preserve the selected error object. Apply the existing `_wrapException` - or `_wrapExceptionAsync` decoration once, outside the retry loop, only when - the public invocation ultimately fails. - -The delays describe the wait schedule, not a maximum total duration. Timers -can run late, and retries repeat filesystem work. Separate locked children -can consume the shared budget on different attempts; this is an accepted -tradeoff to avoid depth-dependent budgets and a new recursive-delete engine. - -## Folder-emptying behavior - -Each attempt reads child names using `fsx.readdirSync` or `fsx.readdir`, -joins each name with the caller's `folderPath`, and removes the children -without deleting the parent. Do not use `Dirent.parentPath` or rely on a -bound `this`. Re-read the directory after a partial failure so already-removed -children are not scheduled again. - -If enumeration fails with `ENOENT`, create the folder using the existing -`fs-extra` directory-creation operation. Propagate every other enumeration -error, including `ENOTDIR`; do not remove or replace a file occupying the -requested path. Errors during creation are part of the same attempt and -follow the same retry policy. - -Keep existing successful behavior for missing, empty, and non-empty folders, -relative paths, nested contents, and child entries removed concurrently by -another process (`force: true`). Retrying does not make these operations -transactional or guarantee the folder remains empty if another process adds -children after enumeration. - -### Asynchronous draining and error selection - -Retain the limit of 10 concurrent top-level child-removal calls: - -1. Before starting a child-removal call, check whether a failure has already - been observed in this attempt. If so, skip starting that call. -2. Catch and record each started child's failure locally, allowing its - callback to fulfill so `Async.forEachAsync` waits for all started callbacks. - A separate failure flag must distinguish "no failure" from the value thrown. -3. Preserve the first observed error unless a later error has a non-transient - code and the preserved error has a transient code. Here, "transient" means - exactly `EBUSY`, `ENOTEMPTY`, or `EPERM`, irrespective of platform. Prefer - the first non-transient error on every platform; the decision to retry - remains Windows-only. Missing and unknown codes count as non-transient. -4. After all started calls settle, throw the selected error, if any. Only then - may the outer helper decide to retry or reject. - -This prevents retries from overlapping top-level removals from the preceding -attempt and prevents the public method from rejecting while those removal -promises are still pending. The limit and draining guarantee apply to calls -owned by node-core-library, not recursive work inside Node.js. Node's own -recursive implementation may reject while its internal work remains in -flight; redesigning that implementation is out of scope. - -## Implementation constraints - -- Use small, private synchronous and asynchronous retry helpers in the - existing `FileSystem.ts`, sharing the error/budget predicate. -- Synchronous waits use `Atomics.wait` on an `Int32Array` backed by a - `SharedArrayBuffer`. Asynchronous waits use `Async.sleepAsync`. -- Keep the sleep calls mockable without exporting test-only APIs; spies on - `Atomics.wait` and `Async.sleepAsync` are sufficient if verified by tests. -- Keep the retry predicate platform check dynamic so deterministic tests - can substitute the platform. Include the issue's explanatory comment about - Windows open-handle semantics and extending the policy only if needed. -- Replace the existing `FS_RM_DEFAULT_OPTIONS` comment with an explanation - that native retries and waits are deliberately disabled. -- Reuse `Async.forEachAsync` without changing its semantics for other callers. - Do not use `Async.runWithRetriesAsync`, which retries arbitrary errors with - a constant delay. - -## Documentation and release notes - -All four methods' TSDoc will include: - -> 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. - -"Reported as" is intentional: native synchronous error-code reporting varies -by Node.js version, and unknown codes must not be inferred or retried. -Document the folder read-error behavior and clarify that asynchronous -draining and concurrency apply to top-level calls. - -Release notes state the benefit and impacted callers concisely, not the -implementation. Use Markdown code quotes for code references and describe -changes relative to the last published package, rather than intermediate -unreleased implementations. The two user-visible changes are: - -1. The Windows reliability benefit for callers of all four deletion methods - when another process temporarily holds a file open. -2. The user-visible emptying behavior changes relative to the last published - package: at most 10 concurrent top-level deletions in - `FileSystem.ensureEmptyFolderAsync`, and propagation of folder read errors - other than `ENOENT` by both emptying methods instead of silently leaving - an unreadable folder unemptied. - -The Node.js 20.9-20.11 and unbound-call regressions were introduced only by the -unreleased implementation in microsoft/rushstack#5836, not a published package. - -### Historical context - -`fs-extra` 7 used vendored rimraf, not a `rimraf@2` dependency. Its three-retry -policy applied to asynchronous removal on all platforms with per-recursion -budgets. Synchronous removal used a Windows-only final-`rmdir` spin of up to -500 ms and could silently leave a folder behind when that spin expired. - -## Verification and acceptance criteria - -Extend the existing `FileSystem.test.ts` tests, retaining their existing -behavioral coverage while updating mocks to the new enumeration primitive. - -Use mocked failures and mockable waits, not OS file locking, for deterministic -retry tests. Restore platform descriptors and mocks after every test. -Asynchronous cases must exercise actual promise rejection and pending -promises, not only synchronously thrown mocks. - -Required cases: - -- Each public method retries a recognized Windows failure and succeeds, - passing both disabled native retry settings to each removal. -- Both helper paths exhaust four failed attempts with exactly - `[100, 200, 300]` waits, propagate the final attempt's selected error by - identity, and decorate only that selected error. -- Non-retryable/missing/unknown codes, a retryable failure followed by a - non-retryable failure, and non-Windows failures cause no further retries. -- Emptying re-enumerates after partial deletion and handles enumeration and - directory-creation failures using the same budget. -- Real filesystem cases cover existing/missing/empty folders, relative and - unbound calls, nested contents, and preserving an existing file on failure. -- Async emptying never exceeds 10 started, pending top-level calls; stops - starting new removals after observing a failure; and drains pending calls - before both retries and final rejection. -- Mixed failures choose the first non-retryable error regardless of whether - it occurs before or after a retryable failure, including on non-Windows - platforms using code-only classification. All-transient failures preserve - the first observed error within the final attempt. -- Async tests complete without unhandled rejections or leaked work. - -Run the smallest combined Heft selection covering `FileSystem.test` and -`Async.test`, including compilation, linting, and API extraction. Verify -formatting and Rush change-file coverage. Use existing upstream CI for its -supported Linux/Windows Node.js matrix; investigate failures and distinguish -introduced failures from unrelated baseline failures. From 910795ce03f9aa26a06eee09e56adc42b5aa3244 Mon Sep 17 00:00:00 2001 From: Ian Clanton-Thuon Date: Thu, 26 Nov 2026 17:30:37 -0800 Subject: [PATCH 5/5] fixup! [node-core-library] Implement reviewed Windows deletion retries fixup! [node-core-library] Implement reviewed Windows deletion retries Trim redundant folder deletion retry tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/test/FileSystem.test.ts | 273 +++--------------- 1 file changed, 35 insertions(+), 238 deletions(-) diff --git a/libraries/node-core-library/src/test/FileSystem.test.ts b/libraries/node-core-library/src/test/FileSystem.test.ts index f1179e8b03f..7ad94575a47 100644 --- a/libraries/node-core-library/src/test/FileSystem.test.ts +++ b/libraries/node-core-library/src/test/FileSystem.test.ts @@ -215,15 +215,6 @@ describe(FileSystem.name, () => { expect(fs.readdirSync(tempDir)).toEqual([]); }); - test('keeps an already-empty folder', () => { - FileSystem.ensureFolder(tempDir); - - FileSystem.ensureEmptyFolder(tempDir); - - expect(fs.existsSync(tempDir)).toBe(true); - expect(fs.readdirSync(tempDir)).toEqual([]); - }); - test('does not delete or replace an existing file', () => { FileSystem.ensureFolder(testTempFolder); FileSystem.writeFile(tempDir, 'keep'); @@ -284,15 +275,6 @@ describe(FileSystem.name, () => { expect(fs.readdirSync(tempDir)).toEqual([]); }); - test('keeps an already-empty folder', async () => { - await FileSystem.ensureFolderAsync(tempDir); - - await FileSystem.ensureEmptyFolderAsync(tempDir); - - expect(fs.existsSync(tempDir)).toBe(true); - expect(fs.readdirSync(tempDir)).toEqual([]); - }); - test('does not delete or replace an existing file', async () => { await FileSystem.ensureFolderAsync(testTempFolder); await FileSystem.writeFileAsync(tempDir, 'keep'); @@ -348,33 +330,8 @@ describe(FileSystem.name, () => { Object.defineProperty(process, 'platform', platformDescriptor); }); - test('returns immediately on success', async () => { - await run(folderPath); - - expect(rmSpy).toHaveBeenCalledTimes(1); - expect(sleeps).toEqual([]); - }); - - test.each(['EBUSY', 'ENOTEMPTY', 'EPERM'])( - 'retries %s then succeeds with native retries disabled', - async (code) => { - rmSpy.mockImplementationOnce(() => failOperation(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('classifies transient errors without requiring errno or syscall properties', async () => { - rmSpy.mockImplementationOnce(() => failOperation(Object.assign(new Error('busy'), { code: 'EBUSY' }))); + test('retries a transient error then succeeds', async () => { + rmSpy.mockImplementationOnce(() => failOperation(createDeletionError('EBUSY'))); await run(folderPath); @@ -382,7 +339,7 @@ describe(FileSystem.name, () => { expect(sleeps).toEqual([100]); }); - test('waits exactly 100, 200 and 300 ms and decorates only the final selected error', async () => { + test('throws the last error after exhausting retries', async () => { const errors: NodeJS.ErrnoException[] = ['EBUSY', 'ENOTEMPTY', 'EPERM', 'EPERM'].map( createDeletionError ); @@ -393,29 +350,10 @@ describe(FileSystem.name, () => { expect(rmSpy).toHaveBeenCalledTimes(4); expect(sleeps).toEqual([100, 200, 300]); - expect(errors[3].message.match(/File or folder could not be deleted:/g)).toHaveLength(1); - expect(errors.slice(0, 3).map(({ message }) => message)).toEqual([ - 'EBUSY: deletion failed', - 'ENOTEMPTY: deletion failed', - 'EPERM: deletion failed' - ]); }); - 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(() => failOperation(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'); + test('does not retry a non-transient error', async () => { + const error: NodeJS.ErrnoException = createDeletionError('EACCES'); rmSpy.mockImplementation(() => failOperation(error)); await expect(async () => run(folderPath)).rejects.toBe(error); @@ -424,20 +362,8 @@ describe(FileSystem.name, () => { expect(sleeps).toEqual([]); }); - test('stops when a subsequent attempt fails with a non-transient error', async () => { - const error: NodeJS.ErrnoException = createDeletionError('EACCES'); - rmSpy - .mockImplementationOnce(() => failOperation(createDeletionError('EPERM'))) - .mockImplementationOnce(() => failOperation(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 }); + test('does not retry on non-Windows platforms', async () => { + Object.defineProperty(process, 'platform', { value: 'linux' }); const error: NodeJS.ErrnoException = createDeletionError('EPERM'); rmSpy.mockImplementation(() => failOperation(error)); @@ -469,7 +395,6 @@ describe(FileSystem.name, () => { ['first', 'second', 'second'].map((name) => path.join(folderPath, name)) ); expect(readSpy).toHaveBeenCalledTimes(2); - expect(sleeps).toEqual([100]); }); test('shares the retry budget between enumeration and child deletion', async () => { @@ -480,173 +405,45 @@ describe(FileSystem.name, () => { expect(readSpy).toHaveBeenCalledTimes(4); expect(rmSpy).toHaveBeenCalledTimes(3); - expect(sleeps).toEqual([100, 200, 300]); - }); - - test('retries folder creation only within the same whole-operation budget', async () => { - readSpy.mockImplementation(() => failOperation(createDeletionError('ENOENT'))); - const ensureSpy: jest.SpyInstance = isAsync - ? jest.spyOn(fsx, 'ensureDir') - : jest.spyOn(fsx, 'ensureDirSync'); - ensureSpy - .mockImplementationOnce(() => failOperation(createDeletionError('EPERM'))) - .mockImplementation(() => (isAsync ? Promise.resolve() : undefined)); - - await run(folderPath); - - expect(readSpy).toHaveBeenCalledTimes(2); - expect(ensureSpy).toHaveBeenCalledTimes(2); - expect(rmSpy).not.toHaveBeenCalled(); - expect(sleeps).toEqual([100]); - }); - - test('propagates non-transient folder creation errors', async () => { - readSpy.mockImplementation(() => failOperation(createDeletionError('ENOENT'))); - const ensureSpy: jest.SpyInstance = isAsync - ? jest.spyOn(fsx, 'ensureDir') - : jest.spyOn(fsx, 'ensureDirSync'); - const error: NodeJS.ErrnoException = createDeletionError('EACCES'); - ensureSpy.mockImplementation(() => failOperation(error)); - - await expect(async () => run(folderPath)).rejects.toBe(error); - - expect(readSpy).toHaveBeenCalledTimes(1); - expect(ensureSpy).toHaveBeenCalledTimes(1); - expect(rmSpy).not.toHaveBeenCalled(); - expect(sleeps).toEqual([]); }); } }); - describe('ensureEmptyFolderAsync in-flight deletions', () => { - const platformDescriptor: PropertyDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!; + test('ensureEmptyFolderAsync settles started deletes and stops starting new ones after a failure', async () => { + const error: NodeJS.ErrnoException = createDeletionError('EACCES'); + const [started, signalStarted] = Async.getSignal(); + const [firstDelete, , rejectFirst] = Async.getSignal(); + const [otherDeletes, resolveOthers] = Async.getSignal(); + jest.spyOn(fsx, 'readdir').mockImplementation(async () => Array.from({ length: 20 }, (v, i) => `c${i}`)); + let startedDeletes: number = 0; + const rmSpy: jest.SpyInstance = jest.spyOn(fsPromises, 'rm').mockImplementation(() => { + if (++startedDeletes === 10) { + signalStarted(); + } - afterEach(() => { - jest.restoreAllMocks(); - Object.defineProperty(process, 'platform', platformDescriptor); + return startedDeletes === 1 ? firstDelete : otherDeletes; }); - test.each([ - { - name: 'before retrying', - earlierFailures: 0, - firstCode: 'EBUSY', - secondCode: undefined, - platform: 'win32' - }, - { - name: 'before rejecting after exhausting retries', - earlierFailures: 3, - firstCode: 'EPERM', - secondCode: undefined, - platform: 'win32' - }, - { - name: 'preferring a later non-transient error', - earlierFailures: 0, - firstCode: 'EPERM', - secondCode: 'EACCES', - platform: 'win32' - }, - { - name: 'preserving an earlier non-transient error', - earlierFailures: 0, - firstCode: 'EACCES', - secondCode: 'EPERM', - platform: 'win32' - }, - { - name: 'preserving the first transient error', - earlierFailures: 3, - firstCode: 'EBUSY', - secondCode: 'EPERM', - platform: 'win32' - }, - { - name: 'preferring a non-transient error on Linux', - earlierFailures: 0, - firstCode: 'EPERM', - secondCode: 'EACCES', - platform: 'linux' - }, - { - name: 'preserving a non-transient error on macOS', - earlierFailures: 0, - firstCode: 'EACCES', - secondCode: 'EPERM', - platform: 'darwin' - } - ])( - 'settles started deletes and stops starting new ones $name', - async ({ earlierFailures, firstCode, secondCode, platform }) => { - Object.defineProperty(process, 'platform', { value: platform }); - 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 && platform === 'win32'; - 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'); - } + try { + let settled: boolean = false; + const operation: Promise = FileSystem.ensureEmptyFolderAsync('mock-folder').finally(() => { + settled = true; + }); + const result: Promise = expect(operation).rejects.toBe(error); - 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(); - } + await started; + rejectFirst(error); + await new Promise((resolve) => setImmediate(resolve)); - 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(); - } + expect(settled).toBe(false); - await result; + 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] : []); - } - ); + expect(rmSpy).toHaveBeenCalledTimes(10); + } finally { + jest.restoreAllMocks(); + } }); describe(FileSystem.createWriteStreamAsync.name, () => {