Repository navigation
Conversation
ffeb3a4 to
8a4aebe
Compare
|
Hi @alexey-milovidov @rschu1ze, This PR is related to my feature request #93756 for partial aggregate caching (from Intern Tasks 2025/2026). I've started with a skeleton implementation to show the proposed cache structure. Would appreciate feedback on the approach! Happy to adjust based on your suggestions. |
|
Workflow [PR], commit [8f17e21] Summary: ❌
AI ReviewSummaryAdds experimental per-part caching of intermediate aggregate states, with planning-time read avoidance and execution-time population. Two correctness issues remain: incompatible plan serialization toward older peers and stale results from mutable set dependencies hidden in read-time defaults. One regression test does not exercise the intended cache reuse. Plan-hit consumers traced: Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Correct the serialization gate and mutable-default eligibility, and repair the radix regression before merging. |
7bce5fe to
9fa7ee0
Compare
9fa7ee0 to
9a03c03
Compare
|
Hi ClickHouse Team (@alexey-milovidov @rschu1ze @Avogar @clickhouse-admin), PR is ready for review. The failing checks are unrelated to this PR. All relevant checks pass: builds (amd/arm), style, stateless tests (including 03800_partial_aggregate_cache), and unit tests. Failures are in integration test infrastructure, fuzzer edge cases, and unrelated features. Stack traces show nothing related to aggregation or caching. The partial aggregate cache test passes. PR is ready for review. Thanks in advance for any comments, suggestions, or approval. |
9a03c03 to
66170ba
Compare
| /// produce the same partial aggregates on every execution, so we cache and reuse them. | ||
| /// | ||
| /// Enable with: SET use_partial_aggregate_cache = 1 | ||
| class PartialAggregateCache |
There was a problem hiding this comment.
The new cache will live side-by-side to the regular query cache which isn't really great. I would rather like to see the normal query cache develop into an intermediate result cache.
Would you please check if the existing query result cache can be extended into this direction? Perhaps we can have just another key/entry type.
There was a problem hiding this comment.
Thanks for your review! I spent some time looking into this.
So bascially the QueryResultCache and PartialAggregateCache both use CacheBase, but the key/entry and invalidation story is quite different: the query cache is AST + user/roles with TTL, partial aggregates are semantic hash + part + mutation version, and they hook into the pipeline in different places. Folding that into QueryResultCache as “just another entry kind” would need a proper design pass, not a small tweak.
I suggest kept them split here to keep the PR focused. And possible in the future open a tracking issue for a unified intermediate-result cache if that direction still makes sense.
There was a problem hiding this comment.
🕵 Leaving this thread open for a maintainer decision: whether the partial aggregate cache should become a new entry kind of QueryResultCache or stay a separate CacheBase-backed cache is an architectural choice. This update only merged the latest master into the branch (resolving conflicts in ProtocolDefines.h and ReadFromMergeTree.cpp), moved the Aggregating step-version-2 gate to plan version 21 because 20 shipped in 26.10, and fixed the settings_changes_history style check. @rschu1ze, does the author's reasoning above work for you, or should the unification happen before this PR is merged?
|
@rschu1ze Thank you so much for the code review! This really helps a lot! I will be working on them based on the feedback in the next few days and continuously making contribution to ClickHouse! |
005c8f2 to
d17e874
Compare
nickitat
left a comment
There was a problem hiding this comment.
Please outline the entire design, and let's first make sure it will work. Then we can talk about the implementation.
Thank you for reviewing this! I am currently working on it and will upload the design soon! |
# Conflicts: # src/Interpreters/Aggregator.cpp # src/Interpreters/Aggregator.h # src/Interpreters/InterpreterSelectQuery.cpp # src/Planner/Planner.cpp # src/Processors/QueryPlan/AggregatingStep.cpp # src/Processors/Sources/LazyReadFromMergeTreeSource.cpp # src/Processors/Transforms/AggregatingTransform.cpp # src/Storages/MergeTree/MergeTreeSource.cpp # src/Storages/MergeTree/MergeTreeSource.h
Fix the correctness issues reported in the review of the partial aggregate cache: - Length-prefix strings and collection sizes in the query hash, so `sum(a), count()` and `sum(acount)` differ. - Represent changed settings (e.g. `session_timezone`) in the semantic key, except the ones affecting only logging, resources or the execution strategy. - Disable the cache with settings that can stop reading a part early (`read_overflow_mode = 'break'`, `timeout_overflow_mode = 'break'`, `partial_result_on_first_cancel`), with parallel replicas and with `SAMPLE`. - Drop the plan-time hash when the optimized plan aggregates in order. - Disable the cache in `ReadFromMergeTree` for parallel replicas and distributed read buckets, masking policies, `UNIQUE KEY` tables and nondeterministic virtual columns such as `_part_index`. - Add the columns of the metadata snapshot to the cache key, so a metadata-only `ALTER` of a `DEFAULT` invalidates it. - Never spill in the per-part aggregator of a miss, whose temporary files would not be merged. - Add regression tests, and a test of the `SYSTEM DROP AGGREGATE CACHE` privilege. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Processors/QueryPlan/ReadFromMergeTree.h
…ansform.cpp` Fixes the style check: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=93757&sha=latest&name_0=PR&name_1=Style%20check PR: ClickHouse#93757 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Processors/QueryPlan/ReadFromMergeTree.cpp # src/Processors/QueryPlan/ReadFromMergeTree.h # src/Processors/Transforms/FilterTransform.cpp
…eters in the partial aggregate cache key `FieldVisitorHash` hashes the type and the raw value of a decimal but not its scale, so `exponentialMovingAverage(toDecimal32(5, 0))` and `exponentialMovingAverage(toDecimal32(0.5, 1))` had the same query hash and the second query reused the cached states of the first one. Also hash the textual form of every parameter, which includes the scale, also for nested decimals. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…inistic default expressions The reader evaluates the default expressions of columns missing in a part. If such an expression is not deterministic, e.g. it reads a dictionary with `dictGet`, the values read from the part change without a change of the part or the metadata, so the cached states become stale. The determinism check of the query does not see these expressions, so check the default expressions of all columns of the table in `ReadFromMergeTree::initPartialAggregateCacheReaderSettings`. Add a test for this and for the decimal scale of aggregate function parameters. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…unt their heap memory Merging a block of states without keys calls `parallelizeMergePrepare`, which converts the source states in place (`uniqExact` turns a single-level set into a two-level one). For the states of the partial aggregate cache, which other queries may read concurrently, this is a data race. Add a `sources_are_shared` flag to `Aggregator::mergeOnBlock` that skips the preparation for the source states, and pass it for cache hits and for the states just published to the cache. The weight of a cache entry counted only the arenas of the states, but states can own memory outside of them (the hash set of `uniqExact`). Use the larger of the arena size and the size of the states in serialized form. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Use `UnorderedSetWithMemoryTracking` and `UnorderedMapWithMemoryTracking` for the partial aggregate cache bookkeeping containers, and declare the aggregate state pointer as `auto * const` (`readability-qualified-auto`). https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=93757&sha=212113f1838f56abee8e5f7b3d1afbac4d6a9d15&name_0=PR&name_1=Style%20check https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=93757&sha=212113f1838f56abee8e5f7b3d1afbac4d6a9d15&name_0=PR&name_1=Build%20%28arm_tidy%2C%204%2F4%29 PR: ClickHouse#93757 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ry-cache
Resolve conflicts:
- `src/Planner/Planner.cpp`: master moved the planner step helpers into `src/Planner/PlannerSteps.cpp`
(`getAggregatorParams`, `addAggregationStep`, `addCubeOrRollupStepIfNeeded`), so the partial aggregate
cache changes of these helpers (`hasNonMergeTreeTableInputs`, `hasRowPolicyOnTableInputs`, the semantic key
passed to `Aggregator::Params`) are ported to `PlannerSteps.{h,cpp}`, and `SelectQueryInfo` is passed to them.
- `src/Processors/QueryPlan/QueryPlan.cpp`: keep both the partial aggregate cache settings override and the new
pretty-names capture.
- `src/Processors/QueryPlan/ReadFromMergeTree.cpp`: master removed `indexTypeToString`; drop its declaration.
- `src/Interpreters/Aggregator.cpp`, `src/Processors/Transforms/AggregatingTransform.h`,
`src/Parsers/ParserSystemQuery.cpp`: keep both sides.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review: `Aggregator::mergeOnBlock` forwarded `sources_are_shared` only to the merge without keys. The keyed merge could still defer large states (e.g. two-level `uniqExact` sets) to `mergeDeferredLargeStates`, whose `parallelizeMergeMulti` converts the sources in place via `asTwoLevelChecked`, racing with concurrent readers of the same cached states. Pass the flag through `mergeStreamsImpl` to `mergeStreamsImplCase` and merge shared sources row by row. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review: `Aggregator::mergeOnBlock` forwarded `sources_are_shared` only to the merge without keys. The keyed merge could still defer large states (e.g. two-level `uniqExact` sets) to `mergeDeferredLargeStates`, whose `parallelizeMergeMulti` converts the sources in place via `asTwoLevelChecked`, racing with concurrent readers of the same cached states. Pass the flag through `mergeStreamsImpl` to `mergeStreamsImplCase` and merge shared sources row by row (the declarations were changed in the previous commit). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review: `k IN dim` keeps the table `dim` as an identifier, not an `ASTSubquery`, so the subquery check did not see it, and the contents of `dim` are not represented in the per-part key: after `dim` changes, the identical query reused stale states. Accept only a literal or a `tuple`/`array` on the right side of `IN`-family functions, and disable the key for `joinGet`, which reads a `Join` table. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tations Address review: a pending `DROP COLUMN` followed by re-adding the column changes the values read through `AlterConversions`, while the part name, `info.mutation` and the current column definitions stay the same, so the per-part key would serve stale states. Use the same guard as the query condition cache (`MergeTreeDataSelectExecutor::hasPendingAlterOrMetadataMutations`). Also disable the cache when a masking policy is enabled: it rewrites the values for the current user, and the shared cache does not represent it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… consuming aggregation Address review: - The plan-time query hash was passed to every `ReadFromMergeTree` of the plan, so in `SELECT k, sum(v) FROM t GROUP BY k UNION ALL SELECT k, v FROM t` the raw arm replaced its rows with hit chunks that nothing consumes, and its rows disappeared from the result. - The radix partitioned `uniqExact` (and the in-order `uniqExact`) replace `AggregatingTransform` and do not consume hit chunks, so a hash warmed at the `with_mergeable_state` stage made a complete-stage query lose the cached parts. Replace `planHasGroupByTopK` / `planHasAggregationInOrder` with `planCanConsumePartialAggregatePlanHits`, which requires exactly one aggregation executed by `AggregatingTransform` and every `ReadFromMergeTree` of the optimized plan to be in its subtree; otherwise the hash is dropped before the pipeline is built. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tics_projection` - `05828_partial_aggregate_cache_scope_regressions`: repeated `UNION ALL` with a raw arm, `IN table` with a changing table, pending `DROP COLUMN` followed by `ADD COLUMN`. - `05829_partial_aggregate_cache_stage_and_keyed_concurrency`: warm-up at `with_mergeable_state` followed by a complete-stage radix `uniqExact`, and concurrent keyed `uniqExact` over cached two-level sets (for TSan). - `04267_partial_aggregate_cache_array_join_key`, `04650_partial_aggregate_cache_final`: master now answers `sum` without keys from part statistics (`use_statistics_for_sum_avg_aggregation`) without reading the parts, so the cache was not used. Disable it to keep testing the cache. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ry-cache Conflicts: `Aggregator::Params` keeps both `enable_fixed_and_packed_string_keys` and `query_semantic_hash_for_partial_cache`; the planner `getAggregatorParams` now delegates to the shared helper from `PlannerAggregation.h` and sets the partial aggregate cache semantic key on the result. Co-Authored-By: Claude Fable 5.2 <[email protected]>
After the merge, `buildReaders` iterates over `group_and_index_of_part` instead of the parts, so take the data part for the partial aggregate cache identity from `group.parts[index_in_group]`. Co-Authored-By: Claude Fable 5.2 <[email protected]>
The test `05621_documentation_no_docusaurus_syntax` failed with `Statement SYSTEM`: the description used a `:::note` admonition. Use `<Note>` and the current route of the `GRANT` page. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=93757&sha=539224694c9b54852061f844194d6e6679ee6a54&name_0=PR&name_1=Fast%20test ClickHouse#93757 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged |
…ry-cache Conflicts in `src/Interpreters/Aggregator.cpp` (keep only the `NOT_IMPLEMENTED` error code, `BAD_ARGUMENTS` is no longer used there) and `src/Planner/PlannerSteps.cpp` (keep the partial aggregate cache semantic key together with the new `shared_kept_keys_for_overflow_any` condition from master). Co-Authored-By: Claude Fable 5.2 <[email protected]>
The `settings_changes_history` style check requires new settings to be recorded under the current version, which is 26.12 after the merge with master. Move the records of `use_partial_aggregate_cache` and `partial_aggregate_cache_allow_parallel_aggregation_streams` from 26.11. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=93757&sha=f9537944deb4b5f199f399f771318661a5b750dd&name_0=PR&name_1=Style%20check ClickHouse#93757 Co-Authored-By: Claude Fable 5.2 <[email protected]>
The `cpp` style check forbids bare standard containers in `src/Processors/QueryPlan`; `Pipes` is the existing alias accepted by `Pipe::unitePipes`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=93757&sha=f9537944deb4b5f199f399f771318661a5b750dd&name_0=PR&name_1=Style%20check ClickHouse#93757 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged Verification: all translation units of the merged tree compile, except that Still open: the review thread on |
| /// First global query-plan version that writes version 2 of `Aggregating`, which carries the | ||
| /// partial aggregate cache semantic key. Towards an older peer the key is omitted: the peer then | ||
| /// aggregates without the partial aggregate cache, which only loses the caching. | ||
| static constexpr auto DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_PARTIAL_AGGREGATE_CACHE_KEY = 21; |
There was a problem hiding this comment.
[Blocker] Gate the new Aggregating encoding on a new global plan version.
Global plan version 21 already exists without this change: its Aggregating registry accepts only step versions 0 and 1. With this threshold, a new sender negotiating version 21 with that peer selects step version 2, which the peer rejects in QueryPlanStepRegistry::checkVersionReadable. This also breaks queries with use_partial_aggregate_cache = 0, because version 2 is selected and its zero semantic key is written unconditionally.
The tree is now 26.12, while the global version was last bumped for 26.11. Bump the global version to 22, introduce this step version at 22, and retain step version 1 when writing to a version-21 peer. Please add a compatibility check for that negotiated version.
| { | ||
| for (const auto & column : storage_snapshot->metadata->getColumns()) | ||
| { | ||
| if (column.default_desc.expression && astContainsNonDeterministicFunctions(column.default_desc.expression, context)) |
There was a problem hiding this comment.
[Blocker] Apply the mutable-set dependency check to read-time defaults too.
astContainsNonDeterministicFunctions accepts in: FunctionIn inherits isDeterministic = true. Consequently, a physical column added as v UInt8 DEFAULT k IN keys, where keys uses the Set engine, passes this guard. For an older part missing v, IMergeTreeReader::evaluateMissingDefaults reads the current set through FutureSetFromStorage, but the main aggregation AST contains only v, so the query-level IN guard never sees this dependency.
For example, insert k = 1, 2 into the main table before adding v, put only 1 in keys, and warm SELECT sum(v) with the cache enabled. Insert 2 into keys and repeat: an uncached read returns 2, while the unchanged part/query/metadata key reuses the cached sum 1.
Reject mutable IN inputs in default expressions, including transitive default dependencies, or include their effective identity in the key. Please add this warm/change-set/repeat regression using a Set table.
| INSERT INTO t_pac_radix SELECT number + 500 FROM numbers(1000); | ||
| " | ||
| $CLICKHOUSE_CLIENT --stage with_mergeable_state --format Null -q "SELECT uniqExact(v) FROM t_pac_radix SETTINGS $SETTINGS" | ||
| $CLICKHOUSE_CLIENT -q "SELECT uniqExact(v) FROM t_pac_radix SETTINGS $SETTINGS, optimize_uniq_exact_radix_partitioning = 1" |
There was a problem hiding this comment.
[Major] Use identical effective cache-key settings for the warm-up and repeat.
The warm-up above omits optimize_uniq_exact_radix_partitioning, whereas this query explicitly sets it to 1. Explicit assignments enter Settings::changes even when they equal the default, and this setting is included by partialAggregateCacheSemanticKey. Under the normal default configuration these two queries therefore have different cache keys, so the test passes even if the radix plan-hit guard is removed.
Put optimize_uniq_exact_radix_partitioning = 1 in the shared SETTINGS string so both stages use the same key, and verify that the warm-up populated entries before testing the complete-stage consumer.
Add experimental part-level partial aggregate cache for
GROUP BYonMergeTreetables, with planning-stage and execution-stage integration. Motivation: avoid re-reading unchanged parts by reusing mergeable intermediate aggregate states keyed by query semantics and part identity.Related issue: #93756
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add experimental setting
use_partial_aggregate_cacheforMergeTreeGROUP BYqueries to cache per-part intermediate aggregate states and reuse them either at planning stage inReadFromMergeTreeor at execution stage inAggregatingTransform; include a correctness fix so planning-stage hit chunks carryingPartialAggregatePlanHitInfoare preserved through pre-aggregationFilterTransformand are not dropped before aggregation.Documentation entry for user-facing changes
How it works
Two integration points:
ReadFromMergeTree): probePartialAggregateCacheby part before readers are built. On hit, emitPartialAggregatePlanHitChunkSourceand exclude the part from the read pipeline.AggregatingTransform): on miss, buffer rows per part and put mergeable states into cache when complete; on hit, merge cached states viamergeOnBlockand skip subsequent chunks from that part.Cache stores mergeable intermediate states, not finalized results.
Cache key:
(query_hash, table_uuid, part_name, part_mutation_version)Invalidation is key-based: merged/mutated parts naturally produce new keys.
Current limits / behavior
GROUPING SETSuse execution-stage caching only.AggregatingInOrderTransform).partial_aggregate_cache_allow_parallel_aggregation_streams=1keeps parallelism and disables only execution-stage cache (planning-stage hits still apply).Tests
03800_partial_aggregate_cache.sql04064_partial_aggregate_cache_analyzer.sql04065_partial_aggregate_cache_grouping_sets.sql04131_prometheus_query_parseris reproducible without random settings and appears unrelated to this change set.Note
High Risk
Touches core query planning/execution paths (
ReadFromMergeTree,AggregatingStep,AggregatingTransform) and adds new caching behavior and invalidation logic, which risks subtle correctness/performance regressions despite being gated behind experimental settings.Overview
Adds an experimental partial aggregate cache for repeated
GROUP BYqueries onMergeTree, caching per-part intermediate aggregate states and reusing them across semantically identical queries.Integrates the cache at both planning time (probing in
ReadFromMergeTreeto skip reading parts on cache hits viaPartialAggregatePlanHitChunkSource) and execution time (buffering per-part misses inAggregatingTransform, then merging andput-ing completed intermediate states). Cache keys incorporate query semantics (incl.current_database,apply_deleted_mask, and guards for subqueries/row policies/additional filters) plus part identity (table_uuid,part_name,part_mutation_version), with hit/miss metrics/events added.Introduces new settings (
use_partial_aggregate_cache,partial_aggregate_cache_allow_parallel_aggregation_streams), server config knobs/defaults for cache sizing,SYSTEM CLEAR|DROP AGGREGATE CACHEsupport with a new privilege, and documentation/tests (including analyzer and grouping-sets coverage); also tightens function-factory query logging and makes query-cache nondeterminism checks robust to gated/deprecated functions.Reviewed by Cursor Bugbot for commit 4f92f09. Bugbot is set up for automated code reviews on this repo. Configure here.
Workflow [PR]
Sync PR [sync-upstream/pr/93757]