bug: cancel_task does not kill CLI subprocess (process keeps running)
Description
When a background task is cancelled via cancel_task.py, the asyncio task is properly cancelled but the underlying CLI subprocess (claude) is not killed. The process continues running and consuming resources (GPU, API tokens).
Steps to reproduce
- Create a long-running background task (e.g. generating 12 music tracks)
- Cancel it via
python3 tools/task_tools/cancel_task.py TASK_ID - Observe that the task status changes to "cancelled" in the registry
- Check
ps aux | grep claude— the CLI subprocess is still running
Root cause
In tasks/hub.py, the cancel() method (line ~293) calls inflight.asyncio_task.cancel(), which raises CancelledError in the _run() coroutine. The except CancelledError handler (line ~463) updates the task status to "cancelled" but does not kill the subprocess.
In cli/executor.py, the streaming generator's finally block (line ~179) only cancels the stderr drain and unregisters the tracked process — it does not call force_kill_process_tree(). The force_kill_process_tree() is only called in the except TimeoutError path.
Impact
- Zombie CLI processes consume API tokens and system resources
- If a new task is started immediately after cancel (e.g. to reuse GPU), the old and new processes compete for the same resources
- In our case, the old agent detected the conflict, overwrote the new task's script with a BLOCKED stub, and killed the new process via SIGTERM
Suggested fix
Option A: In hub.py:_run(), the except CancelledError block should retrieve the subprocess PID from the process registry and call force_kill_process_tree().
Option B: In cli/executor.py, the finally block of _stream_subprocess() should detect CancelledError and kill the subprocess before cleanup:
finally:
# Kill subprocess if we were cancelled
if process.returncode is None:
force_kill_process_tree(process.pid)
await process.wait()
await _cancel_drain(stderr_drain)
if tracked and reg:
reg.unregister(tracked)
Option B is cleaner because it handles cancellation at the subprocess level regardless of who triggered it.
Environment
- Ductor v0.15.x (installed via uv)
- macOS (Darwin 25.4.0)
- Claude CLI as backend
Fixed in v0.16.0 (commit 8a1e6d8).
Added ProcessRegistry.kill_for_task(task_id) that mirrors kill_stale semantics (SIGTERM → 2s grace → SIGKILL → reap, whole process tree). TaskHub.cancel / cancel_all now call it before asyncio_task.cancel() — the order matters because cli.execute was blocked on the subprocess pipe and CancelledError couldn't propagate until the pipe closed. Real-subprocess regression test spawns sleep 30, calls kill_for_task, asserts exit within 3 seconds. A follow-up fix (same release) also makes exit code 143/137 classify as cancelled in /tasks instead of failed, so the UX matches intent.