Skip to content

Simplify and optimize building of posting lists in text index [3] - #107367

Closed
CurtizJ wants to merge 6 commits into
ClickHouse:masterfrom
CurtizJ:text-index-build-3
Closed

CurtizJ wants to merge 6 commits into
ClickHouse:masterfrom
CurtizJ:text-index-build-3

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Jun 12, 2026

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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 bitpacking codec).

Collect row ids of each token as raw values instead of building Roaring
Bitmaps during the index build. `PostingListBuilder` is a 56-byte
`std::variant` stored by value in the hash map, so a cell with a short
token key fits in one cache line: the first 11 row ids are stored inline
(tokens serialized as raw postings never allocate), more frequent tokens
buffer row ids in a small vector and append them in blocks of 128 into
`IPostingListAccumulator`, which encodes them into the codec's in-memory
form and splits them into segments of `posting_list_block_size` row ids.

Serialization of posting lists is unified: they are always written and
read through `IPostingListCodec` (the `none` codec owns the Roaring
format including `decode`), small posting lists are written as raw
VarUInts by `serializeRawPostings`, and `splitPostings` with the
special-cased `PostingsSerialization` serialize overloads are removed.
On merges, posting lists are extracted from the merged Roaring Bitmap in
fixed-size batches and streamed through the same accumulator.

As a side effect, the `none` codec now splits posting lists into
segments by row count, honoring `posting_list_block_size` (like
`bitpacking`), instead of splitting by Roaring containers.

Results of `tests/performance/text_index_build.xml` (also extended to
cover both codecs), measured against master with identical build flags;
INSERT wall clock and peak memory by codec and vocabulary size:

  none       50/5000/500000:  +1%/-11%/-39% time,  +0%/+0%/+4% memory
  bitpacking 50/5000/500000:  -9%/-23%/-41% time,  +0%/+12%/+4% memory

This preserves the speedup of the vocabulary-500000 case achieved by the
streaming accumulators in ClickHouse#106735
(https://s3.amazonaws.com/clickhouse-test-reports/PRs/106735/3c33b60ff8e062133e7fb13598d6953f8033bbc2/performance_comparison_amd_release_master_head_6_6/report.html)
while keeping the per-row hot path free of codec calls.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ecd33fe]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, flaky check) DROPPED

AI Review

Summary

This PR refactors text-index posting-list construction and serialization to buffer row ids and encode through per-codec encoders, with a performance claim for insert-time text index builds. I found two unresolved issues: undefined behavior in the inline-to-large builder transition, and a merge-time memory regression that breaks the advertised streaming merge behavior.

Missing context / blind spots
  • ⚠️ Latest CI still had in-progress jobs when checked (Fast test, Build (arm_tidy), and this review job). Passing the latest CI run would close this CI-signal gap.
Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeIndexText.cpp:1359] PostingListBuilder must preserve the inline values when spilling to Large, but state.emplace<Large>(inline_state->values, ...) ends the active Inline lifetime before Large copies from inline_state->values. That makes the 12th distinct row id for a token read from storage whose object lifetime has ended, which is undefined behavior. Thread: Simplify and optimize building of posting lists in text index [3] #107367 (comment)

    Suggested fix: copy inline_state->values into a local std::array before calling state.emplace<Large>, or restore the previous helper that copied out before changing the std::variant alternative.

  • [src/Storages/MergeTree/MergeTreeIndexText.cpp:929] Text-index merges must keep peak memory bounded by streaming the merged PostingList, but serializePostings now materializes the whole bitmap into a dense UInt32 array before encoding. A token present in N rows allocates about 4 * N extra bytes during background merge, and the none codec then builds Roaring segments again, regressing from the old path that serialized Roaring data/splits without this dense copy. Thread: Simplify and optimize building of posting lists in text index [3] #107367 (comment)

    Suggested fix: feed the encoder from roaring_uint32_iterator_read in bounded batches, or keep a direct none-codec merge path that avoids the dense row-id array.

