From d517cae7e6f8955499103ebcd7e6ffde01c89e1d Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Mon, 23 Nov 2026 00:04:06 -0500 Subject: [PATCH] Fix orphaned quick commands, prompt timeouts and worker delete (#6, #21, #34) - #6: a quick command to a disconnected worker is refused before an execution is recorded, instead of leaving one stuck in 'running'. - #21: an unanswered prompt fails the execution (prompt_timeout) instead of continuing as if someone had chosen; prompt and wait steps never wait past the execution's deadline, and a wait cut short by it fails with execution_timeout. PULSE_PROMPT_TIMEOUT_MS (minimum 1 s, default 60 min) lets the test stack use 8 s. - #34: deleting a connected worker is a 409 explaining it would re-register on its next heartbeat; offline workers delete as before. Tests for each (integration 45/45). Co-Authored-By: Claude Opus 5.5 --- scripts/ci/ui-stack.sh | 1 + server.js | 57 ++++++++++++++++++++++------ tests/integration/reliability.int.js | 26 +++++++++++++ tests/integration/workflows.int.js | 12 ++++++ 4 files changed, 85 insertions(+), 11 deletions(-) diff --git a/scripts/ci/ui-stack.sh b/scripts/ci/ui-stack.sh index da4aa84..b979f1e 100755 --- a/scripts/ci/ui-stack.sh +++ b/scripts/ci/ui-stack.sh @@ -26,6 +26,7 @@ export GANDALF_API_KEY=ui-test-gandalf-key export SECRET_KEY=ui-test-secret EXECUTION_RETENTION_DAYS=30 export PULSE_API_RATE_MAX=100000 PULSE_EXEC_RATE_MAX=100000 # one test client makes many requests export PULSE_SCHEDULER_TICK_MS=1000 # scheduler tests shouldn't wait a minute +export PULSE_PROMPT_TIMEOUT_MS=8000 # nor prompt-timeout tests an hour stop() { for f in "$RUN"/*.pid; do diff --git a/server.js b/server.js index f8488ff..8b813da 100644 --- a/server.js +++ b/server.js @@ -98,6 +98,12 @@ const executionLimiter = rateLimit({ // Named constants for timeouts and limits const PROMPT_TIMEOUT_MS = 60 * 60 * 1000; // 60 min: how long a prompt waits for user input +// Tests shorten it (minimum 1 s); production keeps the default above. +const PROMPT_TIMEOUT_EFFECTIVE_MS = (() => { + const v = parseInt(process.env.PULSE_PROMPT_TIMEOUT_MS, 10); + return Number.isInteger(v) && v >= 1000 ? v : PROMPT_TIMEOUT_MS; +})(); +const PROMPT_TIMED_OUT = Symbol('prompt timed out'); const COMMAND_TIMEOUT_MS = 120_000; // 2 min: workflow step command timeout const QUICK_CMD_TIMEOUT_MS = 60_000; // 1 min: quick/direct/gandalf command timeout const WEBHOOK_TIMEOUT_MS = 10_000; // 10 s: outbound webhook HTTP timeout @@ -1033,7 +1039,17 @@ async function executeWorkflowSteps(executionId, workflowId, definition, usernam } } else if (step.type === 'prompt') { - const response = await executePromptStep(executionId, step, currentIndex + 1); + const response = await executePromptStep(executionId, step, currentIndex + 1, executionDeadline); + if (response === PROMPT_TIMED_OUT) { + // Unanswered: fail rather than carry on as if someone had chosen (#21). + await addExecutionLog(executionId, { + step: currentIndex + 1, step_name: stepLabel, action: 'prompt_timeout', + message: 'Nobody answered the prompt in time', + timestamp: new Date().toISOString() + }); + await updateExecutionStatus(executionId, 'failed'); + return; + } if (response !== null) { execState.state[step.key || 'lastPrompt'] = response; execState.state.promptResponse = response; // backwards compat @@ -1051,7 +1067,18 @@ async function executeWorkflowSteps(executionId, workflowId, definition, usernam step: currentIndex + 1, action: 'waiting', duration_ms: ms, timestamp: new Date().toISOString() }); - await abortableDelay(ms, execState.abort && execState.abort.signal); + // Never wait past the execution's deadline (#21). + const remaining = executionDeadline - Date.now(); + await abortableDelay(Math.max(0, Math.min(ms, remaining)), execState.abort && execState.abort.signal); + if (ms > remaining && !(execState.abort && execState.abort.signal.aborted)) { + await addExecutionLog(executionId, { + action: 'execution_timeout', + message: `Execution exceeded maximum runtime of ${maxMinutes} minutes during a wait step`, + timestamp: new Date().toISOString() + }); + await updateExecutionStatus(executionId, 'failed'); + return; + } } else if (step.type === 'parse') { // Parse KEY=VALUE lines from last command output into execution state. @@ -1141,7 +1168,7 @@ async function executeWorkflowSteps(executionId, workflowId, definition, usernam // Pause execution and wait for user to respond via POST /api/executions/:id/respond. // Resolves with the chosen option string, or null on 60-minute timeout. -async function executePromptStep(executionId, step, stepNumber) { +async function executePromptStep(executionId, step, stepNumber, deadline = Infinity) { const execState = _executionState.get(executionId); // Apply param substitution to the message so {{server_name}}, {{iface}} etc. work let message = step.message || 'Please choose an option:'; @@ -1167,11 +1194,13 @@ async function executePromptStep(executionId, step, stepNumber) { }); return new Promise(resolve => { + // Never wait past the execution's own deadline (#21). + const ms = Math.max(0, Math.min(PROMPT_TIMEOUT_EFFECTIVE_MS, deadline - Date.now())); const timer = setTimeout(() => { _executionPrompts.delete(executionId); console.warn(`[Workflow] Prompt timed out for execution ${executionId}`); - resolve(null); - }, PROMPT_TIMEOUT_MS); + resolve(PROMPT_TIMED_OUT); + }, ms); _executionPrompts.set(executionId, { resolve: (response) => { @@ -2053,6 +2082,11 @@ app.delete('/api/workers/:id', authenticateSSO, async (req, res) => { if (!req.user.isAdmin) { return res.status(403).json({ error: 'Admin access required' }); } + // A connected worker would re-register on its next heartbeat (#34). + const live = workers.get(req.params.id); + if (live && live.readyState === WebSocket.OPEN) { + return res.status(409).json({ error: 'Worker is connected. Stop its service first; otherwise it re-registers on its next heartbeat.' }); + } await pool.query('DELETE FROM workers WHERE id = ?', [req.params.id]); res.json({ success: true }); @@ -2069,8 +2103,14 @@ app.post('/api/workers/:id/command', authenticateSSO, requireJSON, async (req, r if (!command || typeof command !== 'string' || !command.trim()) { return res.status(400).json({ error: 'command is required' }); } - const executionId = crypto.randomUUID(); const workerId = req.params.id; + // Check the worker before recording anything, so an offline worker doesn't leave + // an execution stuck in 'running' (#6). + const workerWs = workers.get(workerId); + if (!workerWs || workerWs.readyState !== WebSocket.OPEN) { + return res.status(400).json({ error: 'Worker not connected' }); + } + const executionId = crypto.randomUUID(); // Create execution record in database await pool.query( @@ -2093,11 +2133,6 @@ app.post('/api/workers/:id/command', authenticateSSO, requireJSON, async (req, r timeout: QUICK_CMD_TIMEOUT_MS }; - const workerWs = workers.get(workerId); - if (!workerWs || workerWs.readyState !== WebSocket.OPEN) { - return res.status(400).json({ error: 'Worker not connected' }); - } - sendCommandToWorker(workerWs, commandMessage); console.log(`Command sent to worker ${workerId}: ${command}`); diff --git a/tests/integration/reliability.int.js b/tests/integration/reliability.int.js index a3c0411..03b6425 100644 --- a/tests/integration/reliability.int.js +++ b/tests/integration/reliability.int.js @@ -90,3 +90,29 @@ test('aborting a command kills its process on the worker (#8)', async () => { expect((await waitForExecution(id)).status).toBe('failed'); } finally { await w.stop(); } }); + +test('a quick command to an offline worker is refused without leaving a running execution (#6)', async () => { + const mysql = require('mysql2/promise'); + const marker = `offline-${unique()}`; + const w = await startWorker(unique()); + w.child.kill('SIGKILL'); + try { + await waitFor(async () => (await sso('POST', `/api/workers/${w.id}/command`, { command: `echo ${marker}` })).status === 400, + { timeout: 5000, what: 'the server to notice the worker is gone' }); + const db = await mysql.createConnection({ + host: process.env.DB_HOST || '127.0.0.1', port: Number(process.env.DB_PORT || 3306), + user: process.env.DB_USER || 'pulse', password: process.env.DB_PASSWORD || 'ci-only', database: process.env.DB_NAME || 'pulse', + }); + try { + const [rows] = await db.query('SELECT id FROM executions WHERE logs LIKE ?', [`%${marker}%`]); + expect(rows).toEqual([]); + } finally { await db.end(); } + } finally { await w.stop(); } +}); + +test('a connected worker cannot be deleted; it would re-register on its next heartbeat (#34)', async () => { + const node1 = await workerByName('node-01'); + const r = await sso('DELETE', `/api/workers/${node1.id}`); + expect(r.status).toBe(409); + expect((await workerByName('node-01'))?.id).toBe(node1.id); +}); diff --git a/tests/integration/workflows.int.js b/tests/integration/workflows.int.js index 7aa83ce..924ae1e 100644 --- a/tests/integration/workflows.int.js +++ b/tests/integration/workflows.int.js @@ -204,3 +204,15 @@ test('abort during a long command stops the workflow at once, without waiting fo expect(logs(ex, 'step_started').map(l => l.step)).toEqual([1]); expect(Date.now() - t0).toBeLessThan(10_000); }); + +test('an unanswered prompt fails the execution instead of continuing (#21)', async () => { + // The test stack sets PULSE_PROMPT_TIMEOUT_MS=8000. + const id = await start(await createWorkflow([ + { id: 'ask', type: 'prompt', message: 'Anyone there?', options: ['Yes'] }, + { id: 'after', type: 'execute', command: 'echo continued', targets: ['node-01'] }, + ])); + const ex = await waitForExecution(id, { timeout: 20_000 }); + expect(ex.status).toBe('failed'); + expect(logs(ex, 'prompt_timeout')).toHaveLength(1); + expect(outputs(ex)).toEqual([]); +});