Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ command or session completes and what a timeout reports.
`run()` whose caller awaits `exitPromise` before reading no longer hang or
wait for the deadline. `terminate()` releases stdout at once and stderr once
git has exited.
- **stderr is complete when a command completes**: The Node runner used to resolve `exitPromise` on the child's `exit` event, which Node emits before the stdio pipes close, so a short git failure under concurrency could report exit 128 with empty stderr, and a compare-and-swap race classified as a generic `GitPlumbingError` instead of `GitRepositoryLockedError`. Completion on every runtime now waits for both pipes to end after the exit (since the process-group work above), and the stderr returned is everything git wrote up to the stderr bound. After a deadline, `exitPromise` and `finished` also wait for both released pipes to close before reporting `timedOut: true`; releasing a pipe closes it, so a helper that holds the other end still cannot hold the caller. Tests cover stderr that arrives after the exit event, settlement once across `error`, `exit` and `close`, the shared completion contract on Node and Web streams, and many concurrent short failures on Node, Bun and Deno (git-stunts/plumbing#9).
- **Input a command never reads**: A `run()` whose child exits without reading
its `input` reports the child's exit status. Node no longer crashes on an
unhandled `EPIPE`, Bun no longer leaves an unhandled rejection, and Deno no
Expand Down
7 changes: 5 additions & 2 deletions docs/CUSTOM_RUNNERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,15 @@ ended. Git starts helpers of its own (remote helpers, hooks, pagers, credential
helpers), and a helper that outlives git keeps the pipe open, so exit alone is
not completion.

