Repository navigation
Simplify and optimize building of posting lists in text index [4] - #113856
Conversation
Port the encoder-based posting list build from ClickHouse#107367 onto the pluggable per-block codec framework: - `IPostingListEncoder` accumulates row ids of one token encoded into the codec's in-memory form and serializes all segments on `finalize`. Both codecs implement it: `bitpacking` via `SegmentedPostingListCodecImpl` (works for any per-block payload codec) and `none` via per-segment Roaring bitmaps, so large posting lists are no longer materialized as a single Roaring bitmap during the build. - `PostingListBuilder` becomes a variant of an inline array (up to 11 row ids, no heap) and a heap state, whose raw values are flushed to the encoder every `append_granularity` row ids. The encoder is created lazily on the first flush, so raw and embedded posting lists never allocate one. - Positions for phrase search are now built by `PostingListBuilder` itself (in its heap state) instead of a separate token map, and add no overhead when disabled. The heap state is the extension point for future optional per-token payloads (per-row term frequencies and document length norms for BM25 scoring). - The `none` codec now splits posting lists into exact `posting_list_block_size` segments (previously it split by Roaring containers), which changes the number of posting blocks in the test reference.
|
Workflow [PR], commit [314e079] Summary: ❌
AI ReviewSummaryThis PR substantially rewrites text-index posting-list building and merge-time encoding, and most of the new corruption checks look sound. I would still block it: the merge path keeps one release-build validation hole for decoded row ids, so corrupted posting-list data can still reach offset remapping or be forwarded as invalid merged postings. Findings❌ Blockers
Final VerdictChanges requested. The merge-time rewrite still relies on debug-only assertions for one of its core on-disk invariants, so corrupted posting lists can still trigger out-of-bounds remap lookups or produce invalid merged output in release builds. LLVM Coverage ReportMeasured on commit 314e079.
Changed lines: Changed C/C++ lines covered: 750/824 (91.02%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there. This PR rewrites the text-index posting-list encoder and serialization path (MergeTreeIndexText, IPostingListCodec, bitpacking codec) — a write/build path that ClickBench queries do not exercise. The only flagged query, ClickBench Q5, shows a -12.9% median drop but essentially unchanged CPU time (2938.8 vs 2889.7 ms), and the changed code cannot plausibly touch its execution path, so this reads as normal run-to-run variance rather than a real speedup. Downgraded to not_sure accordingly; no evidence of any regression from this change. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
Conflicts came from both branches touching the same posting list codec code: * `SegmentedPostingListCodecImpl` is renamed to `SegmentedPostingListCodec` (from `postings-codec-refactoring`), while keeping the new batch `append` API and the `IPostingListEncoder` accumulators from `text-index-build-4`. The segment size is no longer a constructor argument: it is passed to `append` and normalized in `PostingListCodecBitpacking::getSegmentSize`. * In `BitpackingPostingListBlockCodec::encodeBlock`, the manual reservation of the output buffer is dropped, because `std::string::resize` already grows the buffer geometrically. Both branches were fixing the same pathological `reserve` that reallocated on almost every block. * Comment simplifications from `postings-codec-refactoring` are kept. Co-Authored-By: Claude Opus 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes11 object files changed (+103.80 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units32 translation units recompiled, 297 s compile time in total, 32 of them have a recent master baseline. |
`PostingsSerialization::deserialize` decoded posting lists marked `IsCompressed` with the configured codec, but handled the uncompressed roaring format inline, so `PostingListCodecNone::decode` was an unused no-op. Implement it, and route everything except raw postings through the codec, in both the posting list and the row ids overloads. The codec is now selected by the posting list header instead of the codec configured for the part, so `resolveCompressedCodec` is replaced by `resolveCodec`. An uncompressed posting list is always a serialized roaring bitmap, and picking the codec by the header keeps that independent of the lazy `Bitpacking` resolution done for pre-`WithCodec` parts. Adapted from ClickHouse#113856 Co-Authored-By: Claude Opus 5 <[email protected]>
`PostingsSerialization::deserialize` decoded posting lists marked `IsCompressed` with the configured codec, but handled the uncompressed roaring format inline, so `PostingListCodecNone::decode` was an unused no-op. Implement it, and route everything except raw postings through the codec. The codec is now selected by the posting list header instead of the codec configured for the part, so the resolution is extracted into `resolveCodec`. An uncompressed posting list is always a serialized roaring bitmap, and picking the codec by the header keeps that independent of the lazy `Bitpacking` resolution done for pre-`WithCodec` parts. Adapted from ClickHouse#113856 Co-Authored-By: Claude Opus 5 <[email protected]>
`PostingsSerialization::deserialize` decoded posting lists marked `IsCompressed` with the configured codec, but handled the uncompressed roaring format inline, so `PostingListCodecNone::decode` was an unused no-op. Implement it, and route everything except raw postings through the codec. The codec is now selected by the posting list header instead of the codec configured for the part, so the resolution is extracted into `resolveCodec`. An uncompressed posting list is always a serialized roaring bitmap, and picking the codec by the header keeps that independent of the lazy `Bitpacking` resolution done for pre-`WithCodec` parts. Adapted from ClickHouse#113856 Co-Authored-By: Claude Opus 5 <[email protected]>
Resolved conflicts with `Minor refactoring of posting lists deserialization` (ClickHouse#114317) in the text index posting list codecs: - `IPostingListCodec::decode` keeps the new `PaddedPODArray<char> & buffer` scratch parameter from master, threaded through `SegmentedPostingListCodec`, `PostingListCodecBitpacking` and `PostingListCodecNone`, while keeping `createEncoder` from this branch. `IPostingListCodec::encode` and `encodePostingsInBlocks` stay removed - encoding goes through `IPostingListEncoder`. - `PostingsSerialization::deserialize` uses `resolveCodec` from master, so an uncompressed posting list is always decoded by `PostingListCodecNone` instead of the configured codec, and contradictory `RawPostings` / `IsCompressed` header flags are rejected. - `PostingListCodecNone::decode` now reuses the shared `readContiguousBytes` helper and the caller-owned scratch buffer instead of a local `std::vector`. - Kept both `TextIndexSerialization::serializeRawPostings` (this branch) and `TextIndexSerialization::checkTokenSize` (master). Co-Authored-By: Claude Opus 5 <[email protected]>
# Conflicts: # src/Storages/MergeTree/MergeTreeIndexText.cpp # src/Storages/MergeTree/MergeTreeIndexText.h # src/Storages/MergeTree/MergeTreeIndexTextPostingListCodec.cpp # src/Storages/MergeTree/TextIndexUtils.cpp
|
Merges of text index have slowed down. I'm implementing a proper solution for merges using encoders. |
# Conflicts: # src/Storages/MergeTree/MergeTreeIndexText.cpp # src/Storages/MergeTree/MergeTreeIndexText.h
Port the build-path refactoring from the BM25 branch (the parts not related to scoring): - Introduce `PostingListBuildContext` (codec, segment size, positions flag), built once per batch by `MergeTreeIndexTextGranuleBuilder::buildContext` and passed down to `addDocument`/`addToken` and to the serialization of posting lists. - Unify `PostingListBuilder::add` and the constructor for indexes with and without positions. - Rework `PostingListBuilder::Large::flush`: it now flushes all buffered row ids unconditionally and the callers control the flush size. `add` flushes a full block before appending a new row id, so `values` is never empty between adds and `Large::last_value` is not needed anymore. - Pass `TextIndexHeader` to `TextIndexSerialization::serializeHeader` instead of separate arguments. Ported from ClickHouse/clickhouse-private#70235 (on top of ClickHouse#113856). Co-Authored-By: Claude Fable 5 <[email protected]>
Rewrite the posting-list handling in `MergeTextIndexesTask`. Postings of the current token are no longer decoded eagerly into a union of roaring bitmaps with a full array materialization. Instead the merge queue only collects a `TokenSource` (source number and `TokenPostingsInfo`) per source, and postings are decoded lazily when the token is flushed: - The merged cardinality is known upfront because sources own disjoint row sets, so the serialization format is chosen before decoding a single posting. - Posting lists of up to `MAX_CARDINALITY_FOR_RAW_POSTINGS` row ids are merged into a buffer and written as raw or embedded postings. - Larger posting lists are fed into `IPostingListEncoder` through a k-way merge over cursors that decode and remap one segment of one source at a time. Row ids of the winning cursor below the second-smallest cursor head are emitted in bulk without heap operations. - A duplicate row id across sources and a mismatch between the encoded and the expected cardinality throw an `INCORRECT_DATA` exception. - `TextIndexSerialization::serializePostings` is replaced by `MergeTextIndexesTask::serializeSmallPostings` and `MergeTextIndexesTask::encodePostings`. - `TextIndexPositionCodec::decode` reads into a memory-tracked `PaddedPODArray` on the merge path. Co-Authored-By: Claude Fable 5 <[email protected]>
Rework the k-way merge of posting lists in `MergeTextIndexesTask`: - Fix an out-of-bounds access: `postings_merge_cursors` was never sized, so the first flush of a posting list aborted the server with a libc++ hardening assertion in the release build. - Replace the hand-rolled binary heap over cursors with `SortingQueueBatch<SpecializedSingleColumnSortCursor<ColumnUInt32>>`, the same machinery the dictionary merge above it uses. Each cursor decodes into its own `ColumnUInt32` and its `SortCursorImpl` is built once in the task constructor, so a segment refill only rewinds the cursor instead of paying `SortCursorImpl::reset` per token and source. - A token that lives in a single source (the most common case) is drained directly into the sink without touching the queue. - A granularity-aligned chunk arriving on an empty staging buffer is passed to the encoder directly, skipping a copy for whole segments. - A duplicate row id across sources throws `INCORRECT_DATA`: sources must own disjoint row sets, and the queue would otherwise silently order equal values by cursor number. An alternative tier that unioned overlapping sources into a roaring bitmap was measured and dropped: on 50M rows of real server logs (`message` column, 6-part merges, both time-disjoint and fully interleaved part layouts) the queue merge is the fastest variant on both layouts, while the bitmap union only wins on the synthetic uniform-random interleave of `text_index_merge.xml`, where the `*_intersecting_*` queries are expected to regress. Co-Authored-By: Claude Fable 5 <[email protected]>
…them `PostingListCodecNone::decode` grew the decode buffer to the VarUInt size prefix read from disk before checking anything. The allocator rejects only sizes of 2^63 and above, and with `LOGICAL_ERROR`, which aborts debug and sanitizer builds. Smaller corrupted sizes failed with `MEMORY_LIMIT_EXCEEDED` or `CANNOT_READ_ALL_DATA` after the allocation. Reject the size up front with `CORRUPTED_DATA` when it exceeds the upper bound of a portable Roaring bitmap with `max_cardinality` row ids, so the bounded-decode contract of `IPostingListCodec::decode` holds for the `none` codec as it does for `bitpacking`. ClickHouse#113856 (comment) Co-Authored-By: Claude Fable 5.1 <[email protected]>
Resolves conflicts with the `pfor` posting list codec from ClickHouse#118123: - `SegmentedPostingListCodecBase` keeps master's class hierarchy and takes over `getSegmentSize`, `createEncoder` and the `decode` overloads bounded by the token metadata; `createEncoder` uses the codec's own type, so `pfor` indexes are built with a PFor encoder - `addDocumentsFromMap` from master takes the `PostingListBuildContext` - the memory accounting of posting list encoders is removed together with the granule memory accounting removed in ClickHouse#119927 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Remove the global `BLOCK_SIZE` from `BitpackingBlockCodec.h`. Each `BitpackingBlockCodecImpl` specialization now owns the block size of the bit-packing layout, and `IPostingListBlockCodec::BLOCK_SIZE` owns the number of row ids in one block of a segmented posting list, with a static assertion that the latter is a multiple of the former. Add `IPostingListCodec::getBlockSize`, overridden by `SegmentedPostingListCodecBase`, and round the segment size to it in `getSegmentSize`. Resolves ClickHouse#113856 (comment) Co-Authored-By: Claude Fable 5.1 <[email protected]>
…f every `append` The segment size cannot change between `append` calls of one encoder, so it is fixed when the encoder is created. `IPostingListEncoder::append` takes only the row ids, and the codec rounds the requested size itself, which makes `getSegmentSize` and `getBlockSize` unnecessary in `IPostingListCodec`. Addresses ClickHouse#113856 (comment) Co-Authored-By: Claude Fable 5.1 <[email protected]>
…range The lazy cursor only checked that the segment cardinality fits into the row range stored in the dictionary. A corrupted segment whose header or Index Section disagreed with that range was still accepted: `advance` and the skip heuristics position by the range and by `block_last_row_ids`, while `decodeBlock` uses the header `first_row_id` and the previous block's last row id as delta bases, so such a segment could silently drop rows or return rows outside the token range. Now `buildPostingSegment` requires the header to start at the first row id of the range, the block index to end at its last row id and to stay after the segment start, and `decodeBlock` requires every decoded block to end at the row id its Index Section entry claims. Otherwise the segment is rejected with a `CORRUPTED_DATA` exception, matching `checkSegmentRowRange` on the eager path. ClickHouse#113856 (comment) Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Fix for fuzzer failure: #121522. |
889b021
Resolve the conflicts with the merged text-index-build-4 (ClickHouse#113856) and the later text index changes on master: keep the `max_cardinality` bound of the segment decoding, `createEncoder(segment_size)`, the `PFor` block codec and the `PODArray` output, and layer the BM25 term frequencies (`tf_minus_one`, `decodeWithTermFrequencies`) on top of them. Add the `.dl` substream to `getPotentialSubstreams`, implement `encodeZeros` and `skipBlock` for the `PFor` block codec, and resolve the text index streams from the part's checksums in `BM25State`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Improved performance of building text indexes during inserts (especially for indexes with
bitpackingcodec).Depends on #113843.
Workflow [PR]
Sync PR [sync-upstream/pr/113856]
Version info
26.10.1.418-master(included in26.10and later)