mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-02 20:59:56 -05:00
A refresh compare and the doc modeler read file_group through its indexes (#1083)
A refresh compared its roots with `directory LIKE 'root/%'`, and the doc modeler found comics with `primary_path LIKE '%.cbz'`. SQLite cannot use an index for either, so both read every row of file_group. With a cold page cache on a large library, a refresh of one empty directory took ~3.5 minutes, and a move queued behind it waited that long. The compare now uses a range on `directory` (as `directory_or_descendant` does), which also stops `_` and `%` in a path acting as wildcards: refreshing `a_b` reported the FileGroups of `aXb/...` as deleted. The doc modeler matches the indexed, lowercased `suffix` column instead. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1c095d1104
commit
0ccedde3b0
4 changed files with 82 additions and 10 deletions
|
|
@ -1,7 +1,7 @@
|
|||
import logging
|
||||
from typing import Callable
|
||||
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy import and_, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from wrolpi.common import register_modeler, register_refresh_cleanup, \
|
||||
|
|
@ -23,13 +23,13 @@ DOC_PROCESSING_LIMIT = 10
|
|||
DOC_LOCK_RETRIES = 3
|
||||
|
||||
|
||||
def _select_doc_ids(session, skip_ids: set) -> list[int]:
|
||||
query = session.query(FileGroup.id) \
|
||||
.outerjoin(Doc, Doc.file_group_id == FileGroup.id) \
|
||||
.filter(
|
||||
def _doc_candidate_filter():
|
||||
return and_(
|
||||
or_(
|
||||
*[FileGroup.mimetype == mt for mt in DOC_MIMETYPES],
|
||||
*[FileGroup.primary_path.like(f'%{suffix}') for suffix in COMIC_BOOK_SUFFIXES],
|
||||
# A comic whose mimetype was not detected is found by its suffix. `suffix` is indexed and
|
||||
# lowercased; `primary_path LIKE '%.cbz'` read every row of file_group.
|
||||
FileGroup.suffix.in_(COMIC_BOOK_SUFFIXES),
|
||||
),
|
||||
# Model any doc that has no Doc row yet (even if `apply_indexers` already set
|
||||
# `indexed=True` before this modeler ran), or any doc explicitly flagged for
|
||||
|
|
@ -40,6 +40,12 @@ def _select_doc_ids(session, skip_ids: set) -> list[int]:
|
|||
FileGroup.indexed != True,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _select_doc_ids(session, skip_ids: set) -> list[int]:
|
||||
query = session.query(FileGroup.id) \
|
||||
.outerjoin(Doc, Doc.file_group_id == FileGroup.id) \
|
||||
.filter(_doc_candidate_filter())
|
||||
query = skip_clause(query, FileGroup.id, skip_ids)
|
||||
return [row[0] for row in query.limit(DOC_PROCESSING_LIMIT).all()]
|
||||
|
||||
|
|
|
|||
|
|
@ -5,10 +5,11 @@ import sqlite3
|
|||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import sqlalchemy
|
||||
from PIL import Image
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from modules.docs import doc_modeler
|
||||
from modules.docs import doc_modeler, _doc_candidate_filter, _select_doc_ids
|
||||
from modules.docs.models import Doc, DocSection
|
||||
from wrolpi.files import lib as files_lib
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
|
@ -435,3 +436,31 @@ async def test_doc_modeler_pdf_poster(test_session, example_pdf):
|
|||
assert file_group.data.get('cover_path') == poster_path.name
|
||||
|
||||
|
||||
|
||||
|
||||
def test_select_doc_ids_uses_indexes(test_session):
|
||||
"""The modeler's candidate query reads file_group through its indexes, never by scanning every row.
|
||||
|
||||
A scan of a large library with a cold page cache held each refresh (and the move waiting behind it) for
|
||||
minutes even when there was nothing to model."""
|
||||
statement = test_session.query(FileGroup.id) \
|
||||
.outerjoin(Doc, Doc.file_group_id == FileGroup.id) \
|
||||
.filter(_doc_candidate_filter()).statement \
|
||||
.compile(compile_kwargs={'literal_binds': True})
|
||||
plan = ' '.join(row[3] for row in test_session.execute(sqlalchemy.text(f'EXPLAIN QUERY PLAN {statement}')))
|
||||
assert 'SCAN file_group' not in plan, plan
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_doc_modeler_models_comic_by_suffix(async_client, test_session, test_directory, example_cbz):
|
||||
"""A comic book whose mimetype was not detected as a comic is still modeled by its suffix."""
|
||||
upper = example_cbz.with_name('Upper Comic.CBZ')
|
||||
example_cbz.rename(upper)
|
||||
file_group = FileGroup.from_paths(test_session, upper)
|
||||
file_group.mimetype = 'application/zip'
|
||||
test_session.commit()
|
||||
|
||||
assert _select_doc_ids(test_session, set()) == [file_group.id]
|
||||
|
||||
await doc_modeler()
|
||||
assert test_session.query(Doc).one().file_group_id == file_group.id
|
||||
|
|
|
|||
|
|
@ -236,14 +236,19 @@ def _normalize_roots(roots: Path | list[Path] | None) -> list[Path]:
|
|||
|
||||
|
||||
def _directory_in_roots_sql(roots: list[Path], column: str = 'fg.directory') -> Tuple[str, dict]:
|
||||
"""SQL fragment: `column` is any of the roots or a subdirectory of one."""
|
||||
"""SQL fragment: `column` is any of the roots or a subdirectory of one.
|
||||
|
||||
A range is used instead of `LIKE 'root/%'` so SQLite can use the column's index (it cannot for a
|
||||
case-insensitive LIKE), and so `_` and `%` in a path are not wildcards. '0' is the character after '/'.
|
||||
See `directory_or_descendant`."""
|
||||
clauses = []
|
||||
params = {}
|
||||
for i, root in enumerate(roots):
|
||||
root_str = str(root)
|
||||
clauses.append(f'({column} = :root_{i} OR {column} LIKE :root_pat_{i})')
|
||||
clauses.append(f'({column} = :root_{i} OR ({column} >= :root_lo_{i} AND {column} < :root_hi_{i}))')
|
||||
params[f'root_{i}'] = root_str
|
||||
params[f'root_pat_{i}'] = f'{root_str}/%'
|
||||
params[f'root_lo_{i}'] = f'{root_str}/'
|
||||
params[f'root_hi_{i}'] = f'{root_str}0'
|
||||
return '(' + ' OR '.join(clauses) + ')', params
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ from wrolpi.files.worker import (
|
|||
from wrolpi.files.refresh import (
|
||||
_split_nul_field_triples,
|
||||
_entry_from_printf_fields,
|
||||
_directory_in_roots_sql,
|
||||
_normalize_roots,
|
||||
GNU_FIND_PRINTF,
|
||||
_stream_gnu_find_entries,
|
||||
|
|
@ -2033,3 +2034,34 @@ async def test_refresh_missing_path_keeps_lookalike_directories(
|
|||
|
||||
test_session.expire_all()
|
||||
assert [i.primary_path for i in test_session.query(FileGroup)] == [kept]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_compare_file_groups_ignores_lookalike_directories(test_session, test_directory, make_files_structure):
|
||||
"""Comparing one directory never reports a directory whose name differs by a character `LIKE` would treat as a
|
||||
wildcard (`_` matches any one character)."""
|
||||
make_files_structure(['a_b/kept.txt', 'aXb/lookalike.txt', 'aXb/sub/deep.txt'])
|
||||
for path in (test_directory / 'a_b/kept.txt', test_directory / 'aXb/lookalike.txt',
|
||||
test_directory / 'aXb/sub/deep.txt'):
|
||||
FileGroup.from_paths(test_session, path)
|
||||
test_session.commit()
|
||||
# The lookalike's files are gone from disk; only a refresh of `aXb` may report them deleted.
|
||||
(test_directory / 'aXb/lookalike.txt').unlink()
|
||||
(test_directory / 'aXb/sub/deep.txt').unlink()
|
||||
|
||||
result = await compare_file_groups(test_directory / 'a_b')
|
||||
|
||||
assert result.deleted == []
|
||||
assert [d.stem for d in result.unchanged] == ['kept']
|
||||
|
||||
|
||||
def test_directory_in_roots_sql_uses_directory_index(test_session):
|
||||
"""The compare's directory filter reads file_group through the directory index, never by scanning every row.
|
||||
|
||||
A scan of a large library with a cold page cache held a refresh of one empty directory (and the move waiting
|
||||
behind it) for most of a minute."""
|
||||
roots_sql, params = _directory_in_roots_sql([pathlib.Path('/media/a'), pathlib.Path('/media/b')])
|
||||
rows = test_session.execute(text(f'EXPLAIN QUERY PLAN SELECT fg.id FROM file_group fg WHERE {roots_sql}'), params)
|
||||
plan = ' '.join(row[3] for row in rows)
|
||||
assert 'SCAN fg' not in plan and 'SCAN file_group' not in plan, plan
|
||||
assert 'file_group_directory' in plan, plan
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue