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

View file

@ -1912,14 +1912,19 @@ async def search_file_suggestion_count(session: Session, search_str: str, tag_na
wheres, params = months_selector_to_where(wheres, params, months)
wheres, params = date_range_to_where(wheres, params, from_year, to_year)
joins = "\n".join(joins)
wheres = 'WHERE ' + "\nAND ".join(wheres) if wheres else ''
stmt = f'''
SELECT COUNT(*) AS estimate
FROM file_group fg
{joins}
{wheres}
'''
if deep_match and len(wheres) == 1:
# Only the search string: count inside the FTS index. Joining each match to its (large) file_group row is
# a random read per match, which is slow from a cold disk cache for a common word.
stmt = 'SELECT COUNT(*) AS estimate FROM file_group_fts WHERE file_group_fts MATCH :fts_match'
else:
joins = "\n".join(joins)
wheres = 'WHERE ' + "\nAND ".join(wheres) if wheres else ''
stmt = f'''
SELECT COUNT(*) AS estimate
FROM file_group fg
{joins}
{wheres}
'''
logger.debug(f'search_file_suggestion_count: {stmt} {params}')
with session_curs(session) as curs:

View file

@ -2398,3 +2398,38 @@ def test_file_statistics_index_does_not_serve_mimetype_lookups(test_session, vid
plan = [i[3] for i in connection.execute("EXPLAIN QUERY PLAN SELECT COUNT(*) FROM file_group WHERE mimetype = 'a/b'")]
assert not any('file_group_statistics_idx' in i for i in plan), plan
@pytest.mark.asyncio
async def test_search_file_suggestion_count_counts_inside_fts(test_session, test_directory, make_files_structure):
"""With only a search string, the estimates are counted from the FTS index alone: joining each match to its
(large) file_group row is a random read per match, which took most of a minute from a cold disk cache."""
make_files_structure(['solar panel.txt', 'solar wiring.txt', 'garden.txt'])
for path, text in [('solar panel.txt', 'roof'), ('solar wiring.txt', 'the roof wiring'), ('garden.txt', 'roof')]:
file_group = FileGroup.from_paths(test_session, test_directory / path)
file_group.a_text = path
file_group.d_text = text
file_group.mimetype = 'text/plain'
test_session.commit()
statements = []
connection = test_session.connection().connection.dbapi_connection
connection.set_trace_callback(lambda sql: statements.append(sql) if 'estimate' in sql else None)
try:
assert await lib.search_file_suggestion_count(test_session, 'solar', [], []) == \
dict(file_groups=2, file_groups_deep=2)
assert await lib.search_file_suggestion_count(test_session, 'roof', [], []) == \
dict(file_groups=0, file_groups_deep=3)
finally:
connection.set_trace_callback(None)
assert statements
for statement in statements:
plan = [i[3] for i in connection.execute(f'EXPLAIN QUERY PLAN {statement}')]
assert not any(re.match(r'(SEARCH|SCAN) (file_group|fg)\b', i) for i in plan), plan
# Other filters still apply to the matches.
assert await lib.search_file_suggestion_count(test_session, 'roof', [], ['text']) == \
dict(file_groups=0, file_groups_deep=3)
assert await lib.search_file_suggestion_count(test_session, 'roof', [], ['video']) == \
dict(file_groups=0, file_groups_deep=0)