refactor(tasks): simplify pass on the task catalog split

Loads every model where the engine is built rather than per job, so only
processes that touch the ORM pay for it. Resolves task paths with RQ's
import_attribute, references the scan failure callback by path, hoists
the recommendations builder's registry import now that the registry
loads no task modules, and gates push-pull on its spec.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-10-01 11:06:27 -04:00
parent e62c452ea9
commit 656c85bc46
7 changed files with 35 additions and 26 deletions

View File

@@ -7,6 +7,7 @@ from sqlalchemy.orm import sessionmaker
from config import DB_POOL_RECYCLE_SECONDS, DEV_SQL_ECHO
from config.config_manager import ConfigManager
from models import load_all_models
# A ping on a socket the server already closed blocks the worker until TCP gives
# up, so `pool_pre_ping` alone is not enough.
@@ -59,3 +60,8 @@ def affected_rows(result: Result[Any]) -> int:
"""How many rows an UPDATE or DELETE run through `Session.execute` matched."""
# Session.execute is typed to return Result, but DML gets a CursorResult.
return cast(CursorResult[Any], result).rowcount
# A process may load one model, whose relationships name others by string, and
# the mappers configure only once every one of them is loaded.
load_all_models()

View File

@@ -18,6 +18,7 @@ from typing import Any, Final
from handler.database import db_recommendation_handler
from handler.database.recommendations_handler import RomFeatureRow
from logger.logger import log
from tasks.registry import enqueue_task
from .feed import invalidate_all_cached_feeds
from .scoring import (
@@ -583,10 +584,6 @@ def top_up_similarity(rom_ids: Collection[int]) -> None:
return
if len(unique_ids) > MAX_TOP_UP_ROMS:
# Deferred: the task registry imports every task module, and one of
# them imports this package.
from tasks.registry import enqueue_task
log.info(
f"{len(unique_ids)} ROMs scanned, more than a recommendations top-up "
"is worth; queueing a full rebuild instead"

View File

@@ -1,10 +1,10 @@
"""The catalog of tasks, kept free of task code so scheduling or listing them imports none."""
import importlib
from typing import Any, Final
from typing import Any, Final, cast
from rq.job import Job
from rq.job import Callback, Job
from rq.queue import Queue
from rq.utils import import_attribute
from config import (
AUDIT_LOG_RETENTION_DAYS,
@@ -271,9 +271,7 @@ def get_task(name: str) -> Task | None:
spec = get_task_spec(name)
if spec is None:
return None
module, _, attribute = spec.implementation.rpartition(".")
task: Task = getattr(importlib.import_module(module), attribute)
return task
return cast(Task, import_attribute(spec.implementation))
def enqueue_task(
@@ -327,8 +325,6 @@ def enqueue_scheduled_scan(name: str) -> str:
Returns:
The id of the enqueued scan job.
"""
# Imported here because the cron process registers this function and must
# not load the scan stack to do it.
from endpoints.sockets.scan import report_scan_failure
return enqueue_task(name, queue=scan_queue, on_failure=report_scan_failure).id
# By path, so the dispatch job doesn't load the scan stack to reference it.
on_failure = Callback("endpoints.sockets.scan.report_scan_failure")
return enqueue_task(name, queue=scan_queue, on_failure=on_failure).id

View File

@@ -11,7 +11,6 @@ import asyncssh
from anyio import Path as AnyioPath
from anyio import open_file
from config import ENABLE_SYNC_PUSH_PULL
from handler.database import (
db_deleted_asset_handler,
db_device_handler,
@@ -37,7 +36,7 @@ async def run_push_pull_sync(
force: bool = False,
) -> dict[str, Any]:
"""Execute push-pull sync for one or all push_pull devices."""
if not ENABLE_SYNC_PUSH_PULL and not force:
if not SYNC_PUSH_PULL_SPEC.enabled and not force:
log.info("Push-pull sync not enabled, skipping")
return {"status": "disabled"}

View File

@@ -39,12 +39,8 @@ async def run_task_by_name(
Whatever the task returns.
"""
# Imported here because the task modules the registry resolves import this one.
from models import load_all_models
from tasks.registry import get_task
# A task module may load a model whose relationships name models it doesn't
# import, and the mappers configure only once every one of them is loaded.
load_all_models()
task = get_task(name)
if task is None:
raise TaskNotFoundException(name)

View File

@@ -1,4 +1,5 @@
import pytest
from rq.utils import import_attribute
from config import TASK_RESULT_TTL
from endpoints.sockets.scan import report_scan_failure
@@ -98,7 +99,7 @@ class TestEnqueueScheduledScan:
args, kwargs = scan_queue.enqueue.call_args
assert args[0] is run_task_by_name
assert kwargs["kwargs"]["name"] == "scan_library"
assert kwargs["on_failure"] is report_scan_failure
assert import_attribute(kwargs["on_failure"].func) is report_scan_failure
def test_the_scan_carries_its_own_timeout(self, scan_queue):
# The dispatch itself runs on the ordinary task timeout, so the scan

View File

@@ -1,5 +1,6 @@
"""Tests for SyncPushPullTask initialization and configuration."""
from dataclasses import replace
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch
@@ -18,6 +19,7 @@ from models.device import Device, SyncMode
from models.platform import Platform
from models.rom import Rom
from models.user import User
from tasks.registry import SYNC_PUSH_PULL_SPEC
from tasks.sync_push_pull_task import (
SyncPushPullTask,
_process_remote_save,
@@ -49,14 +51,20 @@ class TestSyncPushPullTaskInit:
class TestRunPushPullSync:
@patch("tasks.sync_push_pull_task.ENABLE_SYNC_PUSH_PULL", False)
@patch(
"tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC",
replace(SYNC_PUSH_PULL_SPEC, enabled=False),
)
async def test_run_disabled_returns_disabled(self):
from tasks.sync_push_pull_task import run_push_pull_sync
result = await run_push_pull_sync()
assert result["status"] == "disabled"
@patch("tasks.sync_push_pull_task.ENABLE_SYNC_PUSH_PULL", True)
@patch(
"tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC",
replace(SYNC_PUSH_PULL_SPEC, enabled=True),
)
@patch("tasks.sync_push_pull_task.db_device_handler")
async def test_run_no_devices(self, mock_device_handler):
from tasks.sync_push_pull_task import run_push_pull_sync
@@ -66,7 +74,10 @@ class TestRunPushPullSync:
result = await run_push_pull_sync()
assert result["status"] == "no_devices"
@patch("tasks.sync_push_pull_task.ENABLE_SYNC_PUSH_PULL", True)
@patch(
"tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC",
replace(SYNC_PUSH_PULL_SPEC, enabled=True),
)
@patch("tasks.sync_push_pull_task.db_device_handler")
async def test_run_device_not_found(self, mock_device_handler):
from tasks.sync_push_pull_task import run_push_pull_sync
@@ -77,7 +88,10 @@ class TestRunPushPullSync:
assert result["status"] == "error"
assert "not found" in result["message"]
@patch("tasks.sync_push_pull_task.ENABLE_SYNC_PUSH_PULL", False)
@patch(
"tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC",
replace(SYNC_PUSH_PULL_SPEC, enabled=False),
)
async def test_run_force_override(self):
from tasks.sync_push_pull_task import run_push_pull_sync