From 533e17e0b15ffc9c57deec464e8de446154ccdbd Mon Sep 17 00:00:00 2001 From: ordinary being Date: Sat, 24 Oct 2026 14:32:22 +0800 Subject: [PATCH] fix(swarm): make running-worker cancellation terminal (#4457) cancel() marked a running WorkerDispatchService worker 'cancelled', but executeWorker() later overwrote it with 'completed' and emitted worker:completed when the in-flight executor returned. The caller saw a successful terminal result for work it had cancelled. cancel() also removed the id from the concurrency set immediately, so another worker could start while the cancelled executor was still running, exceeding maxConcurrent.\n\nKeep the slot until the executor settles in finally, and make executeWorker/catch preserve the cancelled state without emitting completed/failed. Pending cancellation also records the terminal timestamp and phase.\n\nRegression uses maxConcurrent=1: it cancels after the first worker starts, queues a second, and asserts the slot is not released before the cancelled executor settles, status/phase stay cancelled, result is undefined, and no completed/failed event is emitted. Baseline fails because the second worker starts immediately; candidate passes. Full swarm suite 353/353 and tsc --noEmit clean. --- .../worker-dispatch-cancellation.test.ts | 71 +++++++++++++++++++ .../swarm/src/workers/worker-dispatch.ts | 29 +++++++- 2 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 v3/@claude-flow/swarm/__tests__/worker-dispatch-cancellation.test.ts diff --git a/v3/@claude-flow/swarm/__tests__/worker-dispatch-cancellation.test.ts b/v3/@claude-flow/swarm/__tests__/worker-dispatch-cancellation.test.ts new file mode 100644 index 0000000000..6689e36a33 --- /dev/null +++ b/v3/@claude-flow/swarm/__tests__/worker-dispatch-cancellation.test.ts @@ -0,0 +1,71 @@ +/** + * Cancelling a running WorkerDispatchService worker must be terminal. + * + * The placeholder executors cannot be aborted mid-flight, so cancel() marks the + * worker cancelled and keeps its concurrency slot until the executor settles. + * Previously executeWorker() unconditionally overwrote the status with + * 'completed' and emitted worker:completed after cancel(), and cancel() + * released the slot immediately so a second worker could exceed maxConcurrent. + */ + +import { describe, expect, it } from 'vitest'; +// Import the TS source explicitly: src/workers/worker-dispatch.js is a stale +// tracked build artifact that would otherwise shadow the implementation. +import { WorkerDispatchService } from '../src/workers/worker-dispatch.ts'; + +describe('WorkerDispatchService running-worker cancellation', () => { + it('keeps a cancelled worker cancelled and does not release its slot early', async () => { + const service = new WorkerDispatchService({ maxConcurrent: 1 }); + const completed: string[] = []; + const failed: string[] = []; + const cancelled: string[] = []; + + service.on('worker:completed', ({ workerId }: { workerId: string }) => completed.push(workerId)); + service.on('worker:failed', ({ workerId }: { workerId: string }) => failed.push(workerId)); + service.on('worker:cancelled', ({ workerId }: { workerId: string }) => cancelled.push(workerId)); + + let firstStartedResolve!: (workerId: string) => void; + const firstStarted = new Promise(resolve => { + firstStartedResolve = resolve; + }); + service.once('worker:started', ({ workerId }: { workerId: string }) => firstStartedResolve(workerId)); + + const sessionId = 'cancel-running-session'; + const firstId = await service.dispatch('ultralearn', 'first', sessionId); + expect(await firstStarted).toBe(firstId); + + const cancelledAt = Date.now(); + expect(await service.cancel(firstId)).toBe(true); + expect(service.getWorker(firstId)?.status).toBe('cancelled'); + + // maxConcurrent is 1. The second worker must not start until the cancelled + // worker's in-flight executor has settled; baseline released the slot in + // cancel() and started this one immediately. + let secondStartedResolve!: (startedAt: number) => void; + const secondStarted = new Promise(resolve => { + secondStartedResolve = resolve; + }); + service.once('worker:started', ({ workerId }: { workerId: string }) => { + if (workerId !== firstId) secondStartedResolve(Date.now()); + }); + + const secondId = await service.dispatch('preload', 'second', sessionId); + const secondDone = new Promise(resolve => { + service.once('worker:completed', ({ workerId }: { workerId: string }) => { + if (workerId === secondId) resolve(); + }); + }); + + const secondStartedAt = await secondStarted; + expect(secondStartedAt - cancelledAt).toBeGreaterThanOrEqual(10); + await secondDone; + + const first = service.getWorker(firstId); + expect(first?.status).toBe('cancelled'); + expect(first?.phase).toBe('cancelled'); + expect(first?.result).toBeUndefined(); + expect(completed).not.toContain(firstId); + expect(failed).not.toContain(firstId); + expect(cancelled).toContain(firstId); + }); +}); diff --git a/v3/@claude-flow/swarm/src/workers/worker-dispatch.ts b/v3/@claude-flow/swarm/src/workers/worker-dispatch.ts index 40d5084239..5f32a3193d 100644 --- a/v3/@claude-flow/swarm/src/workers/worker-dispatch.ts +++ b/v3/@claude-flow/swarm/src/workers/worker-dispatch.ts @@ -500,11 +500,17 @@ export class WorkerDispatchService extends EventEmitter { if (worker.status === 'running') { worker.status = 'cancelled'; + worker.phase = 'cancelled'; worker.completedAt = new Date(); - this.running.delete(workerId); + // Keep the id in `running` until its executor actually settles: the + // placeholder executors cannot be aborted mid-flight, so releasing the + // concurrency slot here would let another worker start while this one is + // still doing work. The finally block in executeWorker() releases it. this.emit('worker:cancelled', { workerId }); } else if (worker.status === 'pending') { worker.status = 'cancelled'; + worker.phase = 'cancelled'; + worker.completedAt = new Date(); this.queue = this.queue.filter(q => q.id !== workerId); this.emit('worker:cancelled', { workerId }); } @@ -608,6 +614,14 @@ export class WorkerDispatchService extends EventEmitter { // Execute based on trigger type const result = await this.executeWorkerByTrigger(worker); + // cancel() may have marked this worker while its executor was in + // flight. Never overwrite that terminal state with 'completed' or emit a + // second terminal event for a worker the caller already cancelled. + if (this.isCancelled(worker)) { + worker.phase = 'cancelled'; + return; + } + worker.status = 'completed'; worker.completedAt = new Date(); worker.result = result; @@ -620,6 +634,11 @@ export class WorkerDispatchService extends EventEmitter { duration: worker.completedAt.getTime() - worker.startedAt.getTime(), }); } catch (error) { + if (this.isCancelled(worker)) { + worker.phase = 'cancelled'; + return; + } + worker.status = 'failed'; worker.completedAt = new Date(); worker.error = error as Error; @@ -1054,6 +1073,14 @@ export class WorkerDispatchService extends EventEmitter { return `worker_${trigger}_${++this.idCounter}_${Date.now().toString(36)}`; } + /** + * Read cancellation through a helper so TypeScript does not narrow the + * status to 'running' across the executor await; cancel() can mutate it. + */ + private isCancelled(worker: WorkerInstance): boolean { + return worker.status === 'cancelled'; + } + private getPriorityValue(priority: 'low' | 'normal' | 'high' | 'critical'): number { const priorities = { low: 1, normal: 2, high: 3, critical: 4 }; return priorities[priority];