Tests
  • ⚠️ Add focused regression coverage for the spill boundary, with a token appearing in at least 12 distinct rows, so the Inline to Large transition is exercised and serialized postings are verified.
  • ⚠️ The performance test covers insert-time index build, but not text-index merge peak memory. Add merge-path evidence or a focused performance test with a very common token for both none and bitpacking.
Final Verdict

Status: ❌ Block

Minimum required actions: fix the state.emplace<Large> lifetime bug, restore bounded merge serialization, and add the focused regression/performance evidence above.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 12, 2026
CurtizJ and others added 2 commits June 12, 2026 21:15
`HashTable::emplace` requires the caller to make a placement new of the
mapped value of an inserted key, because the hash table does not
construct it itself, but calls its destructor on destruction. Construct
`PostingListBuilder` in place with the first row id of the token.

Also remove the default member initializer from `Inline`: initializers
of a nested class are parsed in the complete-class context of the outer
class, so the variant's default constructor (which requires `Inline` to
be default-constructible) was unavailable within `PostingListBuilder`
itself. The default constructor of the variant value-initializes
`Inline`, so the `size` member is still zeroed.

Fixes the review comment
ClickHouse#107367 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

This PR is confined to the full-text (text) index posting-list builder and serialization codec — it rewrites how row ids are accumulated and encoded during index build. The two flagged ClickBench improvements (Q4 -16.98%, Q15 -19.84%) run against the hits table, which has no text index, so the changed code is never exercised by either query. Both queries are also marked trending on master, meaning the baseline has been drifting and inflating the apparent gain. We are downgrading both to not-sure: the deltas are real measurements but cannot be attributed to this change.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 268 222 -17.0% <0.0001 PR only touches text-index posting-list build; ClickBench Q4 uses no text index. Off-path; trending base inflates delta.
⚠️ 15 not_sure 252 202 -19.8% <0.0001 PR only rewrites text-index posting-list encoding; Q15 never executes that path. Off-path improvement; run-to-run varian

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
  • StressHouse run: 1731b3b6-c328-4314-835a-c270d129b86b
  • MIRAI run: 3ab219a6-348f-43b0-b566-05fec759f6bc
  • PR check IDs:
    • clickbench_166312_1781921507
    • clickbench_166326_1781921507
    • clickbench_166332_1781921507
    • tpch_adapted_1_official_166343_1781921507
    • tpch_adapted_1_official_166349_1781921507
    • tpch_adapted_1_official_166362_1781921507

PaddedPODArray<UInt32> values(info.cardinality);
postings.toUint32Array(values.data());

if (info.cardinality <= MAX_CARDINALITY_FOR_EMBEDDED_POSTINGS)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This helper is also used by text-index merges (MergeTextIndexesTask::flushPostingList), so expanding every merged PostingList into a dense UInt32 array makes merge peak memory proportional to the most common token's full cardinality. For the none codec this is a regression from the previous path, which serialized Roaring data/splits without first materializing all row ids; now a token present in N rows allocates about 4 * N extra bytes and then builds Roaring segments again in PostingListEncoderNone.

Please keep this path streaming: read the bitmap with roaring_uint32_iterator_read in bounded batches and feed the encoder, or keep a direct none-codec path that avoids the dense row-id array.

if (value == large.last_value)
return;

large.last_value = value;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

state.emplace<Large> destroys the active Inline alternative before constructing Large, but the argument inline_state->values still refers into that same alternative. The Large constructor copies from it by value, so the copy happens after the Inline lifetime has ended (and while the new alternative is being constructed in the same storage), which makes the spill on the 12th distinct row id undefined behavior. Please keep the previous "copy out before emplace" pattern, e.g. copy inline_state->values to a local std::array and pass that local to emplace.

@clickhouse-gh

clickhouse-gh Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.20% -0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.50% 77.40% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 252/275 (91.64%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 4 line(s) · Uncovered code

Full report · Diff report

@CurtizJ

CurtizJ commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Continued in #113856.

@CurtizJ CurtizJ closed this Aug 7, 2026
PedroTadim pushed a commit to clickgapai/ClickHouse that referenced this pull request Sep 22, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants