Skip to content

Add optimize_trivial_group_by_count_query optimization - #103490

Draft
amosbird wants to merge 22 commits into
ClickHouse:masterfrom
amosbird:count-by-pk-monotonic
Draft

amosbird wants to merge 22 commits into
ClickHouse:masterfrom
amosbird:count-by-pk-monotonic

Conversation

@amosbird

@amosbird amosbird commented Apr 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

A generalization of the exact-ranges trivial count optimization (#60463) to GROUP BY queries: optimize SELECT monotonic_f(pk_col), count() FROM t GROUP BY 1 by computing counts directly from MergeTree primary key index and granularity metadata, avoiding full table scans.

This is particularly useful for log histogram scenarios (e.g., SELECT toStartOfInterval(ts, INTERVAL 1 HOUR), count() FROM logs GROUP BY 1) where the primary key is a timestamp. It also lays the groundwork for combining histogram counting with full-text index filtering in future work.

For granules fully within a single bucket, row counts come from MergeTreeIndexGranularity::getRowsCountInRange (zero data I/O). For granules that cross a bucket boundary, only the PK column of that granule is read to determine the exact split point. With PREWHERE/WHERE on PK range conditions, exact_ranges from selectRangesToRead identify granules where all rows match — these use metadata counting. Non-exact boundary granules read the PK column and apply the filter.

Changes:

  • New setting optimize_trivial_group_by_count_query (default true)
  • New second-pass query plan optimization optimizeCountByGranularity: pattern-matches AggregatingStep + ExpressionStep + ReadFromMergeTree, validates GROUP BY keys are monotonic functions of the sorting key prefix via matchTrees, rewrites the subtree to ReadFromCountByGranularity and switches AggregatingStep to merge-only mode via requestOnlyMergeForAggregateProjection
  • New ISourceStep subclass ReadFromCountByGranularity with parallel CountByGranularitySource instances sharing an atomic work pool, tasks split by mark ranges for load balancing across threads
  • Supports multiple GROUP BY keys (matching sorting key prefix), PREWHERE/WHERE on PK range conditions, distributed queries (outputs ColumnAggregateFunction intermediate states)
  • Bails out safely for lightweight deletes, expression-based PK columns, FINAL, SAMPLE

Benchmark (50M rows, 20 parts, RelWithDebInfo):

Scenario ON OFF Speedup
50 buckets, multi-thread 6ms 22ms 3.7x
500 buckets, multi-thread 14ms 22ms 1.6x
PREWHERE on PK, 30 buckets 5ms 19ms 3.8x
50 buckets, single-thread 33ms 610ms 18x
500 buckets, single-thread 302ms 620ms 2x

Changelog category (leave one):

  • Performance Improvement

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

Add optimize_trivial_group_by_count_query setting that optimizes GROUP BY monotonic_function(primary_key) + count() queries by computing counts from primary key index and granularity metadata instead of reading data columns.

Documentation entry for user-facing changes

  • Documentation is not required

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

@clickhouse-gh

clickhouse-gh Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [13a4e8b]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
Build ClickHouse FAIL
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Apr 24, 2026
@amosbird
amosbird force-pushed the count-by-pk-monotonic branch from ab8b049 to 3bff9f8 Compare April 24, 2026 09:28
Comment thread src/Core/Settings.cpp Resolved
@amosbird
amosbird force-pushed the count-by-pk-monotonic branch 2 times, most recently from bcbf392 to 61e1686 Compare April 24, 2026 12:31
@amosbird
amosbird force-pushed the count-by-pk-monotonic branch from 61e1686 to 9e90750 Compare April 24, 2026 13:40
@amosbird
amosbird force-pushed the count-by-pk-monotonic branch 3 times, most recently from 37e3d14 to 1437f6e Compare April 25, 2026 01:50
@amosbird
amosbird force-pushed the count-by-pk-monotonic branch from 1437f6e to 08c80fc Compare April 25, 2026 07:57
@amosbird
amosbird force-pushed the count-by-pk-monotonic branch 3 times, most recently from 8cc9006 to e804968 Compare April 25, 2026 10:05
Comment thread src/Core/Settings.cpp Outdated
When enabled together with `read_in_order_use_virtual_row`, emit a virtual row after each block read (not only at the beginning of each part).
This allows `MergingSortedTransform` to reprioritize sources more frequently, which is useful when downstream filters discard many rows and data is distributed unevenly across parts.
Note that it disables `read_in_order_use_buffering` optimization and preliminary merge (`read_in_order_two_level_merge_threshold`) for reading.
)", 0) \

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 PR adds a new user-facing setting, optimize_trivial_group_by_count_query, but the PR body currently uses a non-template documentation checkbox (- [ ] Documentation is not required).

