fix(scan): report a scheduled scan whose worker dies, and keep its history

`on_failure=report_scan_failure` is attached where a scan is enqueued by
the socket handler and the watcher, but a scan cron enqueues carried
nothing: `CronScheduler.register()` takes no `on_failure` and `CronJob`
has no equivalent, so the one scan nobody is watching is also the one
whose worker can die without a `scan:done_ko` reaching the clients. RQ
reaps the job correctly and moves it to the failed registry, but no
callback runs, so the client keeps showing a scan that no longer exists
and `/tasks/status` cannot recover it either.

Cron now registers a dispatch job for a scan instead. It enqueues the
real scan onto the scan queue with the callback attached, mirroring what
the socket handler does. The dispatch sits on the low priority queue
rather than the scan queue so it fires on the tick instead of waiting
behind a scan that is already running, and because it only enqueues, it
takes the ordinary task timeout and hands the scan timeout to the scan
itself. That last part is a behaviour change: the cron job's own timeout
drops from `SCAN_TIMEOUT` to `TASK_TIMEOUT`.

The dispatch is left out of the task history, because it carries the
scan's own name and finishes in milliseconds, so listing it would show
one scheduled rescan as two runs. A dispatch that failed is still listed,
since then no scan ran at all.

Cron jobs also get an explicit result TTL. `register()` defaults it to
RQ's 500 seconds and writes that onto the job, so `job.get_result_ttl()`
never fell back to the worker's own 86400 and the Task History panel
emptied about eight minutes after each run. Passing `TASK_RESULT_TTL`
restores what rq-scheduler gave for free, since it passed no TTL at all.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Sam Dornan
2026-08-29 13:38:34 -05:00
parent dc11fcfc24
commit 83ba4d92fe
7 changed files with 258 additions and 33 deletions

View File

@@ -35,7 +35,7 @@ from handler.redis_handler import (
scan_queue,
)
from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS
from tasks.tasks import Task, TaskType, run_task_by_name
from tasks.tasks import SCAN_DISPATCH_META_KEY, Task, TaskType, run_task_by_name
from utils.router import APIRouter
router = APIRouter(
@@ -72,6 +72,18 @@ def _build_task_info(name: str, task: Task) -> TaskInfo:
)
def _is_spent_scan_dispatch(job: Job) -> bool:
"""Whether a job is a scan dispatch that has already handed off.
It carries the scan's own name, so listing it too would show one scheduled
scan as two runs. A failed dispatch stays, because then no scan ran at all.
"""
return (
bool(job.get_meta().get(SCAN_DISPATCH_META_KEY))
and job.get_status() is not JobStatus.FAILED
)
def _build_task_status_response(
job: Job,
) -> TaskStatusResponse:
@@ -208,12 +220,14 @@ async def get_tasks_status(request: Request) -> list[TaskStatusResponse]:
except NoSuchJobError:
continue
if current_job:
if current_job and not _is_spent_scan_dispatch(current_job):
all_tasks.append(_build_task_status_response(current_job))
# Get all jobs from the queues (including completed ones)
for queue in ALL_QUEUES:
for job in queue.get_jobs():
if _is_spent_scan_dispatch(job):
continue
all_tasks.append(_build_task_status_response(job))
finished_registries = [FinishedJobRegistry(queue=queue) for queue in ALL_QUEUES]
@@ -227,11 +241,9 @@ async def get_tasks_status(request: Request) -> list[TaskStatusResponse]:
except NoSuchJobError:
registry.remove(job_id)
continue
all_tasks.append(
_build_task_status_response(
job,
)
)
if _is_spent_scan_dispatch(job):
continue
all_tasks.append(_build_task_status_response(job))
# Process failed jobs
for registry in failed_registries:

View File

