From f341e386adc905c59436180f472ef9131c1d1fe6 Mon Sep 17 00:00:00 2001 From: Roland Date: Thu, 23 Jul 2026 09:36:21 -0600 Subject: [PATCH] downloader: fix self-deadlock that silently stopped all downloads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `_dispatch_new_downloads` claimed downloads inside a `get_immediate_db_session()` (BEGIN IMMEDIATE) transaction and then `await`ed `api_app.dispatch(...)` while that write transaction was still open. Under NullPool (production, one connection per session) the dispatched `signal_download_download` opens its OWN connection and — inheriting the thread-local `_immediate_txn` flag — also issues BEGIN IMMEDIATE, which blocks on the write lock the outer transaction still holds until busy_timeout (30s) expires: `(sqlite3.OperationalError) database is locked [SQL: BEGIN IMMEDIATE]`. Every dispatch cycle died on the first download, so nothing downloaded at all. Fix: claim the downloads inside the transaction, collect (id, url), and dispatch the signals AFTER the `with` block commits and releases the write lock. Diagnosed live on 10.0.0.9 (downloads had silently stopped); with this change the 14 stuck recurring downloads drained immediately and no lock errors recurred. Why tests missed it: the `test_session` fixture returns a single shared (engine, session) for every `_get_db_session` call, so all sessions in a test ride one connection -- the second-connection write-lock contention that causes the deadlock cannot occur. Added a regression test asserting the invariant instead: the download signal must be dispatched with no immediate transaction active. Co-Authored-By: Claude Opus 4.8 (1M context) --- wrolpi/downloader.py | 16 +++++++++++++-- wrolpi/test/test_downloader.py | 36 ++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/wrolpi/downloader.py b/wrolpi/downloader.py index 8c0a3e88..90eb2036 100644 --- a/wrolpi/downloader.py +++ b/wrolpi/downloader.py @@ -1113,6 +1113,13 @@ class DownloadManager: Uses `get_immediate_db_session` because this is a read-then-write transaction (it reads the `new` downloads, then claims each by setting `last_download_attempt`); a deferred lock upgrade here fails instantly with "database is locked" under concurrency.""" + # (download_id, url) pairs claimed this cycle. The signals are dispatched AFTER the + # immediate (write) transaction below commits: dispatching inside it deadlocks, because the + # awaited `signal_download_download` opens its own write session (which also emits + # `BEGIN IMMEDIATE`, inheriting `_immediate_txn`) and blocks on the write lock this + # transaction still holds — timing out after `busy_timeout` with "database is locked" so no + # download ever starts. + to_dispatch = [] with get_immediate_db_session() as session: new_downloads = list(session.query(Download).filter( Download.status == 'new', @@ -1193,8 +1200,8 @@ class DownloadManager: domain_counts[limit_domain] = domain_counts.get(limit_domain, 0) + 1 self._add_processing_domain(domain) - context = dict(download_id=download.id, download_url=download.url) - await api_app.dispatch('wrolpi.download.download', context=context) + # Claim now; dispatch after the transaction commits (see `to_dispatch` above). + to_dispatch.append(dict(download_id=download.id, download_url=download.url)) count += 1 else: # Domain is already being processed, or all worker slots are in use. A domain @@ -1217,6 +1224,11 @@ class DownloadManager: except (AttributeError, RuntimeError): pass + # The immediate (write) transaction has now committed and released the write lock, so the + # download signal handlers can open their own write sessions without deadlocking. + for context in to_dispatch: + await api_app.dispatch('wrolpi.download.download', context=context) + async def do_downloads(self): """Schedule any downloads that are new. diff --git a/wrolpi/test/test_downloader.py b/wrolpi/test/test_downloader.py index f050992a..67c506f2 100644 --- a/wrolpi/test/test_downloader.py +++ b/wrolpi/test/test_downloader.py @@ -1708,6 +1708,42 @@ async def test_daily_limit_per_domain_allows_under_limit(test_session, test_down assert new.last_download_attempt is not None +@pytest.mark.asyncio +async def test_download_dispatched_outside_immediate_transaction(test_session, test_download_manager, test_downloader): + """The download signal must be dispatched AFTER the claiming write transaction commits. + + Regression test for a production deadlock (found on 10.0.0.9, where downloads silently stopped): + `_dispatch_new_downloads` claimed downloads inside a `get_immediate_db_session()` (BEGIN + IMMEDIATE) transaction and `await`ed `api_app.dispatch(...)` while that transaction was still + open. Under NullPool (production) the dispatched `signal_download_download` opens its OWN + connection and — inheriting the `_immediate_txn` flag — also issues BEGIN IMMEDIATE, which + blocks on the write lock the outer transaction still holds until `busy_timeout` (30s) expires: + `database is locked`, and no download ever starts. + + The test database shares a single connection, so it cannot reproduce the lock itself; instead it + asserts the invariant that prevents it — the signal is dispatched with no immediate transaction + active.""" + from wrolpi.db import _immediate_txn + name = test_downloader.name + d = Download(url='https://example.com/new', downloader=name, status='new') + test_session.add(d) + test_session.commit() + + immediate_active_at_dispatch = [] + + async def record(event, *args, **kwargs): + if event == 'wrolpi.download.download': + immediate_active_at_dispatch.append(getattr(_immediate_txn, 'active', False)) + + with mock.patch.object(type(api_app), 'dispatch', new_callable=mock.AsyncMock) as dispatch: + dispatch.side_effect = record + await test_download_manager.dispatch_downloads() + + assert immediate_active_at_dispatch, 'expected the download to be dispatched' + assert not any(immediate_active_at_dispatch), \ + 'download signal was dispatched inside an open BEGIN IMMEDIATE transaction (deadlocks under NullPool)' + + @pytest.mark.asyncio async def test_dispatch_downloads_tolerates_locked_db(test_session, test_download_manager, test_downloader): """A transient 'database is locked' during dispatch is swallowed (retried next cycle), not raised.