Skip to content

Optimize text index analysis - #109886

Merged
CurtizJ merged 7 commits into
ClickHouse:masterfrom
CurtizJ:optimize-text-index-analysis
Jul 16, 2026
Merged

CurtizJ merged 7 commits into
ClickHouse:masterfrom
CurtizJ:optimize-text-index-analysis

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Jul 9, 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):

Optimized analysis of the text index.

Additional context

Cache the SipHash value in TextSearchQuery because we need to compute the hash for each granule, and this path became hot during index analysis in large tables.

Version info

  • Backported to: 26.6.2.93

CurtizJ and others added 3 commits July 4, 2026 17:40
Precompute the hash of `TextSearchQuery` in the constructor because
`getHash` is called on hot paths (per part, per virtual column and per
mark). For that, `phrase_tokens` are now passed to the constructor, so
all fields are set before the hash is calculated. Added an overload of
`getSipHash128AsHexString` that takes a precomputed `UInt128`; the byte
order of the hex string differs from the `SipHash`-based overload, so
the names of text index virtual columns in test references changed.

Reserve the memory for result columns in `MergeTreeReaderTextIndex` for
the number of rows to read. Previously the columns grew mark by mark
through a chain of large reallocations, which caused heavy contention
on allocator mutexes (`malloc_mutex_lock_slow` at ~10% of CPU in
profiles) across reading threads and made `shrinkToFit` copy the whole
column again. Reduces CPU time of a `hasAllTokens` `count()` benchmark
query by ~40%.

Co-Authored-By: Claude Fable 5 <[email protected]>
All fields of TextSearchQuery must not be mutated after construction,
otherwise the precomputed hash becomes stale. Enforce this invariant by
making the fields private and exposing them through const getters.

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

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [278afe2]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) FAIL
02346_text_index_hint_map FAIL cidb IGNORED

AI Review

Summary

This PR precomputes TextSearchQuery hashes and reserves text-index result columns to remove repeated hashing and allocation work from hot paths. After reviewing the current diff, the touched code paths, and the prior PR discussion, I did not find a correctness or compatibility issue that still reproduces in the current head.

Missing context / blind spots
  • ⚠️ I did not run local text-index benchmarks or local stateless tests in this environment; the review is based on code inspection plus the green PR CI summary.
Final Verdict

No blocking issues found in the current revision.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 9, 2026
Comment on lines +558 to +560
auto column = columns_to_read[i].type->createColumn(*serializations[i]);
column->reserve(max_rows_to_read);
columns[i] = std::move(column);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

A minor improvement with preallocation.

cursors.push_back(it->second);
}
else if (query_builder.postings->cardinality() > 0)
else if (!query_builder.postings->isEmpty())

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

A minor improvement: roaring::cardinality has the complexity O(number of containers).

const TextIndexAnalyzer::QueryBuilder & TextIndexAnalyzer::getQueryBuilder(const TextSearchQuery & query) const
{
auto hash = query.getHash().get128();
auto hash = query.getHash();

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

A hot path with hash for which this refactoring is done.

@ahmadov ahmadov self-assigned this Jul 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR is a text-index refactor: it precomputes the SipHash of TextSearchQuery, moves its fields behind getters, and reserves reader columns up front. None of that touches the code paths ClickBench Q4 and Q15 execute (a plain aggregate scan and a GROUP BY), so neither query's apparent improvement can come from this change. Both show flat CPU with only wall-clock dipping and medians pinned to the bottom of the master variance band, so the deterministic no_change/within-envelope verdicts are correct — the ~19-20% deltas are run-to-run noise, not a real effect. No regressions or genuine improvements are attributable to this PR.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 0990f23c-abe5-4985-99ab-10aa9dc70782
  • MIRAI run: ccfdd588-af2b-4ef5-83d3-c8fccc905f5b
  • PR check IDs:
    • clickbench_674434_1784155152
    • clickbench_674447_1784155152
    • clickbench_674453_1784155152
    • tpch_adapted_1_official_674459_1784155152
    • tpch_adapted_1_official_674466_1784155152
    • tpch_adapted_1_official_674477_1784155152

@ahmadov ahmadov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM 👍

@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 28.60% 85.90% +57.30%
Functions 39.40% 92.70% +53.30%
Branches 20.60% 78.00% +57.40%

Changed lines: Changed C/C++ lines covered: 266/275 (96.73%) · Uncovered code

Full report · Diff report

@CurtizJ

CurtizJ commented Jul 16, 2026

Copy link
Copy Markdown
Member Author

A flaky check failed because of high load in parallel runs of tests: Reason: Test runs too long (> 180s). Make it faster.

@CurtizJ

CurtizJ commented Jul 16, 2026

Copy link
Copy Markdown
Member Author

The reason why the name of virtual column has changed:

The virtual column name is built in MergeTreeIndexConditionText::replaceToVirtualColumn as __text_index_<index>_<function>_<hex-hash>. 
Before the PR, TextSearchQuery::getHash returned the raw SipHash state object, and the caller did this:

auto query_hash = query.getHash();                        // SipHash state, not finalized
auto it = all_search_queries.find(query_hash.get128());   // finalize #1 -> value A (map key)
...
auto hash_str = getSipHash128AsHexString(query_hash);     // get128() again -> finalize #2 -> value B

SipHash::finalize (src/Common/SipHash.h:70) is not idempotent - each call XORs current_word into the state and runs four more SIPROUNDs, and get128 calls it unconditionally with no "already finalized" guard. 
So the hex string embedded in the column name was value B (a hash of an already-finalized state), different from the value A used as the key in the all_search_queries map. 
It was still deterministic - the same two-call sequence ran every time - so everything worked, but the name carried a "garbage" derived value.

It shouldn't be a problem, though, because we expose this column with an alias to the original column name to the planner, and distributed queries on different versions won't break.

@CurtizJ
CurtizJ added this pull request to the merge queue Jul 16, 2026
Merged via the queue into ClickHouse:master with commit c920e6f Jul 16, 2026
174 of 176 checks passed
@CurtizJ
CurtizJ deleted the optimize-text-index-analysis branch July 16, 2026 14:37
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 16, 2026
@CurtizJ

CurtizJ commented Jul 20, 2026

Copy link
Copy Markdown
Member Author

This is kind of a performance regression. Let's backport it to 26.6

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 20, 2026
CurtizJ added a commit that referenced this pull request Jul 21, 2026
Resolve cherry-pick conflicts for #109886 (Optimize text index analysis).
The release branch does not contain #108114 (`num_live_tokens` / better
discarding of `Any` text queries), so the conflicts are resolved by keeping
26.6's logic and applying only #109886's changes: the field->getter refactor
of `TextSearchQuery`, the precomputed hash, and the result-column memory
reservation in `MergeTreeReaderTextIndex`.

The `02346_text_index_bug90778` reference is updated for the fixed virtual
column name hash (the old name was a double-finalized `SipHash` accident);
the `equals` query uses `direct_read_mode = Exact` on 26.6, giving the hash
`55ee63b12fbf5cb6a7510c6b2df99282`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
robot-ch-test-poll4 added a commit that referenced this pull request Jul 21, 2026
Cherry pick #109886 to 26.6: Optimize text index analysis
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 21, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 21, 2026
Backport #109886 to 26.6: Optimize text index analysis
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants