Skip to content

Commit 9ee6d54

Browse files
trek-esimclaude
authored
fix(#4306): extend fault-injection fd-swallow fix across the whole suite (#4308)
* fix(#4306): forward real bytes through io.test.cjs's fault-injection mocks The bug #1008 fault-injection tests mock fs.writeSync scoped only by file descriptor. On their "success" arms (the retry-after-EAGAIN/EINTR call, and the short-write simulation) they fabricated a return byte count without ever calling the real writeSync -- the bytes went into a local array and nowhere else. node:test's process-isolation runner (default on Node >= 22) reads each test file's own stdout to parse its child-to-parent result protocol. If the runner's own reporter write for an adjacent test lands on fd 1 while one of these mocks is installed, that write was silently swallowed instead of reaching the real pipe -- observed in CI as "Unable to deserialize cloned data" (a corrupted/truncated byte stream on the parent's read side), not a thrown exception. Every "success" arm now forwards the real bytes to orig()/restore() instead of fabricating a return value, so anything else sharing the fd during the mocked window still gets its bytes delivered for real. writeAllSync (the only production caller reaching this mock) always passes a Buffer, so the forwarded calls use the buffer-form fs.writeSync overload unambiguously. Co-Authored-By: Claude Sonnet 5 <[email protected]> * fix(#4306): extend fault-injection fd-swallow fix across the whole suite The originally-fixed instance (tests/io.test.cjs) was one occurrence of a copy-pasted defect: mocked fs.writeSync arms fabricated a return byte count without ever forwarding the call to the real fs.writeSync, silently discarding bytes. Under node:test's process-isolated runner, the parent reads the child's real stdout to parse v8-serialized report frames interleaved with plain output (confirmed against node's own lib/internal/test_runner/runner.js and a matching upstream issue, nodejs/node#64061) — a swallowed write on that fd corrupts the parent's parse ("Unable to deserialize cloned data"). Adds a shared, safe capture helper to tests/helpers.cjs, captureFdSync(fd, fn): it always forwards every write to the real fs.writeSync first, then records only the observed fd's bytes, sliced by the real return count (not the requested length), decoded once via Buffer.concat so a short write can't split a multi-byte codepoint across two decodes. 17 test files migrate their local copy of the unsafe mock to this shared helper. tests/worktree-base-ref.test.cjs keeps a narrower in-place fix instead (it needs to record every fd a write touched, which the shared helper doesn't expose). tests/io.test.cjs gets two follow-up correctness fixes on top of the already-committed forwarding fix: the EAGAIN/EINTR/short-write arms now derive their recorded chunk from the real return count everywhere (including the string-form overload), and the short-write test no longer forces a Buffer-shaped truncation call onto a string-form write that could land on the same fd. Co-Authored-By: Claude Sonnet 5 <[email protected]> --------- Co-authored-by: sim <sim@local> Co-authored-by: Claude Sonnet 5 <[email protected]>
1 parent 4499933 commit 9ee6d54

19 files changed

Lines changed: 208 additions & 380 deletions

‎tests/agent-install-check.test.cjs‎

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ const { describe, test, beforeEach, afterEach } = require('node:test');
2020
const assert = require('node:assert/strict');
2121
const fs = require('node:fs');
2222
const path = require('node:path');
23-
const { createTempDir, cleanup } = require('./helpers.cjs');
23+
const { createTempDir, cleanup, captureFdSync } = require('./helpers.cjs');
2424

2525
const AGENT_INSTALL_CHECK_PATH = path.join(
2626
__dirname, '..', 'gsd-core', 'bin', 'lib', 'agent-install-check.cjs'
@@ -1183,7 +1183,7 @@ describe('cmdValidateAgents surfaces the Codex posture result (#3242 row 20)', (
11831183
cleanup(tmpDir);
11841184
});
11851185

1186-
test('row 20: validate agents output carries the posture result for a violating install', (t) => {
1186+
test('row 20: validate agents output carries the posture result for a violating install', () => {
11871187
const { cmdValidateAgents } = require(
11881188
path.join(__dirname, '..', 'gsd-core', 'bin', 'lib', 'verify.cjs'),
11891189
);
@@ -1193,22 +1193,9 @@ describe('cmdValidateAgents surfaces the Codex posture result (#3242 row 20)', (
11931193
`name = "${EXPECTED_AGENTS[0]}"\nmodel = "sonnet"\ndeveloper_instructions = '''\nWork.\n'''\n`,
11941194
);
11951195

1196-
const written = [];
1197-
const realWriteSync = fs.writeSync;
1198-
t.mock.method(fs, 'writeSync', (fd, data, offset, length) => {
1199-
if (fd !== 1) {
1200-
return realWriteSync.call(fs, fd, data, offset, length);
1201-
}
1202-
const chunk = Buffer.isBuffer(data)
1203-
? data.subarray(offset ?? 0, length === undefined ? data.length : (offset ?? 0) + length).toString('utf8')
1204-
: String(data);
1205-
written.push(chunk);
1206-
return Buffer.byteLength(chunk, 'utf8');
1207-
});
1208-
1209-
cmdValidateAgents(tmpDir, false);
1196+
const written = captureFdSync(1, () => cmdValidateAgents(tmpDir, false));
12101197

1211-
const parsed = JSON.parse(written.join(''));
1198+
const parsed = JSON.parse(written);
12121199
assert.ok(
12131200
parsed.codex_posture,
12141201
`expected cmdValidateAgents output to carry a codex_posture key, got keys: ${Object.keys(parsed).join(', ')}`,

‎tests/codex-inherit-smoke.test.cjs‎

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ const { install } = require('../bin/install.js');
5656
const { checkCodexModelPosture } = require('../gsd-core/bin/lib/agent-install-check.cjs');
5757
const { cmdEffortSync } = require('../gsd-core/bin/lib/commands.cjs');
5858
const { parseCodexAgentToml } = require('../gsd-core/bin/lib/codex-agent-toml.cjs');
59-
const { cleanup } = require('./helpers.cjs');
59+
const { cleanup, captureFdSync } = require('./helpers.cjs');
6060

6161
const REPO_ROOT = path.resolve(__dirname, '..');
6262

@@ -149,17 +149,9 @@ function findKeyLine(header, key) {
149149
* structure, never prose.
150150
*/
151151
function runEffortSyncDryRun(codexHome) {
152-
const origWriteSync = fs.writeSync;
153-
let captured = '';
154-
fs.writeSync = (fd, data) => {
155-
if (fd === 1) { captured += data; return data.length; }
156-
return origWriteSync(fd, data);
157-
};
158-
try {
159-
cmdEffortSync(codexHome, false, { dryRun: true, configDir: codexHome, runtime: 'codex' });
160-
} finally {
161-
fs.writeSync = origWriteSync;
162-
}
152+
const captured = captureFdSync(1, () =>
153+
cmdEffortSync(codexHome, false, { dryRun: true, configDir: codexHome, runtime: 'codex' })
154+
);
163155
return JSON.parse(captured);
164156
}
165157

‎tests/commands.test.cjs‎

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4343,7 +4343,7 @@ const assert = require('node:assert/strict');
43434343
const fs = require('node:fs');
43444344
const path = require('node:path');
43454345
const os = require('node:os');
4346-
const { cleanup } = require('./helpers.cjs');
4346+
const { cleanup, captureFdSync } = require('./helpers.cjs');
43474347
const { runNode } = require('./helpers/process-seam.cjs');
43484348
const { toLegacyResult } = require('./helpers/git-fixture.cjs');
43494349

@@ -4369,18 +4369,7 @@ function makeTmpDir(prefix) {
43694369
// output() in core.cjs uses fs.writeSync(1, data) — intercept fd=1 writes.
43704370
// Pass raw=false so output() emits JSON (raw=true emits the plain rawValue string).
43714371
function captureOutput(fn) {
4372-
const origWriteSync = fs.writeSync;
4373-
let captured = '';
4374-
fs.writeSync = (fd, data) => {
4375-
if (fd === 1) captured += data;
4376-
else origWriteSync(fd, data);
4377-
};
4378-
try {
4379-
fn();
4380-
} finally {
4381-
fs.writeSync = origWriteSync;
4382-
}
4383-
return JSON.parse(captured);
4372+
return JSON.parse(captureFdSync(1, fn));
43844373
}
43854374

43864375
function makeAgentsDir(tmpDir) {

‎tests/commit-docs-bypass.test.cjs‎

Lines changed: 12 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -844,7 +844,7 @@ const assert = require('node:assert/strict');
844844
const fs = require('fs');
845845
const path = require('path');
846846
const fc = require('./helpers/fast-check-setup.cjs');
847-
const { cleanup, createTempGitProject } = require('./helpers.cjs');
847+
const { cleanup, createTempGitProject, captureFdSync } = require('./helpers.cjs');
848848
const { seedPhase } = require('./fixtures/index.cjs');
849849
const { gitOrThrow } = require('./helpers/git-fixture.cjs');
850850
const { GIT_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
@@ -881,23 +881,7 @@ function writeConfig(tmpDir, config) {
881881
* tests/config-get-default.test.cjs's captureFdWrite.
882882
*/
883883
function captureFdWrite(fd, fn) {
884-
const orig = fs.writeSync;
885-
let captured = Buffer.alloc(0);
886-
fs.writeSync = (writeFd, ...rest) => {
887-
if (writeFd !== fd) return orig.call(fs, writeFd, ...rest);
888-
const [data, offset = 0, length] = rest;
889-
const chunk = Buffer.isBuffer(data)
890-
? data.subarray(offset, offset + (length ?? data.length - offset))
891-
: Buffer.from(String(data), 'utf8');
892-
captured = Buffer.concat([captured, chunk]);
893-
return chunk.length;
894-
};
895-
try {
896-
fn();
897-
} finally {
898-
fs.writeSync = orig;
899-
}
900-
return captured.toString('utf-8');
884+
return captureFdSync(fd, fn);
901885
}
902886

903887
function runCommit(tmpDir, message, files) {
@@ -912,28 +896,21 @@ function runCommit(tmpDir, message, files) {
912896
* ExitError-throwing path (ADR-3889 — error() throws ExitError directly, it
913897
* no longer calls process.exit()). */
914898
function runConfigSetExpectError(tmpDir, keyPath, value) {
915-
const origWriteSync = fs.writeSync;
916899
io.setJsonErrorMode(true);
917-
let stderr = '';
918-
fs.writeSync = (fd, ...rest) => {
919-
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
920-
const [data, offset = 0, length] = rest;
921-
const chunk = Buffer.isBuffer(data)
922-
? data.subarray(offset, offset + (length ?? data.length - offset)).toString('utf8')
923-
: String(data);
924-
stderr += chunk;
925-
return Buffer.byteLength(chunk);
926-
};
900+
let capturedStderr = '';
927901
try {
928-
configCli.cmdConfigSet(tmpDir, keyPath, value, true);
929-
assert.fail('expected cmdConfigSet to throw ExitError');
930-
} catch (e) {
931-
if (!(e instanceof ExitError)) throw e;
902+
capturedStderr = captureFdSync(2, () => {
903+
try {
904+
configCli.cmdConfigSet(tmpDir, keyPath, value, true);
905+
assert.fail('expected cmdConfigSet to throw ExitError');
906+
} catch (inner) {
907+
if (!(inner instanceof ExitError)) throw inner;
908+
}
909+
});
932910
} finally {
933-
fs.writeSync = origWriteSync;
934911
io.setJsonErrorMode(false);
935912
}
936-
const parts = stderr.split('\n').filter(Boolean);
913+
const parts = capturedStderr.split('\n').filter(Boolean);
937914
let payload = {};
938915
try { payload = JSON.parse(parts[parts.length - 1]); } catch { /* leave {} */ }
939916
return payload;

‎tests/config-get-default.test.cjs‎

Lines changed: 17 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ const assert = require('node:assert/strict');
1414
const fs = require('fs');
1515
const path = require('path');
1616
const os = require('os');
17-
const { cleanup } = require('./helpers.cjs');
17+
const { cleanup, captureFdSync } = require('./helpers.cjs');
1818

1919
// In-process invocation, not execFileSync: cmdConfigGet is a pure CJS
2020
// function reachable without spawning `node` as a child. The prior
@@ -65,23 +65,7 @@ const { ExitError } = require(path.join(__dirname, '..', 'gsd-core', 'bin', 'lib
6565
* would have hit the fd.
6666
*/
6767
function captureFdWrite(fd, fn) {
68-
const orig = fs.writeSync;
69-
let captured = Buffer.alloc(0);
70-
fs.writeSync = (writeFd, ...rest) => {
71-
if (writeFd !== fd) return orig.call(fs, writeFd, ...rest);
72-
const [data, offset = 0, length] = rest;
73-
const chunk = Buffer.isBuffer(data)
74-
? data.subarray(offset, offset + (length ?? data.length - offset))
75-
: Buffer.from(String(data), 'utf8');
76-
captured = Buffer.concat([captured, chunk]);
77-
return chunk.length;
78-
};
79-
try {
80-
fn();
81-
} finally {
82-
fs.writeSync = orig;
83-
}
84-
return captured.toString('utf-8');
68+
return captureFdSync(fd, fn);
8569
}
8670

8771
/**
@@ -276,39 +260,28 @@ describe('config-get --default flag (#1893)', () => {
276260

277261
function runExpectError(...args) {
278262
const { keyPath, raw, defaultValue } = parseConfigGetArgs(args);
279-
const origWriteSync = fs.writeSync;
280263
io.setJsonErrorMode(true);
281-
let writeCount = 0;
282-
let stderr = '';
283-
fs.writeSync = (fd, ...rest) => {
284-
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
285-
writeCount++;
286-
const [data, offset = 0, length] = rest;
287-
const chunk = Buffer.isBuffer(data)
288-
? data.subarray(offset, offset + (length ?? data.length - offset)).toString('utf8')
289-
: String(data);
290-
stderr += chunk;
291-
return Buffer.byteLength(chunk);
292-
};
293-
const lastError = () => {
294-
const parts = stderr.split('\n').filter(Boolean);
295-
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
296-
};
297-
// ADR-3889: error() throws ExitError directly; catch it here rather
298-
// than mocking process.exit.
299264
let exitCode;
265+
let stderr;
300266
try {
301-
config.cmdConfigGet(tmpDir, keyPath, raw, defaultValue);
302-
assert.fail('expected cmdConfigGet to throw ExitError');
303-
} catch (e) {
304-
if (!(e instanceof ExitError)) throw e;
305-
exitCode = e.code;
267+
stderr = captureFdSync(2, () => {
268+
try {
269+
config.cmdConfigGet(tmpDir, keyPath, raw, defaultValue);
270+
assert.fail('expected cmdConfigGet to throw ExitError');
271+
} catch (e) {
272+
if (!(e instanceof ExitError)) throw e;
273+
exitCode = e.code;
274+
}
275+
});
306276
} finally {
307-
fs.writeSync = origWriteSync;
308277
io.setJsonErrorMode(false);
309278
}
279+
const lines = stderr.split('\n').filter(Boolean);
280+
const lastError = () => {
281+
try { return JSON.parse(lines[lines.length - 1]); } catch { return {}; }
282+
};
310283
assert.ok(exitCode !== 0 && exitCode !== undefined, 'Expected non-zero exit code');
311-
assert.equal(writeCount, 1, 'error() must fire exactly once');
284+
assert.equal(lines.length, 1, 'error() must emit exactly one stderr line');
312285
const payload = lastError();
313286
return { status: exitCode, reason: payload.reason, message: payload.message, stderr };
314287
}

‎tests/core-utils.test.cjs‎

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ const { SCOPE } = require('../gsd-core/bin/lib/planning-scope.cjs');
3232
const {
3333
cleanup, runGsdTools, scrubConfigLocationEnv,
3434
saveSessionEnv, restoreSessionEnv, clearSessionEnv, TEST_HOME_SANDBOX_MARKER,
35+
captureFdSync,
3536
} = require('./helpers.cjs');
3637
const phaseLocator = require('../gsd-core/bin/lib/phase-locator.cjs');
3738
const phaseId = require('../gsd-core/bin/lib/phase-id.cjs');
@@ -63,23 +64,7 @@ const initMod = require('../gsd-core/bin/lib/init.cjs');
6364
// `~/.gsd` config or leak real session-identity env into the slug output.
6465

6566
function captureFd1Sync(fn) {
66-
const chunks = [];
67-
const origWriteSync = fs.writeSync.bind(fs);
68-
fs.writeSync = (fd, data, offset, length) => {
69-
if (fd === 2) return Buffer.isBuffer(data) ? data.length : String(data).length;
70-
if (fd !== 1) return origWriteSync(fd, data, offset, length);
71-
const chunk = Buffer.isBuffer(data)
72-
? data.subarray(offset ?? 0, length === undefined ? data.length : (offset ?? 0) + length).toString('utf8')
73-
: String(data);
74-
chunks.push(chunk);
75-
return Buffer.byteLength(chunk, 'utf8');
76-
};
77-
try {
78-
fn();
79-
} finally {
80-
fs.writeSync = origWriteSync;
81-
}
82-
return chunks.join('');
67+
return captureFdSync(1, fn);
8368
}
8469

8570
function withHermeticInProcessEnv(dir, fn) {

‎tests/discuss-mode.test.cjs‎

Lines changed: 5 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ const { test, describe } = require('node:test');
88
const assert = require('node:assert/strict');
99
const fs = require('fs');
1010
const path = require('path');
11-
const { createTempProject, cleanup } = require('./helpers.cjs');
11+
const { createTempProject, cleanup, captureFdSync } = require('./helpers.cjs');
1212

1313
describe('workflow.discuss_mode config', () => {
1414
test('config template includes discuss_mode default', () => {
@@ -153,26 +153,10 @@ describe('workflow.discuss_mode config', () => {
153153

154154
// cmdInitPlanPhase writes its JSON result directly to fd 1 via
155155
// io.cjs's writeAllSync (bypasses console.log — captureConsole()
156-
// cannot observe it). Monkeypatch fs.writeSync and restore it in a
157-
// finally, the project's standard IO-capture seam.
158-
const orig = fs.writeSync;
159-
let captured = Buffer.alloc(0);
160-
fs.writeSync = (fd, ...rest) => {
161-
if (fd !== 1) return orig.call(fs, fd, ...rest);
162-
const [data, offset = 0, length] = rest;
163-
const chunk = Buffer.isBuffer(data)
164-
? data.subarray(offset, offset + (length ?? data.length - offset))
165-
: Buffer.from(String(data), 'utf8');
166-
captured = Buffer.concat([captured, chunk]);
167-
return chunk.length;
168-
};
169-
let result;
170-
try {
171-
cmdInitPlanPhase(cwd, 'does-not-exist', false, {});
172-
result = JSON.parse(captured.toString('utf8'));
173-
} finally {
174-
fs.writeSync = orig;
175-
}
156+
// cannot observe it). Delegates to the shared, safe fd-capture helper
157+
// (#4306) — see tests/helpers.cjs's captureFdSync.
158+
const captured = captureFdSync(1, () => cmdInitPlanPhase(cwd, 'does-not-exist', false, {}));
159+
const result = JSON.parse(captured);
176160
assert.strictEqual(
177161
result.text_mode, true,
178162
'cmdInitPlanPhase result must propagate config.workflow.text_mode'

‎tests/estimate-calibrate.test.cjs‎

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ const assert = require('node:assert/strict');
2121
const fs = require('node:fs');
2222
const path = require('node:path');
2323

24-
const { createTempProject, cleanup, runGsdTools } = require('./helpers.cjs');
24+
const { createTempProject, cleanup, runGsdTools, captureFdSync } = require('./helpers.cjs');
2525
const est = require('../gsd-core/bin/lib/phase-estimation.cjs');
2626
const estimateCli = require('../gsd-core/bin/lib/estimate-cli.cjs');
2727
// io.cjs owns error()/ERROR_REASON/JSON-error-mode — driven directly here so
@@ -549,37 +549,28 @@ describe('unreadable phases directory refuses calibration (#3882, ADR-3473 §8.5
549549
* throws (ADR-3889 — error() no longer calls process.exit() directly) with
550550
* stderr(fd 2) captured. */
551551
function runCalibrateExpectError(tmpDir) {
552-
const origWriteSync = fs.writeSync;
553552
io.setJsonErrorMode(true);
554-
let writeCount = 0;
555-
let stderr = '';
556-
fs.writeSync = (fd, ...rest) => {
557-
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
558-
writeCount++;
559-
const [data, offset = 0, length] = rest;
560-
const chunk = Buffer.isBuffer(data)
561-
? data.subarray(offset, offset + (length ?? data.length - offset)).toString('utf8')
562-
: String(data);
563-
stderr += chunk;
564-
return Buffer.byteLength(chunk);
565-
};
566-
const lastError = () => {
567-
const parts = stderr.split('\n').filter(Boolean);
568-
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
569-
};
570553
let exitCode;
554+
let stderr;
571555
try {
572-
estimateCli.cmdEstimateCalibrate(tmpDir, [], false);
573-
assert.fail('expected cmdEstimateCalibrate to throw ExitError');
574-
} catch (e) {
575-
if (!(e instanceof ExitError)) throw e;
576-
exitCode = e.code;
556+
stderr = captureFdSync(2, () => {
557+
try {
558+
estimateCli.cmdEstimateCalibrate(tmpDir, [], false);
559+
assert.fail('expected cmdEstimateCalibrate to throw ExitError');
560+
} catch (e) {
561+
if (!(e instanceof ExitError)) throw e;
562+
exitCode = e.code;
563+
}
564+
});
577565
} finally {
578-
fs.writeSync = origWriteSync;
579566
io.setJsonErrorMode(false);
580567
}
568+
const lines = stderr.split('\n').filter(Boolean);
569+
const lastError = () => {
570+
try { return JSON.parse(lines[lines.length - 1]); } catch { return {}; }
571+
};
581572
assert.ok(exitCode !== 0 && exitCode !== undefined, 'expected a non-zero exit code');
582-
assert.equal(writeCount, 1, 'error() must fire exactly once');
573+
assert.equal(lines.length, 1, 'error() must emit exactly one stderr line');
583574
return { status: exitCode, ...lastError() };
584575
}
585576

0 commit comments

Comments
 (0)