Please align the PR metadata with .github/PULL_REQUEST_TEMPLATE.md (- [ ] Documentation is written (mandatory for new features)) and either add docs for the new setting or clearly justify why docs are unnecessary.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

setting documentation is self-included.

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.

The PR still does not follow the required template field for docs.

Documentation is not required is not a valid checkbox from .github/PULL_REQUEST_TEMPLATE.md; for this user-facing setting change, please keep the template line and mark it accordingly:

- [x] Documentation is written (mandatory for new features)

(Using source-level setting docs is fine, but the PR body still needs to use the template checkbox.)

amosbird added 15 commits April 29, 2026 03:11
…g and old analyzer aggregation-in-order test
- Drop no-parallel: test uses independent table names
- Drop no-random-settings: EXPLAIN checks now use explicit SETTINGS
  clauses (optimize_aggregation_in_order=0, force_aggregation_in_order=0,
  allow_experimental_parallel_reading_from_replicas=0,
  force_aggregate_partitions_independently=0) to ensure optimization
  triggers regardless of random settings
- toStartOfInterval queries use SETTINGS session_timezone='UTC'
- Restore no-random-settings tag: command-line random settings override
  query-level SETTINGS clauses, causing EXPLAIN checks to fail when
  optimize_aggregation_in_order is randomly enabled (confirmed flaky in
  ASAN flaky check with 50 runs)
- Simplify prewhere input validation to strict equality: only accept when
  input names exactly match PK column names, bail out on qualified names
  (e.g. __table1.k) to prevent UNKNOWN_IDENTIFIER errors
Instead of relying on canUseProjection() (which fails when random settings
enable force_aggregation_in_order), add requestOnlyMergeForCountByGranularity
that clears sort_description_for_merging before switching to merge-only mode.

Also simplify prewhere input check to strict PK name equality (bail out on
qualified names like __table1.k).
Use bucket expression DAG's INPUT node names (which may be qualified
like __table1.k) when building blocks, instead of unqualified PK column
names. This ensures the expression can execute correctly regardless of
whether the analyzer adds table prefixes.
- Move parts_with_ranges binding after selectRangesToRead to avoid stale
  reference when analyzed_result_ptr is replaced
- Make filter column fetch strict: getByName throws if column is missing
  instead of silently counting all rows
- Handle qualified vs unqualified column names: build block with both PK
  names (for filter) and bucket_inputs names (for bucket expression)
  when they differ
- Precompute InputToPKMapping once per source instead of per-granule
  string matching for qualified name -> PK column resolution
- Determine KeyMode (SingleNumeric/MultiNumeric/Generic) once in
  makePipe via dummy block execution, pass as enum to sources
- Precompute key column positions in output header for buildChunk
- Reuse aggregate state buffer across buckets instead of per-bucket
  vector allocation
- Reserve ColumnAggregateFunction capacity
- Separate filter/no-filter paths completely: countGranuleByReading
  vs countGranuleWithFilter, processMarkRangesNoFilter vs
  processMarkRangesWithFilter — zero branches on hot path
- Extract executeBucketExpression, computeNonExactMarks,
  buildIndexBlock helpers to reduce duplication
- Fix multi-key GROUP BY: map bucket inputs to PK columns by name
  instead of assuming positional correspondence
- Fix PREWHERE SEGV: capture filter_col as ColumnPtr value instead
  of dangling reference invalidated by bucket_expression->execute
- Use absl::flat_hash_map for all bucket count maps
- For single-column numeric GROUP BY, dispatch on TypeIndex to
  concrete ColumnVector<T> at processTask entry, then use
  getData()[row] / getData().push_back() — zero virtual calls
  on the hot path for both reading and inserting keys
- Remove MultiNumeric (vector<UInt64>) specialization — multi-key
  numeric GROUP BY falls back to the generic Field path; the
  allocation overhead of vector<UInt64> per row was not meaningfully
  better than Field, and the extra code/template instantiation was
  not worth it
- NumericCounts<T> uses the native key type (e.g. UInt32) as hash
  map key, avoiding UInt64 truncation and enabling smaller map
  entries for narrow types
- Extend numeric fast path to Date (UInt16), Date32 (Int32),
  DateTime (UInt32), DateTime64 (ColumnDecimal<DateTime64>);
  these are the most common GROUP BY key types for log histogram
  queries like toStartOfHour(ts)
