From 071b4072c24a98e018509c6e3ec7af8d3603404d Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Sun, 22 Nov 2026 01:17:09 -0500 Subject: [PATCH] Fail stuck executions, keep worker error details, guard terminal status Quick, scheduled and Gandalf commands relied entirely on the worker sending a command_result. If the worker was at capacity, disconnected or restarted, the execution stayed 'running' forever (#7). Failed commands also lost the worker's error message (#14). - Direct commands now get a server-side timeout: the command timeout plus 30 s. When it expires, the execution fails with a command_result entry carrying the error, which the UI already renders and Gandalf treats as 'failed' and retries. - When a worker socket closes, every command sent over it fails at once. Pending workflow step waits resolve as failures, so the engine moves on. - Every 5 minutes, a backstop sweep fails 'running' executions past EXECUTION_MAX_MINUTES + 10 that nothing is tracking. - updateExecutionStatus only changes a 'running' execution and reports whether it did. A late result, or the engine finishing after an abort, can no longer flip a failed execution to completed or fire a second webhook. - Aborting a quick command clears its timeout. - command_result keeps error, exit_code, signal and timed_out in the log, the broadcast and the workflow step result. - The worker reports "at capacity" as a failed result instead of staying silent, and includes exit_code, signal and timed_out on failures. - Fix: after a worker reconnected, the old socket closing removed the new socket's mapping and marked the worker offline, so commands got "Worker not connected" until the next heartbeat. Closes #7 Closes #14 Co-Authored-By: Claude Opus 5.5 --- server.js | 127 ++++++++++++++++++++++++++++++++++++++++++++--- worker/worker.js | 17 +++++++ 2 files changed, 137 insertions(+), 7 deletions(-) diff --git a/server.js b/server.js index 6ef69a3..2c94879 100644 --- a/server.js +++ b/server.js @@ -403,8 +403,35 @@ async function markStaleWorkersOffline() { console.error('[Worker] Stale check error:', error); } } +// Backstop for #7: fail any execution still 'running' long past the global limit +// that nothing in this process is tracking any more (no workflow engine loop, no +// command awaiting a result). Restart recovery covers executions orphaned by a restart. +async function reapOrphanedExecutions() { + try { + const maxMinutes = parseInt(process.env.EXECUTION_MAX_MINUTES) || 60; + const [rows] = await pool.query( + `SELECT id FROM executions WHERE status = 'running' + AND started_at < DATE_SUB(NOW(), INTERVAL ? MINUTE)`, + [maxMinutes + 10] + ); + const tracked = new Set([..._commandTargets.values()].map(t => t.executionId)); + for (const { id } of rows) { + if (_executionState.has(id) || tracked.has(id)) continue; + await addExecutionLog(id, { + action: 'execution_timeout', + message: `Execution was still running after ${maxMinutes + 10} minutes with nothing tracking it; marked failed`, + timestamp: new Date().toISOString() + }); + if (await updateExecutionStatus(id, 'failed')) console.warn(`[Reaper] Failed orphaned execution ${id}`); + } + } catch (error) { + console.error('[Reaper] Error reaping orphaned executions:', error); + } +} + if (!DEV_READONLY) { setInterval(markStaleWorkersOffline, 60_000); + setInterval(reapOrphanedExecutions, 5 * 60_000); } else { console.log('[DEV] skipped: markStaleWorkersOffline interval'); } @@ -419,15 +446,62 @@ const workers = new Map(); // Map worker_id -> WebSocket connection // connection are dropped, so a connection cannot forge another worker's output. // The DB worker id is used rather than the socket so a worker that reconnects // mid-command can still deliver its result. -const _commandTargets = new Map(); // key → { dbWorkerId, sentAt } +const _commandTargets = new Map(); // key → { dbWorkerId, ws, executionId, direct, timer, sentAt } const COMMAND_TARGET_TTL_MS = 25 * 60 * 60_000; // longer than any command or wait step +const COMMAND_RESULT_GRACE_MS = 30_000; // slack on top of the command's own timeout function sendCommandToWorker(workerWs, message) { const key = message.command_id || message.execution_id; - _commandTargets.set(key, { dbWorkerId: workerWs.dbWorkerId, sentAt: Date.now() }); + const target = { + dbWorkerId: workerWs.dbWorkerId, + ws: workerWs, + executionId: message.execution_id, + // Workflow steps carry a command_id and time out in waitForCommandResult. + // Direct commands (quick, scheduled, Gandalf) had no server-side timeout and + // could stay 'running' forever when the result never came back (#7). + direct: !message.command_id, + timer: null, + sentAt: Date.now() + }; + if (target.direct) { + const ms = (message.timeout || QUICK_CMD_TIMEOUT_MS) + COMMAND_RESULT_GRACE_MS; + target.timer = setTimeout(() => { + failInflightCommand(key, `No result from the worker within ${Math.round(ms / 1000)}s`) + .catch(err => console.error('[Command] Timeout handling failed:', err)); + }, ms); + } + _commandTargets.set(key, target); workerWs.send(JSON.stringify(message)); } +// Give up on an in-flight command: the worker timed out, disconnected, or never answered. +// Direct commands get a failed command_result log entry (rendered like any other failed +// result, and seen by Gandalf as status 'failed'); workflow steps get their pending +// waitForCommandResult resolved as a failure so the engine moves on immediately. +async function failInflightCommand(key, error) { + const t = _commandTargets.get(key); + if (!t) return; + _commandTargets.delete(key); + clearTimeout(t.timer); + console.warn(`[Command] ${t.direct ? 'Execution' : 'Workflow command'} ${key} failed: ${error}`); + if (!t.direct) { + const resolver = _commandResolvers.get(key); + if (resolver) resolver({ success: false, error, stdout: '', stderr: '' }); + return; + } + const timestamp = new Date().toISOString(); + await addExecutionLog(t.executionId, { + step: 'command_execution', action: 'command_result', worker_id: t.dbWorkerId, + success: false, error, stdout: '', stderr: '', timestamp + }); + if (await updateExecutionStatus(t.executionId, 'failed')) { + broadcast({ + type: 'command_result', execution_id: t.executionId, worker_id: t.dbWorkerId, + success: false, error, stdout: '', stderr: '' + }); + } +} + // Entries for commands whose result never arrives would otherwise accumulate. setInterval(() => { const cutoff = Date.now() - COMMAND_TARGET_TTL_MS; @@ -460,6 +534,13 @@ wss.on('connection', (ws, req) => { if (message.type === 'command_result') { // Handle command result from worker const { execution_id, command_id, worker_id, success, stdout, stderr, duration, timestamp } = message; + // Failure details from the worker (#14). Older workers send only `error`. + const failure = success ? {} : { + error: typeof message.error === 'string' ? message.error.slice(0, 2000) : undefined, + exit_code: message.exit_code, + signal: message.signal || undefined, + timed_out: message.timed_out || undefined + }; const targetKey = command_id || execution_id; const target = _commandTargets.get(targetKey); @@ -469,6 +550,7 @@ wss.on('connection', (ws, req) => { return; } _commandTargets.delete(targetKey); + clearTimeout(target.timer); // Add result to execution logs await addExecutionLog(execution_id, { @@ -479,6 +561,7 @@ wss.on('connection', (ws, req) => { success: success, stdout: stdout, stderr: stderr, + ...failure, duration: duration, timestamp: timestamp || new Date().toISOString() }); @@ -498,7 +581,7 @@ wss.on('connection', (ws, req) => { if (command_id) { const resolver = _commandResolvers.get(command_id); if (resolver) { - resolver({ success, stdout, stderr }); + resolver({ success, stdout, stderr, ...failure }); } } @@ -516,6 +599,7 @@ wss.on('connection', (ws, req) => { success: success, stdout: stdout, stderr: stderr, + ...failure, is_automated: isAutomated, }); @@ -632,13 +716,25 @@ wss.on('connection', (ws, req) => { ws.on('close', () => { clearTimeout(ws.identifyTimer); + // Commands sent over this socket can no longer report back (the worker drops + // results while disconnected), so fail them now rather than leave them 'running'. + if (ws.isWorker) { + for (const [key, t] of _commandTargets) { + if (t.ws === ws) { + failInflightCommand(key, 'Worker disconnected before returning a result') + .catch(err => console.error('[Command] Disconnect handling failed:', err)); + } + } + } browserClients.delete(ws); workerClients.delete(ws); - if (ws.workerId) { + if (ws.workerId && workers.get(ws.workerId) === ws) { workers.delete(ws.workerId); console.log(`Worker ${ws.workerId} (runtime ID) disconnected`); } - if (ws.dbWorkerId) { + // Only if this socket is still the live connection for the worker: after a + // reconnect, the old socket closing must not unmap the new one or mark it offline. + if (ws.dbWorkerId && workers.get(ws.dbWorkerId) === ws) { workers.delete(ws.dbWorkerId); console.log(`Worker ${ws.dbWorkerId} (database ID) disconnected`); // Mark worker offline in DB @@ -674,12 +770,19 @@ async function addExecutionLog(executionId, logEntry) { } // Helper function to update execution status +// Only a running execution changes status: once failed (aborted, timed out, worker +// gone) or completed, a late result or the workflow engine finishing can't flip it +// back or fire a second webhook. Returns true if the status changed. async function updateExecutionStatus(executionId, status) { try { - await pool.query( - 'UPDATE executions SET status = ?, completed_at = NOW() WHERE id = ?', + const [result] = await pool.query( + "UPDATE executions SET status = ?, completed_at = NOW() WHERE id = ? AND status = 'running'", [status, executionId] ); + if (!result || result.affectedRows === 0) { + console.log(`[Workflow] Execution ${executionId} is no longer running; not changing status to ${status}`); + return false; + } broadcast({ type: 'execution_status', @@ -695,8 +798,10 @@ async function updateExecutionStatus(executionId, status) { console.error(`[Webhook] Delivery error for execution ${executionId}:`, err.message); }); } + return true; } catch (error) { console.error(`[Workflow] Error updating execution status:`, error); + return false; } } @@ -1520,6 +1625,14 @@ app.post('/api/executions/:id/abort', authenticateSSO, async (req, res) => { // Update execution status to failed await updateExecutionStatus(executionId, 'failed'); + // Stop tracking its direct command so the result timeout doesn't fire later + for (const [key, t] of _commandTargets) { + if (t.direct && t.executionId === executionId) { + clearTimeout(t.timer); + _commandTargets.delete(key); + } + } + // Unblock any pending prompt so the thread can exit const pending = _executionPrompts.get(executionId); if (pending) pending.resolve(null); diff --git a/worker/worker.js b/worker/worker.js index 000da38..b593ce9 100644 --- a/worker/worker.js +++ b/worker/worker.js @@ -147,6 +147,18 @@ class PulseWorker { if (this.activeTasks >= this.maxConcurrentTasks) { console.log(`[PULSE Worker] Max concurrent tasks reached, rejecting command`); + // Tell the server, or the execution would wait for a result that never comes (#7). + this.sendResult({ + type: 'command_result', + execution_id, + worker_id: this.workerId, + command_id, + success: false, + error: `Worker at capacity (${this.maxConcurrentTasks} commands already running)`, + stdout: '', + stderr: '', + timestamp: new Date().toISOString() + }); return; } @@ -183,6 +195,11 @@ class PulseWorker { 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()