startup: thread the downloads import too; test covers every import

import_downloads_config is async but never awaited anything: its body
called the synchronous DownloadManagerConfig.import_config on the event
loop, so a large download_manager.yaml still froze the worker. The
db_up check stays on the loop and only the import moves to a thread.

The responsiveness test now patches every import the startup path
performs, including that sync downloads import, with the same blocking
sleep, and requires ~90% of the total sleep budget in ticks so any one
import returning to the loop fails it. The ticker is awaited after
cancel so the task does not outlive the loop. Docstring trimmed to the
one constraint not visible at the call site.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-09-24 18:16:08 -06:00
parent 1aada9aea6
commit 9e9958176f
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
3 changed files with 33 additions and 12 deletions

View file

@ -1183,11 +1183,8 @@ async def import_all_db_configs() -> dict[str, bool]:
Returns a dict mapping config name to success status.
Used by main.py startup and disaster recovery tests.
This runs in a Sanic worker's after_server_start listener while that worker is already
accepting connections. Each synchronous import is run in a thread so a large config (minutes
of tags/channels/downloads work) does not freeze the worker's event loop and hang every
request routed to it. The SQLite engine allows cross-thread connections (check_same_thread
off); imports still run one at a time, in order.
This runs from a worker's after_server_start while the worker is already accepting requests,
so no import may block the event loop.
Import order matters:
1. Tags - no dependencies

View file

@ -2381,7 +2381,9 @@ async def import_downloads_config():
logger.warning(f'Refusing to import downloads config when DB is not up.')
return
get_download_manager_config().import_config()
# The import upserts every download on the calling thread; keep it off the event loop (this runs
# from a worker's after_server_start while the worker is already accepting requests).
await asyncio.to_thread(get_download_manager_config().import_config)
def parse_feed(url: str) -> FeedParserDict:

View file

@ -20,6 +20,7 @@ Import Order (from import_all_db_configs):
5. Inventories
"""
import asyncio
import contextlib
import pathlib
import shutil
@ -589,24 +590,45 @@ async def test_import_all_db_configs_does_not_block_event_loop(test_session, tes
import makes every request routed to that worker hang. The imports must run off the loop."""
import time
sleep_seconds = 0.2
def slow_import(*args, **kwargs):
time.sleep(0.5) # deliberately synchronous, like a real large import
time.sleep(sleep_seconds) # deliberately synchronous, like a real large import
# Every import import_all_db_configs performs, including the sync import behind the async
# downloads wrapper. Each is replaced with the same blocking sleep.
patched = [
'wrolpi.tags.import_tags_config',
'wrolpi.downloader.DownloadManagerConfig.import_config',
'modules.videos.lib.import_channels_config',
'modules.archive.lib.import_domains_config',
'modules.inventory.common.import_inventories_config',
'wrolpi.collections.config.PlaylistsConfig.import_config',
'modules.map.pins.MapPinsConfig.import_config',
'modules.flasher.config.FlasherConfig.import_config',
]
ticks = 0
tick_seconds = 0.05
async def ticker():
nonlocal ticks
while True:
await asyncio.sleep(0.05)
await asyncio.sleep(tick_seconds)
ticks += 1
ticker_task = asyncio.create_task(ticker())
try:
with mock.patch('wrolpi.tags.import_tags_config', slow_import), \
mock.patch('modules.videos.lib.import_channels_config', slow_import):
with contextlib.ExitStack() as stack:
for target in patched:
stack.enter_context(mock.patch(target, slow_import))
await import_all_db_configs()
finally:
ticker_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await ticker_task
# Two 0.5s imports; a responsive loop ticks ~20 times. A blocked loop ticks ~0.
assert ticks >= 10, f'event loop was blocked during import ({ticks=})'
# A responsive loop ticks through the whole sleep budget; require most of it so that any one
# import moving back onto the loop (losing its share of ticks) fails.
expected = len(patched) * sleep_seconds / tick_seconds
assert ticks >= expected * 0.9, f'event loop was blocked during import ({ticks=}, {expected=})'