Skip to content

Add per-part aggregation cache for incremental GROUP BY - #101073

Open
sociopate-sss wants to merge 114 commits into
ClickHouse:masterfrom
sociopate-sss:sociopate-sss/query_cache_for_partial_results
Open

sociopate-sss wants to merge 114 commits into
ClickHouse:masterfrom
sociopate-sss:sociopate-sss/query_cache_for_partial_results

Conversation

@sociopate-sss

@sociopate-sss sociopate-sss commented Mar 29, 2026 •

Copy link
Copy Markdown

Cache intermediate per-part aggregation states in an LRU cache. On repeated GROUP BY queries, reuse cached states for unchanged MergeTree parts and only aggregate new ones. Uses the existing AggregatingProjectionStep mechanism to merge cached and fresh results.

Changelog category

Experimental Feature

Changelog entry

Add per-part aggregation cache for incremental GROUP BY over MergeTree tables. Gated behind allow_experimental_part_aggregation_cache.


Note

Medium Risk
Adds a new caching layer that rewrites GROUP BY query plans and stores intermediate aggregation states, which can affect correctness/performance and memory usage if hashing/invalidation/configuration is wrong. Gated behind experimental/settings but touches core query planning and system commands.

Overview
Adds an experimental per-part aggregation cache for GROUP BY over MergeTree tables, caching intermediate (non-final) per-part aggregation states and reusing them across repeated queries to avoid re-aggregating unchanged parts.

Wires the cache into server/local startup and config reload (part_aggregation_cache.max_size_in_bytes), introduces session settings to gate/enable reads+writes, and adds SYSTEM DROP PART AGGREGATION CACHE plus a system.part_aggregation_cache table for introspection.

Implements a new query-plan optimization (optimizeUsePartAggregationCache) that splits aggregation into cached-part reads (PartAggregationCacheSource) + normal aggregation for uncached parts, with a populator that can precompute missing entries. Includes new stateless and performance tests, and minor repo maintenance updates (PR template doc checklist; remove disabled Cargo entries from dependabot.yaml).

Reviewed by Cursor Bugbot for commit 7f7ba63. Bugbot is set up for automated code reviews on this repo. Configure here.


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

@CLAassistant

CLAassistant commented Mar 29, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [532b887]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 2/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 3/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 4/4) FAIL
Build ClickHouse FAIL cidb
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_asan_ubsan) DROPPED

AI Review

Summary

Adds an experimental cache of per-part GROUP BY states for MergeTree, including incremental reuse, cache controls, and introspection. Reviewed head 532b887b41a07612301e1cff60bbb0010b294943 and all prior discussion. No outstanding findings; the latest change applies the query’s ExpressionActionsSettings to every replayed action and adds focused regression coverage. Resolved the remaining bot-authored thread.

Missing context / blind spots
  • ⚠️ No current-head executable was published. Ten focused result comparisons and one mixed cached/fresh check passed on the available PR binary 1d13faf814c1; the latest action-settings change was reviewed from source. Running 05828_part_aggregation_cache_actions_settings on the current head would close this runtime-validation gap.
Final Verdict

Status: ✅ Approve. No new inline findings. Existing CI checks remain responsible for build and lint failures.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 29, 2026
Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Parsers/ParserSystemQuery.cpp Resolved
Comment thread programs/server/Server.cpp Resolved
alexey-milovidov and others added 3 commits September 26, 2026 23:20
…_cache_for_partial_results

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.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…cache` perf test

`allow_experimental_analyzer = 0` is rejected on master since the setting
became obsolete, so drop it and let the performance test exercise the
analyzer plan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits October 11, 2026 05:38
# Conflicts:
#	src/Interpreters/Context.cpp
…gs` in `MergeTreeSequentialSource`

Master added a `reader_executor.enabled` check on the local `read_settings`, which this PR
moved into the merge/mutation branch. Check it on the final `MergeTreeReaderSettings` instead.

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

`table_id` + `part_name` is not a stable identity of the part contents: e.g.
`SYSTEM RESTORE REPLICA` resets block number counters in ZooKeeper, so a part with an
already used name but different data can appear while the table `UUID` stays the same.
Hash the total checksum of the part files into the key, so stale states are never reused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The optimization deliberately fails closed for parallel-replica reads, so the tests that check
that the cache is populated and used cannot pass in the `ParallelReplicas` CI job.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits October 19, 2026 19:47
… `joinGet` or `dictGet`