- Use FilterDescription instead of raw getBool for filter column:
  handles Nullable, LowCardinality, Const, Sparse, and wider-than-
  8-bit filter columns correctly — accesses the underlying UInt8
  array directly without virtual dispatch
- Template processTaskNumeric on both value type T and column type
  ColumnType to support ColumnVector<T> for integers/floats and
  ColumnDecimal<DateTime64> for DateTime64
- Detect Nullable wrapping in bucket expression output type and
  unwrap to get the nested TypeIndex for dispatch
- Add processTaskNullableNumeric: extracts nested ColumnVector<T>
  data + null_map from ColumnNullable, counts null rows separately
  into null_count, non-null rows into NumericCounts<T>
- Add countGranuleByReadingNullable / countGranuleWithFilterNullable
  for granule-level processing with null awareness
- Add buildChunkNullable: inserts non-null keys via ColumnNullable
  nested + null_map, then appends the null bucket via insertDefault
- Use FilterDescription for PREWHERE filter column to correctly
  handle Nullable/LowCardinality/Const/Sparse filter results
- Add test case for Nullable PK with allow_nullable_key
…atch, add tests

- Use make_unique<char[]> for aggregate state buffer instead of
  vector<char> to avoid unaligned access (count state needs 8-byte
  alignment)
- Remove Float32/Float64 from numeric fast path — NaN equality
  semantics in absl::flat_hash_map differ from ClickHouse bitwise
  equality, producing wrong GROUP BY results for NaN keys
- Cache per-part bucket columns: precompute bucket_expression on
  each part's index in makePipe once, store in CountTask; eliminates
  redundant O(marks_in_part) expression execution per task
- Fix ambiguous suffix match in buildInputToPKMapping: use first-dot
  split instead of ends_with to avoid matching t.n.x to PK column x
  when the actual column is n.x
- Add comprehensive tests: DateTime/Date/DateTime64 key types,
  signed integers, reverse sorting key (ORDER BY k DESC),
  Nullable with WHERE, all-null part, single row, ON/OFF comparison
  for all new cases
…ests

- convertToFullIfNeeded on bucket columns to handle ColumnSparse
  wrapping that occurs with random sparse serialization settings;
  fixes Bad cast from ColumnSparse to ColumnNullable crash
- Validate all bucket expression inputs map to PK columns in the
  optimization; bail out if any input is unresolvable to prevent
  NOT_FOUND_COLUMN_IN_BLOCK at runtime
- Clear group_by_sort_description and
  explicit_sorting_required_for_aggregation_in_order in
  requestOnlyMergeForCountByGranularity to keep AggregatingStep
  in consistent state for plan serialization paths
- Add optimize_trivial_group_by_count_query=0 to
  01231_distributed_aggregation_memory_efficient_mix_levels
- Fix reverse key test: add explicit SETTINGS to avoid flaky
  behavior from random optimize_aggregation_in_order
- Fix reference file for new test cases
- Rename bucket expression DAG input nodes from qualified names
  (__tableN.col_name) to bare PK column names during optimization,
  before constructing ExpressionActions
- Remove InputToPKMapping, buildInputToPKMapping, and all alias
  handling — no longer needed since DAG inputs match PK names
- Simplify readGranule: just insert PK columns by name, no aliases
- Simplify makePipe index_block: iterate PK columns directly
- Fix Nullable get_key: use typeid_cast to handle both ColumnNullable
  and unwrapped columns in get_key_unwrap lambda
- Restore multi-key GROUP BY support with correct reference file
@amosbird
amosbird force-pushed the count-by-pk-monotonic branch from 88856fe to e2d6ede Compare April 28, 2026 19:12
alexey-milovidov and others added 3 commits May 9, 2026 19:43
…ated index

In `processTaskNullableNumeric` the row count formula for the last mark
of the non-null section used `part.rows_count - getRowsCountInRange(0, mark)`,
which is the residual to the end of the part. When `first_null_mark` is
not the last mark in the part, that boundary granule overlaps the row
range of subsequent NULL granules, so `countBlockNullable` over-counted
NULLs into the non-null mark and the dedicated boundary handler then
counted them again. Use `getRowsCountInRange(mark, mark + 1)` for marks
that are not the actual last mark of the part; only the true final
granule may have a partial row count. Pin `index_granularity = 64` in
the `nullable_pk_on` test case so the boundary granule is exercised
deterministically.

