Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

fix(diagnostics): stop truncating large renderer receipts on a pipe (#374)

henry201605d673e8300df6
diff --git a/archify.zip b/archify.zip
index a44866db..f7fdf0f8 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/renderers/shared/diagnostics.mjs b/archify/renderers/shared/diagnostics.mjs
index 03cf6aa3..5d74de7d 100644
--- a/archify/renderers/shared/diagnostics.mjs
+++ b/archify/renderers/shared/diagnostics.mjs
@@ -111,13 +111,46 @@ function rendererFailure(error) {
};
}
+const readerSignal = new Int32Array(new SharedArrayBuffer(4));
+
+function waitForReader() {
+ // Sleep instead of spinning on EAGAIN. A retry budget looks like a safeguard
+ // and behaves like a truncation gate: a spinning loop burns thousands of
+ // attempts in a few milliseconds, so a reader that is merely slow to start
+ // exhausts it and loses the tail of the receipt. Waiting costs nothing while
+ // the reader catches up, and a reader that goes away raises EPIPE, which the
+ // caller already treats as a real write failure.
+ Atomics.wait(readerSignal, 0, 0, 1);
+}
+
export function installRendererDiagnosticBoundary() {
if (!DIAGNOSTIC_MODE || globalThis[boundaryKey]) return;
globalThis[boundaryKey] = true;
process.on('uncaughtException', (error) => {
const payload = `${JSON.stringify(rendererFailure(error))}\n`;
try {
- fs.writeSync(process.stderr.fd, payload);
+ // stderr may be a pipe. fs.writeSync performs a PARTIAL write once the
+ // payload exceeds the OS pipe buffer (8KB on macOS) and returns the byte
+ // count actually written. Ignoring that return value silently truncated
+ // large diagnostic payloads mid-JSON, so the parent CLI's JSON.parse
+ // failed and the fail-closed boundary reported internal/unclassified
+ // instead of the diagnostics we had already computed. Loop until drained.
+ // A full pipe also makes writeSync throw EAGAIN; wait for the reader
+ // rather than treat it as a stream failure, otherwise the tail is
+ // dropped just the same.
+ const buffer = Buffer.from(payload, 'utf8');
+ let written = 0;
+ while (written < buffer.length) {
+ try {
+ written += fs.writeSync(process.stderr.fd, buffer, written, buffer.length - written);
+ } catch (writeError) {
+ if (writeError?.code === 'EAGAIN') {
+ waitForReader();
+ continue;
+ }
+ throw writeError;
+ }
+ }
} catch {
// The renderer is already failing. Avoid replacing its real error with a
// secondary stream failure; the parent CLI still has the exit status.
diff --git a/archify/test/renderer-diagnostic-boundary.test.mjs b/archify/test/renderer-diagnostic-boundary.test.mjs
new file mode 100644
index 00000000..15b79601
--- /dev/null
+++ b/archify/test/renderer-diagnostic-boundary.test.mjs
@@ -0,0 +1,107 @@
+import { spawn, spawnSync } from 'node:child_process';
+import { once } from 'node:events';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+
+const diagnostics = new URL('../renderers/shared/diagnostics.mjs', import.meta.url).href;
+
+// A pipe holds 8KB on macOS and 64KB on Linux before it blocks. The large case
+// stays far above both so the receipt cannot leave the renderer in one write.
+const LARGE_DIAGNOSTIC_COUNT = 400;
+const SMALL_DIAGNOSTIC_COUNT = 2;
+const LARGEST_COMMON_PIPE_BUFFER = 64 * 1024;
+const STALLED_READER_MS = 300;
+
+function crashingRenderer(t, count) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-diagnostic-boundary-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const script = path.join(dir, 'crash.mjs');
+ fs.writeFileSync(script, [
+ `import { installRendererDiagnosticBoundary, throwDiagnosticError } from ${JSON.stringify(diagnostics)};`,
+ '',
+ 'installRendererDiagnosticBoundary();',
+ '',
+ `const diagnostics = Array.from({ length: ${count} }, (unused, index) => ({`,
+ " code: 'layout/constraint',",
+ " severity: 'error',",
+ " message: 'transition ' + index + ' is too short — ' + 'route it through a channel. '.repeat(12),",
+ ' subject: { transition: index },',
+ " evidence: { clearance: index, detail: 'measured segment. '.repeat(8) },",
+ " supportedFixes: ['route it through a channel or drop its label'],",
+ '}));',
+ '',
+ 'setImmediate(() => {',
+ " throwDiagnosticError('Lifecycle layout validation failed', diagnostics);",
+ '});',
+ '',
+ ].join('\n'));
+ return script;
+}
+
+function runCrashingRenderer(script) {
+ return spawnSync(process.execPath, [script], {
+ encoding: 'utf8',
+ env: { ...process.env, ARCHIFY_DIAGNOSTIC_FORMAT: 'json' },
+ maxBuffer: 64 * 1024 * 1024,
+ });
+}
+
+test('the renderer boundary delivers a receipt larger than the pipe buffer', t => {
+ const result = runCrashingRenderer(crashingRenderer(t, LARGE_DIAGNOSTIC_COUNT));
+
+ assert.equal(result.status, 1, result.stderr);
+ assert.ok(
+ Buffer.byteLength(result.stderr, 'utf8') > LARGEST_COMMON_PIPE_BUFFER,
+ 'the regression needs a receipt that cannot fit in one pipe write',
+ );
+
+ // A partial write used to truncate this receipt mid-JSON, so the parent CLI
+ // discarded every computed diagnostic and reported internal/unclassified.
+ const receipt = JSON.parse(result.stderr);
+ assert.equal(receipt.ok, false);
+ assert.equal(receipt.source, 'renderer');
+ assert.equal(receipt.diagnostics.length, LARGE_DIAGNOSTIC_COUNT);
+ assert.deepEqual([...new Set(receipt.diagnostics.map(entry => entry.code))], ['layout/constraint']);
+ assert.equal(receipt.diagnostics.at(-1).subject.transition, LARGE_DIAGNOSTIC_COUNT - 1);
+});
+
+test('the renderer boundary waits for a stalled reader instead of truncating', async t => {
+ const script = crashingRenderer(t, LARGE_DIAGNOSTIC_COUNT);
+ const child = spawn(process.execPath, [script], {
+ env: { ...process.env, ARCHIFY_DIAGNOSTIC_FORMAT: 'json' },
+ stdio: ['ignore', 'ignore', 'pipe'],
+ });
+ t.after(() => child.kill('SIGKILL'));
+
+ // A parent that has not started reading fills the pipe, so every write
+ // reports EAGAIN. A fixed retry budget expires here in a few milliseconds and
+ // delivers a truncated receipt, which is the same data loss under a different
+ // trigger.
+ const chunks = [];
+ child.stderr.on('data', (chunk) => chunks.push(chunk));
+ child.stderr.pause();
+ const delivered = once(child.stderr, 'end');
+ const exited = once(child, 'exit');
+
+ await delay(STALLED_READER_MS);
+ child.stderr.resume();
+ await delivered;
+
+ assert.deepEqual(await exited, [1, null]);
+ const receipt = JSON.parse(Buffer.concat(chunks).toString('utf8'));
+ assert.equal(receipt.diagnostics.length, LARGE_DIAGNOSTIC_COUNT);
+ assert.equal(receipt.diagnostics.at(-1).subject.transition, LARGE_DIAGNOSTIC_COUNT - 1);
+});
+
+test('the renderer boundary keeps delivering receipts that fit in one write', t => {
+ const result = runCrashingRenderer(crashingRenderer(t, SMALL_DIAGNOSTIC_COUNT));
+
+ assert.equal(result.status, 1, result.stderr);
+ const receipt = JSON.parse(result.stderr);
+ assert.equal(receipt.diagnostics.length, SMALL_DIAGNOSTIC_COUNT);
+ assert.equal(receipt.diagnostics[0].code, 'layout/constraint');
+});