From 9c258b41eed40a9e1113b2d747914b164291935b Mon Sep 17 00:00:00 2001 From: lrnselfreliance <33263708+lrnselfreliance@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:38:37 -0700 Subject: [PATCH] A refresh groups each stem's files together even when another stem sorts between them (#929) group_files_by_stem and chunks_by_stem assumed a stem's files are adjacent once sorted. They are not: foo.f137.mp4 (stem foo.f137) sorts between foo.en.vtt and foo.mp4 (stem foo), and foo.tar.gz between foo.jpg and foo.txt. _upsert_files then built two FileGroups for one (directory, stem) and the refresh failed with "UNIQUE constraint failed: file_group.directory, file_group.stem". A chunk boundary could split a stem the same way. Both helpers now group by (directory, stem). Co-authored-by: Claude Opus 5.5 --- wrolpi/common.py | 40 ++++++++-------------- wrolpi/files/lib.py | 43 +++++++++++------------- wrolpi/files/test/test_lib.py | 62 +++++++++++++++++++++++++++++++++++ wrolpi/test/test_common.py | 7 ++++ 4 files changed, 103 insertions(+), 49 deletions(-) diff --git a/wrolpi/common.py b/wrolpi/common.py index 747599eb..6636e1d3 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -2784,14 +2784,14 @@ def chunks(it: Iterable, size: int): def chunks_by_stem(it: List[Union[pathlib.Path, str, int]], size: int) -> Generator[List[pathlib.Path], None, None]: """ - Attempt to split a list of paths near the defined size. Keep groups of files together when they share - matching names. + Attempt to split a list of paths near the defined size. All files sharing a (directory, stem) are in the + same chunk. >>> files = ['1.mp4', '1.txt', '2.mp4', '2.txt', '2.png', '3.mp4'] - >>> chunks_by_stem(files, 2) - [['1.mp4', '1.txt'], ['2.mp4', '2.txt', '2.png'], ['3.mp4']] + >>> chunks_by_stem(files, 1) + [['1.mp4', '1.txt'], ['2.mp4', '2.png', '2.txt'], ['3.mp4']] >>> chunks_by_stem(files, 3) - [['1.mp4', '1.txt', '2.mp4', '2.txt', '2.png'], ['3.mp4']] + [['1.mp4', '1.txt', '2.mp4', '2.png', '2.txt'], ['3.mp4']] """ if not isinstance(size, int) or size < 1: raise ValueError('size must be a positive integer') @@ -2803,28 +2803,16 @@ def chunks_by_stem(it: List[Union[pathlib.Path, str, int]], size: int) -> Genera if not isinstance(it, list): raise ValueError('iterable must a list') - from wrolpi.files.lib import split_path_stem_and_suffix - it = sorted(it.copy()) - index = size - last_key = None - while it: - if index >= len(it): - # Ran out of items, yield what is left. - yield it - return - path = it[index] - path = pathlib.Path(path) - stem, _ = split_path_stem_and_suffix(path) - key = (str(path.parent), stem) - if last_key and key != last_key: - # Found a break in directory or stem, yield and reset. - chunk, it = it[:index], it[index:] - index = size - last_key = None + from wrolpi.files.lib import group_files_by_stem + # Pack whole stem groups; a chunk ends at the first group that takes it past `size`. + chunk = [] + for group in group_files_by_stem(it): + chunk.extend(group) + if len(chunk) > size: yield chunk - continue - last_key = key - index += 1 + chunk = [] + if chunk: + yield chunk @contextlib.contextmanager diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index 99369c08..66c8ccd2 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -831,6 +831,10 @@ def choose_primary_file(files: Union[Tuple[pathlib.Path], Iterable[pathlib.Path] return sorted(paths)[0] +# About how many files `_upsert_files` writes per transaction. A stem's files are never split across chunks. +UPSERT_CHUNK_SIZE = 500 + + def _upsert_files(files: List[pathlib.Path], progress_callback: Callable[[int, int], None] = None): """Insert/update all records of the provided files. @@ -847,9 +851,9 @@ def _upsert_files(files: List[pathlib.Path], processed_count = 0 non_primary_files = set() - for chunk in chunks_by_stem(files, 500): - # Group all files by their shared full-stem. `chunk_by_stem` already sorted the files. - grouped = group_files_by_stem(chunk, pre_sorted=True) + for chunk in chunks_by_stem(files, UPSERT_CHUNK_SIZE): + # Group all files by their shared full-stem. `chunks_by_stem` keeps each stem in one chunk. + grouped = group_files_by_stem(chunk) # Convert the groups into file_groups. Extract common information into `file_group.data`. values = dict() for group in grouped: @@ -1681,32 +1685,25 @@ def get_file_statistics(session: Session): return statistics -def group_files_by_stem(files: List[pathlib.Path], pre_sorted: bool = False) -> \ - Generator[List[pathlib.Path], None, None]: +def group_files_by_stem(files: Iterable[pathlib.Path]) -> Generator[List[pathlib.Path], None, None]: """ - Return lists of paths, each list contains only paths that share a common stem. + Return lists of paths, each list contains only paths that share a common directory and stem. + + Groups are ordered by (directory, stem), and each group is sorted. >>> a = ['foo.txt', 'foo.mp4', 'bar.txt'] >>> group_files_by_stem(list(map((pathlib.Path, a)))) - # Generator(['foo.mp4', 'foo.txt'], ['bar.txt']) - - @param files: A list of paths to be grouped. All paths must be in the same directory! - @param pre_sorted: This function requires the files to be sorted, it will sort them by default. + # Generator(['bar.txt'], ['foo.mp4', 'foo.txt']) """ - files = sorted(files) if not pre_sorted else files.copy() - file = files.pop(0) - group = [file, ] - prev_dir, prev_stem = file.parent, split_path_stem_and_suffix(file)[0] + # Sorted paths do not keep a stem's files together: `foo.tar.gz` (stem `foo.tar`) sorts between `foo.jpg` and + # `foo.txt` (stem `foo`). Group by (directory, stem) so each stem yields exactly one group. + groups = dict() for file in files: - stem, _ = split_path_stem_and_suffix(file) - if stem == prev_stem and file.parent == prev_dir: - group.append(file) - continue - # Directory or stem changed, group is finished. - yield group - group = [file, ] - prev_dir, prev_stem = file.parent, stem - yield group + file = pathlib.Path(file) + key = (str(file.parent), split_path_stem_and_suffix(file)[0]) + groups.setdefault(key, set()).add(file) + for key in sorted(groups): + yield sorted(groups[key]) async def _get_tag_and_file_group(session: Session, file_group_id: int, file_group_primary_path: str, tag_name: str, diff --git a/wrolpi/files/test/test_lib.py b/wrolpi/files/test/test_lib.py index ea8e48df..1d5080ae 100644 --- a/wrolpi/files/test/test_lib.py +++ b/wrolpi/files/test/test_lib.py @@ -469,6 +469,50 @@ async def test_refresh_paths(test_session, make_files_structure, test_directory, ]) +@pytest.mark.asyncio +@pytest.mark.parametrize('chunk_size', [500, 1]) +async def test__upsert_files_interleaved_stems(test_session, make_files_structure, test_directory, video_bytes, + assert_file_groups, chunk_size): + """Files sharing a stem are one FileGroup even when another stem sorts between them, and even when the chunk + size would split them. Two FileGroups for one (directory, stem) violate its unique index.""" + files = make_files_structure({ + 'foo.en.vtt': 'WEBVTT', + 'foo.f137.mp4': video_bytes, + 'foo.jpg': 'jpg', + 'foo.mp4': video_bytes, + 'foo.tar.gz': 'tar', + 'foo.txt': 'text', + }) + + with mock.patch('wrolpi.files.lib.UPSERT_CHUNK_SIZE', chunk_size): + lib._upsert_files(files) + + assert_file_groups([ + {'primary_path': 'foo.mp4', 'stem': 'foo', + 'files': [{'path': 'foo.en.vtt'}, {'path': 'foo.jpg'}, {'path': 'foo.mp4'}, {'path': 'foo.txt'}]}, + {'primary_path': 'foo.f137.mp4', 'stem': 'foo.f137', 'files': [{'path': 'foo.f137.mp4'}]}, + {'primary_path': 'foo.tar.gz', 'stem': 'foo.tar', 'files': [{'path': 'foo.tar.gz'}]}, + ]) + + +@pytest.mark.asyncio +async def test_refresh_interleaved_stems(test_session, make_files_structure, test_directory, video_bytes, + refresh_files): + """Refreshing a directory whose stems interleave when sorted creates one FileGroup per stem.""" + make_files_structure({ + 'videos/foo.en.vtt': 'WEBVTT', + 'videos/foo.f137.mp4': video_bytes, + 'videos/foo.jpg': 'jpg', + 'videos/foo.mp4': video_bytes, + }) + await refresh_files([test_directory]) + + file_groups = {i.stem: i for i in test_session.query(FileGroup)} + assert set(file_groups) == {'foo', 'foo.f137'} + assert {'foo.en.vtt', 'foo.jpg', 'foo.mp4'} <= {i['path'].name for i in file_groups['foo'].my_files()} + assert file_groups['foo'].primary_path == test_directory / 'videos/foo.mp4' + + @pytest.mark.asyncio async def test_refresh_groups(test_session, make_files_structure, test_directory, video_bytes, refresh_files): make_files_structure({'dir1/foo.mp4': video_bytes, 'dir1/foo.info.json': 'hello', 'baz.txt': 'hello'}) @@ -988,6 +1032,24 @@ def test_group_files_by_stem(make_files_structure, test_directory): ] +def test_group_files_by_stem_interleaved(make_files_structure, test_directory): + """A stem's files are one group even when another stem sorts between them. + + `foo.f137.mp4` (stem `foo.f137`) and `foo.tar.gz` (stem `foo.tar`) sort between `foo.en.vtt`, `foo.jpg`, + `foo.mp4` and `foo.txt` (stem `foo`).""" + files = make_files_structure([ + 'foo.en.vtt', 'foo.f137.mp4', 'foo.jpg', 'foo.mp4', 'foo.tar.gz', 'foo.txt', + ]) + expected = [ + [test_directory / i for i in ('foo.en.vtt', 'foo.jpg', 'foo.mp4', 'foo.txt')], + [test_directory / 'foo.f137.mp4'], + [test_directory / 'foo.tar.gz'], + ] + assert list(lib.group_files_by_stem(files)) == expected + # Input order does not matter. + assert list(lib.group_files_by_stem(list(reversed(files)))) == expected + + def test_get_primary_file(test_directory, video_file, srt_file3, example_epub, example_mobi, example_pdf, singlefile_contents_factory, make_files_structure): """Test that the most important file is returned from a list of files.""" diff --git a/wrolpi/test/test_common.py b/wrolpi/test/test_common.py index b38e98e5..95b25a20 100644 --- a/wrolpi/test/test_common.py +++ b/wrolpi/test/test_common.py @@ -443,6 +443,13 @@ def test_chunks_by_stem(test_directory, make_files_structure): assert_chunks(6, files, [['1.mp4', '1.txt', '2.mp4', '2.png', '2.txt', '3.mp4']]) assert_chunks(20, files, [['1.mp4', '1.txt', '2.mp4', '2.png', '2.txt', '3.mp4']]) + # A stem is never split across chunks, even when another stem sorts between its files. + files = make_files_structure(['interleaved/foo.jpg', 'interleaved/foo.tar.gz', 'interleaved/foo.txt']) + assert list(common.chunks_by_stem(files, 1)) == [ + [test_directory / 'interleaved/foo.jpg', test_directory / 'interleaved/foo.txt'], + [test_directory / 'interleaved/foo.tar.gz'], + ] + @pytest.mark.parametrize( 'value,expected', [