Skip to content

Text index: add trivial count optimization - #111494

Merged
ahmadov merged 55 commits into
masterfrom
ahmadov/text-index-trivial-count
Aug 13, 2026
Merged

ahmadov merged 55 commits into
masterfrom
ahmadov/text-index-trivial-count

Conversation

@ahmadov

@ahmadov ahmadov commented Jul 22, 2026 •

Copy link
Copy Markdown
Member

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:.

  1. SELECT count() FROM table WHERE hasToken(column, 'foo');
  2. SELECT count() FROM table WHERE hasAnyTokens(column, ['foo', 'bar']);
  3. 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):

  • Performance Improvement

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.

ahmadov added 2 commits July 23, 2026 00:32
Return `COUNT()` queries directly from the text index cardinality metadata.
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4c4ce65]

Summary: ✅


AI Review

Summary

This PR adds a ReadFromTextIndexCount rewrite so exact SELECT count() ... WHERE <text predicate> queries can be answered from text-index metadata / postings instead of materializing rows, with guardrails for mutations, plan shipping, partition limits, and mixed-format upgrade paths. I did not find a remaining correctness bug in the current code, but I do not think the evidence gate is closed yet: two default-on safety bailouts are still not both covered by focused regressions.

Tests
  • ⚠️ UNIQUE KEY / delete-bitmap coverage is still missing. The code now declines the optimization on reading.getStorageMetadata()->hasUniqueKey() in src/Processors/QueryPlan/Optimizations/optimizeTrivialCountFromTextIndex.cpp:258, but the suite still never creates a UNIQUE KEY table with a dead row / duplicate-key replacement and proves the bailout. A focused regression should assert either that EXPLAIN does not contain ReadFromTextIndexCount or that optimized and non-optimized counts stay equal after the replacement.
  • ⚠️ Parallel-replicas coverage is still missing. The current suite opts out with -- Tags: no-parallel-replicas in tests/queries/0_stateless/02346_text_index_optimize_trivial_count.sql, so neither the outer settings.enable_parallel_replicas bailout nor the inner reading.isParallelReadingFromReplicas() bailout is exercised. Add a focused plan-based or local-plan parallel-replicas regression that proves ReadFromTextIndexCount does not appear and replica coordination still executes.
Final Verdict

⚠️ Not ready to sign off yet: current code looks materially improved, but the default-on optimization still lacks focused regressions for two previously fragile safety boundaries.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 395/419 (94.27%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 22, 2026
@ahmadov
ahmadov marked this pull request as ready for review July 27, 2026 08:29
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 556 482 -13.4% <0.0001 ClickBench uses no text index and Q17 is not a bare count(), so this PR's count-from-text-index path and behavior-preserving trivial-count refactor can't touch it. The -13.4% reads as run-to-run variance.
⚠️ 23 not_sure 167 72 ×2.3 faster <0.0001 Q23 does not exercise a text-index count path, its history is noisy, and the source measurements were highly variable, so the x2.3 faster shift is not attributable to this PR.

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

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 574 70 ×8.2 faster <0.0001 TPC-H Q7 is a join/aggregation with no text index and no argument-less count(), so this text-index-count PR cannot produce the x8.2 faster shift. It looks like a measurement or baseline-era artifact.
⚠️ 8 not_sure 175 80 ×2.2 faster <0.0001 Like Q7, Q8 has no text index and no trivial count() path, so the x2.2 faster delta is unrelated to this PR's changes.

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
  • StressHouse run: ac16d328-b63b-49a7-94cf-b86cd2fd115a
  • MIRAI run: 644c8b3d-b3ea-4075-9242-5587cfc7c228
  • PR check IDs:
    • clickbench_1079611_1786637471
    • clickbench_1079722_1786637476
    • clickbench_1079747_1786637477
    • tpch_adapted_1_official_1079932_1786637528
    • tpch_adapted_1_official_1080059_1786637583
    • tpch_adapted_1_official_1080166_1786637590

tackle it properly in follow-up PRs.
mutations && (mutations->hasDataMutations() || mutations->hasPatchParts() || mutations->hasLightweightDeletedMask()))
return false;

if (reading.getStorageMetadata()->hasUniqueKey())

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 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.

@ahmadov
ahmadov requested a review from Ergus July 28, 2026 08:12
@@ -0,0 +1,283 @@
-- Tags: no-parallel-replicas

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 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.

@ahmadov
ahmadov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into master with commit ad8b2a5 Aug 13, 2026
182 checks passed
@ahmadov
ahmadov deleted the ahmadov/text-index-trivial-count branch August 13, 2026 22:57
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026

@rschu1ze rschu1ze 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.

CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Aug 19, 2026
…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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 26, 2026
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]>
pull Bot pushed a commit to Dream-hu/ClickHouse that referenced this pull request Sep 27, 2026
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]>
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 pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants