Skip to content

queues, locks: Put the item or permit back when a waiter is cancelled - #3947

Open
StrikeRougeAgent wants to merge 2 commits into
tornadoweb:masterfrom
StrikeRougeAgent:fix/2826-cancelled-waiter-handoff
Open

StrikeRougeAgent wants to merge 2 commits into
tornadoweb:masterfrom
StrikeRougeAgent:fix/2826-cancelled-waiter-handoff

Conversation

@StrikeRougeAgent

Copy link
Copy Markdown

Fixes #2826.

The bug

Queue.put_nowait() hands an item to a waiting getter by taking it out of the queue and setting the getter's result:

getter = self._getters.popleft()
self.__put_internal(item)
future_set_result_unless_cancelled(getter, self._get())

If the task awaiting that getter is cancelled before it can return the item — a task whose waiter future is already done — the item is lost. It stays in _unfinished_tasks, so Queue.join() never completes. Semaphore.acquire() / Lock.acquire() have the same shape: release() credits the waiter, the waiter is cancelled, and the permit is never given back, so a lock stays held forever.

Reproduced on dbaa6c5b (6.7.dev1):

case before after
getter cancelled right after put_nowait(0) (Queue, LifoQueue, PriorityQueue) item lost; qsize() == 0, _unfinished_tasks == 1 forever qsize() == 1, next get_nowait() returns it
two waiting getters, the first cancelled item lost item handed to the second getter
bare await lock.acquire() cancelled right after release() permit lost, lock held forever permit released, next acquire succeeds
same for Semaphore / BoundedSemaphore permit lost permit released exactly once

The fix

Queue.get() now returns a _QueueGetter, a Future subclass whose __await__ catches CancelledError and, when the getter already holds a result, puts the item back:

  • offered to the next waiting getter, else
  • returned through Queue._put(), so LifoQueue / PriorityQueue ordering is preserved, and
  • _unfinished_tasks is left alone: the item was counted when it was put and is still unfinished.

Semaphore.acquire() returns an _AcquiredPermit that releases the permit in the same situation. Lock.acquire() delegates to it, so Lock.__aenter__ / Semaphore.__aenter__ no longer need their own except CancelledError: release() from #3770: the cleanup now happens for every caller, including the bare await acquire() that @bdarnell noted was still missing and wanted done "as a part of the queue work".

Why a Future subclass instead of async def get() (as asyncio.Queue does): get() / acquire() are documented to return an awaitable that exists immediately — the getter is registered at call time and the 6.6 timeout attaches to it. Making them coroutines would defer registration until the first await and change q.get() without an await, ensure_future(q.get()), and the timeout behaviour. Subclassing Future keeps done() / cancel() / result() and only changes what happens when the await is cancelled.

Scope: Condition.wait() and Event.wait() are deliberately unchanged. They resolve to a bool and hold no resource, so a cancelled waiter has nothing to give back.

An earlier attempt (#3689) covered only the queue half and was closed by its author; this covers the locks path the maintainer asked for as well, and the release notes get both entries.

Tests

All new tests fail on unmodified master (checked with git stash):

  • queues_test: item kept for Queue / LifoQueue / PriorityQueue; _unfinished_tasks and join() unaffected; item passed to the next getter.
  • locks_test: permit kept for Semaphore / BoundedSemaphore / Lock. The BoundedSemaphore subtest fails with ValueError if the permit is released twice, so "released exactly once" is covered too.

Validation on this machine (CPython 3.14.9):

  • python -m tornado.test → Ran 1766 tests ... OK (skipped=136)
  • black --check tornado/ and flake8 clean
  • plus a standalone reproducer of all four cases above, run against master and this branch

Limitation

This fixes cancellation after the handoff. Cancelling before it already worked: the cancelled waiter is dropped by _consume_expired() and never receives an item.

Written by StrikeRougeAgent, an autonomous coding agent.

Queue.put_nowait hands an item to a waiting getter by setting the getter's
result, and takes the item out of the queue while doing so. If the task
awaiting that getter is cancelled before it returns the item, nobody ever
receives it: it is still counted as unfinished, so Queue.join() never
completes, and the item is gone.

Awaiting a getter now goes through _QueueGetter, which puts the item back
when its waiter is cancelled: it is offered to the next waiting getter, or
returned to the queue with its unfinished count unchanged. Queue subclasses
get the right ordering through the existing _put hook, so LifoQueue and
PriorityQueue behave the same way.
A release hands the permit to a waiting acquire by setting its result. If
the task awaiting it is then cancelled before it returns, the permit is
lost: the semaphore's count is not credited back, so a Lock is held forever
and a Semaphore loses a slot. Only the async with path was covered before
(the __aenter__ special case from tornadoweb#3770); acquire() now does it for every
caller, so __aenter__ no longer needs its own cleanup.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Queue.get loses result on CancelledError

1 participant