An automatic `Perpetual` interrupted by a second SIGTERM waits for `redelivery_timeout` before it runs again

Abierto
#511 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
59/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python, redis

Línea de trabajo

Start with the reproduction in tests/test_interrupted_automatic_perpetual.py and run it using the memory backend. Then read Worker._execute, process_completed_tasks(), automatic perpetual scheduling in worker.py, and perpetual_is_live() in src/docket/dependencies/_perpetual.py. Done means an interrupted automatic perpetual runs promptly after the next worker starts, with the regression test passing on both memory and Redis backends.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug python

Since #505, a second SIGTERM or SIGINT during the drain leaves the interrupted task pending for redelivery, so it runs again instead of being lost (#497). For an automatic Perpetual, the runs hash still holds state: running after the worker exits. The next worker's startup seeding skips the task, and so does the reseed loop every 60 seconds. The task runs again only when the redelivery sweep claims its message after redelivery_timeout, which is 5 minutes by default.

In 0.25.2, the worker marked the interrupted run cancelled, and the next worker's startup seeding ran it again at once. asyncio.run() teardown takes the same path as the second SIGTERM, for example after a task calls sys.exit(). A variant of the test below that cancels both tasks together, the way asyncio.run() does, fails the same way on main.

Steps to reproduce

This test fails on main. It interrupts the task during the drain, the way a second SIGTERM does.

"""An automatic perpetual that a worker shutdown interrupts, and the next worker."""

from __future__ import annotations

import asyncio
from datetime import timedelta
from typing import Any, cast

import pytest

from docket import Docket, Perpetual, Worker
from tests._key_leak_checker import KeyCountChecker
from tests.conftest import wait_until


async def test_next_worker_restarts_an_interrupted_automatic_perpetual(
    docket: Docket,
    caplog: pytest.LogCaptureFixture,
    key_leak_checker: KeyCountChecker,
):
    """A second SIGTERM during the drain interrupts the running perpetual.  The
    next worker to start should run it again at once, well before the
    redelivery timeout."""
    runners: list[asyncio.Task[Any]] = []
    release = asyncio.Event()

    async def perpetual_task(
        perpetual: Perpetual = Perpetual(every=timedelta(seconds=30), automatic=True),
    ) -> None:
        runners.append(cast(asyncio.Task[Any], asyncio.current_task()))
        await release.wait()

    docket.register(perpetual_task)

    # The interrupted run's message stays pending for redelivery, so its runs
    # and progress hashes have no TTL.
    key_leak_checker.add_exemption(docket.runs_key("perpetual_task"))
    key_leak_checker.add_exemption(docket.key("progress:perpetual_task"))

    async with Worker(
        docket,
        minimum_check_interval=timedelta(milliseconds=5),
        scheduling_resolution=timedelta(milliseconds=5),
    ) as worker_a:
        run_a = asyncio.create_task(worker_a.run_forever())
        await wait_until(lambda: len(runners) == 1, description="the first run")

        # The first SIGTERM cancels the worker's task, and the worker drains.
        run_a.cancel()
        await wait_until(
            lambda: "Shutdown requested, finishing" in caplog.text,
            description="the drain",
        )

        # The second SIGTERM cancels the task that the worker is draining.
        runners[0].cancel()
        await asyncio.gather(run_a, return_exceptions=True)

    release.set()

    async with Worker(
        docket,
        redelivery_timeout=timedelta(seconds=30),
        minimum_check_interval=timedelta(milliseconds=5),
        scheduling_resolution=timedelta(milliseconds=5),
    ) as worker_b:
        run_b = asyncio.create_task(worker_b.run_forever())
        await wait_until(
            lambda: len(runners) == 2,
            timeout=2.0,
            description="a second run within 2s of the next worker's start",
        )
        run_b.cancel()
        await asyncio.gather(run_b, return_exceptions=True)

    await docket.cancel("perpetual_task")

Save it as tests/test_interrupted_automatic_perpetual.py and run it on the memory backend:

