From b9a892b203d1782c43aa21adb53d8c11bcfc225c Mon Sep 17 00:00:00 2001 From: Roland Date: Sat, 1 Aug 2026 19:39:57 -0600 Subject: [PATCH] =?UTF-8?q?fix:=20act=20on=20review=20=E2=80=94=20don't=20?= =?UTF-8?q?hold=20the=20write=20lock=20across=20the=20source-tree=20walk?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two review points, both correct. The planning session was opened before the filesystem collection that runs inside it, so BEGIN IMMEDIATE held the write lock across every glob and directory walk - trading an instant abort for minutes of global write starvation on a large channel. The collection now finishes before the session opens; only the temp-table load, the FileGroup reads and inserts, and the commit run under the lock. `file_source_set` is built during that same pass instead of re-globbing every file source a second time. `test_file_worker_move_survives_concurrent_writer` held the lock across the whole move, so planning waited it out and the execute phase usually met no contention - the test would have stayed green if only the execute site regressed. It now takes the lock after planning returns. Verified by mutation: reverting either site alone fails its own test. Co-Authored-By: Claude Opus 5 (1M context) --- wrolpi/files/test/test_worker_move.py | 29 ++++++--- wrolpi/files/worker.py | 84 +++++++++++++-------------- 2 files changed, 62 insertions(+), 51 deletions(-) diff --git a/wrolpi/files/test/test_worker_move.py b/wrolpi/files/test/test_worker_move.py index b6ee6284..00ab0b37 100644 --- a/wrolpi/files/test/test_worker_move.py +++ b/wrolpi/files/test/test_worker_move.py @@ -7,6 +7,7 @@ import time import pytest from wrolpi.conftest import production_like_sessions +from wrolpi.files import worker as worker_module from wrolpi.files.lib import _move_file_group_files from wrolpi.files.models import FileGroup, Directory from wrolpi.files.worker import file_worker, FileTask, FileTaskType, build_move_plan_bulk @@ -592,13 +593,14 @@ async def test_build_move_plan_waits_for_concurrent_writer( @pytest.mark.asyncio async def test_file_worker_move_survives_concurrent_writer( - async_client, test_session, test_directory, make_files_structure + async_client, test_session, test_directory, make_files_structure, monkeypatch ): - """A move of already-indexed files must survive a concurrent writer holding the write lock. + """Executing a move must survive a concurrent writer holding the write lock. - Planning writes nothing here (every file is already indexed), so the first write is the - `FileGroup` UPDATE inside `_execute_move_chunks`. That transaction must begin as a writer, - or SQLite refuses the mid-transaction lock upgrade instantly and the move aborts. + `_execute_move_chunks` reads FileGroups/Directories and then writes them, so its transaction + must begin as a writer too - SQLite refuses the mid-transaction lock upgrade instantly and the + move aborts. The lock is taken only *after* planning finishes, so this fails if the execute + site alone regresses; planning cannot absorb the contention on the execute site's behalf. """ file1, = make_files_structure(['source/file1.txt']) FileGroup.from_paths(test_session, file1) @@ -612,9 +614,20 @@ async def test_file_worker_move_survives_concurrent_writer( task = FileTask(FileTaskType.move, [file1], destination=dest) file_worker.private_queue.put_nowait(task) - with production_like_sessions(test_session) as maker: - with _write_lock_held_briefly(db_file): - await file_worker.process_queue() + with contextlib.ExitStack() as stack: + maker = stack.enter_context(production_like_sessions(test_session)) + + real_build_move_plan_bulk = worker_module.build_move_plan_bulk + + async def build_plan_then_hold_write_lock(*args, **kwargs): + plan = await real_build_move_plan_bulk(*args, **kwargs) + # Planning is done; the contention now falls entirely on the execute phase. + stack.enter_context(_write_lock_held_briefly(db_file)) + return plan + + monkeypatch.setattr(worker_module, 'build_move_plan_bulk', build_plan_then_hold_write_lock) + + await file_worker.process_queue() assert (dest / 'file1.txt').is_file(), 'file was not moved' assert not file1.exists(), 'file was left at its old path' diff --git a/wrolpi/files/worker.py b/wrolpi/files/worker.py index 6b508efb..f07887ac 100644 --- a/wrolpi/files/worker.py +++ b/wrolpi/files/worker.py @@ -556,6 +556,46 @@ async def build_move_plan_bulk( if progress_callback and i % 100 == 0: progress_callback(i, total_sources * 2) # *2 because file collection is second half + # Collect all paths to insert: file paths + expanded directory contents. This walks the whole + # source tree, which is slow on Pi storage, so it must finish before the DB session opens - the + # session holds the SQLite write lock for its lifetime and would starve every other writer. + all_file_paths: list[pathlib.Path] = [] + files_collected = 0 + # Use total_sources as the denominator for the second half of progress + total_items = len(file_sources) + len(dir_sources) + + # For files, collect the file and its shared-stem siblings + file_source_set: Set[str] = set() + for i, source in enumerate(file_sources, 1): + files = glob_shared_stem(source) + all_file_paths.extend(files) + file_source_set.update(str(f) for f in files) + files_collected += 1 + # Report progress (second half: 50-100%) + if progress_callback and files_collected % 50 == 0: + progress = total_sources + (files_collected * total_sources // max(total_items, 1)) + progress_callback(progress, total_sources * 2) + + # For directories, walk and collect all files + dir_file_mapping: Dict[pathlib.Path, pathlib.Path] = {} # file -> source_dir + for i, source_dir in enumerate(dir_sources, 1): + for f in walk(source_dir): + if f.is_file(): + all_file_paths.append(f) + dir_file_mapping[f] = source_dir + files_collected += 1 + # Report progress during directory walking (every 10 directories) + if progress_callback and files_collected % 10 == 0: + progress = total_sources + (files_collected * total_sources // max(total_items, 1)) + progress_callback(progress, total_sources * 2) + + # Final progress update before deduplication + if progress_callback: + progress_callback(total_sources * 2, total_sources * 2) + + # Deduplicate + all_file_paths = list(set(all_file_paths)) + # Planning reads FileGroups and then INSERTs the ones missing from the DB, so the transaction # must begin as a writer. A deferred transaction upgrading to a writer mid-way gets "database # is locked" *immediately* (busy_timeout is skipped for lock upgrades), so any concurrent @@ -575,42 +615,6 @@ async def build_move_plan_bulk( """)) session.execute(text("DELETE FROM move_sources")) - # Collect all paths to insert: file paths + expanded directory contents - all_file_paths: list[pathlib.Path] = [] - files_collected = 0 - # Use total_sources as the denominator for the second half of progress - total_items = len(file_sources) + len(dir_sources) - - # For files, collect the file and its shared-stem siblings - for i, source in enumerate(file_sources, 1): - files = glob_shared_stem(source) - all_file_paths.extend(files) - files_collected += 1 - # Report progress (second half: 50-100%) - if progress_callback and files_collected % 50 == 0: - progress = total_sources + (files_collected * total_sources // max(total_items, 1)) - progress_callback(progress, total_sources * 2) - - # For directories, walk and collect all files - dir_file_mapping: Dict[pathlib.Path, pathlib.Path] = {} # file -> source_dir - for i, source_dir in enumerate(dir_sources, 1): - for f in walk(source_dir): - if f.is_file(): - all_file_paths.append(f) - dir_file_mapping[f] = source_dir - files_collected += 1 - # Report progress during directory walking (every 10 directories) - if progress_callback and files_collected % 10 == 0: - progress = total_sources + (files_collected * total_sources // max(total_items, 1)) - progress_callback(progress, total_sources * 2) - - # Final progress update before deduplication - if progress_callback: - progress_callback(total_sources * 2, total_sources * 2) - - # Deduplicate - all_file_paths = list(set(all_file_paths)) - # Bulk insert file paths into temp table if all_file_paths: session.execute( @@ -647,13 +651,7 @@ async def build_move_plan_bulk( logger.info(f'build_move_plan_bulk: found {len(fg_by_path)} FileGroups for {len(all_file_paths)} files') - # Build plan for file sources (direct files, not from directories) - file_source_set = set() - for source in file_sources: - files = glob_shared_stem(source) - file_source_set.update(str(f) for f in files) - - # Process files from direct file sources + # Process files from direct file sources (`file_source_set` was collected above) for path_str, (fg_id, primary_path, directory) in fg_by_path.items(): path = pathlib.Path(path_str) primary_path = pathlib.Path(primary_path)