The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
fix(state): retry Windows sharing reads without dropping published aliases
haelyra068d93251e32
diff --git a/scripts/lib/atomic-write.js b/scripts/lib/atomic-write.jsindex c85c7dad6..d3f2d14ac 100644--- a/scripts/lib/atomic-write.js+++ b/scripts/lib/atomic-write.js@@ -4,6 +4,27 @@ const crypto = require('crypto');const fs = require('fs');const path = require('path');+// Native Windows replacement can temporarily deny a reader's open as well as+// a writer's rename. Retry only sharing errors, never missing files or parsing.+function readFileWithSharingRetry(filePath, options) {+ const deadline = performance.now() + 750;+ let attempts = 0;+ let sleeper;+ while (true) {+ try {+ return fs.readFileSync(filePath, options);+ } catch (error) {+ attempts++;+ const remaining = deadline - performance.now();+ if (process.platform !== 'win32'+ || !['EPERM', 'EACCES', 'EBUSY'].includes(error.code)+ || attempts >= 21 || remaining <= 0) throw error;+ sleeper ||= new Int32Array(new SharedArrayBuffer(4));+ Atomics.wait(sleeper, 0, 0, Math.min(25, remaining));+ }+ }+}+function renameAtomic(tempPath, resolvedPath, options) {const deadline = performance.now() + 750;let attempts = 0;@@ -70,5 +91,6 @@ function writeFileAtomic(filePath, content, options = {}) {}module.exports = {+ readFileWithSharingRetry,writeFileAtomic,};diff --git a/scripts/lib/install-state.js b/scripts/lib/install-state.jsindex ffab9b118..cd56e6031 100644--- a/scripts/lib/install-state.js+++ b/scripts/lib/install-state.js@@ -24,7 +24,8 @@ function cloneJsonValue(value) {function readJson(filePath, label) {try {- return JSON.parse(fs.readFileSync(filePath, 'utf8'));+ const { readFileWithSharingRetry } = require('./atomic-write');+ return JSON.parse(readFileWithSharingRetry(filePath, 'utf8'));} catch (error) {throw new Error(`Failed to read ${label}: ${error.message}`);}diff --git a/scripts/lib/session-aliases.js b/scripts/lib/session-aliases.jsindex 8abe38ab8..5a7e47464 100644--- a/scripts/lib/session-aliases.js+++ b/scripts/lib/session-aliases.js@@ -3,14 +3,12 @@* Manages session aliases stored in $ECC_AGENT_DATA_HOME/session-aliases.json (default ~/.claude).*/-const fs = require('fs');const path = require('path');-const { writeFileAtomic } = require('./atomic-write');+const { readFileWithSharingRetry, writeFileAtomic } = require('./atomic-write');const { acquireSettingsLock } = require('./install/claude-settings-lock');const {getClaudeDir,- readFile,log} = require('./utils');@@ -43,11 +41,15 @@ function getDefaultAliases() {function loadAliases() {const aliasesPath = getAliasesPath();- if (!fs.existsSync(aliasesPath)) {- return getDefaultAliases();+ let content;+ try {+ content = readFileWithSharingRetry(aliasesPath, 'utf8');+ } catch (error) {+ if (error.code === 'ENOENT') return getDefaultAliases();+ // An unreadable published snapshot is not an empty store. Fail closed so+ // a transaction cannot replace existing aliases with a default snapshot.+ throw error;}-- const content = readFile(aliasesPath);if (!content) {return getDefaultAliases();}diff --git a/tests/lib/atomic-write.test.js b/tests/lib/atomic-write.test.jsindex 7c4e955c7..390ce5772 100644--- a/tests/lib/atomic-write.test.js+++ b/tests/lib/atomic-write.test.js@@ -11,11 +11,12 @@ 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.-function loadHelper(platform, rename, { clockStep = 25 } = {}) {+function loadHelper(platform, rename, { clockStep = 25, read = fs.readFileSync } = {}) {let elapsed = 0;let waits = 0;const filesystem = Object.create(fs);filesystem.renameSync = rename;+ filesystem.readFileSync = read;const module = { exports: {} };vm.runInNewContext(source, {module, exports: module.exports,@@ -152,5 +153,74 @@ test('parent replacement during retry preserves both destinations and original passert.strictEqual(fs.readFileSync(destination, 'utf8'), 'old');});+for (const code of ['EPERM', 'EACCES', 'EBUSY']) {+ test(`Windows reader recovers ${code} and returns the complete published bytes`, ({ root, destination }) => {+ fs.writeFileSync(destination, '{"published":true}');+ let attempts = 0;+ const helper = loadHelper('win32', fs.renameSync, { read(file, options) {+ attempts++;+ assert.strictEqual(file, destination);+ assert.strictEqual(options, 'utf8');+ if (attempts < 3) throw sharingError(code);+ return fs.readFileSync(file, options);+ } });+ assert.deepStrictEqual(JSON.parse(helper.readFileWithSharingRetry(destination, 'utf8')), { published: true });+ assert.strictEqual(attempts, 3);+ assert.strictEqual(helper.waits(), 2);+ assert.deepStrictEqual(fs.readdirSync(root), ['state.json']);+ });++ test(`Windows reader preserves the final permanent ${code} and never writes`, ({ root, destination }) => {+ let attempts = 0;+ const expected = sharingError(code);+ const helper = loadHelper('win32', fs.renameSync, { read() { attempts++; throw expected; } });+ assert.throws(() => helper.readFileWithSharingRetry(destination, 'utf8'), error => error === expected);+ assert.strictEqual(attempts, 21);+ assert.strictEqual(helper.waits(), 20);+ assert.strictEqual(fs.readFileSync(destination, 'utf8'), 'old');+ assert.deepStrictEqual(fs.readdirSync(root), ['state.json']);+ });+}++for (const platform of ['linux', 'darwin']) {+ for (const code of ['EPERM', 'EACCES', 'EBUSY']) {+ test(`${platform} reader propagates ${code} immediately`, ({ destination }) => {+ let attempts = 0;+ const expected = sharingError(code);+ const helper = loadHelper(platform, fs.renameSync, { read() { attempts++; throw expected; } });+ assert.throws(() => helper.readFileWithSharingRetry(destination, 'utf8'), error => error === expected);+ assert.strictEqual(attempts, 1);+ assert.strictEqual(helper.waits(), 0);+ });+ }+}++test('Windows reader stops at the elapsed deadline', ({ destination }) => {+ let attempts = 0;+ const expected = sharingError('EPERM');+ const helper = loadHelper('win32', fs.renameSync, { clockStep: 250, read() { attempts++; throw expected; } });+ assert.throws(() => helper.readFileWithSharingRetry(destination, 'utf8'), error => error === expected);+ assert.strictEqual(attempts, 4);+});++test('Windows reader does not retry missing files', ({ root }) => {+ const helper = loadHelper('win32', fs.renameSync);+ assert.throws(() => helper.readFileWithSharingRetry(path.join(root, 'missing'), 'utf8'), error => error.code === 'ENOENT');+ assert.strictEqual(helper.waits(), 0);+});++test('Windows reader does not retry unrelated IO or JSON parse failures', ({ destination }) => {+ const expected = sharingError('EIO');+ const denied = loadHelper('win32', fs.renameSync, { read() { throw expected; } });+ assert.throws(() => denied.readFileWithSharingRetry(destination, 'utf8'), error => error === expected);+ assert.strictEqual(denied.waits(), 0);+ fs.writeFileSync(destination, '{malformed');+ let reads = 0;+ const invalid = loadHelper('win32', fs.renameSync, { read(file, options) { reads++; return fs.readFileSync(file, options); } });+ assert.throws(() => JSON.parse(invalid.readFileWithSharingRetry(destination, 'utf8')), /JSON|property|Unexpected/);+ assert.strictEqual(reads, 1);+ assert.strictEqual(invalid.waits(), 0);+});+console.log(`Results: Passed: ${passed}, Failed: ${failed}`);process.exitCode = failed ? 1 : 0;diff --git a/tests/lib/session-aliases-read.test.js b/tests/lib/session-aliases-read.test.jsnew file mode 100644index 000000000..6be272140--- /dev/null+++ b/tests/lib/session-aliases-read.test.js@@ -0,0 +1,78 @@+'use strict';++const assert = require('assert');+const fs = require('fs');+const os = require('os');+const path = require('path');+const vm = require('vm');++// Use a module-local Windows atomic helper while retaining real filesystem and+// lease operations. This exercises the actual alias transaction entry points.+const helperPath = require.resolve('../../scripts/lib/atomic-write');+const record = { exports: {} };+vm.runInNewContext(fs.readFileSync(helperPath, 'utf8'), {+ module: record, exports: record.exports, require,+ process: { platform: 'win32', pid: process.pid },+ performance, Atomics, SharedArrayBuffer, Int32Array,+}, { filename: helperPath });+require.cache[helperPath] = { id: helperPath, filename: helperPath, loaded: true, exports: record.exports };+const aliases = require('../../scripts/lib/session-aliases');+let passed = 0;+let failed = 0;++function test(name, run) {+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-alias-reader-')));+ const keys = ['HOME', 'USERPROFILE', 'ECC_AGENT_DATA_HOME'];+ const saved = Object.fromEntries(keys.map(key => [key, process.env[key]]));+ Object.assign(process.env, { HOME: root, USERPROFILE: root, ECC_AGENT_DATA_HOME: path.join(root, '.claude') });+ try { run(); passed++; console.log(`PASS ${name}`); }+ catch (error) { failed++; console.error(`FAIL ${name}: ${error.stack}`); }+ finally {+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key]; else process.env[key] = value;+ }+ fs.rmSync(root, { recursive: true, force: true });+ }+}++for (const code of ['EPERM', 'EACCES', 'EBUSY']) {+ test(`alias transaction preserves existing entries after a transient ${code} read`, () => {+ aliases.setAlias('preserved', '/original');+ const file = aliases.getAliasesPath();+ const originalRead = fs.readFileSync;+ let attempts = 0;+ fs.readFileSync = function (input) {+ if (input === file && ++attempts === 1) throw Object.assign(new Error('temporary sharing'), { code });+ return originalRead.apply(this, arguments);+ };+ try { assert.strictEqual(aliases.setAlias('added', '/new').success, true); }+ finally { fs.readFileSync = originalRead; }+ assert.strictEqual(aliases.loadAliases().aliases.preserved.sessionPath, '/original');+ assert.strictEqual(aliases.loadAliases().aliases.added.sessionPath, '/new');+ assert.strictEqual(attempts, 2);+ assert.deepStrictEqual(fs.readdirSync(path.dirname(file)), ['session-aliases.json']);+ });++ test(`alias transaction fails closed on a permanent ${code} read and releases its lock`, () => {+ aliases.setAlias('preserved', '/original');+ const file = aliases.getAliasesPath();+ const originalRead = fs.readFileSync;+ const before = originalRead(file, 'utf8');+ const expected = Object.assign(new Error('permanent sharing failure'), { code });+ let attempts = 0;+ fs.readFileSync = function (input) {+ if (input === file) { attempts++; throw expected; }+ return originalRead.apply(this, arguments);+ };+ try { assert.throws(() => aliases.setAlias('added', '/new'), error => error === expected); }+ finally { fs.readFileSync = originalRead; }+ assert.ok(attempts >= 1 && attempts <= 21);+ assert.strictEqual(originalRead(file, 'utf8'), before);+ assert.deepStrictEqual(fs.readdirSync(path.dirname(file)), ['session-aliases.json']);+ assert.strictEqual(aliases.setAlias('after-failure', '/next').success, true);+ assert.strictEqual(aliases.loadAliases().aliases.preserved.sessionPath, '/original');+ });+}++console.log(`Results: Passed: ${passed}, Failed: ${failed}`);+process.exitCode = failed ? 1 : 0;diff --git a/tests/lib/session-aliases.test.js b/tests/lib/session-aliases.test.jsindex 3ab5fa35c..3271dc524 100644--- a/tests/lib/session-aliases.test.js+++ b/tests/lib/session-aliases.test.js@@ -1238,8 +1238,9 @@ function runTests() {assert.strictEqual(aliases.saveAliases({ aliases: { replacement: { sessionPath: '/new' } } }), false);assert.strictEqual(aliases.renameAlias('preserved', 'changed').success, false);assert.strictEqual(fs.readFileSync(aliasesPath, 'utf8'), before);- assert.strictEqual(staged.length, 2, 'Each failed operation attempts one publication');- assert.notStrictEqual(staged[0], staged[1], 'Each write has its own staging file');+ const stagingPaths = [...new Set(staged)];+ assert.strictEqual(stagingPaths.length, 2, 'Each write retains one private staging file across retries');+ assert.ok(staged.length >= 2 && staged.length <= 42, 'Publication attempts remain bounded for both writes');assert.deepStrictEqual(fs.readdirSync(path.dirname(aliasesPath)), ['session-aliases.json']);} finally {fs.renameSync = originalRename;