`stderr` must be complete when `exitPromise` resolves: every byte the process wrote before its pipe ended, up to the stderr bound. A runtime can report the exit before the last stderr arrives (Node emits `exit` before `close`), and the error classifier reads `stderr`, so a runner that resolves on exit can turn a lock race into a generic failure with empty diagnostics. The Node, Bun and Deno runners all wait for the pipe to end before they resolve (git-stunts/plumbing#9).

The built-in runners keep to these rules:

- **Process groups.** Each command starts as the leader of a new process group.
At the deadline the runner sends `SIGKILL` to the whole group and ends both
pipes, so a reader sees the end of stdout and `exitPromise` resolves with
`timedOut: true`. After a `SIGKILL`, or once the command has completed, the
pipes, so a reader sees the end of stdout, and `exitPromise` resolves with
`timedOut: true` once the leader has exited and both released pipes have
closed; stderr then holds what arrived before the deadline. After a `SIGKILL`, or once the command has completed, the
group id is never signalled again: the leader may have been reaped and its
id reused.
- **`signal` and `code`.** `signal` is the signal the leader died of, whoever
Expand Down
19 changes: 15 additions & 4 deletions src/infrastructure/ProcessDeadline.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,17 @@
* outlive it and hold a pipe open, and a caller reading that pipe would wait on
* the helper rather than the deadline.
*
* Every output's `drained` settles only after the last byte of that pipe has
* reached its view, so stderr collected from the view is complete when the
* result resolves, even when it arrives after the leader's exit
* (git-stunts/plumbing#9).
*
* At the deadline the owner's `onDeadline` stops the whole process group, the
* pipes are ended, and the result waits only for the leader's exit, which a
* `SIGKILL` makes certain. A pipe held by any process, even one that left the
* group, never holds the caller past the deadline.
* pipes are released, and the result waits for the leader's exit, which a
* `SIGKILL` makes certain, and for each released pipe to close. A pipe held by
* any process, even one that left the group, never holds the caller past the
* deadline, because releasing it closes our end. The result still reports
* the timeout.
*/
export default class ProcessDeadline {
/**
Expand Down Expand Up @@ -45,6 +52,10 @@ export default class ProcessDeadline {
for (const output of outputs) {
output.stop();
}
return { ...(await exited), timedOut: true };
// Stopping releases each pipe, so it closes however long a helper holds
// its other end; waiting for that close is bounded, and leaves no pipe
// still closing when the timeout is reported (git-stunts/plumbing#9).
const [killed] = await Promise.all([exited, ...outputs.map((output) => output.drained)]);
return { ...killed, timedOut: true };
}
}
324 changes: 324 additions & 0 deletions test/StderrCompleteness.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,324 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { EventEmitter } from 'node:events';
import { PassThrough, Readable, Writable } from 'node:stream';
import ShellRunner from '../ShellRunner.js';
import NodeShellRunner from '../src/infrastructure/adapters/node/NodeShellRunner.js';
import BoundedTextCollector from '../src/infrastructure/BoundedTextCollector.js';
import ProcessDeadline from '../src/infrastructure/ProcessDeadline.js';
import StoppableNodeStream from '../src/infrastructure/adapters/node/StoppableNodeStream.js';
import StoppableWebStream from '../src/infrastructure/StoppableWebStream.js';

// Oracle: git-stunts/plumbing#9. When a command's completion resolves, the
// stderr it reports is all the stderr the command wrote. A git failure whose
// diagnostics arrive after its exit status must never be reported as a failure
// with empty or partial stderr, because the error classifier reads stderr.
//
// Media: controlled process events and real Node and Web streams (no
// subprocess, no clock in any assertion), then real short-lived subprocesses.

// Above Linux's largest pid_max (2^22), so even a stray real signal reaches nothing.
const UNUSED_PID = 4194305;
const ENCODER = new TextEncoder();
const LOCK_FAILURE =
"fatal: cannot lock ref 'refs/heads/main': is at 1111111111111111111111111111111111111111 " +
'but expected 2222222222222222222222222222222222222222\n';

class ControlledChild extends EventEmitter {
constructor({ stderr = new PassThrough() } = {}) {
super();
this.pid = UNUSED_PID;
this.stdout = new PassThrough();
this.stderr = stderr;
this.stdin = new Writable({
write(_bytes, _encoding, done) {
done();
},
});
this.leaderSignals = [];
}

kill(signal) {
this.leaderSignals.push(signal);
return true;
}
}

/** Records settlement without awaiting a promise that may never settle. */
function observe(promise) {
const outcome = { settlements: 0, value: undefined };
promise.then((value) => {
outcome.settlements += 1;
outcome.value = value;
});
return outcome;
}

/** Lets every queued callback and stream event run; reads no clock. */
async function turns(count = 20) {
for (let i = 0; i < count; i += 1) {
await new Promise((resolve) => setImmediate(resolve));
}
}

/** Waits on the condition, never on a duration. */
async function until(condition) {
while (!condition()) {
await new Promise((resolve) => setTimeout(resolve, 1));
}
}

/** Reads a Node or Web stream of output to its end. */
async function drain(stream) {
for await (const _ of stream) {
// Output is not the subject.
}
}

function nodeRunner(child, signals = []) {
return new NodeShellRunner({
spawnProcess: () => child,
signalProcess: (pid, signal) => signals.push([pid, signal]),
});
}

describe('stderr is complete when a Node command completes', () => {
it('waits for stderr written after the exit event and before close', async () => {
const child = new ControlledChild();
const result = await nodeRunner(child).run({ command: 'git', args: [] });
const completion = observe(result.exitPromise);
child.stdout.end();

child.emit('exit', 128, null);
await turns();
child.stderr.write(LOCK_FAILURE.slice(0, 20));
await turns();
expect(completion.settlements).toBe(0);

child.stderr.end(LOCK_FAILURE.slice(20));
child.emit('close', 128, null);
const { code, stderr, timedOut } = await result.exitPromise;

expect(code).toBe(128);
expect(stderr).toBe(LOCK_FAILURE);
expect(timedOut).toBe(false);
});

it('waits for session stderr written after the exit event and before close', async () => {
const child = new ControlledChild();
const session = await nodeRunner(child).open({ command: 'git', args: [], maxStderrBytes: 4096 });
const completion = observe(session.finished);
child.stdout.end();

child.emit('exit', 128, null);
await turns();
child.stderr.write(LOCK_FAILURE.slice(0, 20));
await turns();
expect(completion.settlements).toBe(0);

child.stderr.end(LOCK_FAILURE.slice(20));
child.emit('close', 128, null);
const { code, stderr } = await session.finished;

expect(code).toBe(128);
expect(stderr).toBe(LOCK_FAILURE);
});
});

describe('a Node command settles exactly once', () => {
it('reports a spawn error once, whatever process events follow it', async () => {
const child = new ControlledChild();
const result = await nodeRunner(child).run({ command: 'git', args: [] });
const completion = observe(result.exitPromise);
const failure = new Error('spawn git ENOENT');

child.emit('error', failure);
child.emit('exit', 0, null);
child.stdout.destroy();
child.stderr.destroy();
child.emit('close', 0, null);
await result.exitPromise;
await turns();

expect(completion.settlements).toBe(1);
expect(completion.value.error).toBe(failure);
expect(completion.value.code).toBe(1);
expect(completion.value.stderr).toContain('spawn git ENOENT');
});

it('keeps the exit status when an error follows the exit', async () => {
const child = new ControlledChild();
const result = await nodeRunner(child).run({ command: 'git', args: [] });
const completion = observe(result.exitPromise);

child.emit('exit', 128, null);
child.emit('error', new Error('kill EPERM'));
child.stdout.end();
child.stderr.end(LOCK_FAILURE);
child.emit('close', 128, null);
await result.exitPromise;
await turns();

expect(completion.settlements).toBe(1);
expect(completion.value.code).toBe(128);
expect(completion.value.error).toBeUndefined();
expect(completion.value.stderr).toBe(LOCK_FAILURE);
});

it('kills at the deadline, waits for the pipes to close, and still reports the timeout', async () => {
// A pipe whose close is still in progress when the killed leader exits.
let finishDestroy = null;
const stderr = new Readable({
read() {},
destroy(error, done) {
finishDestroy = () => done(error);
},
});
const child = new ControlledChild({ stderr });
const signals = [];
const result = await nodeRunner(child, signals).run({ command: 'git', args: [], timeout: 1 });
const completion = observe(result.exitPromise);

await until(() => signals.length > 0 && finishDestroy !== null);
child.emit('exit', null, 'SIGKILL');
await turns();
expect(completion.settlements).toBe(0);

finishDestroy();
child.emit('close', null, 'SIGKILL');
await result.exitPromise;
await turns();

expect(signals).toEqual([[-UNUSED_PID, 'SIGKILL']]);
expect(completion.settlements).toBe(1);
expect(completion.value.timedOut).toBe(true);
expect(completion.value.signal).toBe('SIGKILL');
expect(completion.value.code).not.toBe(0);
});
});

// Every runner (Node, Bun, Deno) completes through ProcessDeadline, with the
// leader's exit and one output view per pipe. This is the contract they share:
// completion waits for each pipe to end after the exit, so stderr collected
// from the view is whole when completion resolves.
describe('the shared completion contract keeps late stderr', () => {
async function settlesWithLateStderr(makeOutput) {
const { output, write, end } = makeOutput();
let exit;
const exited = new Promise((resolve) => {
exit = resolve;
});
const stderrText = new BoundedTextCollector(4096).collect(output.stream);
const settled = observe(
ProcessDeadline.settle({ exited, outputs: [output], timeout: 60_000, onDeadline: () => {} })
);

exit({ code: 128, signal: null });
await turns();
write(LOCK_FAILURE.slice(0, 20));
await turns();
expect(settled.settlements).toBe(0);

write(LOCK_FAILURE.slice(20));
end();
await until(() => settled.settlements > 0);
expect(settled.value).toEqual({ code: 128, signal: null, timedOut: false });
expect(await stderrText).toBe(LOCK_FAILURE);
}

it('on a Node stream view (Node)', async () => {
await settlesWithLateStderr(() => {
const pipe = new PassThrough();
return {
output: new StoppableNodeStream(pipe),
write: (text) => pipe.write(text),
end: () => pipe.end(),
};
});
});

it('on a Web stream view (Bun and Deno)', async () => {
await settlesWithLateStderr(() => {
let controller;
const pipe = new ReadableStream({
start(c) {
controller = c;
},
});
return {
output: new StoppableWebStream(pipe),
write: (text) => controller.enqueue(ENCODER.encode(text)),
end: () => controller.close(),
};
});
});
});

// Medium: real subprocesses on this runtime (Node, Bun or Deno, whichever runs
// the suite). Each child writes its diagnostics immediately before a nonzero
// exit, many at once, as concurrent compare-and-swap failures do.
describe('short failing commands never lose stderr', () => {
const ROUNDS = 4;
const CONCURRENT = 32;

async function runAll(start) {
for (let round = 0; round < ROUNDS; round += 1) {
const completions = await Promise.all(
Array.from({ length: CONCURRENT }, async (_, i) => {
const { result, expected } = await start(round * CONCURRENT + i);
await drain(result.stdoutStream);
return { completion: await result.exitPromise, expected };
})
);
for (const { completion, expected } of completions) {
expect(completion.timedOut).toBe(false);
expect(completion.code).not.toBe(0);
expect(completion.stderr).toBe(expected);
}
}
}

it('keeps all of git stderr from concurrent failures', async () => {
const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'plumbing-stderr-'));
// The runner passes LANG and LC_* through; pin git's untranslated messages.
const env = { LC_ALL: 'C' };
const git = async (args) => {
const result = await ShellRunner.run({ command: 'git', args, cwd: repo, env });
await drain(result.stdoutStream);
return { completion: await result.exitPromise };
};
try {
await git(['init', '--quiet']);
// A read that fails takes no lock, so every concurrent failure writes the
// same diagnostic; a guarded update-ref would race on its lock file and
// could legitimately report a different one.
const failing = ['show-ref', '--verify', 'refs/stunts/missing'];
// One failure alone is the baseline every concurrent failure must match.
const { completion: alone } = await git(failing);
expect(alone.code).not.toBe(0);
expect(alone.stderr).toContain('refs/stunts/missing');

await runAll(async () => ({
result: await ShellRunner.run({ command: 'git', args: failing, cwd: repo, env }),
expected: alone.stderr,
}));
} finally {
fs.rmSync(repo, { recursive: true, force: true });
}
});

it('keeps stderr larger than one pipe write written just before exit', async () => {
await runAll(async (n) => {
// 8 KiB: more than PIPE_BUF, so it reaches the parent in several reads.
const expected = `${n}:${'e'.repeat(8192)}\n`;
return {
result: await ShellRunner.run({
command: 'sh',
args: ['-c', 'printf "%s\\n" "$1" >&2; exit 128', 'sh', expected.slice(0, -1)],
}),
expected,
};
});
});
});
1 change: 1 addition & 0 deletions test/deno_entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import './NodeViewReaderDetach.test.js';
import './DenoSignalHost.test.js';
import './SignalHandlerDeclaration.test.js';
import './ProcessGroupDeadline.test.js';
import './StderrCompleteness.test.js';
import './StreamCompletion.test.js';
import './Streaming.test.js';
import './domain/entities/GitCommit.test.js';
Expand Down
Loading