@@ -5,33 +5,49 @@ in Redis has to be unscheduled when a deployment turns one off: the next start
simply leaves it out.
"""
from typing import Any
from rq import cron
from config import TASK_RESULT_TTL, TASK_TIMEOUT
from endpoints.responses import TaskType
from handler.redis_handler import SCAN_QUEUE_NAME, QueuePrio
from handler.redis_handler import QueuePrio
from logger.logger import log
from tasks.registry import SCHEDULED_TASKS
from tasks.tasks import run_task_by_name
from tasks.tasks import (
SCAN_DISPATCH_META_KEY,
enqueue_scheduled_scan,
run_task_by_name,
)
for name, task in SCHEDULED_TASKS.items():
if not task.enabled or not task.cron_string:
continue
# The scheduled rescan belongs on the queue the scan worker consumes, so it
# neither holds up the other tasks nor overlaps another scan.
queue_name = (
SCAN_QUEUE_NAME if task.task_type is TaskType.SCAN else QueuePrio.LOW.value
)
# A scan is enqueued by a dispatch job rather than registered on the scan
# queue, because cron can attach no callback to report a scan whose worker
# died. The dispatch runs on the low queue so it fires on the tick instead
# of waiting behind a scan, and only enqueues, so the scan timeout belongs
# to the scan rather than to this.
is_scan = task.task_type is TaskType.SCAN
meta: dict[str, Any] = {
"task_name": task.title,
"task_type": task.task_type.value,
}
if is_scan:
meta[SCAN_DISPATCH_META_KEY] = True
cron.register(
run_task_by_name,
queue_name,
enqueue_scheduled_scan if is_scan else run_task_by_name,
QueuePrio.LOW.value,
kwargs={"name": name},
cron=task.cron_string,
job_timeout=task.timeout,
meta={
"task_name": task.title,
"task_type": task.task_type.value,
},
job_timeout=TASK_TIMEOUT if is_scan else task.timeout,
# `register()` defaults this to RQ's 500 seconds and always writes it
# onto the job, so the worker's own result TTL can never apply and the
# task history would empty minutes after each run.
result_ttl=TASK_RESULT_TTL,
meta=meta,
)
log.info(f"Scheduled '{name}' at '{task.cron_string}'")

View File

@@ -5,11 +5,15 @@ from typing import Any
import httpx
from rq import get_current_job
from config import TASK_TIMEOUT
from config import TASK_RESULT_TTL, TASK_TIMEOUT
from exceptions.task_exceptions import TaskNotFoundException
from logger.logger import log
from utils.context import ctx_httpx_client
# Marks the cron job that only enqueues a scan, so the task history can tell it
# apart from the scan it creates.
SCAN_DISPATCH_META_KEY = "scan_dispatch"
async def run_task_by_name(name: str, task_kwargs: dict[str, Any] | None = None) -> Any:
"""Run the task registered under ``name``.
@@ -37,6 +41,42 @@ async def run_task_by_name(name: str, task_kwargs: dict[str, Any] | None = None)
return await task.run(**(task_kwargs or {}))
def enqueue_scheduled_scan(name: str) -> str:
"""Put a scheduled scan on the scan queue with the abandoned-job callback.
Cron can attach no `on_failure`, so a scan it enqueues itself is the one
scan whose worker can die without anything telling the clients.
Args:
name: The key the scan task is registered under.
Returns:
The id of the enqueued scan job.
"""
# Imported here for the same reason as in run_task_by_name: the registry
# imports every task module, and the scan module imports this one.
from endpoints.sockets.scan import report_scan_failure
from handler.redis_handler import scan_queue
from tasks.registry import get_task
task = get_task(name)
if task is None:
raise TaskNotFoundException(name)
job = scan_queue.enqueue(
run_task_by_name,
kwargs={"name": name},
on_failure=report_scan_failure,
job_timeout=task.timeout,
result_ttl=TASK_RESULT_TTL,
meta={
"task_name": task.title,
"task_type": task.task_type.value,
},
)
return job.id
def update_job_meta(metadata: dict[str, Any]) -> None:
"""Update the current RQ job's meta data with update stats information"""
try:

View File

