File statistics are counted from a covering index (#1088)

get_file_statistics summed json_array_length(files) and size over every
file_group row.  A row also holds the file's indexed text, so on a large
library reading every row from a cold disk cache took minutes, and the
Statistics page timed out.

file_group_statistics_idx (mimetype, size, json_array_length(files)) holds
everything the query reads, so it scans only the index.  SQLite 3.46 labels
the step "USING INDEX" (it opens the table with a deferred seek it never
performs); the test checks the bytecode, so it holds on both labels.

test_migrations_match_models also checks that every model index exists in
the migrated database: alembic's compare_metadata skips expression indexes.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-12-03 18:04:37 -07:00 • committed by Roland
parent 4aa11c552d
commit 77133fab8d
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
4 changed files with 67 additions and 0 deletions

View file

@ -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')

View file

@ -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.

View file

@ -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

View file

@ -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):