A Python agent runner puts two tool operations on a queue. The worker handles both, calls task_done() in finally, and the coordinator’s await queue.join() returns. The coordinator reports success.
One operation failed before it did any work.
I would reject a completion check built only around join(). It proves that queue accounting reached zero under the queue’s rules. Your application must establish whether each intended operation succeeded, failed or still has an unknown outcome.
The runnable example below makes that mistake visible without a model, external service or file write. It is a synthetic adapter fixture, not a reported defect in Claude Code or an MCP implementation. Its outcome gate is application code; Python does not supply that policy for you.
Open the diagram at full size.
What task_done tells the queue
Python’s asyncio.Queue.join documentation defines the unfinished-task counter. Adding an item increases it. Calling task_done() decreases it. When it reaches zero, join() unblocks.
There is no success parameter in task_done(). The queue does not inspect an API response, check the destination resource or read your exception log. The worker decides when processing is complete.
This pattern can therefore be reasonable queue housekeeping:
operation = await queue.get()
try:
await execute_tool(operation)
finally:
queue.task_done()
The mistake is promoting the queue acknowledgement into a business outcome. A failed attempt may be fully processed: the worker caught the failure, recorded it and has nothing more to do with that queue item. That does not make the requested operation successful.
Moving task_done() into the success branch is an incomplete repair. It can leave join() waiting forever after a failed attempt unless some other path explicitly settles the accounting. Keep the acknowledgement contract clear, and record the outcome separately. A retry is another attempt with its own lifecycle, not a reason to hide the first failure.
Run a batch that joins after failure
Download and inspect agent-queue-outcomes.py. It uses Python 3.11 or later and only the standard library. It makes no network requests and writes no files.
python3 agent-queue-outcomes.py
python3 agent-queue-outcomes.py --test
python3 -O agent-queue-outcomes.py --test
The fixture freezes a two-operation manifest before starting its worker. The first operation records a synthetic success. The second raises a deliberate ValueError before any effect; the worker catches it and records a failure. Both paths call task_done().
The executed output was:
{
"queue_join_returned": true,
"receipts": [
{"id": "tool-1", "status": "succeeded"},
{"id": "tool-2", "status": "failed"}
],
"release_allowed": false
}
Seven unique regression tests passed on Python 3.11.15, both normally and under optimisation. Besides the failed batch, they check a successful batch, an empty queue with unfinished work, cancellation without a receipt, missing receipts, duplicate or unexpected receipts, and invalid manifests or unknown outcomes. The tests use unittest checks, which remain active under python -O.
The synthetic success record does not prove an external write. A real adapter needs its own evidence contract: for example, a destination readback bound to the requested resource version. The example isolates the coordinator’s decision after receipts exist. It deliberately does not implement a database, durable job store or remote verification protocol.
An empty queue can still have active work
queue.empty() answers whether items remain available to retrieve. A worker removes an item with get() before it finishes processing it. The queue can therefore be empty while the worker is still waiting on a tool.
One regression test puts a single item on the queue, retrieves it, and verifies that empty() is true. It then starts a task awaiting join(). An event confirms that this task has entered the join path; the test verifies that it has not completed. Only after task_done() does the join return.
That separates two quantities an operations dashboard might otherwise collapse:
- Queued items have not yet been retrieved by a worker.
- Unfinished items have not yet received the matching processing acknowledgement.
Neither quantity is a count of successful business operations. Report verified successes and unresolved operations from the outcome records, not by subtracting queue depth from submitted work.
Reconcile the closed batch before releasing it
The fixture’s release gate takes the frozen manifest and the collected receipts:
def release_allowed(expected, receipts):
if not expected or len(set(expected)) != len(expected):
return False
ids = [r["id"] for r in receipts]
return (len(ids) == len(set(ids)) and set(ids) == set(expected)
and all(r["status"] == "succeeded" for r in receipts))
This gate requires exactly one successful receipt for each expected identity. It rejects missing, duplicate and unexpected identities. It also rejects an empty manifest: for this example, doing no work must not produce a successful release. A service that permits valid no-op batches should define that policy explicitly.
The function assumes internally constructed rows with the required fields and string IDs. It is not an input-schema validator, an authentication boundary or a retry reconciler. If receipts arrive from another process, validate their schema and provenance before this check. For retries, retain individual attempt records and derive one reconciled operation outcome according to a documented rule; do not pass repeated attempt rows through a gate that expects one row per operation.
The batch must also be closed. In this fixture, the coordinator enqueues every intended operation before creating the worker. If producers can add more work after join() returns, the coordinator has no stable completion boundary. Stop admission or seal a batch manifest first, then account for that manifest. A live queue’s momentary state cannot define the membership of a release.
This is related to joining evaluation results by case identity. Matching counts is not enough in either case. The outcome must belong to the operation you intended to run.
Cancellation can leave no outcome at all
Another test cancels a worker after it has retrieved its item but before it appends a success receipt. The worker’s finally block acknowledges the queue item. The test observes CancelledError, then awaits join() successfully. The receipt list is empty, so the release gate rejects the batch.
That is why the coordinator must observe worker termination separately from queue accounting. The normal fixture awaits the worker task after joining the queue. A production supervisor also needs a bounded response to workers that crash or never acknowledge their items; blindly waiting on join() can strand the coordinator before it inspects their exceptions.
A cancelled coroutine does not automatically establish the outcome of a remote request it already dispatched. If a tool might have written before cancellation, record an unknown outcome and reconcile against the destination before deciding whether to retry. The thread-timeout example demonstrates a related boundary: stopping the await does not necessarily stop the underlying worker.
There is a further shutdown exception to the usual accounting rule. Python added Queue.shutdown() in 3.13. Its immediate-shutdown documentation warns that shutdown(immediate=True) can unblock a join even when no work has been done on drained items. The fixture runs on 3.11 and does not test that newer method. If your service uses immediate shutdown, preserve the manifest and explicitly reconcile discarded items; do not interpret a released join as processing evidence.
Keep the outcome record outside the queue
For a production runner, persist operation identities and outcomes somewhere that survives worker loss. Define what evidence permits succeeded, what establishes a known failure before an effect, and when the outcome must remain unknown. A process-local list is sufficient for this demonstration and insufficient for crash recovery.
Separate acknowledgement failures from tool failures in your alerts. A queue that never drains needs investigation of worker lifecycle and accounting. A queue that drains with failed or missing receipts needs operation-level recovery. Automatically retrying everything in the second case can duplicate effects whose responses were lost.
For the wider approach to tool boundaries and review, see my Claude Code book, available as a Kindle edition on Amazon UK.
Add a regression case that deliberately fails one operation while still acknowledging every queue item. Require the coordinator to return a failed or unresolved batch, and check the exact operation identity in its recovery record.