feat(worker): chunk the library scan + reconnect on DB loss
Two worker-loop robustness fixes: - Scan chunking: maybe_run_scan advances the library scan by at most one scan_chunk (default scan.chunkSize=25 albums) per loop iteration, so a large library no longer blocks job-claim/monitor for minutes-to-hours. Progress persists in scan.inProgress/scan.cursor/scan.progress and is resumable; scan.result (unchanged format) is written on completion. - DB reconnect: wrap the loop body in `except psycopg.OperationalError` (AdminShutdown subclasses it) to close the dead handle and reconnect via wait_for_db() in-process, instead of crashing and relying on the container restart policy. Verified via a backend-termination test. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import psycopg
|
||||
import pytest
|
||||
|
||||
from lyra_worker.db import connect, wait_for_db
|
||||
|
||||
|
||||
def test_terminated_backend_raises_operational_error_then_reconnects(conn):
|
||||
"""The run_forever reconnect boundary catches psycopg.OperationalError and re-runs
|
||||
wait_for_db(). This exercises both primitives: a server-side backend termination (the
|
||||
real AdminShutdown case) surfaces as OperationalError, and wait_for_db reconnects."""
|
||||
victim = connect()
|
||||
try:
|
||||
with victim.cursor() as cur:
|
||||
cur.execute("SELECT pg_backend_pid()")
|
||||
pid = cur.fetchone()[0]
|
||||
with conn.cursor() as cur: # terminate the victim's backend, as a DB restart would
|
||||
cur.execute("SELECT pg_terminate_backend(%s)", (pid,))
|
||||
conn.commit()
|
||||
with pytest.raises(psycopg.OperationalError): # the exact type the loop catches
|
||||
with victim.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
finally:
|
||||
try:
|
||||
victim.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
fresh = wait_for_db() # reconnect exactly as run_forever does
|
||||
try:
|
||||
with fresh.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
assert cur.fetchone()[0] == 1
|
||||
finally:
|
||||
fresh.close()
|
||||
@@ -1,5 +1,5 @@
|
||||
from lyra_worker.adapters.fakes import FakeMbBrowser
|
||||
from lyra_worker.main import _run_scan
|
||||
from lyra_worker.main import maybe_run_scan
|
||||
from lyra_worker.types import MBTarget
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ class FakeProbe:
|
||||
|
||||
class FakeResolver:
|
||||
def resolve(self, artist, album):
|
||||
return MBTarget(artist=artist, album=album, rg_mbid="rg1", artist_mbid="a1")
|
||||
return MBTarget(artist=artist, album=album, rg_mbid=f"rg-{album}", artist_mbid="a1")
|
||||
|
||||
|
||||
def _set(conn, key, value):
|
||||
@@ -31,15 +31,55 @@ def _get(conn, key):
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
def test_run_scan_writes_result_and_clears_flag(conn, tmp_path):
|
||||
(tmp_path / "John Mayer" / "Continuum (2006)").mkdir(parents=True)
|
||||
(tmp_path / "John Mayer" / "Continuum (2006)" / "01.flac").write_bytes(b"")
|
||||
def _album(tmp_path, artist, folder):
|
||||
d = tmp_path / artist / folder
|
||||
d.mkdir(parents=True)
|
||||
(d / "01.flac").write_bytes(b"")
|
||||
|
||||
|
||||
def _cfg(conn):
|
||||
from lyra_worker.config import get_config
|
||||
return get_config(conn)
|
||||
|
||||
|
||||
def test_scan_completes_in_one_chunk_writes_result_and_clears_flag(conn, tmp_path):
|
||||
_album(tmp_path, "John Mayer", "Continuum (2006)")
|
||||
_set(conn, "scan.requested", "true")
|
||||
|
||||
_run_scan(conn, FakeResolver(), FakeProbe(), FakeMbBrowser(), dest_root=str(tmp_path))
|
||||
# one album, default chunk size 25 -> starts + finishes in a single call
|
||||
maybe_run_scan(conn, FakeResolver(), FakeProbe(), FakeMbBrowser(), _cfg(conn), dest_root=str(tmp_path))
|
||||
|
||||
assert _get(conn, "scan.requested") == "false" # flag cleared
|
||||
assert _get(conn, "scan.requested") == "false" # flag cleared
|
||||
assert _get(conn, "scan.inProgress") == "false" # scan finished
|
||||
assert "imported" in (_get(conn, "scan.result") or "") # summary written
|
||||
with conn.cursor() as cur:
|
||||
cur.execute('SELECT count(*) FROM "LibraryItem"')
|
||||
assert cur.fetchone()[0] == 1
|
||||
|
||||
|
||||
def test_scan_chunks_across_iterations_and_totals_correctly(conn, tmp_path):
|
||||
for i in range(3):
|
||||
_album(tmp_path, "Artist", f"Album {i}")
|
||||
_set(conn, "scan.requested", "true")
|
||||
_set(conn, "scan.chunkSize", "2")
|
||||
|
||||
# first call starts the scan and processes chunk 1 (2 albums), leaving it in progress
|
||||
maybe_run_scan(conn, FakeResolver(), FakeProbe(), FakeMbBrowser(), _cfg(conn), dest_root=str(tmp_path))
|
||||
assert _get(conn, "scan.inProgress") == "true"
|
||||
assert _get(conn, "scan.requested") == "false"
|
||||
assert _get(conn, "scan.progress") == "2/0"
|
||||
|
||||
# second call resumes from the cursor, finishes the last album
|
||||
maybe_run_scan(conn, FakeResolver(), FakeProbe(), FakeMbBrowser(), _cfg(conn), dest_root=str(tmp_path))
|
||||
assert _get(conn, "scan.inProgress") == "false"
|
||||
assert _get(conn, "scan.result") == "imported 3, skipped 0"
|
||||
with conn.cursor() as cur:
|
||||
cur.execute('SELECT count(*) FROM "LibraryItem"')
|
||||
assert cur.fetchone()[0] == 3
|
||||
|
||||
|
||||
def test_maybe_run_scan_idle_when_not_requested_or_in_progress(conn, tmp_path):
|
||||
# no flags set -> no-op, no result written
|
||||
maybe_run_scan(conn, FakeResolver(), FakeProbe(), FakeMbBrowser(), _cfg(conn), dest_root=str(tmp_path))
|
||||
assert _get(conn, "scan.result") is None
|
||||
assert _get(conn, "scan.inProgress") is None
|
||||
|
||||
Reference in New Issue
Block a user