Repository navigation
Text index: add trivial count optimization - #111494
Conversation
Return `COUNT()` queries directly from the text index cardinality metadata.
|
Workflow [PR], commit [4c4ce65] Summary: ✅
AI ReviewSummaryThis PR adds a Tests
Final VerdictLLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 395/419 (94.27%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds an optimization that answers SELECT count() WHERE directly from text-index posting-list cardinalities, plus a behavior-preserving refactor of the shared trivial-count state-column builder. Neither ClickBench nor the adapted TPC-H suites use text indexes, and none of the four flagged queries are argument-less count() over a text predicate, so the changed code paths cannot execute here. All four flagged improvements (ClickBench Q17 and Q23, TPC-H Q7 and Q8) are therefore off-path and downgraded to not_sure as run-to-run/baseline variance rather than a real effect of this change. clickbenchFlagged queries (2 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_officialFlagged queries (2 of 22)
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. Debug info
|
tackle it properly in follow-up PRs.
| mutations && (mutations->hasDataMutations() || mutations->hasPatchParts() || mutations->hasLightweightDeletedMask())) | ||
| return false; | ||
|
|
||
| if (reading.getStorageMetadata()->hasUniqueKey()) |
There was a problem hiding this comment.
This new UNIQUE KEY guard fixes the overcounting hole, but the PR still never proves it. The failure only shows up after a duplicate-key replacement leaves a delete bitmap behind, so it is easy to regress by refactoring this bailout away while all current tests stay green. Please add a focused regression with a UNIQUE KEY table, a text index, and a dead row / replacement, and assert either that the rewrite does not fire or that the optimized and non-optimized counts stay equal.
| @@ -0,0 +1,283 @@ | |||
| -- Tags: no-parallel-replicas | |||
There was a problem hiding this comment.
This suite still opts out of parallel replicas entirely, so the two new bailouts that keep the optimization safe there are unproved: the outer settings.enable_parallel_replicas check in optimizeTrivialCountFromTextIndex, and the inner reading.isParallelReadingFromReplicas() guard when a ReadFromLocalParallelReplicaStep subplan is re-optimized.
We already had a real regression on this surface, where replacing the last ReadFromMergeTree node broke coordinated replica reads. With -- Tags: no-parallel-replicas here, that can regress again while every query in this file stays green. Please add a focused parallel-replicas regression (plan-based or local-plan, whichever is easier) that proves EXPLAIN does not contain ReadFromTextIndexCount and that the query still goes through replica coordination / returns the same result.
rschu1ze
left a comment
There was a problem hiding this comment.
@ahmadov Could you please add documentation similar to https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/textindexes#like-ilike-queries-perf ?
…ation `assert_index_used` explained `SELECT count() ... WHERE hasToken(...)`, which the new binary now answers with `ReadFromTextIndexCount` (added to `master` by `optimizeTrivialCountFromTextIndex.cpp`). That plan has no `ReadFromMergeTree` step, so the `Name: idx` line the assertion looks for is absent. The two other call sites run on the old binary, where the optimization does not exist, so only the check on the new binary failed. Explain a query that reads a column instead. Both binaries then produce a `ReadFromMergeTree` step with the `Indexes` section (verified against `clickhouse/clickhouse-server:26.4` and the current build). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111803&sha=416261899380b7f3a8f068a457d99e3b2d29e710&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29 Pull request: ClickHouse#111803 Related: ClickHouse#111494 Co-Authored-By: Claude Opus 5 <[email protected]>
Master answers a count() over a single text predicate straight from the index since ClickHouse#111494 (query_plan_optimize_count_from_text_index, default on), so the one-term EXPLAIN probe no longer has a ReadFromMergeTree listing idx_s and read 'text index used 0' after the master merge. It passed only in the distributed-plan lane, where serialize_query_plan disables that rewrite. Pin the setting off in the probe. The 240-term query the arm cancels is not rewritten, because the rewrite needs exactly one text-index predicate column, so the reader under test still runs and nothing else in the test changes. Also renumber 04746 to 05270: master took 04746 for 04746_distributed_plan_execute_locally_subquery_settings. Measured on the merged head: the probe reads 0 without the pin and 1 with it, and 0 with the pin under use_skip_indexes = 0, with idx_s ignored, and for a non-text predicate. The test passes 50 of 50 runs; with both checkTimeLimit calls neutralized it still fails on the three interrupt-site lines and reads 'text index reader ran 1 100000'. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `system.query_log` checks of `02346_text_index_partially_materialized` and `02346_text_index_optimize_trivial_count` select the `QueryFinish` row of an earlier `count()` with `event_time >= now() - 120`. `event_time` is that query's finish time and `now()` is the check's own start. Between the two the test runs another index scan and `SYSTEM FLUSH LOGS query_log`, which may block in `SystemLogQueue::waitFlush` for up to 180 s. Once the gap passes 120 s the row, which is already in the table, is filtered out: the check returns no row and its expected `1` line disappears from the output. That is the failure seen on a 346 s run: the two lines after `---- use text index reader for all parts` were missing, with nothing added. In the sibling test, `(sum on) < (sum off)` prints `0` when both rows age out, and passes without measuring anything when only the earlier `on` row does. The window was 600 s from ClickHouse#96710 until ClickHouse#111494 narrowed it to 120 s in the commit that made the test faster by shrinking its dataset, and gave the sibling the same value. Restore 600 s in all 10 predicates. 600 s is the per-test timeout (a run still alive after it is killed), so no row a run writes can fall outside the window of a check in the same run, and it is the value ClickHouse#96710 uses across the suite. Dropping the condition instead would undo ClickHouse#96710's pruning of the log scan and, in the Stress and Upgrade jobs where some workers run every test in one fixed database, remove the only bound between executions. A 126 s `sleepEachRow` inserted before the first flush reproduces the exact diff with the 120 s window (3/3) and passes with 600 s (3/3); a 30 s delay passes with 120 s. The same delay before the sibling's flush turns its check from `1` to `0` with 120 s and passes with 600 s. 50 randomized runs of each test pass, and a paired A/B at `-j 8` shows unchanged per-run time. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Currently, the text index direct read optimization deserialize the sparse index, dictionary block and postings when there is token that exists in the index. Once the postings is read from disk, it fills the newly created boolean virtual column with postings data.
With this optimization, we aim to reduce reading postings from disk and creating a virtual column. Instead we can answer queries using the token metadata from the dictionary block for specific query patterns as follows:.
SELECT count() FROM table WHERE hasToken(column, 'foo');SELECT count() FROM table WHERE hasAnyTokens(column, ['foo', 'bar']);SELECT count() FROM table WHERE hasAllTokens(column, ['foo', 'bar']);For the 1. case, we can avoid reading postings at all and use the cardinality metadata stored in the dictionary block to answer the query.
For 2. and 3. cases, we would still read the postings but can avoid creating a virtual column.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Returns
COUNT()queries directly from the text index cardinality metadata.