Skip to content

Answer a repeated count() from exact per-granule match counts in the query condition cache - #129051

Open
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:qcc-exact-count-match-counts
Open

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:qcc-exact-count-match-counts

Conversation

@groeneai

@groeneai groeneai commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #127947

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A repeated SELECT count() FROM t WHERE <filter> whose whole filter is deterministic and evaluated in PREWHERE is now answered from exact per-granule match counts kept in the query condition cache, instead of reading again every granule that has a match. The counts use only the part of query_condition_cache_size that the cached conditions leave free.

Description

The query condition cache keeps one bit per granule, so a repeated count reads every granule with a match again (ClickBench q21 still reads 3,160 of 12,322 granules, #127947). This carries the patch from #127947 by @ snelheidai: a count-only read whose whole filter is a deterministic PREWHERE also records how many rows passed it in each completely read granule (UInt16; 65535 or more matches are not counted), under the same key and guards as the bits. The exact-count path skips those granules and adds their counts. The counts live in a separate LRU limited to the space the bits leave free, so the bits behave as before.

Added on top of the patch: counted granules also go into exact_ranges, otherwise a normal projection could replace a counted part and return its rows twice (100040 instead of 100020 with prefer_optimize_projection = 1).

Option A is implemented, as asked in #127947 (comment): on by default, no setting of its own (optimize_use_implicit_projections = 0 turns it off with the other exact-count optimizations). Option B would add a setting, default off, checked at the start of ReadFromMergeTree::getQueryConditionCacheKeyForMatchCounts. @alexey-milovidov, A or B? The case for B: counts share the bits' key, so a key collision like the one #122966 fixes can make a count wrong, in either direction, even where the bits stay right. With A, ClickBench q21 hot runs are answered from the counts.

Validation: the issue's tests (05493-05495, gtest) with a normal projection case in 05493, and a differential test over 720 random tables (about 2,000 counts, randomized settings) found no wrong count; the issue's patch fails it on the projection case. On 20M rows a repeated count reads 1 row instead of 5.46M. Recording does not slow a first run (release build: median CPU within 0.5% of recording off, also when the counts do not fit).


Workflow [PR]
Sync PR [sync-upstream/pr/129051]

groeneai and others added 8 commits November 3, 2026 11:21
…query condition cache

The query condition cache keeps one bit per granule (no match / maybe), so a
repeated `SELECT count() FROM t WHERE <filter>` still reads every granule with a
match. A count-only read whose whole filter is a deterministic PREWHERE now also
records the number of rows that passed PREWHERE per completely read granule
(UInt16; granules with 65535 or more matches are not counted), under the same key
and guards as the bits. The exact-count path of `optimizeUseAggregateProjections`
removes those granules from the ranges to read and adds their counts.

The counts live in a separate LRU that may use only the part of
`query_condition_cache_size` that the bits leave free, so the bits behave as
before.

Patch by @snelheidai from ClickHouse#127947, tests from the issue renumbered to
05493-05495.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y condition cache counted

`analyzeProjectionCandidate` keeps a part on the parent read when the exact count
optimization cut its ranges, because a projection part returns every matching row
of its part. It recognizes such a part by a non-empty `exact_ranges`. The marks
counted from the query condition cache were removed from `ranges` without being
added to `exact_ranges`, so a part counted only by the cache could be replaced by
a normal projection (for example with `prefer_optimize_projection = 1`) and its
counted rows were then returned again: a repeated
`SELECT count() FROM t PREWHERE s LIKE '%needle%'` over a table with a projection
`(SELECT s ORDER BY s)` returned 100040 instead of 100020.

Add the counted marks to `exact_ranges` too. A new section of
`05366_exact_count_with_normal_projection` covers it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…andomized settings

Every section uses a freshly created table, which has a new UUID and so no
entry in the query condition cache: drop `SYSTEM DROP QUERY CONDITION CACHE`
and the `no-parallel` tag. Clamp the randomized settings the tests depend on
with a `Random settings limits` line instead of body `SET`s, and drop the
obsolete `query_plan_optimize_prewhere`.

Reads through the columns cache record and use exact counts as well (measured:
a count read with 100 columns cache hits recorded counts, and the next count was
answered from them with the right result), and the tests pass with
`use_columns_cache = 1` forced, so it is no longer pinned to 0. The pending
DROP COLUMN pruning workaround of 05495 is not needed on master any more.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ore narrowing it

`computeMarkMatchCounts` emitted the count of a granule as `UInt32`, while
`writeMatchCounts` checks it against `UNKNOWN_MATCH_COUNT` only after that
narrowing. A granule of a non-adaptive part with 2^32 + 7 matching rows was
therefore cached as an exact 7. Carry the count as `size_t` until the limit
check, which is the only place that narrows it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… cache

`writeMatchCounts` constructed the per-part `CountsEntry` (2 bytes per mark of the part, filled) and only then checked
whether it fits into the space the `MatchingMarks` leave free. When it does not fit, every finished read task of the
part allocated and filled the whole array just to throw it away. Compute the weight from the mark count first, with
overflow saturation, and construct the entry only when it fits.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two read tasks of the same part that both missed the lock-free lookup allocated a whole counts array each, and the
second one was dropped because the first had inserted its own meanwhile. Match counts are inserted only under
`counts_size_mutex`, so a second lookup under it sees every insertion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on cache

`count(expr)` must evaluate its argument, which can throw, so it neither records nor uses the counts, like the
statistics shortcut for `count()` in the same file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the comments of the match counts of the query condition cache to their invariants and drop the ones that restate the code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 5 rounds, 7 findings) plus my own review (10 nits).

# Sev Finding Verdict Evidence / action
1 ❌ Counts share the condition hash, so the a UInt8 / aU Int8 collision gives a wrong count in both directions (reproduced: 100 vs 200) DISAGREE This exact risk was put to the maintainers before the PR (#127947, naming #127851) and option A was chosen with B put to @ alexey-milovidov here. The key fixes are #127851, #122966, #128677.
2 ❌ computeMarkMatchCounts narrows the count to UInt32 before the 65535 check, so 2^32+7 matches would be stored as 7 AGREE, fixed the count stays size_t up to the check; gtest CountsAtOrAboveTheLimitAreNotCached
3 ⚠️ First-run cost of recording the counts not measured in a release build AGREE, measured release build, 15 interleaved first-run pairs per shape: median CPU within 0.5% of recording off, with the default cache and with no room for the counts
4 ⚠️ writeMatchCounts allocates the per-part counts before checking that they fit AGREE, fixed size checked before allocating; gtest CountsThatCannotFitAreNotAllocated
4b ⚠️ A second read task of the same part still allocates counts another task has just inserted AGREE, fixed the entry is looked up again under the lock before allocating
4c ❌ With warmed counts, count(throwIf(...)) is answered from them and no longer throws AGREE, fixed only a bare count() uses the counts, as for the statistics shortcut; 05493 section
5 ⚠️ Do not collect the counts at all when they can never fit DISAGREE the no-space case is measured in row 3 (CPU ratio at most 1.0045)
5b ⚠️ A count served by a normal projection never records counts, so repeats keep reading the projection DISAGREE same rows read as on master (no counts exist there); projection reads never record counts, so no wrong result; covering them needs per-projection-part counts
6 💡 readMatchCounts copies the per-part vector at planning noted, not blocking 2 bytes per mark
7 💡 QueryConditionCacheBytes/Entries include the counts, system.query_condition_cache lists the bits only noted, not blocking none
8 💡 Only filters in PREWHERE are counted, so a one-column numeric WHERE keeps reading noted, not blocking stated in the changelog entry
9 💡 Allocating the counts under the size lock can delay a concurrent insertion of bits noted, not blocking 2 bytes per mark, once per part and condition
10 💡 The primary-key exact-count path still answers count(expr) without evaluating it noted, not blocking unchanged master behaviour, deterministic per query and data

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @Algunenano, could you review this and add the can be tested label so CI runs? A bare count() whose whole filter is a deterministic PREWHERE now records the exact number of matching rows per granule in the free part of the query condition cache, and the exact-count projection path adds those counts up (counted marks join exact_ranges) instead of reading the granules again.

@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3ffb168]

Summary: ✅


AI Review

Summary

The PR answers repeated bare count queries with a deterministic PREWHERE from exact per-granule match counts, using cache space left by the existing matching-mark entries. Reviewed head 3ffb168b6b4fab5461914029761a242f18ccbd16; no actionable findings remain. The three new stateless regression tests pass in the current head's Fast test report, and the linked issue supplies before/after performance measurements. Validation used static analysis and reported CI results; no local build or tests were run.

Changed-output consumers traced: MergeTreeReadTask and MergeTreeSelectProcessor carry and publish per-mark counts; countRowsFromQueryConditionCache removes counted marks from residual ranges and supplies the aggregate state; analyzeProjectionCandidate uses exact_ranges_excluded to retain partially counted parent parts; execution and RelationStatisticsEstimator use the reduced ranges and totals. Primary-key and distributed-index analysis precede the added cached ranges, and unique-key reads bypass this optimization.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. labels Nov 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3ffb168b6 with master dde6a0d9f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

88 object files changed (+229.99 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Cache/QueryConditionCache.cpp.o 361.72 KiB 529.88 KiB +168.16 KiB (+46.49%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp.o 968.13 KiB 993.82 KiB +25.68 KiB (+2.65%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

478 translation units recompiled, 5979 s compile time in total, 478 of them have a recent master baseline.

Job report

Dropping or renaming a MergeTree table without a UUID (in an Ordinary database) calls `Context::clearCaches`,
which clears the whole query condition cache, match counts included. Parallel tests do that (01053, 01114,
05218, 05214, 05219 and others), so a count warmed up by these tests could be gone by the query that checks
it: counted -> read in the targeted jobs, where those tests run next to these ones 50 times. Like the other
query condition cache tests that check the cache is used, they run without parallel tests now. The normal
projection case moves from 05366 into 05493, so that 05366 stays as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fdb44cc

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (amd_release, master_head, 4/6) not from this PR: the job hit the 7200 s timeout while its last benchmark test was still running, so no report was written. Its 141 tests took 100 min here against 83 min on another PR's run of this shard on the same instance type, spread over unrelated tests. arm_release 4/6 runs the same tests on this head and found 0 slower queries. amd perf shards were killed at the timeout 10 times on master on 2026-11-03 a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the same task as the row above)

CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20261104-003004

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (amd_release, master_head, 4/6) job timeout: #129176

…ch-counts

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
#	src/Processors/QueryPlan/ReadFromMergeTree.h
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. labels Nov 19, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Answer repeated count() with a filter from exact per-granule counts in the query condition cache

1 participant