diff --git a/alembic/versions/2026_12_05_1200_video_statistics_index_view_count.py b/alembic/versions/2026_12_05_1200_video_statistics_index_view_count.py new file mode 100644 index 00000000..62641674 --- /dev/null +++ b/alembic/versions/2026_12_05_1200_video_statistics_index_view_count.py @@ -0,0 +1,27 @@ +"""Add view_count to video_statistics_idx, so the Videos page can order by view count without reading every +(wide) video row. + +ANALYZE the recreated index: without its statistics row SQLite looks up each Video by the unique file_group_id index +and reads the row anyway. It reads only the index. + +Revision ID: 2026_12_05_1200 +Revises: 2026_12_04_1300 +""" +from alembic import op + +# revision identifiers, used by Alembic. +revision = '2026_12_05_1200' +down_revision = '2026_12_04_1300' +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute('DROP INDEX IF EXISTS video_statistics_idx') + op.execute('CREATE INDEX video_statistics_idx ON video (file_group_id, have_comments, comments_failed, view_count)') + op.execute('ANALYZE video_statistics_idx') + + +def downgrade(): + op.execute('DROP INDEX IF EXISTS video_statistics_idx') + op.execute('CREATE INDEX video_statistics_idx ON video (file_group_id, have_comments, comments_failed)') diff --git a/modules/videos/models.py b/modules/videos/models.py index 199bc36e..e6fb46c5 100644 --- a/modules/videos/models.py +++ b/modules/videos/models.py @@ -36,8 +36,9 @@ class Video(ModelHelper, Base): # Covers a Channel's Videos: video rows are wide (ffprobe_json), so finding a Channel's FileGroups must not # read them. Index('video_channel_file_group_idx', 'channel_id', 'file_group_id'), - # Covers the Video statistics (every Video's FileGroup and comment state) without reading the wide rows. - Index('video_statistics_idx', 'file_group_id', 'have_comments', 'comments_failed'), + # Covers the Video statistics (every Video's FileGroup and comment state) and the view count order of the + # Videos page without reading the wide rows. + Index('video_statistics_idx', 'file_group_id', 'have_comments', 'comments_failed', 'view_count'), Index('video_source_id_idx', 'source_id'), Index('video_view_count_idx', 'view_count'), # Do not reuse ids of deleted Videos (AUTOINCREMENT keeps a sequence table). diff --git a/modules/videos/test/test_api.py b/modules/videos/test/test_api.py index b57f3097..758d7c19 100644 --- a/modules/videos/test/test_api.py +++ b/modules/videos/test/test_api.py @@ -660,6 +660,48 @@ async def test_search_videos_does_not_block_event_loop(async_client): assert search_response.status_code == HTTPStatus.OK +def test_search_videos_by_view_count_reads_only_indexes(test_session, video_factory): + """Ordering by view count reads each Video's view_count from video_statistics_idx, never from the video row. + Video rows are wide (ffprobe_json); reading every one from a cold disk cache took over a minute.""" + view_counts = [5, None, 50, 20] + videos = [video_factory() for _ in view_counts] + for video, view_count in zip(videos, view_counts): + video.view_count = view_count + test_session.commit() + most_viewed = [videos[2].file_group_id, videos[3].file_group_id, videos[0].file_group_id] + + # Plan as on a large library: the mimetype matches many rows, and each FileGroup has one Video. + connection = test_session.connection().connection.dbapi_connection + connection.execute('ANALYZE') + connection.execute("DELETE FROM sqlite_stat1 WHERE tbl IN ('file_group', 'video')") + connection.executemany('INSERT INTO sqlite_stat1 (tbl, idx, stat) VALUES (?, ?, ?)', [ + ('file_group', 'file_group_mimetype_idx', '200000 1000'), + ('video', 'sqlite_autoindex_video_1', '100000 1'), + ('video', 'video_statistics_idx', '100000 1 1 1 1'), + ]) + connection.execute('ANALYZE sqlite_schema') # reload the statistics + + statements = [] + connection.set_trace_callback(lambda sql: statements.append(sql) if 'v.view_count IS NOT NULL' in sql else None) + try: + results, total = video_lib.search_videos(test_session, order='-view_count', limit=24, offset=0) + assert [i['id'] for i in results] == most_viewed and total == 3 + results, total = video_lib.search_videos(test_session, order='view_count', limit=24, offset=0) + assert [i['id'] for i in results] == most_viewed[::-1] and total == 3 + finally: + connection.set_trace_callback(None) + + # The page and its count, for both orders. + assert len(statements) == 4, statements + root_page = connection.execute("SELECT rootpage FROM sqlite_master WHERE type = 'table' AND name = 'video'").fetchone() + for statement in statements: + program = list(connection.execute(f'EXPLAIN {statement}')) + video_cursors = {i[2] for i in program if i[1] == 'OpenRead' and i[3] == root_page[0]} + video_reads = [i for i in program + if i[1] in ('Column', 'SeekRowid', 'NotExists', 'Seek') and i[2] in video_cursors] + assert not video_reads, (statement, video_reads) + + @pytest.mark.asyncio async def test_search_videos_default_page_pagination(test_session, video_factory, audio_factory, assert_video_search): """The unfiltered Videos page (no search/tags/channel) pages through every video and audio file in