Repository navigation
[fix](inverted index) Count only visible rows in BM25 statistics of merge-on-write tables - #69438
guptashivam04 wants to merge 14 commits into
Conversation
…erge-on-write tables A merge-on-write segment keeps rows that a later load overwrote or deleted, marked only in the delete bitmap, and rows written with the delete sign, which queries filter out by predicate. BM25 statistics counted both until compaction removed them, and each replica compacts on its own schedule, so the replicas of a tablet scored the same row differently and a query that picked a different replica returned different scores and orders. When the scan reads a delete bitmap, collect statistics over the rows it returns only: per segment, leave the rows marked at the read version and the rows with the delete sign out of the document count and of each term's document frequency, counting the hidden rows a term's postings hold by leaping between them. Exact token counts of hidden rows are not stored, and norms hold lengths only approximately, so take the token count as the sum of the lengths the norms of the returned rows stand for, which every replica computes alike whether or not it has compacted.
|
Thank you for your contribution to Apache Doris. Please clearly describe your PR:
|
…eplica suite outside cloud mode Cloud mode keeps one shared copy of each tablet, so there are no replicas to compact apart, and its compaction is driven differently. The comparison with a freshly loaded table still runs in every mode.
When every row of a merge-on-write tablet is overwritten or deleted but not yet compacted, the visible-row statistics hold no documents. Scoring then treated them as missing and failed the query with "No data available for SimilarityCollector". Such a tablet has no row a query can match, so record that its segments were collected and report zero documents instead.
…ablet id The delete bitmap's aggregation cache is keyed by tablet, rowset, segment and version. The mock rowsets share their ids, so the second collection in HiddenRowsAreCollectedLikeCompactedAway read the first one's cached hidden rows.
…merge-on-write tables A NULL row has no tokens, but its norm stands for one, so summing the norms of the returned rows counted one token per NULL row. avgdl then grew with the share of NULL rows, and a merge-on-write table scored its rows differently from a duplicate table with the same data. Leave the rows of the index's null bitmap out of the token count; they still count as documents, as before. The sum of the non-NULL norm lengths of a CLucene index never changes, so keep it with the cached searcher instead of summing every row's norm on every query. Each query now reads only the norms of its hidden rows. Read the delete sign with the query's segment, page and file cache settings, and also read it when the zone map cannot vouch for its bounds or shows a non-zero minimum, since any non-zero sign deletes the row. Document the read modes whose returned rows differ from the counted ones. Follow the regression test conventions in the replica suite, and check it against a duplicate table with NULL rows.
…e options The statistics read postings, norms and null bitmaps before the scan does, so they are the reads that fill the file cache, yet their I/O context ignored disable_file_cache and inverted_index_snii_read_no_write_file_cache. Set both for a query's reads, as the rowset reader does; the delete sign read copies the context and follows them too. Document that a row indexed without tokens but not NULL keeps a norm that cannot be told from a one-token row's, and test that the non-NULL norm length sum is computed once per field of a cached searcher.
…stics searchers A CLucene searcher that BM25 statistics open is put into the searcher cache, but its index stream kept the opening query's I/O context, with that query's file cache statistics pointer, and stayed marked as reading index meta. Later reads without their own context went through the finished query's context, and the statistics' own reads ignored the query's file cache options. Reset the stream once the meta is read, as the query path's searcher opener does.
When a CLucene index holds several segments, its reader builds and keeps one more copy of a field's norms for all of them, filled without the segments' own norm caches, so the statistics read the norms a second time and held them twice for the cached searcher's lifetime, uncharged. Read the norms of each segment instead, as scoring does; a segment without the field's norms reads as zero lengths, as the combined norms do. Add a regression test for the statistics searcher's stream reset: with the CSIndexInput.readInternal debug point a cold score() query failed while the stream still read postings as index meta.
…a CLucene index The BM25 statistics opened a segment's CLucene index without catching CLuceneError, so an error reading the index, such as a failed remote read of its header, escaped the scanner thread and aborted the backend. Report it as the query's error, as the query path does. Keep the searcher reset test from passing on searchers the write path caches, test a hidden row whose length the norm holds only approximately (CLucene's norms are exact up to 40 tokens), and correct the norm comment.
|
/review |
|
run buildall |
There was a problem hiding this comment.
Request changes for two resource regressions: eager CLucene norms remain outside searcher-cache accounting (P1), and sparse hidden-row intersections repeatedly allocate segment-sized bitmaps (P2). Both are detailed inline. No existing inline findings were supplied.
Static review covered all 21 changed files, the scanner/read-source chain, both index formats, and the exact pinned CLucene norm implementation. The read flow is: captured rowsets + bitmap/version → scanner/shared tablet statistics → per-segment hidden IDs → document/term/norm totals → BM25 scoring.
| Required checkpoint | Conclusion |
|---|---|
| Goal and proof | Bitmap/delete-sign-hidden MoW rows are removed consistently from document counts and term frequencies; norm-based lengths address replica compaction differences. New unit/regression sources exercise this goal; execution was not performed. |
| Scope, clarity and reuse | Changes stay within BM25 statistics and reuse common IndexSource helpers with backend-specific overrides. |
| Concurrency and locks | Scanner-local results and shared first-collector locking are consistent. The new sum mutex serializes its initial I/O; CLucene reader/norm locks have no identified reverse acquisition path. No new thread or deadlock found. |
| Lifecycle and static initialization | Cached searchers retain readers and captured rowsets remain protected during collection. Borrowed opening I/O context is cleared. Retained norm accounting is the P1 finding; no new static-initialization dependency found. |
| Configuration and dynamic changes | No configuration added. Existing query file-cache, segment-cache and page-cache choices are forwarded on the changed paths; CLucene norms retain the existing context-free API behavior. |
| Symbol/storage compatibility | Internal signatures/default virtual methods change; no persisted index or wire format changes. Existing missing-norm rejection and no-bitmap behavior remain. |
| Thrift/protobuf IDs | Not applicable: no generated definitions changed. |
| Parallel and special paths | CLucene/SNII, split scanners, physical segment IDs, reserved scoring terms, NULLs, no-norm indexes and all-hidden tablets checked. No additional correctness issue confirmed. |
| Conditional checks | Empty inputs, invalid row IDs, zone-map sign pruning and all-hidden handling follow concrete cases and propagate failures. |
| Functional/negative/unit coverage | New tests cover compaction equivalence, NULL/hidden/all-hidden rows, sparse/dense cursors, invalid IDs, cache computation errors, multiple readers and I/O-context reset. The new checked-in end-to-end suites do not explicitly select SNII; its hidden-row behavior was reviewed statically. |
| Changed test results | Updated BM25 score and new golden outputs are consistent with the input rows and BM25 arithmetic. Their generation provenance and runtime reproducibility were not verified. |
| Observability | Existing collection VLOG and error propagation remain available. Local delete-sign read counters are not merged into the parent profile; retained norms also escape cache metrics as described inline. |
| Transactions/persistence/failover | No transaction, EditLog or metadata-write changes. Read-version and aggregate delete-bitmap keys match the normal rowset reader. |
| Writes/atomicity/crashes | No new data writes. I/O/cursor failures clear partial statistics and the shared collector returns the same failure to all callers; memory exhaustion risk is P1. |
| FE/BE variable propagation | No new transmitted variables. FE selected-index schema includes hidden delete-sign metadata; existing cache options reach the new reader context. |
| CPU/memory/performance | One-time norm totals and tablet sharing avoid redundant collection; the two inline findings identify remaining unbounded retained memory and repeated sparse-intersection work. |
| Other issues | Final static recheck found no additional substantiated defect. |
No additional user focus was supplied. Disclosed scope limits remain: light-delete predicates, merge-on-read/duplicate-key delete visibility, skip_delete_sign/show_hidden_columns, non-NULL zero-token encodings, and statistics remaining per tablet. These were considered and are not duplicate inline findings. No builds, tests, format checks or runtime experiments were run, as this invocation permits static review only.
Review converged after 2 round(s).
| #ifdef BE_TEST | ||
| RETURN_IF_ERROR(sum_lengths(&non_null_length_sum)); | ||
| #else | ||
| RETURN_IF_ERROR(inverted_index_cache_handle.get<CluceneSearcherCacheValue>() |
There was a problem hiding this comment.
[P1] Account for the norms retained by statistics collection
This callback now loads norms for every segment in a MoW tablet's captured read set before normal key/zone-map pruning, even when its hidden-row set is empty. CLucene's SegmentReader::norms() allocates and retains one byte per document per scored field, but these searchers were inserted using only getTermInfosRAMUsed() and neither their cache charge nor tracked bytes are updated afterward. A selective query over a large, low-vocabulary tablet can therefore leave gigabytes of norms resident while the searcher cache accounts for only small dictionaries; repeated queries across tablets can exhaust BE memory despite the configured cache limit. Previously such pruned segments only contributed dictionary statistics and did not load these norms. Please reserve/track the added buffers and update the cache charge, including for searchers already in the cache, or compute the sum without retaining unaccounted norm buffers.
There was a problem hiding this comment.
Fixed in 96a0b49: the statistics no longer ask CLucene readers for their retained norms. They read each segment's norms into their own buffer via IndexReader::norms(field, bytes) and free it after use. Only small sums are cached with the searcher: the per-field non-NULL norm-length sum, and the hidden rows' length sum for the last few sets of hidden rows per field (queries at one read version reuse it and read no norms). Measured on a 10M-row tablet with 4 scored fields and a key-pruned query: memory growth went from about +51 MB to +12–15 MB, the same as before the PR. Covered by HiddenNormLengthSumIsComputedOncePerRowSet and NormLengthSumsReadEachSegment.
| // Decodes every posting once and tests it against a bitset of `docs`. | ||
| Status count_listed_docs_by_scan(PostingsCursor& cursor, std::span<const uint32_t> docs, | ||
| uint64_t* out) { | ||
| std::vector<uint64_t> bits(docs.back() / 64 + 1, 0); |
There was a problem hiding this comment.
[P2] Avoid a segment-sized bitmap for sparse term intersections
The scan branch is selected from docs.size() and doc_freq(), but this allocation scales with the largest hidden row ID. For example, hidden_docs = {9999999} and a term with one posting select this branch and zero 1,250,000 bytes just to compare two IDs. CLucene also returns a non-null cursor for an absent term, so df = 0 incurs the same allocation before discovering EOF. Collection statistics repeat this for every query term and every segment with hidden rows on every query, making selective or many-term searches perform substantial segment-sized allocation/zeroing even with tiny or empty posting lists. Please use a sparse/sorted intersection for this case, account for the maximum ID when choosing a dense bitset, and short-circuit zero-frequency terms.
There was a problem hiding this comment.
Fixed in 96a0b49: count_listed_docs no longer allocates a bitset. The scan path walks the hidden rows and the postings together (both ascending) and stops once every hidden row is passed, so the cost no longer depends on the largest row ID. A term with doc_freq() == 0 returns before opening anything. Covered by CountListedDocsScansFarDocsWithoutWalkingEveryBlock (IDs up to 9,999,999) and CountListedDocsOfNothing.
Asking a CLucene segment reader for a field's norms makes it keep them for the cached searcher's lifetime, uncharged to the searcher cache, and the merge-on-write statistics visit every segment of the read set, including the segments the scan prunes and never scores. Read the norms into a buffer of the statistics' own, one segment at a time, and keep only sums with the searcher: the field's non-NULL norm lengths, and the hidden rows' lengths for the last few sets of hidden rows, so queries at one read version read no norms. Count the hidden rows a term's postings list by walking both ascending lists together instead of zeroing a bitset as large as the largest hidden row, and skip terms without postings.
TPC-H: Total hot run time: 28796 ms |
TPC-DS: Total hot run time: 150742 ms |
ClickBench: Total hot run time: 24.39 s |
…w BM25 statistics The merge-on-write cases overwrite and delete rows, which no longer count in the BM25 statistics, so their scores are those of the visible rows. The same rows are returned; only their scores change.
BE Regression && UT Coverage ReportIncrement line coverage Increment coverage report
|
|
run buildall |
|
/review |
There was a problem hiding this comment.
One new P2 finding: temporary hidden/NULL row-ID arrays bypass query memory accounting before scan pruning. It is detailed inline. No P0/P1 issue was independently confirmed for this head.
Both existing threads were revalidated: retained CLucene norms (4365847990) is fixed for the reviewed Doris writer/reader paths by using caller-owned norm buffers and bounded scalar caches; sparse intersection allocation (4365847994) is fixed by sorted intersection and zero-frequency exits. The new finding concerns temporary uint32 row-ID arrays, distinct from retained norm buffers. No existing blocker is carried forward.
Static coverage includes all 22 changed files and their scan, reader, writer, cache and scoring interactions at a690a60. The invocation chain is:
captured rowsets + bitmap/read version
-> scanner/shared tablet statistics
-> per-segment bitmap/delete-sign hidden IDs
-> CLucene or SNII visible document/term/norm totals
-> scanner-local BM25 statistics and matched-row scores
| Required checkpoint | Conclusion |
|---|---|
| Goal and tests | Bitmap/delete-sign-hidden MoW rows are removed from document counts, term frequencies and decoded norm totals. Replica/fresh-table, NULL and all-hidden fixtures support compaction invariance statically; the new memory issue remains. |
| Scope, clarity and reuse | Changes stay within BM25 collection, source helpers, cache sums and associated tests; existing captured read sources and segment/column readers are reused. |
| Concurrency and locks | Scanner tasks and queries can collect concurrently. TabletCollectionStatistics locks once-only collection and copies results into scanner-local maps; one searcher mutex protects sum caches. Its initial I/O is serialized intentionally, with no verified reverse lock order or deadlock. |
| Lifecycle and static initialization | Rowset readers and cache handles preserve reader lifetimes. Synchronous callbacks retain no query references after return; local resources release on errors. No new static initialization dependency or ownership cycle was found. Caller-owned norms fix the historical retention path; untracked ID buffers are the inline finding. |
| Configuration and dynamic changes | No configuration is added. Existing segment/page/file-cache options are forwarded where the read APIs accept them; the existing context-free CLucene norm API remains a limitation. |
| Symbols, formats and rolling compatibility | Internal collection signatures and default virtual helpers have matching callers. No persisted index or wire format changes; old/default delete-sign columns resolve by UID, and existing missing-norm scoring rejection remains. |
| Thrift/protobuf field IDs | Not applicable: no generated definition changed. |
| Parallel and special paths | Serial/shared split scanners, CLucene/SNII, physical cloud segment IDs, reserved scoring terms, NULL/empty inputs, no-norm keyword indexes and all-hidden collections were traced. Explicit deletion/debug exceptions are disclosed below. |
| Conditional checks | Bitmap presence, zero frequency, row bounds, zone-map pruning and all-hidden handling have concrete scenarios. Roaring supplies sorted distinct IDs; bounds/frequency failures return errors instead of silently continuing. |
| Functional, negative and unit coverage | New tests cover hidden/compacted equivalence, NULL and hidden NULL, all-hidden/refill, sparse/dense postings, distant IDs, invalid row IDs, cache callback errors, multiple readers and I/O flags. Memory-limit and concurrent-cache coverage is absent; dedicated reserved-term and schema/segment-ID edge fixtures are limited, with those paths reviewed statically. |
| Changed test results | Every new/modified numeric expectation is consistent with the input corpus and BM25 arithmetic, including .8025915, .60996956/.8713851 and 1.1823694. Output-generation provenance and execution were not verified. |
| Observability | Existing collection timing, query/tablet/term VLOG and error propagation remain available. Temporary raw arrays escape query memory metrics as described inline; context-free CLucene norms also retain the existing I/O-accounting limitation. |
| Transactions, persistence and failover | Read-only collection uses the captured rowsets and the same versioned physical-segment bitmap keys as ordinary reads. No transaction, EditLog, persistence or failover protocol changes. |
| Writes, atomicity and crash behavior | No data-write path changes. Failed collection clears partial statistics and shares the error with other scanners; cache sums are inserted only after successful computation. The verified resource-accounting risk is inline. |
| FE/BE variable propagation | No transmitted variables are added. Existing cache options reach the new scanner context. |
| CPU, memory and performance | Tablet sharing, zone-map delete-sign pruning, bounded batches and cached norm sums reduce repeated work. Sparse posting intersection no longer allocates by maximum ID. Full-cardinality untracked ID buffers remain the new P2 issue. |
| Further issues | Final rechecks of cursor progress, norm ownership/overloads, NULL writer metadata, TopN masks, cached-reader lifetimes and parallel paths found no additional substantiated defect. |
No additional user focus was supplied. Declared scope limits remain: enable_mow_light_delete predicates are still counted until compaction; skip_delete_sign/show_hidden_columns do not change the exclusion of delete-sign rows; skip_delete_bitmap and non-MoW tables retain their existing statistics behavior; non-NULL zero-token encodings remain approximate; statistics remain per tablet. CLucene caller-buffer behavior was checked against the pinned SegmentReader implementation, with Doris NULL-writer metadata traced to exclude a synthetic missing-field branch.
No builds, tests, format checks or Doris runtime experiments were run under this static-only review contract.
Review converged after 2 round(s).
TPC-H: Total hot run time: 28525 ms |
TPC-DS: Total hot run time: 150260 ms |
ClickBench: Total hot run time: 24.53 s |
BE Regression && UT Coverage ReportIncrement line coverage Increment coverage report
|
…mory The hidden and NULL row ID lists the merge-on-write statistics build per segment are as large as the segment's hidden or NULL rows, and were plain vectors that Doris memory tracking does not see. Use tracked vectors, charge the SNII reader's NULL ID vector while it lives, and sum the hidden rows as they are when the segment has no NULL rows instead of copying them.
|
run buildall |
|
/review |
TPC-H: Total hot run time: 28362 ms |
TPC-DS: Total hot run time: 150552 ms |
ClickBench: Total hot run time: 24.35 s |
…w-statistics # Conflicts: # be/test/storage/index/inverted/reader/collection_statistics_test.cpp
|
run buildall |
|
/review |
TPC-H: Total hot run time: 28390 ms |
TPC-DS: Total hot run time: 150312 ms |
ClickBench: Total hot run time: 24.33 s |
BE Regression && UT Coverage ReportIncrement line coverage Increment coverage report
|
Add regression tests for both visibility gaps across V2/V3/SNII. Cache the SNII sums and measure repeated-query cost. Code inspection at |
|
/review |
There was a problem hiding this comment.
Static review of all 22 changed files and related scan, storage, scoring and cache paths at a0d9931 found two new P2 issues: SNII selected-row norm summation allocates a segment-proportional, untracked output array, and bulk CLucene norm reads lose the query I/O context and its cache-write policy. Both are reported inline. No verified P0/P1 remains, and no additional user focus was supplied.
The existing retained-CLucene-norm P1 (4365847990) is fixed by caller-owned per-segment buffers; the sparse-intersection P2 (4365847994) is fixed by allocation-free sorted traversal. The input-row-ID P2 (4366633033) now has tracked inputs; its remaining SNII admission-after-expansion concern stays with that existing thread. The new finding concerns a different allocation storing norm codes, so none of those reports is reposted.
Critical checkpoint conclusions:
- Goal and evidence: bitmap-overwritten rows and delete-sign rows are excluded from document counts, term frequencies and non-NULL norm-length totals. Replica/fresh-table and compaction regressions exercise the intended score consistency; runtime success was not independently verified.
- Scope and reuse: the change stays within query statistics, index-source helpers, cache bookkeeping and tests, reusing existing bitmap, segment and NULL-index readers.
- Concurrency: scanner threads share first collection under the tablet-statistics mutex; searcher sums have their own mutex. Norm reads occur under that mutex to avoid duplicate computation. The traced lock order has no verified reverse acquisition; first-use contention remains possible.
- Lifecycle and initialization: rowsets/searchers stay pinned while observed, callbacks are synchronous, and buffers/handles unwind through RAII. Cached searchers clear query I/O context as the normal query path does. No new cross-translation-unit initialization or ownership cycle was found.
- Configuration: no settings are added. Existing segment/page/file-cache choices are forwarded into collection, but the new CLucene norm reads discard that context (the second inline finding). The separate, pre-existing omission of enable_file_cache/read_file_cache propagation is unchanged.
- Compatibility: no persisted format or wire representation changes. MoW scores intentionally change because avgdl now uses visible decoded norms, including quantization for long documents.
- Thrift/protobuf IDs: no gensrc changes; release-branch field-ID comparison is inapplicable.
- Parallel paths: CLucene and SNII, local/cloud physical segment identities, both scanner split builders, and unsplit scans were traced. The non-bitmap statistics path retains its prior corpus semantics.
- Special conditions: sorted unique bitmap IDs justify subtraction; NULLs contribute documents without tokens; all-hidden collections avoid missing-statistics errors; missing norms and corrupt row bounds fail explicitly. New branches explain their concrete cases.
- Test coverage: added tests cover visible counts/df/long norms, NULL/all-hidden cases, sparse/dense intersections, partitioned norm sums, cache reuse/error/eviction, I/O context, and replica compaction. Direct tests for SNII selected-row memory limits, concurrent cancellation and noncontiguous cloud IDs remain absent.
- Expected results: changed score families and the fault-test row set were independently derived and agree with the checked-in outputs. Output generation provenance and execution were not verified.
- Observability: existing StatisticsCollectTime, collection VLOG counters and propagated index/segment errors cover the changed path; no new critical tracing requirement was identified.
- Transactions and persistence: read-set versions and bitmap aggregation match normal scanning; no EditLog, failover or persistent-write logic changes.
- Data writes and crash atomicity: no data mutation or new commit protocol; captured ownership and failure cleanup were traced without a new leak or inconsistent publication finding.
- FE/BE variable passing: no new transmitted variable; existing query options are consumed locally.
- Performance and memory: sorted intersections remove the old dense-bitmap cost, and CLucene caches bounded scalar sums instead of retaining norms. The untracked SNII output and CLucene cache-policy findings remain. SNII still reads/sums norms for every MoW query, an explicitly documented cost.
- Other issues and user concerns: no additional substantiated issue after the missed-case rechecks; there was no extra user-provided focus.
Limits: this was static review only, with no builds, runtime tests or source changes. Predicate deletes, debug reads exposing delete-sign rows, tokenless non-NULL ambiguity, missing NULL bitmaps inherited from old compaction behavior, and tablet-local statistics remain the PR's documented limits. Those paths were examined and dispositioned; they are not claims of runtime validation.
Review converged after 3 round(s).
| Status IndexSource::sum_norm_lengths_of(std::span<const uint32_t> docs, uint64_t* out) { | ||
| *out = 0; | ||
| const std::span<const float> lengths = norm_lengths(); | ||
| std::vector<uint32_t> norms; |
There was a problem hiding this comment.
[P2] Bound or track the SNII selected-row norm buffer
For an analyzed SNII MoW segment with 10 million NULL rows and one matching row, sum_non_null_norm_lengths passes the entire NULL list here, and SniiIndexSource::encoded_norms assigns one uint32_t per ID. This allocates another roughly 40 MB before scan pruning, without a MemTracker charge or reservation. The manually charged NULL-ID vector and DorisVector hidden IDs cover separate inputs; the 4096-row batching in sum_norm_lengths does not bound this direct call. Large hidden non-NULL sets reach the same path, so concurrent tablet collection can exceed query memory limits. Please batch selected rows here or sum them directly with tracked storage. This is a distinct norm-code output buffer from the previously reported input row-ID arrays.
| void CluceneIndexSource::_read_norms(const ReaderPartition& partition, | ||
| DorisVector<uint8_t>* norms) const { | ||
| norms->assign(partition.end - partition.begin, 0); | ||
| partition.reader->norms(_field.c_str(), norms->data()); |
There was a problem hiding this comment.
[P2] Preserve the query I/O context on statistics norm reads
For a cold remote MoW tablet, the new statistics pass reads norms from every captured segment, including segments a selective scan later prunes. This call never supplies the source's _io_ctx: the norm stream's CSIndexInput has no per-read context, and the cached base stream was reset to defaults. Consequently CacheContext sees is_disposable=false, no query ID and no remote-scan cache-write limiter. Even with disable_file_cache=true or a query cache-write budget, these new bulk reads populate normal-priority cache blocks and bypass that budget. Ordinary scoring had the same limitation, but previously did not read norms of all pruned segments. Please propagate the context per norm read without retaining query-owned pointers on the shared cached searcher.
|
Thanks for the detailed review, @airborne12! Delete-sign options and SNII norm sums were introduced by this PR, so I'll fix both here:
MoW light deletes were already counted in the statistics before this PR. Supporting them means evaluating delete predicates inside the statistics (reading the predicate columns of each older segment, with caching), which is a sizeable change of its own. Since light delete is off by default for MoW tables, could I handle it, with its V2/V3/SNII regression tests, in a follow-up PR right after this one? This PR fixes a production issue for us (replicas returning different |
What problem does this PR solve?
Issue Number: None
Related PR: #69352 (BM25 statistics shared across the parallel scanners of a tablet; this PR is its follow-up for replicas), #69313 (BM25 token totals after CLucene compaction)
Problem Summary:
On a merge-on-write table, BM25
score()gives the same row a different score on each replica of its tablet. A query picks one replica per tablet, so withreplication_num = 3a row has up to three scores. Pagination overORDER BY score()then repeats and skips rows from one page to the next. Each replica is stable on its own (use_fix_replicapins the scores), but the replicas disagree.CollectionStatistics::process_segment()takes the document count, the token count and each term's document frequency straight from every segment's inverted index. Under merge-on-write, a row overwritten or deleted by a later load stays in its segment's index, marked only in the delete bitmap. A row written with the delete sign, which CDC deletes andDELETEproduce, stays as a normal row that queries filter out by predicate. Both kinds are counted until compaction removes them, and each replica compacts on its own schedule. So each replica counts a different set of rows nobody can see.Reproduction (3 BEs,
replication_num = 3, 8 buckets, auto compaction off): 8 loads, 3 rounds of overwriting a quarter of the rows, aDELETE, and full rows inserted with__DORIS_DELETE_SIGN__ = 1. Then a full compaction (POST /api/compaction/run?compact_type=full) of the tablets on one BE only. On master with #69352, the query below changed the score of all 3,799 matching rows from run to run: 1,900 distinct scores instead of 950. Withuse_fix_replica = 0/1/2each replica was stable, but the three disagreed.The token total has a second, replica-independent problem: CLucene index compaction (
inverted_index_compaction_enable, on by default) copies the source token totals even when it drops rows, which #69313 addresses. On master, the same rows scored differently in a compacted table and in a table freshly loaded with its visible rows.Fix:
When the scan reads a delete bitmap (merge-on-write),
CollectionStatisticsdescribes only the rows the scan returns:OlapScannerpasses the scan's delete bitmap and read version (MowHiddenRows) tocollect(), or toTabletCollectionStatistics::copy_to()for a split tablet. Every scanner of a tablet reads with the same bitmap and version, so the statistics shared by [fix](inverted index) Share BM25 statistics across parallel scanners of a tablet #69352 stay correct.get_agg, the same call the rowset reader uses), plus the rows whose hidden__DORIS_DELETE_SIGN__column is set. Every unique-key table has that column, andDELETEon a merge-on-write table writes such rows unlessenable_mow_light_deleteis on. The delete-sign column is read only for segments whose zone map shows a non-zero sign (or cannot tell), so a segment without CDC deletes costs nothing extra. The read follows the query'senable_segment_cacheandenable_page_cache.IndexSource::scoring_doc_freq_among()counts how many hidden rows a term's postings list. When the hidden rows are much rarer than the term's postings, it leaps between them withseek_block. Otherwise it decodes the postings once and walks the hidden rows alongside them, with no allocation, and a term without postings costs nothing. SNII overrides it so that reserved-namespace scoring terms resolve asscoring_doc_freqresolves them.sumTotalTermFreqwould still leave replicas apart. A row's norm is the same in every segment it is written to, so summing norms gives every replica the same count. It is also the same quantity the BM25 tf normalization already divides,dl / avgdl, withdltaken from the same norm.encode_norm(0)). Its length is left out, using the index's null bitmap, and it still counts as a document, as before. So on CLucene a table whose texts all have at most 40 tokens, and none of which is an empty string, scores exactly as a duplicate-key table with the same rows.Why the token count has to change too: a variant that left out hidden rows only from the document count and the document frequencies, keeping today's token total, made the replicas agree only while every replica compacted through inverted index compaction, which carries dropped rows' token counts forward. With one replica compacted with
inverted_index_compaction_enable = false(the index rebuilt from column data), every row again scored differently on that replica. Its scores were also 12–31 % off a fresh load of the visible rows on average, because its token total still counted the hidden rows.A tablet whose rows are all hidden (every row deleted or overwritten, not yet compacted) has no document a query can match. Its statistics report zero documents instead of failing the query with "No data available for SimilarityCollector".
Tables without a delete bitmap (duplicate key, merge-on-read, or
skip_delete_bitmap) collect the same statistics as before.For every
score()query, with or without a delete bitmap:disable_file_cacheandinverted_index_snii_read_no_write_file_cache, as the scan's reads do. They run before the scan, so they are the reads that fill the file cache. CLucene reads norms without a per-read context, as scoring does.create_index_searcher), and a CLucene error while opening it fails the query; before, it escaped the scanner thread uncaught and aborted the backend. Before, a searcher the statistics put into the searcher cache kept the opening query's I/O context, including its file cache statistics pointer, for later queries to read through.Not covered:
DELETEpredicates also count rows that compaction later drops. They need merge or predicate evaluation to tell which rows are visible, and are left for a follow-up.skip_delete_sign = trueorshow_hidden_columns = true, rows written with the delete sign are returned but still left out of the statistics. Rows deleted by a delete predicate (enable_mow_light_delete) are still counted, as the delete bitmap does not mark them.'!!!', or text without ASCII letters or digits under theenglishparser), whose norm SNII stores as that of one token. On CLucene such a text has a zero norm and counts as zero tokens. Telling these rows apart would mean reading the column.Interaction with #69313: that PR makes the token total of a CLucene index built by compaction exact. With this PR, merge-on-write scans no longer read that total, so their scores do not depend on it. Scans of other tables still do. The two changes are independent.
Release note
Fix BM25
score()on merge-on-write tables differing between the replicas of a tablet, and before and after compaction. Statistics now count only rows visible to the query, and the average document length comes from the indexed norms.Check List (For Author)
Test
Regression test:
inverted_index_p0/test_bm25_score_replica_statistics. It loads overwrites,DELETEs and delete-sign rows, then expects every row to score exactly as in a table freshly loaded with the visible rows. It checks before compaction, with one replica compacted (≥ 3 BEs: 10 runs anduse_fix_replica = 0/1/2), and after compacting all replicas (the compaction steps are skipped in cloud mode, which keeps one shared copy of each tablet). It also checks that a merge-on-write table with NULL rows scores exactly as a duplicate-key table with the same rows, and that a bucket whose rows are all deleted returns no rows instead of failing. Without this change it fails before any compaction (1352 rows score differently from a freshly loaded table); with only the first version of this change it failed the NULL check (250 rows score differently). With it, it passes on a 3-BE cluster.Regression test:
fault_injection_p0/test_bm25_score_statistics_searcher_io_context. With theCSIndexInput.readInternaldebug point, which fails a postings read that still reads as index meta, a coldscore()query on a merge-on-write table failed before the searcher reset ("The 'is_index_data' flag should be false for non-meta inverted index files") and passes with it.Existing suites: all 23 suites that use
score()(ininverted_index_p0,search,ann_index_p0,variant_p0andnereids_rules_p0) pass on a 3-BE cluster. One expected value changes: intest_bm25_score, tablet2is a merge-on-write table whose rowa = 3was updated, so the old version of that row no longer counts. Two documents count instead of three, and the score ofhello worldgoes from 1.0925692 to 0.8025915.Unit Test:
CollectionStatisticsTest.HiddenRowsAreCollectedLikeCompactedAway(real CLucene segments: a segment with a hidden 45-token row collects the same doc count, token count, df, avgdl and idf as the segment without the row),CollectionStatisticsTest.AllRowsHiddenCollectsEmptyStatistics,CollectionStatisticsTest.NullRowsCountAsDocumentsWithoutTokens(real CLucene segment with NULL rows: the same doc count and token count with and without the delete bitmap, and with a hidden NULL row),CollectionStatisticsHiddenRowsTest.*(counting hidden rows in postings by scanning and by leaping, over sparse and dense blocks; norm sums with and without NULL rows; rows beyond the index; indexes without norms),CluceneSearcherCacheValueTest.NonNullNormLengthSumIsComputedOncePerFieldandOlapScannerTest.BuildScoreRuntimeCollectionIoContextFollowsQueryFileCacheOptions. Run locally on macOS (ASAN build): all 243 BM25, collection-statistics, scanner, searcher cache, inverted index reader and null bitmap tests pass. A wider set of 2,732 inverted index, SNII, BM25, search and scan tests also passes, except 6 that fail on macOS in code this PR does not touch (5 SNII writer memory-accounting formulas and 1ScoreRuntimeTestdeath-test message).Manual test: master with [fix](inverted index) Share BM25 statistics across parallel scanners of a tablet #69352, with and without this change, macOS arm64, 3 BEs on one host, the reproduction above.
use_fix_replicapins one replica; "random" lets the FE pick a replica per tablet per query.use_fix_replica = 0/1/2comparedSame result for a 2-replica table with
BUCKETS AUTO, theunicodeparser withlower_case, 4 indexed text columns queried bySEARCH('a:x OR b:x OR c:x OR d:x')plus a non-index filter, auto compaction on, updates byINSERT INTO ... SELECTand deletes byDELETE FROM. Before: every row differed between the replicas (e.g. 3.30 vs 2.69). After: identical on both and equal to a fresh load. The same holds with 1–10 MB text values.Each of these also scored identically on every replica (one replica fully compacted) and matched a fresh load of its visible rows: partial-column updates, a sequence column, stream loads with
__DORIS_DELETE_SIGN__and withmerge_type: DELETE, group commit, keyword and lowercase-normalizer indexes, a range-partitioned table, the SNII storage format, a variant column,MATCH_ANY/MATCH_ALL/MATCH_PHRASE, and a tablet split across scanners (enable_parallel_scanandoptimize_index_scan_parallelism). A 90-second run of concurrent upserts, deletes, compactions and score queries finished without errors and left the replicas identical.Overhead, measured from query profiles with a 4-field
SEARCH(... OR ...)and a non-index filter. Each number is the median of 15 runs on the same data and query:On one 8 M-row tablet (20 % NULL, 80 k overwritten rows),
StatisticsCollectTimewent from 0.6 ms to 4.7 ms per query (median of 9), and the query from 27 ms to 22 ms (noise). The first query on a segment also sums its norms (15 ms here).The cost grows with the rows compaction has not removed yet. To count the hidden rows that hold a term, the collector leaps from hidden row to hidden row when they are much rarer than the term's postings (32 times rarer). Otherwise it decodes the postings once and walks the hidden rows alongside. The norms of a segment's hidden rows are read once per set of hidden rows.
No need to test or manual test.
Behavior changed:
Yes. On merge-on-write tables, BM25 statistics leave out rows hidden by the delete bitmap or the delete sign, and avgdl is computed from the norms of the visible rows. Scores no longer depend on the replica or on compaction. They also shift once on tables without deletes, because norms store long lengths only approximately. Measured on freshly loaded tables:
Does this need documentation?
Check List (For Reviewer who merge this PR)