Skip to content

Optimize min/max/uniq aggregate functions by skip index - #93037

Closed
zoomxi wants to merge 41 commits into
ClickHouse:masterfrom
zoomxi:skip-index-aggregation
Closed

zoomxi wants to merge 41 commits into
ClickHouse:masterfrom
zoomxi:skip-index-aggregation

Conversation

@zoomxi

@zoomxi zoomxi commented Dec 25, 2025 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

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

Optimize min/max/uniq aggregate functions by reading from skip indices instead of scanning data. Closes #92758.


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

@amosbird amosbird left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I have an alternative idea for min-max optimization: we could add a part-level min-max per skip index and load it into memory, similar to how we handle partition columns. This approach would be cost-effective and only adds a small overhead per skip index. @alexey-milovidov WDYT?

Currently, I’m using partition by indexHint(a, b, c...) to build this kind of min-max part index.

@zoomxi
zoomxi force-pushed the skip-index-aggregation branch from 9ab9279 to 23ac69c Compare December 25, 2025 04:10
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Dec 25, 2025
@clickhouse-gh

clickhouse-gh Bot commented Dec 25, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b5305cd]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
03774_skip_index_aggregation_set FAIL cidb
03774_skip_index_aggregation_minmax 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
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Dec 25, 2025
@zoomxi
zoomxi force-pushed the skip-index-aggregation branch 2 times, most recently from c7797ca to 4288c15 Compare December 26, 2025 12:02
@rschu1ze

rschu1ze commented Dec 26, 2025 •

Copy link
Copy Markdown
Member

@zoomxi Thanks but this needs a lot more code comments and a description of the logic in the PR message, please.

If I remember correctly, parts already store a min/max value per column. This information can be utilized for aggregate functions min and max but only if no WHERE clause exists. This PR respectively #92758 really helps for the case of additional filters, right?

I have an alternative idea for min-max optimization: we could add a part-level min-max per skip index and load it into memory, similar to how we handle partition columns.

"part-level min-max per skip index" ... it's not really clear to me how that would work. A min-max index stores min/max information already per index granule, why would it store it again per part (which is of coarser granularity)?

@rschu1ze

Copy link
Copy Markdown
Member

@nickitat Like to take a look at this PR?

@amosbird

Copy link
Copy Markdown
Collaborator

"part-level min-max per skip index" ... it's not really clear to me how that would work. A min-max index stores min/max information already per index granule, why would it store it again per part (which is of coarser granularity)?

