Video statistics are counted from covering indexes (#1093)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Dead Code / vulture (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run

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 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-12-04 09:27:03 -07:00 • committed by Roland
parent 6bcd182cd9
commit 94a188097c
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
5 changed files with 142 additions and 13 deletions

View file

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

View file

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

View file

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