Doc section hints match each doc's rowid range, not each section (#1091)

#1087 limited the hint match to the page's section rowids with
`rowid IN (...)`.  FTS5 runs the whole MATCH again for every rowid, so the
cost grew with the page's sections: an all-doc page of a common word took
seconds even with a warm cache.

The match is now limited to each doc's range of section rowids (one
`rowid BETWEEN` per doc, read from covering indexes), so FTS5 runs at most
one MATCH per doc and reads only that doc's part of the match list.
A section of another doc inside a range is dropped by `ds.doc_id`.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-12-03 19:37:19 -07:00 • committed by GitHub
parent 267b0230f4
commit 839aadbb56
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 37 additions and 9 deletions

View file

@ -491,9 +491,18 @@ def _fetch_section_hints(session, file_group_ids, search_str):
# FTS5 auxiliary functions (snippet, rank) must be evaluated in the innermost SELECT that scans the
# FTS table; the window function must live in a separate outer layer.
# The match is limited to the rowids of the requested docs' sections (read from covering indexes), so only
# those sections are joined; a common word may match thousands of sections elsewhere in the library.
# The match is limited to each requested doc's range of section rowids (read from covering indexes): a common
# word matches thousands of sections elsewhere in the library, and joining each to its large row is slow cold.
# One range per doc, not one lookup per section: FTS5 runs the whole MATCH again for every lookup. A doc's
# sections are inserted together, so the range rarely holds another doc's; `ds.doc_id` drops those.
sql = text('''
WITH page AS (
SELECT s.doc_id AS doc_id, MIN(s.id) AS first_id, MAX(s.id) AS last_id
FROM doc page_doc
JOIN doc_section s ON s.doc_id = page_doc.id
WHERE page_doc.file_group_id IN :ids
GROUP BY s.doc_id
)
SELECT fg_id, kind, ordinal, label, snippet FROM (
SELECT fg_id, kind, ordinal, label, snippet,
row_number() OVER (PARTITION BY fg_id
@ -505,14 +514,13 @@ def _fetch_section_hints(session, file_group_ids, search_str):
ds.label AS label,
snippet(doc_section_fts, 0, '[[WROLPI_HL]]', '[[/WROLPI_HL]]', '…', 20) AS snippet,
doc_section_fts.rank AS fts_rank
FROM doc_section_fts
FROM page
CROSS JOIN doc_section_fts
JOIN doc_section ds ON ds.id = doc_section_fts.rowid
JOIN doc d ON d.id = ds.doc_id
WHERE doc_section_fts MATCH :q
AND doc_section_fts.rowid IN (
SELECT s.id FROM doc page_doc
JOIN doc_section s ON s.doc_id = page_doc.id
WHERE page_doc.file_group_id IN :ids)
AND doc_section_fts.rowid BETWEEN page.first_id AND page.last_id
AND ds.doc_id = page.doc_id
)
) WHERE rn = 1
''').bindparams(bindparam('ids', expanding=True))

View file

@ -371,8 +371,28 @@ async def test_section_hints_read_only_the_page_sections(test_session, test_dire
[(statement, parameters)] = statements
plan = test_session.connection().exec_driver_sql(f'EXPLAIN QUERY PLAN {statement}', parameters).fetchall()
[fts_step] = [row[3] for row in plan if 'doc_section_fts VIRTUAL TABLE' in row[3]]
# FTS5 writes "=" in its index string when the scan is limited by rowid: "INDEX 0:=M1", not "INDEX 0:M1".
assert ':=' in fts_step, f'The section match is not limited to the page: {plan}'
# FTS5's index string names the rowid constraints after the MATCH: "M1><" is a range (rowid >= ? AND rowid <= ?),
# "=M1" is one rowid, "M1" alone is every match in the library. One range per doc: a lookup per section runs
# the whole MATCH again for every section, which took seconds for a page of long PDFs even with a warm cache.
index_string = fts_step.rsplit(':', 1)[-1]
assert index_string.endswith('><') and '=' not in index_string, \
f'The section match is not limited to a rowid range per doc: {plan}'
def test_section_hints_ignore_sections_of_other_docs(test_session, test_directory):
"""A doc's sections are looked up by their rowid range; another doc's section inside that range is not a hint."""
first_fg, first = _make_doc_with_sections(test_session, test_directory, 'first.pdf', 'application/pdf', [
(1, 'Page 1', 'cover page text'),
])
other_fg, other = _make_doc_with_sections(test_session, test_directory, 'other.pdf', 'application/pdf', [
(1, 'Page 1', 'mullen is here'),
])
# The first doc's last section is added after the other doc's, so the other doc's section is inside its range.
test_session.add(DocSection(doc_id=first.id, kind='pdf_page', ordinal=2, label='Page 2', content='nothing'))
test_session.commit()
assert _fetch_section_hints(test_session, [first_fg.id], 'mullen') == {}
assert set(_fetch_section_hints(test_session, [first_fg.id, other_fg.id], 'mullen')) == {other_fg.id}
@pytest.mark.asyncio