`ActionsDAG::updateHash` does not hash the contents of an `IN` set (`ColumnSet` is a dummy column),
so `k IN (1)` and `k IN (2)` produce the same cache key, and a set built from a subquery or a
`Set`/`Join` table changes with the data of another table while the query text stays the same.
`joinGet` and `dictGet` read external state in the same way. Skip the optimization (fail-closed)
when any intermediate or source filter DAG, including lambda bodies, uses them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…, use `VectorWithMemoryTracking`

Master is now `26.11`, so the `settings_changes_history` check requires the new settings to be recorded under it.
`src/Processors/Sources` is linted for plain `std` containers, so `PartAggregationCacheSource` now uses `VectorWithMemoryTracking`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101073&sha=d30e4584e346c48e6e9a0d3c3c911a6db8510338&name_0=PR&name_1=Style%20check
ClickHouse#101073

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

Copy link
Copy Markdown
Member

🕵 Pass of 2026-10-21: merged current master (no conflicts) and fixed the two Style check failures in 44dfe41626f: the three new settings are now recorded under 26.11 (the settings_changes_history check), and PartAggregationCacheSource uses VectorWithMemoryTracking instead of std::vector. clickhouse builds; the part_aggregation_cache stateless tests pass locally, except 04510_part_aggregation_cache_unique_key_guard, which needs ZooKeeper that my local server did not have. No review threads are unresolved.

alexey-milovidov and others added 3 commits October 30, 2026 18:04
The reference server does not know `allow_experimental_part_aggregation_cache`,
so putting it in the `<settings>` section failed the performance comparison with
`Unknown setting`. Pass the new settings per query, and add a setup query marked
with `do_not_check_in_pr` that fails on the reference server, so the test runs on
the new server only in this PR.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=101073&sha=e5c237c2a397f597f087471369859b5e2a5f19f9&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%205%2F6%29
ClickHouse#101073

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ambdas in the part aggregation cache

- The populator tracks the row count separately from the block, so a filter
  that removes the last column (`SELECT count() FROM t PREWHERE f`) no longer
  caches an empty state for a non-empty part.
- Aggregate functions with a non-trivial state destructor own memory outside
  the aggregation arenas (`uniqExact`, `quantile`), which the cache budget does
  not see, and functions that parallelize their merge (`uniqExact`) may convert
  the shared cached right-hand side state in place. Skip the optimization for them.
- `ActionsDAG::updateHash` does not hash lambda bodies and the settings captured
  by functions inside them, so skip the optimization for expressions with lambdas.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 2 commits November 8, 2026 09:28
Resolve conflicts in `MergeTreeSequentialSource`: master renamed the `prefetch`
argument to `allow_remote_fs_prefetch` (prefetching is now started separately);
keep the PR's `read_context` argument and apply the remote-FS prefetch switch
in both the query-context and merge/mutation read-settings branches.
…he key

`ActionsDAG::updateHash` does not see settings captured by ordinary functions at
build time (`formatDateTime`, `locate`, `session_timezone`, ...), so a state warmed
under one setting value was reused under another. Mix `queryConditionCacheSettingsSalt`
into the final cache key, which covers keys, aggregate arguments, `WHERE`, `PREWHERE`
and source filters, and add a regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 17, 2026 21:26
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeTree.cpp
#	src/Storages/MergeTree/MergeTreeSequentialSource.cpp
…ggregation cache population

The replayed `ExpressionStep`, `FilterStep` and `PREWHERE` actions were built with
default `ExpressionActionsSettings`, so the cache population ignored short-circuit
evaluation and the `max_temporary_columns` / `max_temporary_non_const_columns` limits.
A query that fails without the cache could then succeed from a cached state, and a
query relying on short-circuit evaluation (e.g. `if(x = 0, 0, intDiv(42, x))`) failed
to populate the cache on every execution.

Build every replayed action with `ExpressionActionsSettings(context)`, and add a
regression test for the temporary-column limit and short-circuit evaluation in the
aggregate argument, `WHERE` and `PREWHERE`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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. external Author is not a member of the ClickHouse organization pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants