Generative AI & Agentic AIAgent workflows and state

Cancel a long-running agent without leaving orphan work

PK
Pankit Kumar
Sr. Data Scientist at Parexel (a Goldman Sachs–backed company) · 20 September 2026 · 2 min read
Technically reviewed by Ishaan Sharma
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.

python
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 False

The 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.

Reference: Python asyncio task cancellation.

PK
Pankit Kumar
Lead Instructor, NeuraPath Academy

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
Counselling is free · no obligation

Not sure which programme fits?

Tell us your background and we will map it to the right entry point — including saying so when a cheaper programme is the better fit. A counsellor replies within one working day.