Abort kills the command on the worker (#8 follow-up)

- worker: commands run with spawn in their own process group (same
  timeout, 10 MB output limit and result fields as exec). A new
  cancel_command message (by command_id, or every command of an
  execution) sends SIGTERM to the group, then SIGKILL after 5 s; the
  result reports cancelled: true. Old workers ignore the message.
- server: the abort route sends cancel_command to the worker running each
  of the execution's commands.
- Tests: the whole process tree dies on cancel (a background child too),
  execution-wide cancel leaves other executions alone, and end to end an
  aborted quick command's process is gone from the worker. Liveness
  checks treat zombies as dead (an orphan waits to be reaped).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-22 23:59:50 -05:00
1 parent dc732a1ec5
commit 073114c92e
4 files changed
+164 -46

No files matched your search

+88 -44
View File
@@ -1,12 +1,54 @@
const axios = require('axios');
const WebSocket = require('ws');
const { exec } = require('child_process');
const { promisify } = require('util');
const { spawn } = require('child_process');
const os = require('os');
const crypto = require('crypto');
require('dotenv').config();
const execAsync = promisify(exec);
const MAX_OUTPUT = 10 * 1024 * 1024; // per stream, like exec's maxBuffer
const KILL_GRACE_MS = 5000; // SIGTERM, then SIGKILL after this
// Runs a shell command in its own process group, so a timeout or a cancel can stop
// the whole tree (sh and everything it started). Resolves with the outcome; the
// error message matches what child_process.exec reported.
function runCommand(command, { timeout = 300000, onSpawn } = {}) {
return new Promise(resolve => {
const child = spawn('/bin/sh', ['-c', command], { detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
let timedOut = false;
let cancelled = false;
let overflow = false;
let killTimer = null;
const kill = () => {
try { process.kill(-child.pid, 'SIGTERM'); } catch { /* already gone */ }
killTimer = setTimeout(() => { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* gone */ } }, KILL_GRACE_MS);
killTimer.unref();
};
const collect = which => chunk => {
if (which === 'out') stdout += chunk; else stderr += chunk;
if (!overflow && (stdout.length > MAX_OUTPUT || stderr.length > MAX_OUTPUT)) { overflow = true; kill(); }
};
child.stdout.setEncoding('utf8').on('data', collect('out'));
child.stderr.setEncoding('utf8').on('data', collect('err'));
const timer = setTimeout(() => { timedOut = true; kill(); }, timeout);
if (onSpawn) onSpawn({ cancel: () => { cancelled = true; kill(); } });
child.on('error', err => {
clearTimeout(timer);
resolve({ ok: false, stdout, stderr, code: undefined, signal: undefined, timedOut, cancelled, message: err.message });
});
child.on('close', (code, signal) => {
clearTimeout(timer);
if (killTimer) clearTimeout(killTimer);
const ok = code === 0 && !timedOut && !cancelled && !overflow;
let message;
if (cancelled) message = 'Cancelled';
else if (overflow) message = 'Output exceeded 10 MB';
else if (!ok) message = `Command failed: ${command}\n${stderr}`;
resolve({ ok, stdout, stderr, code, signal: signal || undefined, timedOut, cancelled, message });
});
});
}
// The commit this worker runs (#40): the VERSION file written by
// deploy/pulse_worker_deploy.sh, or the git checkout it runs from.
@@ -37,6 +79,7 @@ class PulseWorker {
this.maxConcurrentTasks = parseInt(process.env.MAX_CONCURRENT_TASKS || '5');
this.version = detectVersion();
this.activeTasks = 0;
this.running = new Map(); // command_id (or execution_id) -> { execution_id, cancel }
this.ws = null;
this.heartbeatTimer = null;
}
@@ -156,6 +199,9 @@ class PulseWorker {
case 'execute_workflow':
await this.executeWorkflow(message);
break;
case 'cancel_command':
this.cancelCommand(message);
break;
case 'ping':
this.sendPong();
break;
@@ -186,54 +232,52 @@ class PulseWorker {
this.activeTasks++;
console.log(`[PULSE Worker] Executing command (active tasks: ${this.activeTasks})`);
const key = command_id || execution_id;
const startTime = Date.now();
try {
const startTime = Date.now();
const { stdout, stderr } = await execAsync(command, {
timeout: timeout,
maxBuffer: 10 * 1024 * 1024 // 10MB buffer
const r = await runCommand(command, {
timeout,
onSpawn: handle => this.running.set(key, { execution_id, ...handle }),
});
const duration = Date.now() - startTime;
const result = {
type: 'command_result',
execution_id,
worker_id: this.workerId,
command_id,
success: true,
stdout: stdout,
stderr: stderr,
duration: duration,
timestamp: new Date().toISOString()
};
this.sendResult(result);
console.log(`[PULSE Worker] Command completed in ${duration}ms`);
} catch (error) {
const result = {
type: 'command_result',
execution_id,
worker_id: this.workerId,
command_id,
success: false,
error: error.message,
// exec() errors: code is the exit status (number) or a Node error code (string);
// killed is set when the timeout fired; signal names what terminated the process.
exit_code: typeof error.code === 'number' ? error.code : undefined,
signal: error.signal || undefined,
timed_out: error.killed && !!error.signal ? true : undefined,
stdout: error.stdout || '',
stderr: error.stderr || '',
timestamp: new Date().toISOString()
};
this.sendResult(result);
console.error(`[PULSE Worker] Command failed:`, error.message);
const base = { type: 'command_result', execution_id, worker_id: this.workerId, command_id, timestamp: new Date().toISOString() };
if (r.ok) {
this.sendResult({ ...base, success: true, stdout: r.stdout, stderr: r.stderr, duration });
console.log(`[PULSE Worker] Command completed in ${duration}ms`);
} else {
this.sendResult({
...base,
success: false,
error: r.message,
exit_code: typeof r.code === 'number' ? r.code : undefined,
signal: r.signal,
timed_out: r.timedOut || undefined,
cancelled: r.cancelled || undefined,
stdout: r.stdout,
stderr: r.stderr,
});
console.error('[PULSE Worker] Command failed:', r.message.split('\n')[0]);
}
} finally {
this.running.delete(key);
this.activeTasks--;
}
}
// Stops a running command and everything it started (#8): by command_id, or every
// command of an execution. Its result is then reported with cancelled: true.
cancelCommand(message) {
const { execution_id, command_id } = message;
let n = 0;
for (const [key, run] of this.running) {
if ((command_id && key === command_id) || (!command_id && run.execution_id === execution_id)) {
run.cancel();
n++;
}
}
console.log(`[PULSE Worker] Cancel for ${command_id || execution_id}: ${n} command(s) stopped`);
}
async executeWorkflow(message) {
const { workflow, execution_id } = message;
@@ -278,7 +322,7 @@ class PulseWorker {
}
}
module.exports = { PulseWorker, detectVersion };
module.exports = { PulseWorker, detectVersion, runCommand };
// Start only when run directly (node worker.js), so tests can load the class.
if (require.main === module) {