REDIS_VERSION=memory uv run pytest tests/test_interrupted_automatic_perpetual.py -n 0 --no-cov

Without REDIS_VERSION=memory, the test runs against Redis 8.0 in Docker. It fails the same way on both:

E       AssertionError: a second run within 2s of the next worker's start never became truthy within 2.0s

The same test passes on 0.25.2, on both backends. There the worker logs the interrupted run as cancelled, and the next worker runs the task at once:

INFO     docket.worker:worker.py:1073 ↪ [     3ms] perpetual_task(){perpetual_task}
INFO     docket.worker:worker.py:872 Shutdown requested, finishing 1 active tasks...
INFO     docket.worker:worker.py:1194 ✗ [    18ms] perpetual_task(){perpetual_task} (cancelled)
...
INFO     docket.worker:worker.py:1073 ↪ [     2ms] perpetual_task(){perpetual_task}

On main, after worker A exits, the runs hash holds state: running, and the message is pending for worker A's consumer. With redelivery_timeout=3s on worker B, the second run started 3.3 seconds (Redis 8.0) and 3.7 seconds (memory) after worker B started.

I also checked it end to end with docket worker against Redis 8.0.5. The task was an automatic Perpetual with every=timedelta(seconds=1) that sleeps for 3 seconds, and both workers had --redelivery-timeout 10s. Worker A got two SIGTERMs 0.3 seconds apart while the task ran, and worker B started right after worker A exited:

  • On main, worker B ran the task 9.8, 10.3, and 10.8 seconds after it started (3 of 3 runs).
  • On 0.25.2, worker B ran the task 0.3 seconds after it started (3 of 3 runs).
Why it happens

During a shutdown, when something other than docket.cancel() cancels a running task, Worker._execute re-raises the CancelledError:

https://github.com/chrisguidry/docket/blob/7e844b1706264df8022e6475284392bde764292b/src/docket/worker.py#L1218-L1229

process_completed_tasks() then writes nothing for that task. The runs hash keeps the running state that _claim wrote, and the message stays pending:

https://github.com/chrisguidry/docket/blob/7e844b1706264df8022e6475284392bde764292b/src/docket/worker.py#L737-L750

_schedule_all_automatic_perpetual_tasks() skips a task when perpetual_is_live() returns True, and perpetual_is_live() returns True for a running state. The reseed loop calls the same method:

https://github.com/chrisguidry/docket/blob/7e844b1706264df8022e6475284392bde764292b/src/docket/worker.py#L1036-L1047

https://github.com/chrisguidry/docket/blob/7e844b1706264df8022e6475284392bde764292b/src/docket/dependencies/_perpetual.py#L29-L38

Without that check, docket.add() would still refuse the key, because the _schedule script returns EXISTS for a key whose state is running:

https://github.com/chrisguidry/docket/blob/7e844b1706264df8022e6475284392bde764292b/src/docket/_execution_scripts.py#L164-L172

A worker killed with SIGKILL leaves the same runs hash and pending message. After a SIGKILL in the same end-to-end setup, worker B ran the task 10.8 to 12.3 seconds after it started. That held on both main and 0.25.2 (2 of 2 runs each).

Environment
  • Commit 7e844b1 on main (pydocket 0.25.3.dev14), and 0.25.2
  • Python 3.14.7 on Linux, redis-py 8.1.0. On main, the test also fails on Python 3.10.19.
  • Backends: the memory backend, and Redis 8.0.5 in Docker
  • On main, the test failed in 10 of 10 runs on each backend. On 0.25.2, it passed in 10 of 10.
  • The test passes at 5e059e5 (#504), the commit before #505.

Filed by Claude Opus 5.5 on behalf of @chrisguidry.

Lenguaje dominante
Python
Estrellas
148
Forks
12
Merge medio
15 h 49 min
PR fusionados (30 d)
45

Preparar el entorno

  • Incluye un Dockerfile o un archivo de Docker Compose
  • Sin plantilla de pull request
  • Sin guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de chrisguidry/docket

Todos los issues de chrisguidry/docket

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.