diff --git a/alembic/versions/2026_12_03_1200_file_group_statistics_index.py b/alembic/versions/2026_12_03_1200_file_group_statistics_index.py new file mode 100644 index 00000000..3700a519 --- /dev/null +++ b/alembic/versions/2026_12_03_1200_file_group_statistics_index.py @@ -0,0 +1,26 @@ +"""Add file_group_statistics_idx so the file statistics are counted from an index. + +The statistics summed json_array_length(files) and size over every file_group row. A row holds the file's indexed +text, so on a large library reading every row from a cold disk cache took minutes. + +Building the index reads every row once. + +Revision ID: 2026_12_03_1200 +Revises: 2026_12_01_1300 +""" +from alembic import op + +# revision identifiers, used by Alembic. +revision = '2026_12_03_1200' +down_revision = '2026_12_01_1300' +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute('CREATE INDEX IF NOT EXISTS file_group_statistics_idx' + ' ON file_group (mimetype, size, json_array_length(files))') + + +def downgrade(): + op.execute('DROP INDEX IF EXISTS file_group_statistics_idx') diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index cd5f20f3..1729e8a4 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -84,6 +84,9 @@ class FileGroup(ModelHelper, Base): Index('file_group_published_datetime_idx', 'published_datetime'), Index('file_group_published_modified_datetime_idx', 'published_modified_datetime'), 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)')), # 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 61b13233..e28c8c55 100644 --- a/wrolpi/files/test/test_lib.py +++ b/wrolpi/files/test/test_lib.py @@ -2285,6 +2285,40 @@ def test_sha256_files(test_directory): assert lib.sha256_files([video], known=known) == {video: (0, hashlib.sha256(b'video changed').hexdigest())} +def test_file_statistics_read_only_an_index(test_session, test_directory, make_files_structure): + """The file statistics are counted from a covering index, never from the file_group rows. A row holds the + file's indexed text, so reading every row of a large library from a cold disk cache took minutes.""" + make_files_structure(['video.mp4', 'doc.pdf', 'doc.txt']) + FileGroup.from_paths(test_session, test_directory / 'video.mp4') + FileGroup.from_paths(test_session, test_directory / 'doc.pdf', test_directory / 'doc.txt') + test_session.commit() + + statements = [] + connection = test_session.connection().connection.dbapi_connection + connection.set_trace_callback(lambda sql: statements.append(sql) if 'total_count' in sql else None) + try: + statistics = lib.get_file_statistics(test_session) + finally: + connection.set_trace_callback(None) + assert statistics['total_count'] == 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) file_group\b', i)] + assert file_group_steps, plan + for step in file_group_steps: + assert 'INDEX file_group_statistics_idx' in step, plan + + # Older SQLite (3.46) labels this step "USING INDEX", not "COVERING INDEX", because it opens the table with a + # deferred seek; the seek happens only if a table column is read. So check the bytecode: nothing reads a + # column (or seeks a row) from the file_group table cursor. + [root_page] = connection.execute("SELECT rootpage FROM sqlite_master WHERE type = 'table' AND name = 'file_group'") + program = list(connection.execute(f'EXPLAIN {statement}')) + table_cursors = {i[2] for i in program if i[1] == 'OpenRead' and i[3] == root_page[0]} + table_reads = [i for i in program if i[1] in ('Column', 'SeekRowid', 'NotExists', 'Seek') and i[2] in table_cursors] + assert not table_reads, table_reads + + @pytest.mark.parametrize('headline', [False, True]) def test_search_files_pages_inside_fts(test_session, test_directory, headline): """A search with no other filters ranks, pages and counts inside the FTS index, so only the page's rows are read diff --git a/wrolpi/test/test_db_bootstrap.py b/wrolpi/test/test_db_bootstrap.py index 4ac0def2..de311b6c 100644 --- a/wrolpi/test/test_db_bootstrap.py +++ b/wrolpi/test/test_db_bootstrap.py @@ -410,7 +410,11 @@ 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'")} 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}' def test_bootstrap_lock(test_directory):