Study guides · Intermediate

Separate cancellation delivery from cleanup ownership

Fix cancellation at an explicit Event boundary and inspect child completion, finally cleanup and retained evidence of sent effects.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Stopping a wait does not undo a job
  2. Deliver cancellation at a cooperative boundary
  3. Protect the owned interval with finally
  4. Await the canceled task’s termination
  5. Recover external outcomes with a separate protocol
  6. Own child lifetimes and exception destinations
  7. Follow ownership while acquisition itself is cancelable
  8. Retain cleanup failures as distinct outcomes
  9. Exercise: describe the exact cancellation stage
  10. Ask Logeia about this articleCheck your understanding

Stopping a wait does not undo a job

When an order request reaches a deadline, a caller can stop waiting even though the order may already have reached its destination. Task cancellation, release of local resources and reversal of an external side effect are different events. Building on deadline propagation, this guide follows one task's lifetime and cleanup. A cancellation exception is not a reason to erase evidence that work was accepted or sent.

The asyncio example uses an owned-resource set and a separate sent-order list. It sends no real network request. Cancellation triggers finally and removes local ownership while the sent record remains. This combines actual task cancellation with a modeled business effect; it is not an experiment undoing external payment. Declare which events are real and which are represented by local state before interpreting the result.

Deliver cancellation at a cooperative boundary

Calling cancel requests cancellation; it is not identical to completed task termination. A CPU loop that never returns control to the event loop does not provide the same prompt cooperative boundary. Distinguish the request time from actual completion and do not announce resources released merely because cancel was called.

The example waits at an asyncio Event. The parent first awaits a separate acquired marker proving that the child holds its local resource and recorded the send. Only then does it cancel. A fixed sleep is not used to guess acquisition. Separating the stage marker from the business-release event makes the injection point reproducible. A bounded readiness wait fails the test if the intended stage is never reached, instead of silently canceling at a different point.

Protect the owned interval with finally

After acquiring a resource, place its owned interval inside try and release it in finally. Cancellation at an await or another exception can then follow the same cleanup path. Cleanup before ownership was established could instead release an unowned resource, so identify exactly when acquisition succeeded. The set insertion models that transition here and protection begins immediately afterward.

Asynchronous cleanup introduces further cancellation and deadline questions while release itself awaits. Shielding can be useful only with a clear owner and completion-wait policy; discarding exceptions in an invisible background task is not guaranteed cleanup. The example deliberately uses a synchronous set removal to keep the lifetime boundary visible. It directly asserts that the acquired local ownership has been removed once rather than claiming to solve every asynchronous release protocol.

Stageownedsent
Before acquisitionEmptyEmpty
At acquired eventOwns connectionRecords order-7
After cancellation and awaitEmpty after finallyorder-7 remains

Await the canceled task’s termination

After cancel, the parent awaits the task and handles CancelledError at that boundary. It then checks that finally removed local ownership, that order-7 remains in the sent list and that the task reports canceled. The example does not launch cancellation and abandon the child without collecting its lifetime. Task creation and completion ownership are treated as a pair.

asyncio.run provides the short test's entry and exit using only the standard library and no connection credentials. Output identifies three conditions: task cancellation, local release and retained send evidence. It does not inspect a remote order count or stop another process. Keep locally observed state distinct from the external world's state rather than combining both into one unqualified success message.

python
import asyncio
async def main():
    acquired=asyncio.Event();release=asyncio.Event();owned=set();sent=[]
    async def request():
        owned.add('connection')
        try:
            sent.append('order-7');acquired.set();await release.wait()
        finally:owned.remove('connection')
    task=asyncio.create_task(request());await asyncio.wait_for(acquired.wait(),2)
    task.cancel()
    try:await task
    except asyncio.CancelledError:pass
    assert not owned and sent==['order-7'] and task.cancelled()
    print('task cancelled; local connection released; sent order still recorded')
asyncio.run(main())

Recover external outcomes with a separate protocol

Cancellation while awaiting an order response can leave its remote outcome unknown. Closing a connection does not automatically roll back an accepted remote update. Querying by operation ID, retrying with the same identity or applying business compensation are separate recovery procedures connected to the earlier distributed-systems materials.

A retry task also needs rules for carrying the original identity, deadline and unresolved status forward. Creating a new operation ID every time can duplicate an order whose prior success became invisible to the caller. Finally cleans up local ownership; it does not erase committed external effects. Explain which stage can actually be canceled and which stage instead requires outcome reconciliation. An exception class in one process is not a complete business-state description.

Own child lifetimes and exception destinations

A request that creates children must decide whether any may outlive it. Structured waiting mechanisms make child completion and failures easier to manage within one scope. That task-lifetime structure still does not roll back already emitted business effects. Concurrency structure and transaction boundaries solve different ownership problems.

Swallowing CancelledError and continuing as if nothing happened can interfere with the caller's shutdown expectations. If cleanup intercepts cancellation, follow the runtime contract for propagation and state management. Converting normal completion, cancellation, business failure and cleanup failure into the same empty result hides what should be retried or investigated. The small example handles cancellation in the parent and finishes by explicitly checking remaining ownership and evidence.

Follow ownership while acquisition itself is cancelable

Cancellation during acquisition requires the acquisition API's rule for whether ownership was ever transferred. Do not release an unowned resource, and define who returns a lease when cancellation races with a grant. One unconditional cleanup path can otherwise double-return a permit or lose a newly granted resource.

The example makes ownership addition synchronous and begins try immediately afterward. It does not verify every race of a real asynchronous pool acquisition. When moving to an async context manager, inspect exactly what its entry and exit guarantee. An extension should expose waiting, acquired and returned stage markers so cancellation timing is reproducible. The model's simplification is not evidence for an unseen API. Correct cleanup begins with a precise ownership-transfer event, not only with adding the word finally somewhere after an await.

Retain cleanup failures as distinct outcomes

If release itself raises, define how the cleanup failure relates to the original cancellation. Silently converting both into an empty normal result can hide a still-retained resource. Observe business outcome, task termination and ownership release separately because one may succeed while another fails.

Cleanup involving external communication introduces another deadline and retry owner. If the original parent no longer waits, identify who supervises that recovery work and decides it failed. The set-removal example performs no such communication and injects no cleanup failure. Add that path as a new test when extending the implementation rather than inheriting coverage from the ordinary canceled run. Following both the child lifetime and any remaining recovery lifetime makes the cancellation policy inspectable even after the initiating request is gone.

Exercise: describe the exact cancellation stage

For cancellation after acquisition and send recording but while awaiting a response, three outcomes are expected: the task ends canceled, local ownership is released and the send record remains. Retained send evidence does not by itself mean cleanup failed. Released ownership likewise does not mean the remote effect disappeared. Each result describes a different boundary.

Extend the table to cancellation before acquisition, immediately after acquisition, after sending and after receiving a response. Before acquisition there may be nothing to release; after sending there may be an unresolved external result. Move an explicit stage Event in the test and confirm the intended boundary before cancellation. Do not tune sleeps to obtain a convenient accidental order. Keep stage evidence and assertions tied to the lifecycle contract.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Build your CS foundations · STEP 17

Understand the systems behind the web · STEP 7

Prepare for AI systems · STEP 7

Choose a learning path