Cancel a long-running agent without leaving orphan work
In this article (5 sections)
Closing a browser tab does not necessarily stop workers, tool calls or scheduled jobs. Cancellation needs an explicit signal, cleanup and durable final state.
Execute cleanup locally
The agent controls lab starts with a running worker and held temporary lock.
from agent_cases import cancellation_case
result = cancellation_case()
assert result["status"] == "cancelled"
assert result["orphan_resources"] == []
assert result["resources"]["temporary_lock"] == "released"
assert result["external_write_started"] is FalseThe simulation cancels the worker and releases the lock before any write. It does not cancel a real remote task.
Propagate and acknowledge cancellation
Use a run-level token checked between steps and passed to cancellable dependencies. Stop scheduling new work, cancel children, release leases and save completed/unfinished steps. Define a maximum cancellation latency.
Some external operations cannot be cancelled. Record uncertain status, query their receipt and apply compensation or human review rather than assuming rollback. Never erase evidence of already completed side effects.
Test race conditions
Cancel before a call, during a read, while approval is pending and immediately after a write acknowledgement. Verify idempotency, cleanup and one terminal transition. Reap expired leases from crashed workers.
The Generative & Agentic AI course connects cancellation to checkpoints, partial-completion runbooks and observability.
Exercise
Create a workflow with parallel reads and one gated write. Cancel at every boundary, prove no orphan tasks or new writes, and document handling of an uncertain remote outcome.
Continue learning
This article is part of the Agent workflows and state sequence. Use the neighbouring tasks when you need the prerequisite or the next application.
- Review the prerequisite or neighbouring task in Human approval gates: what happens while approval is pending.
- Continue with Tool errors: distinguish retryable and permanent failures.
Reference: Python asyncio task cancellation.
Pankit Kumar has 10 years in Data Science & AI, building and shipping production systems in regulated pharma and clinical environments. He is a freelance trainer at Boston Institute of Analytics, AnalytixLabs and Scaler, and has taught this material to thousands of working professionals.
This article is part of our Generative & Agentic AI programme — 3 months. Add practical GenAI, retrieval and agent-building skills to your existing toolkit.
Explore Generative & Agentic AI