Search estimates and channel suggestions do not read every large row (#1092)
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

Both ran on every global search and were slow from a cold disk cache:

- search_file_estimates joined each FTS match to its file_group row just
  to count it; a common word is a random read per match.  With only a
  search string, both counts now come from the FTS index alone (as files
  search counts since #1086).
- search_suggestions' channel search read every channel row (each holds
  its yt-dlp info_json): the name order scanned the table, and the video
  count order grouped by channel.id, which walks the table in rowid order.
  The matching channel ids now come from collection names and covering
  indexes (a correlated video count instead of GROUP BY), then only those
  channels are loaded.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-12-03 20:36:24 -07:00 • committed by GitHub
parent 839aadbb56
commit 6bcd182cd9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 97 additions and 24 deletions

View file

@ -217,30 +217,34 @@ async def search_channels_by_name(session: Session, name: str, limit: int = 5,
# SQLite sorts by byte value; emulate the old locale-aware (en_US.UTF-8) ordering: compare
# names case-insensitively and without spaces, ties broken with lowercase names first.
name_order = (func.lower(func.replace(Collection.name, ' ', '')).asc(), Collection.name.desc())
# Choose the matching Channels by id (Collection names and covering indexes), then read only their rows: a
# channel row holds its yt-dlp info_json, so reading every row is slow from a cold disk cache.
name_filter = or_(
Collection.name.ilike(f'%{name}%'),
Collection.name.ilike(f'%{name_no_spaces}%'),
)
if order_by_video_count:
stmt = session.query(Channel, func.count(Video.id).label('video_count')) \
.options(*Channel.json_options()) \
# A correlated count, not GROUP BY channel.id: grouping walks the channel table in rowid order, reading
# every row.
video_count = session.query(func.count(Video.id)).filter(Video.channel_id == Channel.id) \
.correlate(Channel).scalar_subquery()
stmt = session.query(Channel.id, video_count.label('video_count')) \
.join(Collection) \
.filter(or_(
Collection.name.ilike(f'%{name}%'),
Collection.name.ilike(f'%{name_no_spaces}%'),
)) \
.outerjoin(Video, Video.channel_id == Channel.id) \
.group_by(Channel.id, Collection.id, Collection.name) \
.filter(name_filter) \
.order_by(desc('video_count'), *name_order) \
.limit(limit)
channels = [i[0] for i in stmt]
else:
stmt = session.query(Channel) \
.options(*Channel.json_options()) \
stmt = session.query(Channel.id) \
.join(Collection) \
.filter(or_(
Collection.name.ilike(f'%{name}%'),
Collection.name.ilike(f'%{name_no_spaces}%'),
)) \
.filter(name_filter) \
.order_by(*name_order) \
.limit(limit)
channels = stmt.all()
channel_ids = [i[0] for i in stmt]
if not channel_ids:
return []
by_id = {i.id: i for i in session.query(Channel).options(*Channel.json_options())
.filter(Channel.id.in_(channel_ids))}
channels = [by_id[i] for i in channel_ids]
return channels

View file

@ -165,6 +165,35 @@ async def test_search_channels_by_name(test_session, channel_factory, video_fact
await assert_search('bar', ['foobar', 'Foo Bar', 'bar'], True)
@pytest.mark.asyncio
@pytest.mark.parametrize('order_by_video_count', [False, True])
async def test_search_channels_by_name_reads_only_matching_rows(test_session, channel_factory, video_factory,
order_by_video_count):
"""Matching Channels are found from their Collection names and indexes; only the matches' channel rows are read.
A channel row holds its yt-dlp info_json, so scanning every row took seconds from a cold disk cache."""
foo = channel_factory(name='Foo')
channel_factory(name='Bar')
video_factory(channel_id=foo.id)
test_session.commit()
statements = []
connection = test_session.connection().connection.dbapi_connection
connection.set_trace_callback(lambda sql: statements.append(sql) if 'channel' in sql else None)
try:
channels = await lib.search_channels_by_name(test_session, 'foo', order_by_video_count=order_by_video_count)
finally:
connection.set_trace_callback(None)
assert [i.name for i in channels] == ['Foo']
for statement in statements:
if not statement.lstrip().upper().startswith(('SELECT', 'WITH')):
continue
plan = [i[3] for i in connection.execute(f'EXPLAIN QUERY PLAN {statement}')]
for step in plan:
if re.match(r'(SEARCH|SCAN) channel\b', step):
assert 'COVERING INDEX' in step or 'INTEGER PRIMARY KEY' in step, (statement, plan)
@pytest.mark.asyncio
async def test_tag_channel_existing(async_client, test_session, test_directory, channel_factory, tag_factory,
video_factory, test_channels_config, await_switches):