From 94a188097cee49a5838459bf55e08387a4354e18 Mon Sep 17 00:00:00 2001 From: lrnselfreliance <33263708+lrnselfreliance@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:27:03 -0700 Subject: [PATCH] Video statistics are counted from covering indexes (#1093) The totals and the monthly counts read every video row (ffprobe_json) and its file_group row (indexed text). On a large library that took minutes from a cold disk cache: the monthly query even walked the published-date index over every FileGroup, reading each row for its size. Both queries now read only indexes, named with INDEXED BY: - video_statistics_idx (file_group_id, have_comments, comments_failed) - file_group_published_size_length_idx gains censored and url, so it covers the FileGroup side as it already does for Channel statistics. url is indexed itself: SQLite does not reliably read an indexed `url IS NOT NULL` expression from the index (not in a FILTER clause, not inside AND). Co-authored-by: Claude Opus 5.5 --- ...026_12_04_1300_video_statistics_indexes.py | 30 ++++++ modules/videos/lib.py | 20 ++-- modules/videos/models.py | 2 + modules/videos/test/test_lib.py | 94 +++++++++++++++++++ wrolpi/files/models.py | 9 +- 5 files changed, 142 insertions(+), 13 deletions(-) create mode 100644 alembic/versions/2026_12_04_1300_video_statistics_indexes.py diff --git a/alembic/versions/2026_12_04_1300_video_statistics_indexes.py b/alembic/versions/2026_12_04_1300_video_statistics_indexes.py new file mode 100644 index 00000000..c368ebc4 --- /dev/null +++ b/alembic/versions/2026_12_04_1300_video_statistics_indexes.py @@ -0,0 +1,30 @@ +"""Cover the Video statistics with indexes: add video_statistics_idx, and censored and url to +file_group_published_size_length_idx. + +The Video statistics read every video row (ffprobe_json) and its file_group row (indexed text); from a cold disk +cache that took minutes on a large library. + +Revision ID: 2026_12_04_1300 +Revises: 2026_12_04_1200 +""" +from alembic import op + +# revision identifiers, used by Alembic. +revision = '2026_12_04_1300' +down_revision = '2026_12_04_1200' +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute('CREATE INDEX IF NOT EXISTS video_statistics_idx ON video (file_group_id, have_comments, comments_failed)') + op.execute('DROP INDEX IF EXISTS file_group_published_size_length_idx') + op.execute('CREATE INDEX file_group_published_size_length_idx' + ' ON file_group (id, published_datetime, size, length, censored, url)') + + +def downgrade(): + op.execute('DROP INDEX IF EXISTS file_group_published_size_length_idx') + op.execute('CREATE INDEX file_group_published_size_length_idx' + ' ON file_group (id, published_datetime, size, length)') + op.execute('DROP INDEX IF EXISTS video_statistics_idx') diff --git a/modules/videos/lib.py b/modules/videos/lib.py index a3de4881..b1b59dab 100644 --- a/modules/videos/lib.py +++ b/modules/videos/lib.py @@ -1163,9 +1163,9 @@ async def get_statistics(session: Session): -- total videos COUNT(v.id) AS "videos", -- total videos downloaded over the past week/month/year - COUNT(v.id) FILTER (WHERE published_datetime >= datetime('now', '-7 days')) AS "week", - COUNT(v.id) FILTER (WHERE published_datetime >= datetime('now', '-1 month')) AS "month", - COUNT(v.id) FILTER (WHERE published_datetime >= datetime('now', '-1 year')) AS "year", + COUNT(v.id) FILTER (WHERE fg.published_datetime >= datetime('now', '-7 days')) AS "week", + COUNT(v.id) FILTER (WHERE fg.published_datetime >= datetime('now', '-1 month')) AS "month", + COUNT(v.id) FILTER (WHERE fg.published_datetime >= datetime('now', '-1 year')) AS "year", -- sum of all video lengths in seconds COALESCE(SUM(fg.length), 0) AS "sum_duration", -- sum of all video file sizes @@ -1175,12 +1175,13 @@ async def get_statistics(session: Session): -- Videos may or may not have comments. COUNT(v.id) FILTER ( WHERE v.have_comments = TRUE ) AS "have_comments", COUNT(v.id) FILTER ( WHERE v.have_comments = FALSE AND v.comments_failed = FALSE - and fg.censored = false and - fg.url is not null) AS "missing_comments", + AND fg.censored = FALSE AND fg.url IS NOT NULL) AS "missing_comments", COUNT(v.id) FILTER ( WHERE v.comments_failed = TRUE ) AS "failed_comments", COUNT(v.id) FILTER ( WHERE fg.censored = TRUE ) as "censored_videos" - FROM video v - LEFT JOIN file_group fg on v.file_group_id = fg.id + -- Both tables' rows are wide (ffprobe_json, indexed text); read only their covering indexes. + FROM video v INDEXED BY video_statistics_idx + LEFT JOIN file_group fg INDEXED BY file_group_published_size_length_idx + ON v.file_group_id = fg.id ''') video_stats = dict(curs.fetchone()) @@ -1191,8 +1192,9 @@ async def get_statistics(session: Session): SELECT strftime('%Y-%m-01 00:00:00', fg.published_datetime) AS "month", COUNT(video.id) AS "count", SUM(fg.size) AS "size" - FROM video - LEFT JOIN file_group fg on video.file_group_id = fg.id + FROM video INDEXED BY video_statistics_idx + LEFT JOIN file_group fg INDEXED BY file_group_published_size_length_idx + ON video.file_group_id = fg.id WHERE fg.published_datetime IS NOT NULL AND fg.published_datetime >= datetime('now', 'start of month', '-24 months') AND fg.published_datetime < datetime('now', 'start of month') diff --git a/modules/videos/models.py b/modules/videos/models.py index 7f1b1d19..199bc36e 100644 --- a/modules/videos/models.py +++ b/modules/videos/models.py @@ -36,6 +36,8 @@ 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'), 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_lib.py b/modules/videos/test/test_lib.py index 4fef71d5..de35b1c8 100644 --- a/modules/videos/test/test_lib.py +++ b/modules/videos/test/test_lib.py @@ -1,4 +1,6 @@ import pathlib +import sqlite3 +from datetime import timedelta from http import HTTPStatus import pytest @@ -8,6 +10,7 @@ from modules.videos.downloader import ChannelDownloader, VideoDownloader from modules.videos.lib import parse_video_file_name, validate_video, get_statistics, format_videos_destination from modules.videos.models import Channel from wrolpi.common import get_wrolpi_config +from wrolpi.dates import now from wrolpi.downloader import Download, RSSDownloader @@ -180,6 +183,97 @@ async def test_get_statistics(test_session, video_factory, channel_factory): assert 'historical' in result['statistics'] + +# The statistics queries before they were made index-only: they read every video and file_group row. Kept as the +# reference the index-only queries must agree with. +REFERENCE_VIDEO_STATISTICS = ''' + SELECT COUNT(v.id) AS "videos", + COUNT(v.id) FILTER (WHERE published_datetime >= datetime('now', '-7 days')) AS "week", + COUNT(v.id) FILTER (WHERE published_datetime >= datetime('now', '-1 month')) AS "month", + COUNT(v.id) FILTER (WHERE published_datetime >= datetime('now', '-1 year')) AS "year", + COALESCE(SUM(fg.length), 0) AS "sum_duration", + COALESCE(SUM(fg.size), 0) AS "sum_size", + COALESCE(MAX(fg.size), 0) AS "max_size", + COUNT(v.id) FILTER (WHERE v.have_comments = TRUE) AS "have_comments", + COUNT(v.id) FILTER (WHERE v.have_comments = FALSE AND v.comments_failed = FALSE + AND fg.censored = FALSE AND fg.url IS NOT NULL) AS "missing_comments", + COUNT(v.id) FILTER (WHERE v.comments_failed = TRUE) AS "failed_comments", + COUNT(v.id) FILTER (WHERE fg.censored = TRUE) AS "censored_videos" + FROM video v LEFT JOIN file_group fg ON v.file_group_id = fg.id +''' +REFERENCE_MONTHLY_VIDEOS = ''' + SELECT strftime('%Y-%m-01 00:00:00', fg.published_datetime) AS "month", COUNT(video.id) AS "count", + SUM(fg.size) AS "size" + FROM video LEFT JOIN file_group fg ON video.file_group_id = fg.id + WHERE fg.published_datetime IS NOT NULL + AND fg.published_datetime >= datetime('now', 'start of month', '-24 months') + AND fg.published_datetime < datetime('now', 'start of month') + GROUP BY 1 ORDER BY 1 +''' + + +@pytest.mark.asyncio +async def test_get_statistics_read_only_indexes(test_session, video_factory, channel_factory): + """The Video statistics are counted from covering indexes, never from video or file_group rows. Both rows are + wide (ffprobe_json, indexed text), so reading every Video's rows from a cold disk cache took minutes.""" + channel = channel_factory() + now_ = now() + videos = [ + # (published, size, length, censored, url, have_comments, comments_failed) + (now_ - timedelta(days=2), 100, 10, False, 'https://example.com/1', True, False), + (now_ - timedelta(days=20), 300, 30, False, 'https://example.com/2', False, False), + (now_ - timedelta(days=60), 200, 20, True, 'https://example.com/3', False, False), + (now_ - timedelta(days=200), 50, 5, False, None, False, False), + (now_ - timedelta(days=500), 70, 7, False, 'https://example.com/5', False, True), + (now_ - timedelta(days=1500), 90, 9, False, 'https://example.com/6', False, False), + (None, 10, 1, False, 'https://example.com/7', False, False), + ] + for published, size, length, censored, url, have_comments, comments_failed in videos: + video = video_factory(channel_id=channel.id) + video.file_group.published_datetime = published + video.file_group.size = size + video.file_group.length = length + video.file_group.censored = censored + video.file_group.url = url + video.have_comments = have_comments + video.comments_failed = comments_failed + test_session.commit() + + connection = test_session.connection().connection.dbapi_connection + connection.row_factory = sqlite3.Row + try: + expected_videos = dict(connection.execute(REFERENCE_VIDEO_STATISTICS).fetchone()) + expected_monthly = [dict(i) for i in connection.execute(REFERENCE_MONTHLY_VIDEOS).fetchall()] + finally: + connection.row_factory = None + + statements = [] + connection.set_trace_callback(statements.append) + try: + result = await get_statistics(test_session) + finally: + connection.set_trace_callback(None) + + statistics = result['statistics'] + assert statistics['videos'] == expected_videos + assert statistics['videos']['videos'] == 7 and statistics['videos']['censored_videos'] == 1 + monthly = [dict(i, month=i['month'].strftime('%Y-%m-%d %H:%M:%S')) for i in statistics['historical']['monthly_videos']] + assert monthly == expected_monthly and len(monthly) >= 2 + assert statistics['channels'] == dict(channels=1, tagged_channels=0) + + # Nothing reads a column (or seeks a row) from the video or file_group table: only their indexes. + root_pages = dict(connection.execute( + "SELECT rootpage, name FROM sqlite_master WHERE type = 'table' AND name IN ('video', 'file_group')")) + for statement in statements: + if not statement.lstrip().upper().startswith('SELECT'): + continue + program = list(connection.execute(f'EXPLAIN {statement}')) + table_cursors = {i[2] for i in program if i[1] == 'OpenRead' and i[3] in root_pages} + 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, (statement, table_reads) + + def test_channel_download_links(test_session, channel_factory, test_download_manager): channel = channel_factory( url='https://www.youtube.com/c/LearningSelfReliance/videos', diff --git a/wrolpi/files/models.py b/wrolpi/files/models.py index acc9233e..09b54279 100644 --- a/wrolpi/files/models.py +++ b/wrolpi/files/models.py @@ -89,10 +89,11 @@ class FileGroup(ModelHelper, Base): # The expression leads so the index serves only that full scan: led by mimetype, SQLite chose it for mimetype # lookups (it has no ANALYZE row), which made the newest-videos page read and sort every video's row. Index('file_group_statistics_idx', text('json_array_length(files)'), 'mimetype', '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'), + # Covers reading the published date, size, length, censored, and url of FileGroups looked up by id (a + # Channel's statistics, a Video's neighbors, the Video statistics): reading those rows themselves is a + # scattered page per FileGroup. SQLite prefers the rowid, so a query must name this index with INDEXED BY. + # (url itself, not `url IS NOT NULL`: SQLite does not reliably read an indexed expression from the index.) + Index('file_group_published_size_length_idx', 'id', 'published_datetime', 'size', 'length', 'censored', 'url'), Index('file_group_url_idx', 'url'), Index('file_group_viewed_idx', 'viewed'), # Identity of a FileGroup. Duplicates are collapsed by