@rschu1ze The idea is to promote skip-index min-max to part-level metadata (kept in memory) to enable pruning entire parts without the IO overhead of reading .skp files, effectively giving arbitrary columns the same "early-filtering" benefits as partition keys. (Reference: #65413 and #64210)

@zoomxi

zoomxi commented Dec 29, 2025 •

Copy link
Copy Markdown
Contributor Author

parts already store a min/max value per column.

@rschu1ze minmax_idx only stores min/max values for partition key columns. The implicit minmax_count_projection covers min/max of partition key columns and the first primary key column , plus count().

@zoomxi

zoomxi commented Dec 29, 2025

Copy link
Copy Markdown
Contributor Author

However, as @amosbird suggested, would it be better to aggregate skip index data to part-level and keep it in memory (like minmax_idx for partition columns), instead of aggregating from .skp files at query time?
@alexey-milovidov @rschu1ze @nickitat

@rschu1ze

Copy link
Copy Markdown
Member

Thanks, I read #65413 and I liked it. I actually think that storing min/max metadata has such a small storage overhead that we could do it implicitly for all parts (i.e. without the user creating requesting it explicitly via CREATE INDEX). If we had that, then the idea of this PR (speed up min/max/uniq aggregate functions) could be applied in a more versatile manner.

PS: Note that there is some overlap with settings add_minmax_index_for_numeric_columns and add_minmax_index_for_string_columns (currently false by default, hopefully soon true) - (blog post).

@zoomxi
zoomxi force-pushed the skip-index-aggregation branch 3 times, most recently from d070b68 to 18f108e Compare December 30, 2025 09:34
@zoomxi
zoomxi force-pushed the skip-index-aggregation branch from 18f108e to f60d233 Compare December 30, 2025 09:50
@zoomxi zoomxi changed the title [WIP] Optimize min/max/uniq aggregate functions by skip index Optimize min/max/uniq aggregate functions by skip index Dec 30, 2025
@nickitat

nickitat commented Jan 7, 2026

Copy link
Copy Markdown
Member

Sorry, I missed all notifications from this PR somehow. Will try to catch up today.

@zoomxi

zoomxi commented Jan 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Will try to catch up today.

Thanks, I've submitted #93318 to implement part-level aggregation for minmax skip index as discussed here.

For minmax, once #93318 is merged, this PR should be updated to use part-level aggregated data first, with the current granule-level approach as fallback.

For set, as set indexes may be unsuitable for part-level aggregation, this PR remains the primary approach.

So perhaps #93318 should be reviewed first, then this PR can be updated accordingly.

Comment thread src/Core/Settings.cpp
DECLARE(Bool, optimize_use_implicit_projections, true, R"(
Automatically choose implicit projections to perform SELECT query
)", 0) \
DECLARE(Bool, optimize_use_skip_index_aggregation, true, R"(

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 introduces a new query-execution optimization path (serving min/max/uniq* from skip indexes / per-part statistics) and enables it by default via optimize_use_skip_index_aggregation = true.

Given the correctness risk profile of a new optimizer execution strategy, this should be guarded behind an explicit experimental gate first (for example allow_experimental_* or a disabled-by-default setting), then enabled by default only after bake time.

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 is still live in the current code: optimize_use_skip_index_aggregation is declared with default true in Settings.cpp, and there is no separate allow_experimental_* gate around the new planner path.

Given this adds new execution paths that answer min/max/uniq* from skip-index / statistics metadata, I still think rollout should be opt-in first (experimental gate, or default false until bake time).

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 concern is still live in the current head.

optimize_use_skip_index_aggregation is still declared with default true in src/Core/Settings.cpp, and the new planner paths in optimizeUseAggregateProjection still apply skip-index / column-statistics aggregate answering without a separate allow_experimental_* guard.

Because this adds new execution paths for min/max/uniq* that can change correctness if any edge case is missed, please gate it behind an experimental setting (or keep the optimization setting default false until GA-level hardening is complete).

Comment thread src/Core/Settings.cpp Resolved
Algunenano pushed a commit to Algunenano/ClickHouse that referenced this pull request May 7, 2026
The stress-test log scanner (`ci/jobs/scripts/log_parser.py`) uses
`rg --text -A 10 -o 'Logical error.*'` against the server log. Test
`04208_iceberg_disk_with_cache_no_bad_cast.sql` previously included
the literal exception string in its SQL comments. When such a query
fails (it is expected to fail at table-resolution time), the full
query — including those comments — is echoed into the
`<Error> executeQuery` log entry. If a later, completely unrelated
fatal error occurs in the same stress-test run, the scanner picks up
the SQL-comment occurrence first and uses it as the failure name,
even though the actual stack trace (and `STID`) belong to a different
bug.

Three master/PR runs on 2026-05-07 hit this false positive:

- `Stress test (experimental, serverfuzz, arm_tsan)` on master
  (commit 69167ef) — actual abort was a `chassert(false)` in
  `paranoidCheckForCoveredPartsInZooKeeperOnStart`,
  reported as `STID 2508-5dc3`.
- `Stress test (arm_asan_ubsan)` on PR ClickHouse#100377 — actual abort was
  `Not-ready Set is passed as the second argument for function 'in'`
  in `FunctionIn::executeImpl`, reported as `STID 0250-4e52`.
- `Stress test (amd_msan)` on PR ClickHouse#93037 — same `Not-ready Set`
  family, reported as `STID 0250-41a5`.

The original `Bad cast from CachedObjectStorage to S3ObjectStorage`
bug that this test guards against is genuinely fixed by ClickHouse#104258 — the
unwrap loop in `S3StorageParsedArguments::fromDisk` is in place and
none of these three runs actually crashed in that code path.

This commit reworks the comments in 04208 so they describe the bug
without containing the verbatim `Logical error: '...'` pattern that
the scanner greps for, and adds a `NOTE` explaining why the verbatim
text is intentionally avoided. The SQL queries and expected
`serverError` codes are unchanged.

CI report (master arm_tsan):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=69167ef25d21358fd8f171e593849ea73195dd1b&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20arm_tsan%29

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 91.59% (610/666) | lost baseline coverage: 6 line(s) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Dear @nickitat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@nickitat nickitat self-assigned this Jun 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Dear @nickitat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@nickitat

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

@zoomxi

zoomxi commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

@copilot resolve the merge conflicts in this pull request

Sorry for the late reply. To make it easier to review and merge, I extracted the part for "Optimize min/max aggregates using column statistics" from this PR into a separate PR #105197. Could you spare some time to review it? Thanks.

@abashkeev abashkeev added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 3, 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/optimizeUseAggregateProjection.cpp`
- `src/Storages/MergeTree/MergeTreeData.cpp`
- `src/Storages/MergeTree/MergeTreeData.h`

`preparePartsPruning` follows master's `ConditionTemplate` min/max condition; the skip-index and column-statistics candidates run only when master's statistics-based min/max path does not apply.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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... manual approve Manual approve required to run CI pr-improvement Pull request with some product improvements submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

min/max/uniq aggregate functions can be calculated from secondary indices of type minmax and set

6 participants