Channel statistics: read from covering indexes, not video or file_group rows (#1059)

* Channel statistics: find a Channel's Videos in an index, not their rows

Each video row carries its ffprobe_json, so the statistics query read a
page per Video to get file_group_id.  A Channel with thousands of Videos
took seconds from a cold disk cache.  An index of (channel_id,
file_group_id) replaces video_channel_id_idx, and the tagged-Videos
subquery reads that index instead of looking up each tagged FileGroup's
video row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Channel statistics: read FileGroup sizes from a covering index

After the video index, the remaining cold cost was reading each Video's
file_group row for its size and length: a scattered page per Video.  An
index of file_group (id, size, length) holds them densely.  SQLite
prefers the rowid for an id lookup, so the query names the index with
INDEXED BY.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Channel statistics: widen the FileGroup index to cover published dates

A Video's neighbors are found by the published dates of its Channel's
Videos, which reads the same scattered file_group rows.  One index of
file_group (id, published_datetime, size, length) serves both, so an
upgrade builds one index rather than two.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-12-01 14:22:21 -07:00 • committed by GitHub
parent 2e46f3a6e3
commit 570c63ffc7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 79 additions and 4 deletions

View file

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

View file

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

View file

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

View file

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