﻿# asyncio wait_for can outlast its timeout during cancellation

wait_for cancels the awaited operation and waits for cancellation to finish. Cleanup duration and cancellation exceptions need their own outcome accounting.

Author: Retrivium team
Updated: 2026-11-06
Canonical URL: https://retrivium.ai/journal/asyncio-wait-for-cancellation-cleanup-duration/
Language: en

## The timer expired but the await has not returned

A service wraps a tool coroutine in asyncio.wait_for and expects control to return exactly at the configured duration. The coroutine begins cancellation cleanup and continues awaiting resource release. The wrapper can remain pending beyond the nominal timeout.

The [task reference](https://docs.python.org/3/library/asyncio-task.html) explicitly says wait_for waits until the future is actually canceled. Its timeout is therefore not a guarantee of instantaneous worker or connection release at a hard wall-clock boundary.

## Separate the lifecycle events

Record operation start, timeout-triggered cancellation, cleanup start, final task outcome and resource release. These events answer different questions. Measuring only the caller-visible return hides the interval in which cancellation is being processed.

Preserve the actual task and ownership relationship. A coroutine calling a remote tool can stop local waiting without proving that the remote side rolled back work. Resource cleanup should not overwrite the operation's uncertain external outcome with a generic canceled label.

## Handle exceptions during cancellation

The task reference states that exceptions raised during cancellation can propagate. A handler that assumes every timeout-shaped path raises only TimeoutError can lose cleanup failures or misclassify them as a new independent request error.

The inspected [timeout implementation](https://raw.githubusercontent.com/python/cpython/main/Lib/asyncio/timeouts.py) shows cancellation and exception translation as explicit state handling. Check the deployed Python contract rather than relying on an assumption that cancellation is an unobservable jump directly to the caller's timeout handler.

## Do not change waiting semantics accidentally

The reference distinguishes wait_for from wait, which returns pending tasks on timeout without canceling them. Shield can also change whether the underlying work is canceled. These choices are policies about continued execution, not interchangeable ways to improve timeout precision.

If continued work is intentional, retain an owner responsible for its later outcome and resource release. If cancellation is required, validate cleanup behavior. Simply selecting a primitive that returns earlier can create orphaned work while making the visible timer look more accurate.

## Acceptance with a cleanup fixture

Use an isolated coroutine with a known cancellation-cleanup phase and another whose cleanup raises an exception. Observe final outcomes and resource ownership, without depending on exact scheduler timing. Include a bounded remote-effect fixture if the real tool performs externally visible operations.

[Deadline and cancellation propagation](/journal/guide-grpc-deadline-hop/) explains the downstream boundary. [Accepted-work shutdown](/journal/provider-graceful-termination-active-streams/) explains why remaining cleanup must fit the service's broader termination policy.

## Define the protected objective

Accept the design when it states whether the objective bounds useful execution, caller waiting or total cleanup, and the chosen mechanism actually supports that objective. A separate supervisor may be needed for stronger containment, with its own partial-work policy. Preserve the first operation failure, cleanup errors and unresolved effects so a timeout is not mistaken for proof that every resource and remote action ended at the same instant.
