Cancelled worker keeps running if Redis fails while it drains in-flight tasks
I maintainer di solito rispondono entro 1 giorno
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 3/5
- Tempo stimato
- 1-2 giorni
- Idoneità per principianti
- 78/100
Direzione di ricerca
Start with tests/worker/test_reconnection.py and the provided regression test, then read the cancellation and Redis-reconnection paths in src/docket/worker.py around _worker_loop and _run. Run the named pytest command against the memory backend first. Done means the cancelled worker stops after a Redis failure while draining, leaving the task pending for another worker's redelivery.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
docket worker handles SIGTERM and SIGINT by cancelling the worker, and a cancelled worker waits for its in-flight tasks to finish before it stops. If Redis fails during that wait, the worker handles the error like any other Redis outage: it reconnects and goes back to claiming new tasks. The cancellation is lost, so the worker keeps running until something kills it.
Steps to reproduce
This test goes in tests/worker/test_reconnection.py, which already has every import it needs except from tests._key_leak_checker import KeyCountChecker. It fakes the Redis failure with the same Execution._mark_as_terminal hook that test_worker_reconnects_when_an_ack_is_refused uses.
async def test_cancelled_worker_stops_when_redis_fails_during_its_drain(
docket: Docket, key_leak_checker: KeyCountChecker
):
"""A cancelled worker stops even when Redis fails while it drains.
Worker.run() cancels run_forever() on SIGTERM and SIGINT, and the worker
then waits for its in-flight tasks to finish. Here Redis drops the
connection as that task finishes, so its acknowledgement fails, the way
it would if Redis restarted at that moment. The worker has to stop
anyway instead of reconnecting."""
started = asyncio.Event()
finish = asyncio.Event()
async def in_flight_task():
started.set()
await finish.wait()
async def dropped_ack(self: Execution, *args: Any, **kwargs: Any) -> None:
raise ConnectionError("Connection closed by server.")
execution = await docket.add(in_flight_task)()
# The failed acknowledgement leaves the task pending for redelivery, so
# its runs and progress hashes have no TTL yet.
key_leak_checker.add_exemption(docket.runs_key(execution.key))
key_leak_checker.add_exemption(docket.key(f"progress:{execution.key}"))
async with Worker(docket, reconnection_delay=timedelta(milliseconds=50)) as worker:
run = asyncio.create_task(worker.run_forever())
await asyncio.wait_for(started.wait(), timeout=5)
run.cancel()
with patch.object(Execution, "_mark_as_terminal", dropped_ack):
finish.set()
_, pending = await asyncio.wait([run], timeout=5)
assert not pending, "the worker kept running after it was cancelled"
REDIS_VERSION=memory uv run pytest "tests/worker/test_reconnection.py::test_cancelled_worker_stops_when_redis_fails_during_its_drain" -n 0 --no-cov
Leave off REDIS_VERSION=memory to run it against Redis 8.0 in Docker instead. Either way it fails after about 5 seconds:
E AssertionError: the worker kept running after it was cancelled
E assert not {<Task cancelling name='Task-5' coro=<Worker.run_forever() running at .../src/docket/worker.py:520> ...>}
The captured log shows the worker reconnecting after the cancel and going back to polling:
INFO docket.worker:worker.py:872 Shutdown requested, finishing 1 active tasks...
WARNING docket.worker:worker.py:590 Redis is unavailable, retrying in 0:00:00.050000...
Traceback (most recent call last):
File "src/docket/worker.py", line 571, in _run
return await self._worker_loop(redis, forever=forever)
File "src/docket/worker.py", line 885, in _worker_loop
await process_completed_tasks()
File "src/docket/worker.py", line 727, in process_completed_tasks
await task
File "src/docket/worker.py", line 1261, in _execute
await execution.mark_as_failed(error_msg, result_key=result_key)
...
redis.exceptions.ConnectionError: Connection closed by server.
DEBUG docket.worker:worker.py:669 Getting redeliveries
DEBUG docket.worker:worker.py:677 Getting new deliveries
DEBUG docket.worker:worker.py:897 Scheduling due tasks
I also tried it in a small script on the memory backend: the cancelled worker claimed and ran a task that I added after the cancel.
What I expected
The worker finishes the drain and stops, the same as when Redis is healthy. The task whose acknowledgement failed stays pending, and another worker's redelivery sweep claims it later.
Why it happens
I followed the traceback above through the code, so I'm fairly confident about this part.
Worker.run()handles SIGTERM and SIGINT by cancelling the task that runsrun_forever()orrun_until_finished()(worker.py L470-L475)._worker_loopcatches thatCancelledError(L870-L876) and drains the in-flight tasks in itsfinallyblock (L877-L887). If a drained task failed on Redis,process_completed_tasks()re-raises that error (L727, called at L885), so theRedisErrorescapes_worker_loop._runhandles that error like any outage (L572-L598). Its only shutdown check isstopping.is_set()(L579), andstoppingis_worker_stopping, which onlyWorker.__aexit__sets (L357). A cancellation never sets it, so_runwaits outreconnection_delayand starts a new_worker_loop.
Leaving the async with Worker(...) block works fine, because __aexit__ sets _worker_stopping before it waits for the worker. I only tested a failed acknowledgement. The other Redis calls in process_completed_tasks(), such as the safety-net mark_as_failed and the admission-control reschedule, look like they'd take the same path, but I haven't tried them.
As a quick check, I added stopping.set() to that except asyncio.CancelledError block locally, and the test passed 3 of 3 times on both backends. I haven't thought through whether that's the right fix.
Environment
- Commit 9d3db18 on main
- Python 3.14.7 and 3.10.19, redis-py 8.1.0, Ubuntu 26.04
- Backends: memory, and Redis 8.0 in Docker (the test suite's default)
- It failed every time: 5 of 5 runs on each backend, on both Python versions
Filed by Claude Opus 5.5 on behalf of @chrisguidry.
- Lingua principale
- Python
- Stelle
- 148
- Fork
- 12
- Merge medio
- 15h 49m
- PR unite (30g)
- 45
Preparare l'ambiente
- Include un Dockerfile o un file Docker Compose
- Nessun modello di pull request
- Nessuna guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di chrisguidry/docket
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 88/100
chrisguidry/docket#642 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
chrisguidry/docket#641 ·
I maintainer di solito rispondono entro 1 giorno
-
`docket.cancel()` misses a running task after an earlier run of the same key ends on the same workerApertabug python
Difficoltà 2/5 1-3 ore Idoneità per principianti 86/100
chrisguidry/docket#512 ·
I maintainer di solito rispondono entro 1 giorno
-
rust
Difficoltà 3/5 Mezza giornata Idoneità per principianti 70/100
chrisguidry/docket#632 ·
I maintainer di solito rispondono entro 1 giorno
-
rust
Difficoltà 5/5 Più di una settimana Idoneità per principianti 18/100
chrisguidry/docket#631 ·
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di chrisguidry/docket
Issue simili
-
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 88/100
openfoodfacts/openfoodfacts-python#573 ·
I maintainer di solito rispondono entro 2 giorni
-
Rasterio reads over HTTPS do not send the Earthdata token and return 500 "HTTP response code: 404"Apertacredentials rasterio
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
developmentseed/titiler-cmr#359 ·
I maintainer di solito rispondono entro 1 giorno
-
Claiming namespace `r33net`Apertanamespace team:operations
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 85/100
EclipseFdn/open-vsx.org#16444 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 68/100
EbookFoundation/free-programming-books#13696 ·
I maintainer di solito rispondono entro 4 giorni
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
ossf/oss-crs#548 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno