From aa92c3ec1e09eae671a9766081bc258ab5be640e Mon Sep 17 00:00:00 2001 From: vnegriy Date: Wed, 18 Nov 2026 20:47:15 +0300 Subject: [PATCH 1/2] fix(install-state): stop concurrent Windows writers from starving on rename On Windows, concurrent writeInstallState calls (and real-time antivirus scans of each freshly published file) can hold replacement sharing locks for over a second. renameAtomic retried at a fixed 25 ms interval, which kept contenders in lockstep, so one writer could lose every round and give up with EPERM at the 2 s deadline. This made tests/lib/install-state.test.js fail in about half of isolated runs. - Retry with a uniform random wait of 1-25 ms instead of a fixed 25 ms. Exponential backoff was measured and made starvation worse. - Add a renameRetryBudgetMs option to writeFileAtomic. The default stays 2 s, so hook callers keep their latency bound, and the attempt cap is derived from the budget (81 for the default). - writeInstallState uses a 10 s budget, since it runs only during installs. Measured on Windows 11 with Defender on: install-state test 0/12 failures (previously 4/8). Co-Authored-By: Claude Opus 5.5 --- scripts/lib/atomic-write.js | 27 ++++++++++++++++++++++----- scripts/lib/install-state.js | 4 +++- tests/lib/atomic-write.test.js | 32 ++++++++++++++++++++++++++++++-- 3 files changed, 55 insertions(+), 8 deletions(-) diff --git a/scripts/lib/atomic-write.js b/scripts/lib/atomic-write.js index 5aa285eab..f423a1662 100644 --- a/scripts/lib/atomic-write.js +++ b/scripts/lib/atomic-write.js @@ -25,10 +25,27 @@ function readFileWithSharingRetry(filePath, options) { } } +// Concurrent Windows writers (and real-time antivirus scans of each freshly +// published file) can hold replacement sharing locks for well over a second. +// Fixed-interval retries keep contenders in lockstep, so one writer can lose +// every round until it gives up. Short, fully jittered waits break that +// lockstep; longer (exponential) waits measurably starve the loser further. +const DEFAULT_RENAME_RETRY_BUDGET_MS = 2000; +const RENAME_RETRY_MIN_WAIT_MS = 1; +const RENAME_RETRY_MAX_WAIT_MS = 25; + +function renameRetryWaitMs(remaining) { + const jittered = RENAME_RETRY_MIN_WAIT_MS + + Math.random() * (RENAME_RETRY_MAX_WAIT_MS - RENAME_RETRY_MIN_WAIT_MS); + return Math.min(remaining, jittered); +} + function renameAtomic(tempPath, resolvedPath, options) { - // Concurrent Windows installers can hold replacement sharing locks beyond - // the reader's shorter retry budget. Keep publication bounded to two seconds. - const deadline = performance.now() + 2000; + // Keep publication bounded by an elapsed budget (callers that are not on a + // latency-sensitive hook path may raise it) and a hard attempt cap. + const budget = options.renameRetryBudgetMs || DEFAULT_RENAME_RETRY_BUDGET_MS; + const maxAttempts = Math.ceil(budget / 25) + 1; + const deadline = performance.now() + budget; let attempts = 0; let sleeper; while (true) { @@ -44,9 +61,9 @@ function renameAtomic(tempPath, resolvedPath, options) { const remaining = deadline - performance.now(); if (process.platform !== 'win32' || !['EPERM', 'EACCES', 'EBUSY'].includes(error.code) - || attempts >= 81 || remaining <= 0) throw error; + || attempts >= maxAttempts || remaining <= 0) throw error; sleeper ||= new Int32Array(new SharedArrayBuffer(4)); - Atomics.wait(sleeper, 0, 0, Math.min(25, remaining)); + Atomics.wait(sleeper, 0, 0, renameRetryWaitMs(remaining)); } } } diff --git a/scripts/lib/install-state.js b/scripts/lib/install-state.js index 8f46c87c8..daff9ee28 100644 --- a/scripts/lib/install-state.js +++ b/scripts/lib/install-state.js @@ -370,7 +370,9 @@ function readInstallState(filePath) { function writeInstallState(filePath, state) { assertValidInstallState(state, filePath); const { writeFileAtomic } = require('./atomic-write'); - writeFileAtomic(filePath, `${JSON.stringify(state, null, 2)}\n`); + // Installs are not on a latency-sensitive hook path; concurrent installers + // on Windows need room to outlast each other's replacement locks. + writeFileAtomic(filePath, `${JSON.stringify(state, null, 2)}\n`, { renameRetryBudgetMs: 10000 }); return state; } diff --git a/tests/lib/atomic-write.test.js b/tests/lib/atomic-write.test.js index cfe499ef0..c2084e616 100644 --- a/tests/lib/atomic-write.test.js +++ b/tests/lib/atomic-write.test.js @@ -14,6 +14,7 @@ const source = fs.readFileSync(filename, 'utf8'); function loadHelper(platform, rename, { clockStep = 25, read = fs.readFileSync } = {}) { let elapsed = 0; let waits = 0; + const timeouts = []; const filesystem = Object.create(fs); filesystem.renameSync = rename; filesystem.readFileSync = read; @@ -23,10 +24,10 @@ function loadHelper(platform, rename, { clockStep = 25, read = fs.readFileSync } require: name => name === 'fs' ? filesystem : require(name), process: { platform, pid: process.pid }, performance: { now: () => elapsed }, - Atomics: { wait: () => { elapsed += clockStep; waits++; } }, + Atomics: { wait: (_buffer, _index, _value, timeout) => { elapsed += clockStep; waits++; timeouts.push(timeout); } }, SharedArrayBuffer, Int32Array, }, { filename }); - return { ...module.exports, waits: () => waits }; + return { ...module.exports, waits: () => waits, timeouts: () => timeouts }; } let passed = 0; @@ -108,6 +109,33 @@ test('Windows retries also stop at the elapsed deadline', ({ root, destination } assert.deepStrictEqual(fs.readdirSync(root), ['state.json']); }); +test('Windows callers can raise the rename retry budget', ({ root, destination }) => { + let attempts = 0; + const expected = sharingError('EPERM'); + const helper = loadHelper('win32', () => { attempts++; throw expected; }, { clockStep: 250 }); + assert.throws(() => helper.writeFileAtomic(destination, 'new', { renameRetryBudgetMs: 10000 }), + error => error === expected); + assert.strictEqual(attempts, 41, 'A 10s budget allows forty 250ms waits'); + assert.deepStrictEqual(fs.readdirSync(root), ['state.json']); +}); + +test('Windows rename retries use short jittered waits so contenders fall out of lockstep', ({ destination }) => { + let attempts = 0; + const helper = loadHelper('win32', (temporary, target) => { + attempts++; + if (attempts <= 40) throw sharingError('EPERM'); + fs.renameSync(temporary, target); + }); + helper.writeFileAtomic(destination, 'new'); + const timeouts = helper.timeouts(); + assert.strictEqual(timeouts.length, 40); + for (const timeout of timeouts) { + assert.ok(timeout >= 1 && timeout <= 25, `wait ${timeout}ms stays within [1, 25]`); + } + assert.ok(new Set(timeouts).size > 1, 'Waits must vary between attempts'); + assert.strictEqual(fs.readFileSync(destination, 'utf8'), 'new'); +}); + for (const platform of ['linux', 'darwin']) { for (const code of ['EPERM', 'EACCES', 'EBUSY']) { test(`${platform} ${code} propagates immediately with original bytes intact`, ({ root, destination }) => { From 8b4723a6131436b3ac461b4b2137df2ed403068a Mon Sep 17 00:00:00 2001 From: vnegriy Date: Wed, 18 Nov 2026 21:28:58 +0300 Subject: [PATCH 2/2] fix(atomic-write): size the rename attempt cap for the shortest wait Review feedback (CodeRabbit, Greptile): the attempt cap still assumed 25 ms per wait, but the jittered waits average about 15 ms, so writers ran out of attempts at roughly 1 s on the default budget and about 5 s on the 10 s install-state budget. - Derive the safety cap from the minimum wait, so the elapsed budget is what actually stops retries. - Raise the minimum jittered wait from 1 ms to 5 ms. That keeps the safety cap meaningful (401 attempts per default write) while the 5-25 ms spread still breaks contender lockstep. - Add tests whose fake clock advances by the requested wait. They fail on the previous commit (retries stopped at 1073 ms and 5127 ms) and pass now. - Update the session-aliases bound that encoded the old cap. Co-Authored-By: Claude Opus 5.5 --- scripts/lib/atomic-write.js | 8 +++++--- tests/lib/atomic-write.test.js | 30 ++++++++++++++++++++++++++---- tests/lib/session-aliases.test.js | 3 ++- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/scripts/lib/atomic-write.js b/scripts/lib/atomic-write.js index f423a1662..3431b02da 100644 --- a/scripts/lib/atomic-write.js +++ b/scripts/lib/atomic-write.js @@ -31,7 +31,7 @@ function readFileWithSharingRetry(filePath, options) { // every round until it gives up. Short, fully jittered waits break that // lockstep; longer (exponential) waits measurably starve the loser further. const DEFAULT_RENAME_RETRY_BUDGET_MS = 2000; -const RENAME_RETRY_MIN_WAIT_MS = 1; +const RENAME_RETRY_MIN_WAIT_MS = 5; const RENAME_RETRY_MAX_WAIT_MS = 25; function renameRetryWaitMs(remaining) { @@ -42,9 +42,11 @@ function renameRetryWaitMs(remaining) { function renameAtomic(tempPath, resolvedPath, options) { // Keep publication bounded by an elapsed budget (callers that are not on a - // latency-sensitive hook path may raise it) and a hard attempt cap. + // latency-sensitive hook path may raise it). The attempt cap is only a + // safety net: size it for the shortest possible wait so it can never end + // retries before the elapsed budget does. const budget = options.renameRetryBudgetMs || DEFAULT_RENAME_RETRY_BUDGET_MS; - const maxAttempts = Math.ceil(budget / 25) + 1; + const maxAttempts = Math.ceil(budget / RENAME_RETRY_MIN_WAIT_MS) + 1; const deadline = performance.now() + budget; let attempts = 0; let sleeper; diff --git a/tests/lib/atomic-write.test.js b/tests/lib/atomic-write.test.js index c2084e616..e5a8f67ab 100644 --- a/tests/lib/atomic-write.test.js +++ b/tests/lib/atomic-write.test.js @@ -11,6 +11,8 @@ const source = fs.readFileSync(filename, 'utf8'); // Load the actual helper with a local platform/filesystem facade. File creation, // fsync, replacement and cleanup remain real; fault injection is module-local. +// clockStep 'requested' advances the fake clock by exactly the wait the helper +// asked for, which exposes attempt caps that undercut the elapsed budget. function loadHelper(platform, rename, { clockStep = 25, read = fs.readFileSync } = {}) { let elapsed = 0; let waits = 0; @@ -24,10 +26,14 @@ function loadHelper(platform, rename, { clockStep = 25, read = fs.readFileSync } require: name => name === 'fs' ? filesystem : require(name), process: { platform, pid: process.pid }, performance: { now: () => elapsed }, - Atomics: { wait: (_buffer, _index, _value, timeout) => { elapsed += clockStep; waits++; timeouts.push(timeout); } }, + Atomics: { wait: (_buffer, _index, _value, timeout) => { + elapsed += clockStep === 'requested' ? timeout : clockStep; + waits++; + timeouts.push(timeout); + } }, SharedArrayBuffer, Int32Array, }, { filename }); - return { ...module.exports, waits: () => waits, timeouts: () => timeouts }; + return { ...module.exports, waits: () => waits, timeouts: () => timeouts, elapsed: () => elapsed }; } let passed = 0; @@ -70,7 +76,7 @@ for (const code of ['EPERM', 'EACCES', 'EBUSY']) { throw expected; }); assert.throws(() => helper.writeFileAtomic(destination, 'new'), error => error === expected); - assert.strictEqual(attempts, 81, 'Hard attempt bound applies even before the deadline'); + assert.strictEqual(attempts, 81, 'Eighty 25ms waits exhaust the default 2s budget'); assert.strictEqual(helper.waits(), 80); assert.strictEqual(fs.readFileSync(destination, 'utf8'), 'old'); assert.deepStrictEqual(fs.readdirSync(root), ['state.json']); @@ -119,6 +125,22 @@ test('Windows callers can raise the rename retry budget', ({ root, destination } assert.deepStrictEqual(fs.readdirSync(root), ['state.json']); }); +for (const budget of [undefined, 10000]) { + const expectedBudget = budget || 2000; + test(`Windows short jittered waits keep retrying through the full ${expectedBudget}ms budget`, ({ root, destination }) => { + let attempts = 0; + const expected = sharingError('EPERM'); + const helper = loadHelper('win32', () => { attempts++; throw expected; }, { clockStep: 'requested' }); + assert.throws(() => helper.writeFileAtomic(destination, 'new', budget ? { renameRetryBudgetMs: budget } : {}), + error => error === expected); + assert.ok(Math.abs(helper.elapsed() - expectedBudget) < 1e-6, + `Retries stop at the elapsed budget, not an attempt cap (stopped at ${helper.elapsed()}ms)`); + assert.ok(attempts > Math.ceil(expectedBudget / 25) + 1, 'Waits shorter than 25ms allow more attempts'); + assert.strictEqual(fs.readFileSync(destination, 'utf8'), 'old'); + assert.deepStrictEqual(fs.readdirSync(root), ['state.json']); + }); +} + test('Windows rename retries use short jittered waits so contenders fall out of lockstep', ({ destination }) => { let attempts = 0; const helper = loadHelper('win32', (temporary, target) => { @@ -130,7 +152,7 @@ test('Windows rename retries use short jittered waits so contenders fall out of const timeouts = helper.timeouts(); assert.strictEqual(timeouts.length, 40); for (const timeout of timeouts) { - assert.ok(timeout >= 1 && timeout <= 25, `wait ${timeout}ms stays within [1, 25]`); + assert.ok(timeout >= 5 && timeout <= 25, `wait ${timeout}ms stays within [5, 25]`); } assert.ok(new Set(timeouts).size > 1, 'Waits must vary between attempts'); assert.strictEqual(fs.readFileSync(destination, 'utf8'), 'new'); diff --git a/tests/lib/session-aliases.test.js b/tests/lib/session-aliases.test.js index d1ade7036..4729e641c 100644 --- a/tests/lib/session-aliases.test.js +++ b/tests/lib/session-aliases.test.js @@ -1253,7 +1253,8 @@ function runTests() { assert.strictEqual(fs.readFileSync(aliasesPath, 'utf8'), before); const stagingPaths = [...new Set(staged)]; assert.strictEqual(stagingPaths.length, 2, 'Each write retains one private staging file across retries'); - const maxAttempts = process.platform === 'win32' ? 162 : 2; + // atomic-write caps each Windows write at budget / min wait + 1 = 2000 / 5 + 1 attempts. + const maxAttempts = process.platform === 'win32' ? 2 * 401 : 2; assert.ok(staged.length >= 2 && staged.length <= maxAttempts, 'Publication attempts remain bounded for both writes'); assert.deepStrictEqual(fs.readdirSync(path.dirname(aliasesPath)), ['session-aliases.json']); } finally {