Skip to content
21 changes: 21 additions & 0 deletions packages/host-kit/src/internal/exec-trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export type ExecSettlementReason =
| 'success'
| 'exit_failure'
| 'timeout'
| 'output_limit'
| 'abort'
| 'spawn_error'
| 'stdin_error';
Expand Down Expand Up @@ -68,3 +69,23 @@ export function createExecTraceContext(
emit('spawn_start');
return { emit };
}

export function commandSettlementReason(input: {
didAbort: boolean;
exceededStream: 'stdout' | 'stderr' | undefined;
didTimeout: boolean;
code: number | null;
allowFailure: boolean | undefined;
}): ExecSettlementReason {
if (input.didAbort) return 'abort';
if (input.didTimeout) return 'timeout';
if (input.exceededStream) return 'output_limit';
return (input.code ?? 1) !== 0 && !input.allowFailure ? 'exit_failure' : 'success';
}

export function normalizeTimeoutMs(value: number | undefined): number | undefined {
if (!Number.isFinite(value)) return undefined;
const timeout = Math.floor(value as number);
if (timeout <= 0) return undefined;
return timeout;
}
129 changes: 128 additions & 1 deletion packages/host-kit/src/internal/exec.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { test } from 'vitest';
import { expect, test } from 'vitest';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
Expand Down Expand Up @@ -500,3 +500,130 @@ test.skipIf(process.platform === 'win32')(
assert.equal('signal' in exited, false);
},
);

test('async captured output enforces a per-stream byte limit', async () => {
for (const stream of ['stdout', 'stderr'] as const) {
const emit = `process.${stream}.write('x'.repeat(Number(process.argv[1])))`;
const within = await runCmd(process.execPath, ['-e', emit, '128'], { maxBuffer: 128 });
expect(within[stream]).toHaveLength(128);
await expect(
runCmd(process.execPath, ['-e', emit, '129'], { maxBuffer: 128 }),
).rejects.toMatchObject({
code: 'COMMAND_FAILED',
details: { reason: 'command_output_limit', stream, maxBuffer: 128 },
});
}
const separate = await runCmd(
process.execPath,
['-e', "process.stdout.write('x'.repeat(128)); process.stderr.write('y'.repeat(128));"],
{ maxBuffer: 128 },
);
expect(separate.stdout).toHaveLength(128);
expect(separate.stderr).toHaveLength(128);
});

test.skipIf(process.platform === 'win32')(
'an output-limit failure retains bounded output with allowFailure enabled',
async () => {
for (const stream of ['stdout', 'stderr'] as const) {
let child: ReturnType<typeof import('node:child_process').spawn> | undefined;
let received = '';
const onChunk = (chunk: string) => {
received += chunk;
if (received.length === 128) child?.kill('SIGUSR1');
};
await expect(
runCmdStreaming(
process.execPath,
[
'-e',
`process.on('SIGUSR1', () => process.${stream}.write('x')); setInterval(() => {}, 1000); process.${stream}.write('x'.repeat(128));`,
],
{
maxBuffer: 128,
allowFailure: true,
onSpawn: (spawned) => {
child = spawned;
},
...(stream === 'stdout' ? { onStdoutChunk: onChunk } : { onStderrChunk: onChunk }),
},
),
).rejects.toMatchObject({
code: 'COMMAND_FAILED',
details: {
reason: 'command_output_limit',
stream,
maxBuffer: 128,
[stream]: 'x'.repeat(128),
},
});
}
},
);

test('async output limits count raw bytes before decoding text', async () => {
for (const stream of ['stdout', 'stderr'] as const) {
for (const bytes of [[0xff], [0xe2, 0x82]]) {
const result = await runCmd(
process.execPath,
['-e', 'process.' + stream + '.write(Buffer.from(' + JSON.stringify(bytes) + '))'],
{ maxBuffer: bytes.length },
);
expect(result[stream]).toBe('\uFFFD');
}
await expect(
runCmd(process.execPath, ['-e', 'process.' + stream + '.write(Buffer.from([0xff, 0xff]))'], {
maxBuffer: 1,
}),
).rejects.toMatchObject({ details: { reason: 'command_output_limit', stream, maxBuffer: 1 } });
}
const binary = await runCmd(
process.execPath,
['-e', 'process.stdout.write(Buffer.from([0xff]))'],
{ binaryStdout: true, maxBuffer: 1 },
);
expect(binary.stdoutBuffer).toEqual(Buffer.from([0xff]));
});

test('bounded text output preserves multibyte characters across pipe chunks', async () => {
const expected = '\u20AC'.repeat(50_000);
for (const stream of ['stdout', 'stderr'] as const) {
const result = await runCmd(
process.execPath,
['-e', 'process.' + stream + '.write(String.fromCharCode(0x20ac).repeat(50000))'],
{ maxBuffer: Buffer.byteLength(expected) },
);
expect(result[stream]).toBe(expected);
}
});

test.skipIf(process.platform === 'win32')(
'graceful shutdown output does not replace an earlier timeout',
async () => {
let stdout = '';
const error = await runCmdStreaming(
process.execPath,
[
'-e',
[
"process.on('SIGTERM', () => { process.stderr.write('x'.repeat(129)); clearInterval(keepAlive); });",
'const keepAlive = setInterval(() => {}, 100);',
"process.stdout.write('ready');",
].join('\n'),
],
{
timeoutMs: 1_000,
maxBuffer: 128,
kill: { signal: 'SIGTERM', graceMs: 1_000 },
onStdoutChunk: (chunk) => {
stdout += chunk;
},
},
).then(
() => undefined,
(error: unknown) => error,
);
assert.equal(stdout, 'ready');
assert.ok(isCommandTimeoutError(error));
},
);
Loading
Loading