Also bail out of `optimizeCountByGranularity` when any part's primary
index has fewer columns than the PK. With the
`primary_key_ratio_of_unique_prefix_values_to_skip_suffix_columns`
setting (default `0.9`), suffix columns are dropped from the in-memory
index when their cardinality ratio meets the threshold, and the bucket
expression then fails with `NOT_FOUND_COLUMN_IN_BLOCK` on the dropped
column.

CI report: ClickHouse#103490

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.70% +0.10%

Changed lines: 90.79% (651/717) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov mentioned this pull request May 12, 2026
1 task done
groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 14, 2026
Before this change, `tests/docker_scripts/stress_runner.sh` exported
`THREAD_POOL_FAULT_INJECTION=1` before `configure`, so install.sh
symlinked `tests/config/config.d/cannot_allocate_thread_injection.xml`
into the server's `config.d/` and the server started with
`cannot_allocate_thread_fault_injection_probability=0.0001` already
active. `stress.py` then ran a small smoke check (two canary tests)
to validate the setup. The smoke check did, among other things:

    CREATE DATABASE IF NOT EXISTS test_N
        ON CLUSTER test_cluster_database_replicated
        ENGINE = Replicated(...)

When thread-pool fault injection fired during the async load of the
Replicated database (`Code: 439. Cannot schedule a task: fault
injected`), the server raised the exception after it had already
started streaming the HTTP response, so
`WriteBufferFromHTTPServerResponse` deliberately broke the chunked
encoding. The client (`clickhouse-test` → `clickhouse_execute_http`)
saw `http.client.IncompleteRead`, the per-test retry was exhausted,
and the smoke check aborted the whole stress test job.

The protocol break is by design — the server uses it to signal that a
streamed response is incomplete and must not be consumed as if it were
successful. Retrying it on the client (the previous attempt) would mask
genuine server failures.

Instead, this commit applies @azat's prescription: run the smoke check
against a server that does *not* have the thread-pool fault injector
installed, then enable it only once the smoke check has passed.

- `tests/docker_scripts/stress_runner.sh` no longer exports
  `THREAD_POOL_FAULT_INJECTION=1` before `configure`. install.sh leaves
  `cannot_allocate_thread_injection.xml` uninstalled. The server starts
  with `cannot_allocate_thread_fault_injection_probability=0` (default),
  so the smoke check runs deterministically.
- `stress.py` gains `--enable-thread-pool-fault-injection`. When set,
  `run_func_test` calls a new `install_thread_pool_fault_injection()`
  helper after the smoke-check loop. The helper symlinks the canonical
  config and runs `SYSTEM RELOAD CONFIG` with retries (the reload can
  itself transiently fail under ZooKeeper fault injection and
  ThreadFuzzer). `stress_runner.sh` passes the flag; the upgrade runner
  does not. If the smoke check raises, the install path is not reached
  and the post-stress cleanup `rm -f`s any stale symlink.
- The obsolete `CANNOT_SCHEDULE_TASK` / `Fault injection` entries are
  removed from the smoke-check `ignored_errors` list. Tolerating them
  would now mask a genuine setup failure since the injector is not
  active during the smoke check.

The failure mode recurs ~weekly across unrelated master PRs (e.g.
ClickHouse#104058, ClickHouse#103490, ClickHouse#102351, ClickHouse#102610, ClickHouse#102203, and master CI on
2026-04-28). Tracked by @alexey-milovidov's directive on PR ClickHouse#96844:
ClickHouse#96844 (comment)

Failing report example (PR ClickHouse#96844, commit 9c4f6f5, MSan stress):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96844&sha=9c4f6f5a34d4bb45fcf73f20c464ba8d855a0c1f&name_0=PR&name_1=Stress%20test%20%28arm_msan%29

Validation: `tmp/test_install_thread_pool_fault_injection.py` (not
committed) covers (a) the symlink+reload mechanics, (b) fail-close when
the source config is missing, (c) flag off → no install, (d) flag on →
install runs once after smoke check, (e) install does not run when
smoke check raises an unrecoverable error, (f) the obsolete entries
are gone from `ignored_errors`. All six pass.
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Dear @amosbird, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@abashkeev abashkeev added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

- retargeted PR record [email protected] to 26.10 (settings-history check rule)

Also resolved conflicts in:
- `src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp`
- `src/Processors/QueryPlan/Optimizations/optimizeTree.cpp`
- `tests/queries/0_stateless/04058_explain_pretty_aggregation_sorting.sql`

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Nov 14, 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-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants