Merge pull request 'Fail stuck executions, keep worker error details, guard terminal status' (#42) from exec-reliability into main
This commit was merged in pull request #42.
This commit is contained in:
commit
8e77c1af0a
2 files changed
+137
-7
No files matched your search
@@ -403,8 +403,35 @@ async function markStaleWorkersOffline() {
|
|||||||
console.error('[Worker] Stale check error:', error);
|
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) {
|
if (!DEV_READONLY) {
|
||||||
setInterval(markStaleWorkersOffline, 60_000);
|
setInterval(markStaleWorkersOffline, 60_000);
|
||||||
|
setInterval(reapOrphanedExecutions, 5 * 60_000);
|
||||||
} else {
|
} else {
|
||||||
console.log('[DEV] skipped: markStaleWorkersOffline interval');
|
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.
|
// 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
|
// The DB worker id is used rather than the socket so a worker that reconnects
|
||||||
// mid-command can still deliver its result.
|
// 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_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) {
|
function sendCommandToWorker(workerWs, message) {
|
||||||
const key = message.command_id || message.execution_id;
|
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));
|
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.
|
// Entries for commands whose result never arrives would otherwise accumulate.
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
const cutoff = Date.now() - COMMAND_TARGET_TTL_MS;
|
const cutoff = Date.now() - COMMAND_TARGET_TTL_MS;
|
||||||
@@ -460,6 +534,13 @@ wss.on('connection', (ws, req) => {
|
|||||||
if (message.type === 'command_result') {
|
if (message.type === 'command_result') {
|
||||||
// Handle command result from worker
|
// Handle command result from worker
|
||||||
const { execution_id, command_id, worker_id, success, stdout, stderr, duration, timestamp } = message;
|
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 targetKey = command_id || execution_id;
|
||||||
const target = _commandTargets.get(targetKey);
|
const target = _commandTargets.get(targetKey);
|
||||||
@@ -469,6 +550,7 @@ wss.on('connection', (ws, req) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_commandTargets.delete(targetKey);
|
_commandTargets.delete(targetKey);
|
||||||
|
clearTimeout(target.timer);
|
||||||
|
|
||||||
// Add result to execution logs
|
// Add result to execution logs
|
||||||
await addExecutionLog(execution_id, {
|
await addExecutionLog(execution_id, {
|
||||||
@@ -479,6 +561,7 @@ wss.on('connection', (ws, req) => {
|
|||||||
success: success,
|
success: success,
|
||||||
stdout: stdout,
|
stdout: stdout,
|
||||||
stderr: stderr,
|
stderr: stderr,
|
||||||
|
...failure,
|
||||||
duration: duration,
|
duration: duration,
|
||||||
timestamp: timestamp || new Date().toISOString()
|
timestamp: timestamp || new Date().toISOString()
|
||||||
});
|
});
|
||||||
@@ -498,7 +581,7 @@ wss.on('connection', (ws, req) => {
|
|||||||
if (command_id) {
|
if (command_id) {
|
||||||
const resolver = _commandResolvers.get(command_id);
|
const resolver = _commandResolvers.get(command_id);
|
||||||
if (resolver) {
|
if (resolver) {
|
||||||
resolver({ success, stdout, stderr });
|
resolver({ success, stdout, stderr, ...failure });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -516,6 +599,7 @@ wss.on('connection', (ws, req) => {
|
|||||||
success: success,
|
success: success,
|
||||||
stdout: stdout,
|
stdout: stdout,
|
||||||
stderr: stderr,
|
stderr: stderr,
|
||||||
|
...failure,
|
||||||
is_automated: isAutomated,
|
is_automated: isAutomated,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -632,13 +716,25 @@ wss.on('connection', (ws, req) => {
|
|||||||
|
|
||||||
ws.on('close', () => {
|
ws.on('close', () => {
|
||||||
clearTimeout(ws.identifyTimer);
|
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);
|
browserClients.delete(ws);
|
||||||
workerClients.delete(ws);
|
workerClients.delete(ws);
|
||||||
if (ws.workerId) {
|
if (ws.workerId && workers.get(ws.workerId) === ws) {
|
||||||
workers.delete(ws.workerId);
|
workers.delete(ws.workerId);
|
||||||
console.log(`Worker ${ws.workerId} (runtime ID) disconnected`);
|
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);
|
workers.delete(ws.dbWorkerId);
|
||||||
console.log(`Worker ${ws.dbWorkerId} (database ID) disconnected`);
|
console.log(`Worker ${ws.dbWorkerId} (database ID) disconnected`);
|
||||||
// Mark worker offline in DB
|
// Mark worker offline in DB
|
||||||
@@ -674,12 +770,19 @@ async function addExecutionLog(executionId, logEntry) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to update execution status
|
// 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) {
|
async function updateExecutionStatus(executionId, status) {
|
||||||
try {
|
try {
|
||||||
await pool.query(
|
const [result] = await pool.query(
|
||||||
'UPDATE executions SET status = ?, completed_at = NOW() WHERE id = ?',
|
"UPDATE executions SET status = ?, completed_at = NOW() WHERE id = ? AND status = 'running'",
|
||||||
[status, executionId]
|
[status, executionId]
|
||||||
);
|
);
|
||||||
|
if (!result || result.affectedRows === 0) {
|
||||||
|
console.log(`[Workflow] Execution ${executionId} is no longer running; not changing status to ${status}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
broadcast({
|
broadcast({
|
||||||
type: 'execution_status',
|
type: 'execution_status',
|
||||||
@@ -695,8 +798,10 @@ async function updateExecutionStatus(executionId, status) {
|
|||||||
console.error(`[Webhook] Delivery error for execution ${executionId}:`, err.message);
|
console.error(`[Webhook] Delivery error for execution ${executionId}:`, err.message);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[Workflow] Error updating execution status:`, 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
|
// Update execution status to failed
|
||||||
await updateExecutionStatus(executionId, '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
|
// Unblock any pending prompt so the thread can exit
|
||||||
const pending = _executionPrompts.get(executionId);
|
const pending = _executionPrompts.get(executionId);
|
||||||
if (pending) pending.resolve(null);
|
if (pending) pending.resolve(null);
|
||||||
|
|||||||
@@ -147,6 +147,18 @@ class PulseWorker {
|
|||||||
|
|
||||||
if (this.activeTasks >= this.maxConcurrentTasks) {
|
if (this.activeTasks >= this.maxConcurrentTasks) {
|
||||||
console.log(`[PULSE Worker] Max concurrent tasks reached, rejecting command`);
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,6 +195,11 @@ class PulseWorker {
|
|||||||
command_id,
|
command_id,
|
||||||
success: false,
|
success: false,
|
||||||
error: error.message,
|
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 || '',
|
stdout: error.stdout || '',
|
||||||
stderr: error.stderr || '',
|
stderr: error.stderr || '',
|
||||||
timestamp: new Date().toISOString()
|
timestamp: new Date().toISOString()
|
||||||
|
|||||||
Reference in new issue
Block a user