An agent tool wraps a blocking SDK call in an async interface. The coordinator sets a deadline, catches TimeoutError and records the operation as stopped. A worker thread can still complete the write after that handler returns.
I would reject stopped as the operation’s status unless the adapter can establish what stopped. Cancelling an async wrapper does not terminate a running executor thread. A useful run record needs to distinguish the caller’s timeout from worker completion and the destination’s final state.
This is a local failure mode. It does not require a remote queue or a server that ignores cancellation. The runnable example below starts a real thread, holds it before a temporary file write, times out its async wrapper, then releases the thread. The file appears after the timeout handler has checked that it does not exist.
Two futures can describe different states
Python’s asyncio.wait_for cancels its awaited operation when the timeout expires and raises TimeoutError. It waits for cancellation of that awaitable, so its elapsed time can exceed the requested timeout. None of that promises termination of a separate thread.
The concurrent.futures.Future.cancel contract is explicit: a call that is already executing cannot be cancelled through that method. It returns False.
An async adapter can therefore have these states at once:
async_wrapper_cancelled: true
thread_running_at_handler: true
thread_cancel_accepted: false
Those values come from different future objects. Reading only the asyncio future gives an incomplete account of the operation.
asyncio.to_thread is useful for running blocking I/O without blocking the event loop. Moving the call to a thread does not make the blocking library cooperatively cancellable. Before wrapping a synchronous client, inspect its own connection and read timeouts, cancellation support and write semantics. An outer timeout cannot supply missing capabilities inside that client.
The fixture uses an explicit ThreadPoolExecutor and asyncio.wrap_future rather than to_thread. This exposes the underlying executor future so the test can inspect it independently and wait for its actual completion. It is a test of the running-thread boundary, not a benchmark of an SDK or a claim that every cancellation happens after a worker starts. Queued work that has not begun is a different case.
Reproduce the write after timeout
Download and inspect agent-thread-timeout.py. It requires Python 3.11 or later and only the standard library. Run it from a directory where temporary fixture files are permitted:
python3 agent-thread-timeout.py
python3 agent-thread-timeout.py --test
python3 -O agent-thread-timeout.py --test
You can select an existing scratch directory with --scratch /path/to/scratch. The fixture creates a temporary subdirectory there, joins its worker and removes the subdirectory before returning. It makes no network or model calls.
The test controls ordering with events. First, the thread reports that it has started. It then waits at a threading.Event, before the write. Only after that start signal does the coordinator apply the short timeout to the async wrapper. The event remains closed until the timeout handler has inspected both futures and the file path.
This avoids guessing whether a thread has started based on a sleep. The 10 ms timeout triggers cancellation; it does not decide which side wins a write race. Separate watchdogs make missing test signals fail visibly.
The executed timeout case returned:
{
"wrapper_state": "timeout",
"async_wrapper_cancelled": true,
"thread_running_at_handler": true,
"thread_cancel_accepted": false,
"effect_at_handler": false,
"worker_result": "committed",
"effect_after_join": true
}
The handler saw no file. After release, the same thread wrote committed to that file. That word is the fixture’s result label: this example does not call fsync or prove crash durability.
Six unique regression tests passed on Python 3.11.15, normally and with optimisation enabled. They check the running thread at timeout, refusal of executor cancellation, the later write, task-group cancellation, a cooperative stop before a checkpoint, and an effect completed before that stop. The tests use unittest checks, which remain active under python -O.
A task group still owns tasks, not thread termination
The earlier agent batch cancellation article showed why a task group is preferable to default gather behaviour when a failing child should cancel related coroutine work. That recommendation has a boundary at a blocking worker.
The new fixture puts a coroutine awaiting the wrapped executor future inside a TaskGroup. A second child raises ValueError. The group cancels the awaiting coroutine and exits with an exception group. At the surrounding handler, the thread is still running. Releasing it produces the file.
This result does not contradict the task-group contract. The group has cancelled and awaited its local tasks. The executor call is separate work that has already started. Replacing gather with TaskGroup cannot add an interrupt mechanism to that call.
Keep a worker handle or a supervised operation record after the request ends. Otherwise the service can lose its ability to observe completion while the worker retains its ability to change state. The fixture retains the executor future and attaches a fresh async wrapper after the first wrapper is cancelled. A production supervisor needs a longer lifetime than the request that timed out, plus a recovery path for process failure.
Cooperative cancellation needs an honest checkpoint
The cooperative variant adds a threading.Event that means stop requested. The timeout handler sets it before releasing the worker. The worker checks that event before writing and returns stop_observed. No file appears in this controlled sequence.
That is a useful behaviour to implement when you own the worker code. It is also a narrower guarantee than “cancellation prevents writes”. There is a gap between checking an event and performing an effect. A request arriving after the check may be too late. The fixture does not close that gap with a transaction or a lock.
Another test writes the file before announcing readiness. The handler subsequently requests a stop, and the worker observes it. The file remains. stop_observed means the worker reached a checkpoint; it does not mean that the worker performed no earlier effects.
For a real adapter, document where checkpoints exist. A stop before dispatch can prevent a request from leaving. A stop while waiting for a response may leave the remote outcome unknown. If a deadline must forbid admission of a write, enforce that decision at the destination’s commit or admission boundary, with the required concurrency controls. A client-side event check alone cannot provide that guarantee.
Record timeout without starting a duplicate write
An operation record can retain caller_outcome=timeout while leaving effect_outcome=unknown. Once a supervisor observes the worker result and verifies the destination, it can update the effect outcome without rewriting the fact that the caller timed out.
Do not immediately schedule a fresh write because the async future says cancelled. The original worker may still be executing. Use the operation’s stable identity and the destination’s documented idempotency or status interface where available. The article on timed-out MCP writes covers that reconciliation path. Today’s local fixture supplies a concrete reason to enter it even before introducing a network service.
Shutdown also needs care. The example joins its executor during cleanup so it leaves no worker behind. That synchronous join is acceptable in this small, bounded test; copying it into a busy event-loop handler would block other requests while the thread finishes. Production shutdown needs a declared waiting policy and a way to retain unresolved operation records. Abandoning the observation is not evidence of stopping the effect.
For the wider approach to bounded tool work and review, see my Claude Code book, available as a Kindle edition on Amazon UK.
Add a controlled blocking worker to your adapter tests. Cancel its async wrapper after the worker has started, then inspect the destination after releasing and joining it. Keep the caller outcome and effect outcome as separate assertions.