Cancelled worker keeps running if Redis fails while it drains in-flight tasks

Aperta
#498 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

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
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python, redis
Ambito
backend

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

bug python

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.

  1. Worker.run() handles SIGTERM and SIGINT by cancelling the task that runs run_forever() or run_until_finished() (worker.py L470-L475).
  2. _worker_loop catches that CancelledError (L870-L876) and drains the in-flight tasks in its finally block (L877-L887). If a drained task failed on Redis, process_completed_tasks() re-raises that error (L727, called at L885), so the RedisError escapes _worker_loop.
  3. _run handles that error like any outage (L572-L598). Its only shutdown check is stopping.is_set() (L579), and stopping is _worker_stopping, which only Worker.__aexit__ sets (L357). A cancellation never sets it, so _run waits out reconnection_delay and 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

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di chrisguidry/docket

Tutte le issue di chrisguidry/docket

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.