diff --git a/alembic/versions/2026_12_04_1200_file_group_statistics_index_order.py b/alembic/versions/2026_12_04_1200_file_group_statistics_index_order.py new file mode 100644 index 00000000..f99dc958 --- /dev/null +++ b/alembic/versions/2026_12_04_1200_file_group_statistics_index_order.py @@ -0,0 +1,26 @@ +"""Lead file_group_statistics_idx with json_array_length(files), so it serves only the statistics scan. + +Led by mimetype, SQLite chose it for mimetype lookups: a database analyzed before the index existed has no +statistics for it, so the planner guessed it was the most selective. The newest-videos page then read and sorted +every video's row instead of reading one page from file_group_mimetype_effective_idx. + +Revision ID: 2026_12_04_1200 +Revises: 2026_12_03_1200 +""" +from alembic import op + +# revision identifiers, used by Alembic. +revision = '2026_12_04_1200' +down_revision = '2026_12_03_1200' +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute('DROP INDEX IF EXISTS file_group_statistics_idx') + op.execute('CREATE INDEX file_group_statistics_idx ON file_group (json_array_length(files), mimetype, size)') + + +def downgrade(): + op.execute('DROP INDEX IF EXISTS file_group_statistics_idx') + op.execute('CREATE INDEX file_group_statistics_idx ON file_group (mimetype, size, json_array_length(files))') diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index 1729e8a4..acc9233e 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -86,7 +86,9 @@ class FileGroup(ModelHelper, Base): Index('file_group_size_ix', 'size'), # Covers the file statistics (counts by mimetype, total size, total file count), so they are counted without # reading every (large) file_group row. The query must use this exact expression: json_array_length(files). - Index('file_group_statistics_idx', 'mimetype', 'size', text('json_array_length(files)')), + # The expression leads so the index serves only that full scan: led by mimetype, SQLite chose it for mimetype + # lookups (it has no ANALYZE row), which made the newest-videos page read and sort every video's row. + Index('file_group_statistics_idx', text('json_array_length(files)'), 'mimetype', 'size'), # Covers reading the published date, size, and length of FileGroups looked up by id (a Channel's statistics, # a Video's neighbors): reading those rows themselves is a scattered page per FileGroup. SQLite prefers the # rowid, so a query must name this index with INDEXED BY. diff --git a/wrolpi/files/test/test_lib.py b/wrolpi/files/test/test_lib.py index e28c8c55..802840b6 100644 --- a/wrolpi/files/test/test_lib.py +++ b/wrolpi/files/test/test_lib.py @@ -17,6 +17,7 @@ from PIL import Image import wrolpi.common from modules.videos import Video +from modules.videos.video.lib import search_videos from wrolpi.common import timer, get_wrolpi_config from wrolpi.config_version import get_config_version, set_config_version from wrolpi.conftest import await_switches, await_file_worker @@ -2359,3 +2360,41 @@ def test_search_files_pages_inside_fts(test_session, test_directory, headline): assert re.search(r'ORDER BY rank\s+LIMIT :limit OFFSET :offset\s*\)', statement), statement for call in count_query.call_args_list: assert 'file_group fg' not in call.args[1] and 'file_group_fts' in call.args[1], call.args[1] + + +def test_file_statistics_index_does_not_serve_mimetype_lookups(test_session, video_factory): + """file_group_statistics_idx covers only the full statistics scan. It must not be chosen for a mimetype lookup: + the newest-videos page needs file_group_mimetype_effective_idx to read just one page in date order, instead of + reading and sorting every video's row.""" + for _ in range(3): + video_factory() + test_session.commit() + + # Plan as on a large library whose statistics predate this index: ANALYZE rows say a mimetype matches many + # rows, and there is no row for file_group_statistics_idx, so SQLite guesses that index is selective. + connection = test_session.connection().connection.dbapi_connection + connection.execute('ANALYZE') + connection.execute("DELETE FROM sqlite_stat1 WHERE tbl = 'file_group'") + connection.executemany("INSERT INTO sqlite_stat1 (tbl, idx, stat) VALUES ('file_group', ?, ?)", [ + ('file_group_mimetype_idx', '200000 1000'), + ('file_group_mimetype_effective_idx', '200000 1000 1000'), + ]) + connection.execute('ANALYZE sqlite_schema') # reload the statistics + + statements = [] + connection.set_trace_callback(lambda sql: statements.append(sql) if 'UNION ALL' in sql or 'LIMIT 20)' in sql else None) + try: + videos, total = search_videos(test_session, order='-published_datetime', limit=20, offset=0) + finally: + connection.set_trace_callback(None) + assert total == 3 + + [statement] = statements + plan = [i[3] for i in connection.execute(f'EXPLAIN QUERY PLAN {statement}')] + file_group_steps = [i for i in plan if re.match(r'(SEARCH|SCAN) fg\b', i)] + assert file_group_steps, plan + for step in file_group_steps: + assert 'file_group_mimetype_effective_idx' in step, plan + + plan = [i[3] for i in connection.execute("EXPLAIN QUERY PLAN SELECT COUNT(*) FROM file_group WHERE mimetype = 'a/b'")] + assert not any('file_group_statistics_idx' in i for i in plan), plan diff --git a/wrolpi/test/test_db_bootstrap.py b/wrolpi/test/test_db_bootstrap.py index de311b6c..e3143a14 100644 --- a/wrolpi/test/test_db_bootstrap.py +++ b/wrolpi/test/test_db_bootstrap.py @@ -1,8 +1,12 @@ """Tests for wrolpi.db_bootstrap: DB auto-creation, migration, and the drive-portability guard.""" +import re import sqlite3 import mock import pytest +from sqlalchemy import Column +from sqlalchemy.dialects import sqlite +from sqlalchemy.schema import CreateIndex from wrolpi import db_bootstrap from wrolpi.db import get_db_file @@ -410,11 +414,22 @@ def test_migrations_match_models(test_directory): with engine.connect() as conn: context = MigrationContext.configure(conn, opts={'include_object': include_object, 'render_as_batch': True}) diffs = compare_metadata(context, Base.metadata) - # compare_metadata skips expression indexes, so check by name that every model index was migrated. - db_indexes = {i for i, in conn.exec_driver_sql("SELECT name FROM sqlite_master WHERE type = 'index'")} + # compare_metadata skips expression indexes, so check by name that every model index was migrated, and + # compare an expression index's terms (their order decides which queries SQLite can use it for). + db_indexes = dict(conn.exec_driver_sql("SELECT name, sql FROM sqlite_master WHERE type = 'index'").fetchall()) assert not diffs, diffs - model_indexes = {i.name for name in model_tables for i in Base.metadata.tables[name].indexes} - assert model_indexes <= db_indexes, f'Model indexes without a migration: {model_indexes - db_indexes}' + model_indexes = {i.name: i for name in model_tables for i in Base.metadata.tables[name].indexes} + missing = set(model_indexes) - set(db_indexes) + assert not missing, f'Model indexes without a migration: {missing}' + + def terms(create_sql: str) -> str: + return re.sub(r'\s+', '', create_sql[create_sql.index('(') + 1:create_sql.rindex(')')]) + + for name, index in model_indexes.items(): + if all(isinstance(e, Column) for e in index.expressions): + continue + model_sql = str(CreateIndex(index).compile(dialect=sqlite.dialect())) + assert terms(model_sql) == terms(db_indexes[name]), f'{name}: model {model_sql!r}, migrated {db_indexes[name]!r}' def test_bootstrap_lock(test_directory):