Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(headless): cancel settles the execution, deadline timer cleared, escalation keys off exit (#4463) (#4466)

rUv075503c34eaa
diff --git a/v3/@claude-flow/cli/__tests__/headless-executor-cancel-4463.test.ts b/v3/@claude-flow/cli/__tests__/headless-executor-cancel-4463.test.ts
new file mode 100644
index 0000000000..f33978789b
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/headless-executor-cancel-4463.test.ts
@@ -0,0 +1,92 @@
+/**
+ * Regression guard for ruvnet/ruflo#4463 (HeadlessWorkerExecutor.executeClaudeCode).
+ * 1. cancel() must settle the execution promise and escalate to SIGKILL.
+ * 2. The fallback deadline timer must not outlive the child.
+ * 3. SIGKILL escalation keys off "child exited", not `child.killed`
+ * (which only means a signal was delivered).
+ * Uses a fake child and fake timers; no CLI is launched and no real signal is sent.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+const fake = vi.hoisted(() => ({ child: null as any }));
+vi.mock('child_process', async (orig) => {
+ const actual = await orig<typeof import('child_process')>();
+ return { ...actual, spawn: vi.fn(() => fake.child) };
+});
+
+import { HeadlessWorkerExecutor } from '../src/services/headless-worker-executor.js';
+
+function makeChild() {
+ const child: any = new EventEmitter();
+ child.pid = 12345;
+ child.killed = false;
+ child.exitCode = null;
+ child.signalCode = null;
+ child.stdin = { end() {} };
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn(() => { child.killed = true; return true; });
+ return child;
+}
+
+describe('#4463 — HeadlessWorkerExecutor cancel / timers / escalation', () => {
+ let signals: Array<[number, string]>;
+ let killSpy: any;
+ let exec: any;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ fake.child = makeChild();
+ signals = [];
+ killSpy = vi.spyOn(process, 'kill').mockImplementation(((pid: number, sig: string) => { signals.push([pid, sig]); return true; }) as any);
+ exec = new HeadlessWorkerExecutor('/tmp/ruflo-4463-nonexistent');
+ });
+
+ afterEach(() => {
+ killSpy.mockRestore();
+ vi.useRealTimers();
+ });
+
+ const run = (timeoutMs = 10_000) =>
+ exec.executeClaudeCode('p', { sandbox: 'strict', model: 'haiku', timeoutMs, executionId: 'e1', workerType: 'audit' });
+
+ it('cancel() settles the promise and SIGKILLs a child that ignores SIGTERM', async () => {
+ const p = run();
+ expect(exec.cancel('e1')).toBe(true);
+ const r = await p; // must not hang
+ expect(r.success).toBe(false);
+ expect(r.error).toMatch(/cancel/i);
+ expect(signals.map((s) => s[1])).toEqual(['SIGTERM']);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(signals.map((s) => s[1])).toEqual(['SIGTERM', 'SIGKILL']);
+ });
+
+ it('cancel() does not SIGKILL a child that exited after SIGTERM', async () => {
+ const p = run();
+ exec.cancel('e1');
+ fake.child.exitCode = 0;
+ fake.child.emit('close', 0);
+ await p;
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(signals.map((s) => s[1])).toEqual(['SIGTERM']);
+ });
+
+ it('clears the fallback deadline timer once the child closes', async () => {
+ const p = run();
+ fake.child.exitCode = 0;
+ fake.child.emit('close', 0);
+ await p;
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('timeout escalation sends exactly one SIGTERM then SIGKILL while the child has not exited', async () => {
+ const p = run(1_000);
+ // A signal was delivered (killed=true) but the child has not exited.
+ fake.child.killed = true;
+ await vi.advanceTimersByTimeAsync(1_000);
+ await vi.advanceTimersByTimeAsync(5_000);
+ await p;
+ expect(signals.map((s) => s[1])).toEqual(['SIGTERM', 'SIGKILL']);
+ });
+});
diff --git a/v3/@claude-flow/cli/src/services/headless-worker-executor.ts b/v3/@claude-flow/cli/src/services/headless-worker-executor.ts
index 54c53603ba..32c66f6f63 100644
--- a/v3/@claude-flow/cli/src/services/headless-worker-executor.ts
+++ b/v3/@claude-flow/cli/src/services/headless-worker-executor.ts
@@ -213,6 +213,8 @@ interface PoolEntry {
workerType: HeadlessWorkerType;
startTime: Date;
timeout: NodeJS.Timeout;
+ /** #4463 — settles the execution promise, signals the tree and escalates to SIGKILL. Idempotent. */
+ abort?: () => void;
}
/**
@@ -857,7 +859,11 @@ export class HeadlessWorkerExecutor extends EventEmitter {
}
clearTimeout(entry.timeout);
- this.killEntryTree(entry.process, 'SIGTERM');
+ if (entry.abort) {
+ entry.abort();
+ } else {
+ this.killEntryTree(entry.process, 'SIGTERM');
+ }
this.processPool.delete(executionId);
this.emit('cancelled', { executionId });
@@ -877,11 +883,16 @@ export class HeadlessWorkerExecutor extends EventEmitter {
const entries = Array.from(this.processPool.entries());
for (const [executionId, entry] of entries) {
clearTimeout(entry.timeout);
- this.killEntryTree(entry.process, 'SIGTERM');
- // SIGKILL fallback after 5s to prevent orphan processes (#1395 Bug 6)
- setTimeout(() => {
- try { if (!entry.process.killed) this.killEntryTree(entry.process, 'SIGKILL'); } catch { /* already dead */ }
- }, 5000).unref();
+ if (entry.abort) {
+ // Settles the promise and owns the SIGTERM -> SIGKILL escalation (#4463).
+ entry.abort();
+ } else {
+ this.killEntryTree(entry.process, 'SIGTERM');
+ // SIGKILL fallback after 5s to prevent orphan processes (#1395 Bug 6)
+ setTimeout(() => {
+ try { if (entry.process.exitCode === null && entry.process.signalCode === null) this.killEntryTree(entry.process, 'SIGKILL'); } catch { /* already dead */ }
+ }, 5000).unref();
+ }
this.emit('cancelled', { executionId });
cancelled++;
}
@@ -1417,16 +1428,30 @@ Analyze the above codebase context and provide your response following the forma
try { child.kill(signal); } catch { /* already dead */ }
};
+ // #4463 — `child.killed` only means a signal was delivered, not that the
+ // child exited, so escalation keys off the exit state instead.
+ const hasExited = () => child.exitCode !== null || child.signalCode !== null;
+ let escalationHandle: NodeJS.Timeout | undefined;
+ let deadlineHandle: NodeJS.Timeout | undefined;
+ const terminate = () => {
+ if (escalationHandle) return; // already signalled; never repeat SIGTERM
+ killTree('SIGTERM');
+ // Give it a moment to terminate gracefully, then force it.
+ escalationHandle = setTimeout(() => {
+ if (!hasExited()) killTree('SIGKILL');
+ }, 5000);
+ };
+ const stopTimers = () => {
+ clearTimeout(escalationHandle);
+ clearTimeout(deadlineHandle);
+ };
+ child.once('exit', () => clearTimeout(escalationHandle));
+ child.once('close', stopTimers);
+
// Setup timeout
const timeoutHandle = setTimeout(() => {
if (this.processPool.has(options.executionId)) {
- killTree('SIGTERM');
- // Give it a moment to terminate gracefully
- setTimeout(() => {
- if (!child.killed) {
- killTree('SIGKILL');
- }
- }, 5000);
+ terminate();
}
}, options.timeoutMs);
@@ -1446,9 +1471,18 @@ Analyze the above codebase context and provide your response following the forma
const cleanup = () => {
clearTimeout(timeoutHandle);
+ clearTimeout(deadlineHandle);
this.processPool.delete(options.executionId);
};
+ poolEntry.abort = () => {
+ if (resolved) return;
+ resolved = true;
+ terminate();
+ cleanup();
+ resolve({ success: false, output: stdout || stderr, error: 'Execution cancelled' });
+ };
+
child.stdout?.on('data', (data: Buffer) => {
const chunk = data.toString();
stdout += chunk;
@@ -1502,12 +1536,14 @@ Analyze the above codebase context and provide your response following the forma
});
// Handle timeout
- setTimeout(() => {
+ deadlineHandle = setTimeout(() => {
if (resolved) return;
if (!this.processPool.has(options.executionId)) return;
resolved = true;
- killTree('SIGTERM');
+ // Normally a no-op: the timeout handler above already signalled the
+ // tree and owns the SIGKILL escalation (no duplicate SIGTERM).
+ terminate();
cleanup();
resolve({