diff --git a/alembic/versions/2026_12_01_1200_video_channel_file_group_index.py b/alembic/versions/2026_12_01_1200_video_channel_file_group_index.py new file mode 100644 index 00000000..ee746c51 --- /dev/null +++ b/alembic/versions/2026_12_01_1200_video_channel_file_group_index.py @@ -0,0 +1,31 @@ +"""Cover a Channel's Videos with indexes: video (channel_id, file_group_id) and +file_group (id, published_datetime, size, length). + +A Channel's statistics find its Videos' FileGroups and sum their sizes and lengths, and a Video's neighbors are +found by the published dates of its Channel's Videos. Reading those video and file_group rows is a scattered page +per Video; a Channel with thousands of Videos took seconds from a cold disk cache. The video index replaces +video_channel_id_idx, whose lookups it also serves. + +Revision ID: 2026_12_01_1200 +Revises: 2026_10_30_1200 +""" +from alembic import op + +# revision identifiers, used by Alembic. +revision = '2026_12_01_1200' +down_revision = '2026_10_30_1200' +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute('CREATE INDEX IF NOT EXISTS video_channel_file_group_idx ON video (channel_id, file_group_id)') + op.execute('DROP INDEX IF EXISTS video_channel_id_idx') + op.execute('CREATE INDEX IF NOT EXISTS file_group_published_size_length_idx' + ' ON file_group (id, published_datetime, size, length)') + + +def downgrade(): + op.execute('CREATE INDEX IF NOT EXISTS video_channel_id_idx ON video (channel_id)') + op.execute('DROP INDEX IF EXISTS video_channel_file_group_idx') + op.execute('DROP INDEX IF EXISTS file_group_published_size_length_idx') diff --git a/modules/videos/channel/test/test_models.py b/modules/videos/channel/test/test_models.py index 4383d318..52d2a696 100644 --- a/modules/videos/channel/test/test_models.py +++ b/modules/videos/channel/test/test_models.py @@ -1,4 +1,5 @@ import json +import re from http import HTTPStatus import pytest @@ -144,6 +145,42 @@ async def test_channel_statistics_with_tagged_videos(async_client, test_session, assert statistics['video_tags'] == 2 +@pytest.mark.asyncio +async def test_channel_statistics_read_no_rows(async_client, test_session, channel_factory, video_factory, + tag_factory): + """A Channel's statistics are read from indexes, never from video or file_group rows. + + Reading a large Channel's rows from a cold disk cache is a scattered page per Video, which took seconds.""" + channel = channel_factory() + video = video_factory(channel_id=channel.id) + video_factory(channel_id=channel.id) + video.add_tag(test_session, (await tag_factory()).name) + test_session.commit() + + # get_statistics uses a raw cursor, so trace the sqlite3 connection itself; the traced SQL has its + # parameters filled in. + statements = [] + connection = test_session.connection().connection.dbapi_connection + connection.set_trace_callback(lambda sql: statements.append(sql) if 'video_tags' in sql else None) + try: + statistics = channel.get_statistics() + finally: + connection.set_trace_callback(None) + assert statistics['video_count'] == 2 + assert statistics['video_tags'] == 1 + + assert len(statements) == 1 + plan = [i[3] for i in connection.execute(f'EXPLAIN QUERY PLAN {statements[0]}')] + video_steps = [i for i in plan if re.match(r'(SEARCH|SCAN) (video|v)\b', i)] + assert video_steps, plan + for step in video_steps: + assert 'COVERING INDEX video_channel_file_group_idx' in step, plan + 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 'COVERING INDEX file_group_published_size_length_idx' in step, plan + + def test_channel_directory_video_counts(test_session, channel_factory, video_factory): """A Channel can count the video FileGroups in its directory, and which Channel they are assigned to. diff --git a/modules/videos/models.py b/modules/videos/models.py index eb0e640b..5b2acb78 100644 --- a/modules/videos/models.py +++ b/modules/videos/models.py @@ -33,7 +33,9 @@ AUDIO_PLAYLIST_MIMETYPES = ('audio/x-mpegurl', 'audio/mpegurl', 'audio/x-scpls', class Video(ModelHelper, Base): __tablename__ = 'video' __table_args__ = ( - Index('video_channel_id_idx', 'channel_id'), + # 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'), 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). @@ -949,10 +951,11 @@ class Channel(ModelHelper, Base): -- Count Videos with at least one Tag; a Video may use multiple Tags. (SELECT COUNT(DISTINCT tf.file_group_id) FROM tag_file tf - INNER JOIN video v ON v.file_group_id = tf.file_group_id - WHERE v.channel_id = :id) AS "video_tags" + WHERE tf.file_group_id IN (SELECT v.file_group_id FROM video v + WHERE v.channel_id = :id)) AS "video_tags" FROM video - LEFT JOIN file_group fg on fg.id = video.file_group_id + LEFT JOIN file_group fg INDEXED BY file_group_published_size_length_idx + ON fg.id = video.file_group_id WHERE channel_id = :id \ ''' curs.execute(stmt, dict(id=self.id)) diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index 4f71f16a..cd5f20f3 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -84,6 +84,10 @@ 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 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. + Index('file_group_published_size_length_idx', 'id', 'published_datetime', 'size', 'length'), Index('file_group_url_idx', 'url'), Index('file_group_viewed_idx', 'viewed'), # Identity of a FileGroup. Duplicates are collapsed by