@@ -1,10 +1,12 @@
from contextlib import contextmanager
from unittest.mock import Mock, patch
import pytest
from fastapi import status
from rq.exceptions import NoSuchJobError
from rq.job import JobStatus
from tasks.tasks import Task, TaskType
from tasks.tasks import SCAN_DISPATCH_META_KEY, Task, TaskType
@pytest.fixture
@@ -75,6 +77,40 @@ def create_mock_job(job_id="1", status="queued"):
return mock_job
def _scan_dispatch_job(job_status):
"""The cron job that only enqueues a scheduled scan."""
job = create_mock_job(job_id="dispatch", status=job_status)
job.started_at = None
job.ended_at = None
job.get_meta.return_value = {
"task_name": "Scan Library",
"task_type": TaskType.SCAN.value,
SCAN_DISPATCH_META_KEY: True,
}
return job
@contextmanager
def _registries(*, finished, failed):
"""Serve these jobs from the two registries, with every queue empty."""
by_id = {job.id: job for job in (*finished, *failed)}
queue = Mock()
queue.get_jobs.return_value = []
def registry(jobs):
mock = Mock()
mock.get_job_ids.return_value = [job.id for job in jobs]
return mock
with (
patch("endpoints.tasks.ALL_QUEUES", new=(queue,)),
patch("endpoints.tasks.Job.fetch", side_effect=lambda id, **_: by_id[id]),
patch("endpoints.tasks.FinishedJobRegistry", return_value=registry(finished)),
patch("endpoints.tasks.FailedJobRegistry", return_value=registry(failed)),
):
yield
class TestListTasks:
"""Test suite for the list_tasks endpoint"""
@@ -379,6 +415,39 @@ class TestGetTasksStatus:
assert response.status_code == status.HTTP_200_OK
assert response.json() == []
@patch("endpoints.tasks.Worker.all", return_value=[])
def test_a_spent_scan_dispatch_is_left_out(
self, mock_worker_all, client, access_token
):
# The dispatch carries the scan's own name, so listing it next to the
# scan it enqueued would show one scheduled scan as two runs.
dispatch = _scan_dispatch_job(JobStatus.FINISHED)
with _registries(finished=[dispatch], failed=[]):
response = client.get(
"/api/tasks/status",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json() == []
@patch("endpoints.tasks.Worker.all", return_value=[])
def test_a_failed_scan_dispatch_is_reported(
self, mock_worker_all, client, access_token
):
# A dispatch that failed means no scan ran at all, so it has to be seen.
dispatch = _scan_dispatch_job(JobStatus.FAILED)
with _registries(finished=[], failed=[dispatch]):
response = client.get(
"/api/tasks/status",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert [task["task_id"] for task in response.json()] == ["dispatch"]
class TestGetTaskById:
"""Test suite for the get_task_by_id endpoint"""

View File

@@ -2,11 +2,16 @@ import importlib
import pytest
from config import TASK_RESULT_TTL, TASK_TIMEOUT
from endpoints.responses import TaskType
from handler.redis_handler import SCAN_QUEUE_NAME, QueuePrio
from handler.redis_handler import QueuePrio
from tasks import cron_config
from tasks.registry import SCHEDULED_TASKS
from tasks.tasks import run_task_by_name
from tasks.tasks import (
SCAN_DISPATCH_META_KEY,
enqueue_scheduled_scan,
run_task_by_name,
)
@pytest.fixture
@@ -33,6 +38,12 @@ def _task(mocker, *, enabled=True, cron_string="0 4 * * *"):
)
def _scan_task(mocker, **kwargs):
task = _task(mocker, **kwargs)
task.task_type = TaskType.SCAN
return task
class TestCronConfig:
"""The cron process registers what this module declares, and nothing else."""
@@ -44,18 +55,29 @@ class TestCronConfig:
assert args[0] is run_task_by_name
assert kwargs["kwargs"] == {"name": "test_task"}
assert kwargs["cron"] == "0 4 * * *"
assert kwargs["job_timeout"] == 100
def test_a_scan_is_registered_on_the_scan_queue(self, mocker, registered):
task = _task(mocker)
task.task_type = TaskType.SCAN
register = registered({"scan_library": task})
def test_a_scan_is_registered_through_the_dispatch_job(self, mocker, registered):
# Cron takes no failure callback, so the scan is enqueued by a job that
# can attach one rather than being registered with cron directly.
register = registered({"scan_library": _scan_task(mocker)})
assert register.call_args.args[1] == SCAN_QUEUE_NAME
kwargs = register.call_args.kwargs
assert register.call_args.args[0] is enqueue_scheduled_scan
assert kwargs["job_timeout"] == TASK_TIMEOUT
assert kwargs["meta"][SCAN_DISPATCH_META_KEY] is True
def test_everything_else_stays_on_the_low_queue(self, mocker, registered):
def test_everything_runs_on_the_low_queue(self, mocker, registered):
for tasks in ({"cleanup": _task(mocker)}, {"scan": _scan_task(mocker)}):
register = registered(tasks)
assert register.call_args.args[1] == QueuePrio.LOW.value
def test_history_outlives_rq_s_own_result_ttl(self, mocker, registered):
# `register()` defaults this, and a default is written onto the job, so
# leaving it out would pin every cron job to RQ's 500 seconds.
register = registered({"cleanup": _task(mocker)})
assert register.call_args.args[1] == QueuePrio.LOW.value
assert register.call_args.kwargs["result_ttl"] == TASK_RESULT_TTL
def test_skips_a_disabled_task(self, mocker, registered):
assert registered({"off": _task(mocker, enabled=False)}).call_count == 0

View File

@@ -3,8 +3,15 @@ from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import pytest
from config import TASK_RESULT_TTL
from exceptions.task_exceptions import TaskNotFoundException
from tasks.tasks import PeriodicTask, RemoteFilePullTask, TaskType, run_task_by_name
from tasks.tasks import (
PeriodicTask,
RemoteFilePullTask,
TaskType,
enqueue_scheduled_scan,
run_task_by_name,
)
class ConcretePeriodicTask(PeriodicTask):
@@ -200,3 +207,58 @@ class TestRunTaskByName:
with pytest.raises(TaskNotFoundException, match="some_task"):
await run_task_by_name("some_task")
class TestEnqueueScheduledScan:
"""Cron cannot attach a failure callback, so a dispatch job does it."""
@pytest.fixture
def scan_queue(self, mocker):
queue = mocker.patch("handler.redis_handler.scan_queue")
queue.enqueue.return_value = MagicMock(id="job-1")
return queue
@pytest.fixture
def task(self, mocker):
task = MagicMock(title="Scan Library", task_type=TaskType.SCAN, timeout=14400)
mocker.patch("tasks.registry.get_task", return_value=task)
return task
def test_enqueues_the_scan_with_the_abandoned_job_callback(
self, scan_queue, task
) -> None:
from endpoints.sockets.scan import report_scan_failure
assert enqueue_scheduled_scan("scan_library") == "job-1"
kwargs = scan_queue.enqueue.call_args.kwargs
assert scan_queue.enqueue.call_args.args[0] is run_task_by_name
assert kwargs["kwargs"] == {"name": "scan_library"}
assert kwargs["on_failure"] is report_scan_failure
def test_the_scan_carries_its_own_timeout_and_result_ttl(
self, scan_queue, task
) -> None:
# The dispatch runs on the ordinary task timeout; the scan timeout
# belongs to the scan the dispatch creates.
enqueue_scheduled_scan("scan_library")
kwargs = scan_queue.enqueue.call_args.kwargs
assert kwargs["job_timeout"] == task.timeout
assert kwargs["result_ttl"] == TASK_RESULT_TTL
def test_the_scan_is_labelled_for_the_task_history(self, scan_queue, task) -> None:
enqueue_scheduled_scan("scan_library")
assert scan_queue.enqueue.call_args.kwargs["meta"] == {
"task_name": "Scan Library",
"task_type": TaskType.SCAN.value,
}
def test_raises_for_a_name_that_is_not_registered(self, mocker, scan_queue) -> None:
mocker.patch("tasks.registry.get_task", return_value=None)
with pytest.raises(TaskNotFoundException, match="nope"):
enqueue_scheduled_scan("nope")
scan_queue.enqueue.assert_not_called()

View File

@@ -1389,6 +1389,10 @@ registered only when it is enabled and has a cron string, so turning one off is
a restart rather than an unschedule. Delayed jobs, which is how the filesystem
watcher defers a rescan, are released by the worker itself (`--with-scheduler`).
Everything is registered on `low_prio_queue`. A scan is registered as a dispatch
job that enqueues the real scan onto `scan_queue`, because cron can attach no
failure callback and a scan needs one to report a worker that died mid-scan.
Toggled via environment variables:
| Task | Env Toggle | Default Cron | Description |