Skip to content

Add PartialAggregateCache for part-level aggregate caching. - #93757

Open
zex-hyd wants to merge 76 commits into
ClickHouse:masterfrom
zex-hyd:feature/partial-query-cache
Open

zex-hyd wants to merge 76 commits into
ClickHouse:masterfrom
zex-hyd:feature/partial-query-cache

Conversation

@zex-hyd

@zex-hyd zex-hyd commented Jan 9, 2026 •

Copy link
Copy Markdown

Add experimental part-level partial aggregate cache for GROUP BY on MergeTree tables, 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):

  • Experimental Feature

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

Add experimental setting use_partial_aggregate_cache for MergeTree GROUP BY queries to cache per-part intermediate aggregate states and reuse them either at planning stage in ReadFromMergeTree or at execution stage in AggregatingTransform; include a correctness fix so planning-stage hit chunks carrying PartialAggregatePlanHitInfo are preserved through pre-aggregation FilterTransform and are not dropped before aggregation.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

How it works

Two integration points:

  • Planning stage (ReadFromMergeTree): probe PartialAggregateCache by part before readers are built. On hit, emit PartialAggregatePlanHitChunkSource and exclude the part from the read pipeline.
  • Execution stage (AggregatingTransform): on miss, buffer rows per part and put mergeable states into cache when complete; on hit, merge cached states via mergeOnBlock and 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

  • Planning-stage probing is enabled for legacy interpreter flow; analyzer-side planning support is follow-up.
  • GROUPING SETS use execution-stage caching only.
  • Not used with in-order aggregation (AggregatingInOrderTransform).
  • With execution-stage cache enabled, aggregation pipeline is resized to one stream for per-part ownership; partial_aggregate_cache_allow_parallel_aggregation_streams=1 keeps parallelism and disables only execution-stage cache (planning-stage hits still apply).

Tests

  • 03800_partial_aggregate_cache.sql
  • 04064_partial_aggregate_cache_analyzer.sql
  • 04065_partial_aggregate_cache_grouping_sets.sql
  • Existing CI integration failure 04131_prometheus_query_parser is 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 BY queries on MergeTree, caching per-part intermediate aggregate states and reusing them across semantically identical queries.

Integrates the cache at both planning time (probing in ReadFromMergeTree to skip reading parts on cache hits via PartialAggregatePlanHitChunkSource) and execution time (buffering per-part misses in AggregatingTransform, then merging and put-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 CACHE support 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]

@zex-hyd
zex-hyd force-pushed the feature/partial-query-cache branch from ffeb3a4 to 8a4aebe Compare January 9, 2026 00:53
@CLAassistant

CLAassistant commented Jan 9, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@zex-hyd

zex-hyd commented Jan 9, 2026

Copy link
Copy Markdown
Author

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.

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

clickhouse-gh Bot commented Jan 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8f17e21]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Adds 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: AggregatingTransform consumes embedded states; expression, conversion, and materialization transforms retain ChunkInfos; resizing and concatenation forward chunks; FilterTransform explicitly preserves hits. Eligibility guards exclude joins, ARRAY JOIN, aggregate-projection rewrites, planning-time grouping sets, and in-order, radix, and top-K aggregation consumers.

Missing context / blind spots
  • ⚠️ The current-head Fast test passes all 28 partial aggregate cache tests. Full stateless and TSan jobs remain skipped by the review-threads gate, so the shared-state concurrency fixes still need current-head TSan evidence. No local binary was available; the findings below follow concrete source traces.
Findings

❌ Blockers

  • src/Core/ProtocolDefines.h:268: Aggregating step version 2 is introduced at global plan version 21, which older peers already advertise while supporting only step versions 0 and 1. Negotiation therefore sends an unreadable step, including with caching disabled. Introduce global version 22 for 26.12, gate the new encoding there, and preserve step version 1 toward version-21 peers.
  • src/Processors/QueryPlan/ReadFromMergeTree.cpp:716: The default-expression check misses mutable IN inputs because FunctionIn reports determinism. Add v UInt8 DEFAULT k IN keys after inserting an old part containing k = 1, 2, with keys a Set table containing only 1. Warm SELECT sum(v), insert 2 into keys, and repeat: the cache reuses 1 although an uncached read returns 2. The part and column metadata are unchanged. Apply mutable-input rejection to default dependencies or represent their identity in the key.

⚠️ Majors

Tests
  • ⚠️ Add a version-21 peer compatibility check and a missing-column default regression that changes a Set table between identical cached queries.
  • ⚠️ Correct the radix regression's settings so removing the consumer guard makes the test fail.
Final Verdict

Status: ❌ Block

Correct the serialization gate and mutable-default eligibility, and repair the radix regression before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jan 9, 2026
@zex-hyd
zex-hyd force-pushed the feature/partial-query-cache branch from 7bce5fe to 9fa7ee0 Compare January 11, 2026 23:38
@zex-hyd zex-hyd changed the title Add PartialAggregateCache skeleton for part-level aggregate caching. Add PartialAggregateCache for part-level aggregate caching. Jan 12, 2026
@zex-hyd
zex-hyd force-pushed the feature/partial-query-cache branch from 9fa7ee0 to 9a03c03 Compare January 13, 2026 21:08
@zex-hyd

zex-hyd commented Jan 14, 2026

Copy link
Copy Markdown
Author

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.

@zex-hyd
zex-hyd force-pushed the feature/partial-query-cache branch from 9a03c03 to 66170ba Compare January 18, 2026 22:56
/// produce the same partial aggregates on every execution, so we cache and reuse them.
///
/// Enable with: SET use_partial_aggregate_cache = 1
class PartialAggregateCache

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 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?

Comment thread programs/local/LocalServer.cpp Resolved
Comment thread programs/server/Server.cpp Resolved
@zex-hyd

zex-hyd commented Jan 22, 2026

Copy link
Copy Markdown
Author

@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!

@zex-hyd
zex-hyd force-pushed the feature/partial-query-cache branch 3 times, most recently from 005c8f2 to d17e874 Compare February 2, 2026 07:19

@nickitat nickitat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please outline the entire design, and let's first make sure it will work. Then we can talk about the implementation.

@zex-hyd

zex-hyd commented Feb 12, 2026

Copy link
Copy Markdown
Author

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!

@nickitat nickitat self-assigned this Mar 26, 2026
Comment thread src/Interpreters/Context.cpp Resolved
Comment thread src/Planner/Planner.cpp Resolved
alexey-milovidov and others added 4 commits October 29, 2026 20:54
# 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
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 6 commits November 8, 2026 09:44
# 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]>
Comment thread src/Interpreters/Aggregator.cpp Resolved
alexey-milovidov and others added 10 commits November 18, 2026 01:08
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and resolved the conflicts (Aggregator::Params, ParserSystemQuery.cpp, PlannerSteps.cpp, ReadFromMergeTree.cpp, 01271_show_privileges.reference). The planner getAggregatorParams now delegates to the shared helper from PlannerAggregation.h and sets the partial aggregate cache semantic key on the result; LazyReadFromMergeTreeSource was adapted to the part groups introduced on master. Also fixed the 05621_documentation_no_docusaurus_syntax failure in the Fast test: the SYSTEM CLEAR AGGREGATE CACHE documentation used a :::note admonition, now <Note>. The remaining open thread (a new entry kind of QueryResultCache vs. a separate cache) is still a design decision for a maintainer.

alexey-milovidov and others added 3 commits November 24, 2026 04:21
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and resolved the conflicts in src/Interpreters/Aggregator.cpp (only the NOT_IMPLEMENTED error code is kept; BAD_ARGUMENTS is no longer used there) and src/Planner/PlannerSteps.cpp (the partial aggregate cache semantic key is kept together with the new shared_kept_keys_for_overflow_any condition from master). Also fixed both Style check failures: the records of use_partial_aggregate_cache and partial_aggregate_cache_allow_parallel_aggregation_streams moved to 26.12, and std::vector<Pipe> in ReadFromMergeTree.cpp became Pipes.

Verification: all translation units of the merged tree compile, except that Aggregator.cpp was verified with -fsyntax-only only - its optimized compile did not fit on the shared build machine, so the binary was not linked and the tests were not run locally. They need to be confirmed by CI on this commit.

Still open: the review thread on PartialAggregateCache.h (a new entry kind of QueryResultCache vs. a separate cache) is a design decision for a maintainer; while it is unresolved, the review-threads gate keeps the full CI suite skipped.

/// 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;

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.

[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))

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.

[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"

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.

[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.

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-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants