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

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