Skip to content

Make the subquery query result cache safe under make_distributed_plan - #130377

Merged
alexey-milovidov merged 10 commits into
masterfrom
query-result-cache-distributed-plan
Nov 20, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
query-result-cache-distributed-plan

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Related: #102192

Split out of #102192 (part 5 of 6).

The Planner-level query result cache steps of a subquery hold node-local state with no serialized representation, so they must not end up in a fragment that QueryPlan::convertToDistributed ships to a worker under make_distributed_plan.

  • Write path: StreamInQueryResultCacheStep is a removable pass-through. It no longer makes make_distributed_plan keep the plan local, nor stops convertSetSourceForDistributedPlan from distributing an IN set source. cutIntoDistributedPlan drops it before the split; the local fallback keeps it, so the cache still works there.
  • Read path: a cache hit replaces the whole subquery plan with a non-removable ReadFromQueryResultCacheStep, so the plan shape would depend on cache contents. Reads are disabled while a distributed plan is being built. The ban is keyed to a new sticky SelectQueryOptions::building_distributed_plan and to the query-level context, so a subquery cannot escape it with its own SETTINGS make_distributed_plan = 0.
  • Because the Planner now sets that option on the options it is given, UNION branches and the subqueries planned for partition pruning / index analysis get their own copy, so a branch-local setting does not leak into siblings.
  • PlannerContext::mayBeSerializedForRemoteExecution (which disables JIT-compiled expressions) also honours make_distributed_plan via the sticky option and the query-level context.

Tests: 05024_query_result_cache_subquery_distributed_plan_local_fallback, 05029_make_distributed_plan_in_subquery_query_cache_set_source, 05054_query_result_cache_subquery_read_ban_settings_escape, 05141_query_result_cache_subquery_union_branch_isolation, 05339_query_result_cache_subquery_local_fragment_no_read, 05616_query_result_cache_subquery_distributed_plan_drops_write_step.

Changelog category (leave one):

  • Improvement

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

The subquery query result cache works together with make_distributed_plan: cacheable subqueries no longer prevent distributed execution, and cache reads never change the shape of a distributed plan.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.12.1.72-master (included in 26.12 and later)

Split out of #102192.

The Planner-level query result cache steps of a subquery hold node-local state
with no serialized representation, so they must not end up in a fragment that
`QueryPlan::convertToDistributed` ships to a worker.

- Write path: `StreamInQueryResultCacheStep` is a removable pass-through. It no
  longer makes `make_distributed_plan` keep the plan local, nor stops
  `convertSetSourceForDistributedPlan` from distributing an `IN` set source.
  `cutIntoDistributedPlan` drops it before the split; the local fallback keeps
  it, so the cache still works there.
- Read path: a cache hit replaces the whole subquery plan with a non-removable
  `ReadFromQueryResultCacheStep`, so the plan shape would depend on cache
  contents. Reads are disabled while a distributed plan is being built. The ban
  is keyed to a new sticky `SelectQueryOptions::building_distributed_plan` (and
  the query-level context), so a subquery cannot escape it with its own
  `SETTINGS make_distributed_plan = 0`.
- Because the Planner now mutates its options, `UNION` branches and the
  subqueries planned for partition pruning / index analysis get their own copy.
- `PlannerContext::mayBeSerializedForRemoteExecution` (which disables JIT
  compiled expressions) also honours `make_distributed_plan` on the sticky
  option and on the query-level context.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Nov 9, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Nov 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b62668e]

Summary: ✅


AI Review

Summary

The PR allows cacheable subqueries to participate in make_distributed_plan by removing cache writers before optimization and fragment splitting, suppressing cache reads during distributed planning, and isolating branch options. Reviewed the current diff and surrounding planning, set construction, and serialization paths, plus all prior discussion. The previous Cascades finding is addressed; no remaining findings. All seven added regression tests passed against the Fast test binary for commit b62668e49eb4c9293aa8c2e2abc5db9c745e6038, with output matching their reference files exactly.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 10, 2026
alexey-milovidov and others added 2 commits November 11, 2026 14:36
…in Fast test

With `use_index_for_in_with_subqueries = 1` the set for the `IN` subquery is
built speculatively during primary key analysis by
`FutureSetFromSubquery::buildOrderedSetInplace`. That build distributes only a
clone of the set source, and `StreamInQueryResultCacheStep` has no `clone` yet
(see #130375), so it fell back to
running the original source locally and wrote the cache entry, making the
"distributed" case report 1 instead of 0.

The test is about the set source conversion of the deferred build, so disable
the speculative build.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130377&sha=latest&name_0=PR&name_1=Fast%20test
PR: #130377

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

Copy link
Copy Markdown
Member Author

🕵 Fast test failure of 05029_make_distributed_plan_in_subquery_query_cache_set_source: with use_index_for_in_with_subqueries = 1 the set is built speculatively during primary key analysis (FutureSetFromSubquery::buildOrderedSetInplace), which distributes only a clone of the set source. StreamInQueryResultCacheStep has no clone yet (that is #130375), so the build fell back to running the original source locally and wrote the cache entry. Reproduced with the CI binary. The test now disables that speculative build, so it checks only the set source conversion of the deferred build (verified locally: passes). Once #130375 lands, the speculative path should distribute as well. Also merged master.

Comment thread src/Processors/QueryPlan/QueryPlan.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b62668e49 with master da3dc325b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 31628339d; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

520 translation units recompiled, 3783 s compile time in total, 520 of them have a recent master baseline.

Job report

alexey-milovidov and others added 2 commits November 13, 2026 15:22
# Conflicts:
#	src/Interpreters/SelectQueryOptions.h
#	src/Planner/PlannerContext.cpp
…nes the plan

With `enable_cascades_optimizer = 1`, `QueryPlan::optimize` clones every step of a
plan accepted by `make_distributed_plan`, and `StreamInQueryResultCacheStep` cannot be
cloned, so the query threw `Cannot clone StreamInQueryResultCache plan step`. Remove
the cache write steps as soon as `applyDistributedPlanFallbackToLocal` accepts the plan
for distributed execution, before the optimization; the removal at the fragment cut
stays as a safety net. Add a Cascades regression test.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130377&sha=861fe54c7917a9c05e145b3960e4995213b990b7&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29 (Logical error: Initiator received more initial requests than there are replicas, STID 8765-7cc2) and provide a fix in a separate PR. If the fix is already in progress, link it here. The same error also showed up on master (Stress test (amd_debug), 2026-10-20) and in PRs 130540 and 122069, so this PR did not cause it.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the same bug as the Stress test (amd_debug) failure on #118375, and the fix is my open PR #115916 (issue #121105).

The aborting query (d08625e6) is an AST fuzzer copy of the subquery SETTINGS case of 05211_parallel_replicas_analyze_indexes_correlated_subquery, without the outer SETTINGS:

SELECT count() FROM mergeTreeAnalyzeIndexes(currentDatabase(), t_pr_ai, (key IN (SELECT (SELECT key) FROM t_pr_ai_2 ORDER BY key DESC LIMIT 10 SETTINGS enable_parallel_replicas = 1, max_parallel_replicas = 2, parallel_replicas_for_non_replicated_merge_tree = 1, cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost'))))

The fuzzed query's context has parallel replicas off, so DisableParallelReplicasPass::run returns at its canUseParallelReplicasOnInitiator() check (still DisableParallelReplicasPass.cpp:54 on master) and never visits the correlated subquery, which keeps parallel replicas from its own SETTINGS. #115916 removes that early return and checks each query node against its own context; its 05211 covers this shape. #122069 aborted on another fuzzed copy of the same case. #115916 is mergeable, its CI is green, and it is waiting for review.

The 2026-10-20 run is ReleaseBranchCI on the 26.8 branch, not master: a CREATE MATERIALIZED VIEW ... POPULATE from 04649 (the fuzzed collaborative worker path), fixed on master by #115786, which is not in 26.8. #130540 is a 26.8 backport, so it also runs without #115786.

@clickhouse-gh clickhouse-gh Bot added comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 13, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai: the stress test abort is tracked by #115916 (issue #121105), so nothing to do here. The remaining red, 03634_autopr_output_bytes_estimation on Stateless tests (arm_binary, parallel), ran with enable_parallel_single_level_merge = True and is fixed on master by #131358; merged master to pick it up (all PR translation units rebuild cleanly on the merged tree).

…distributed-plan

Resolve conflict in `PlannerContext.h`: keep the PR's extended comment for
`mayBeSerializedForRemoteExecution` and master's `[[nodiscard]]`.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master (one conflict in PlannerContext.h: kept this PR's comment for mayBeSerializedForRemoteExecution plus master's [[nodiscard]]). The 7 tests added by this PR pass locally on the merged tree. The Upgrade check (amd_release) red, Logical error: Context has expired (STID: 1805-3f9b) in FunctionKQLMultiply, is unrelated: it appears on many other PRs and is fixed by #131363 (backported to 26.10 in #132081). It most likely comes from the previous-release binary the Upgrade check starts with. The other Upgrade check failures (Cannot list the mutations ... etc.) follow from that server abort.

alexey-milovidov and others added 2 commits November 20, 2026 02:23
…-parallel-replicas execution

Under the `Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, sequential)`
profile the whole query is distributed by plan-based parallel replicas, so the subquery query
result cache is intentionally not probed and the test printed `0` instead of `1`. The test is
about a local `UNION` branch not inheriting a sibling's `make_distributed_plan`, so disable
parallel replicas like the sibling tests do.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130377&sha=8ad9b709690279f4a81bec89cce188adf8aff07e&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20plan-based%2C%20s3%20storage%2C%20sequential%29
#130377

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

Copy link
Copy Markdown
Member Author

🕵 Merged master, which includes 94e368e ("Pin 05829 to query-based parallel replicas") and fixes the 05829_autopr_skip_index_on_read_in_subquery failure on Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel); that failure also happened on master and many other PRs. The 05141_query_result_cache_subquery_union_branch_isolation failure in the sequential job came from this PR's test: plan-based parallel replicas distribute the whole query, so the subquery cache is intentionally not probed. The test now sets enable_parallel_replicas = 0, like the sibling tests. I reproduced the failure locally with the plan-based profile and confirmed the fix.

@clickhouse-gh clickhouse-gh Bot added comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... and removed comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 20, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed the Style check failure: removeQueryResultCacheWriteSteps now uses VectorWithMemoryTracking instead of std::vector (b62668e). No unresolved review threads remain.

@alexey-milovidov alexey-milovidov self-assigned this Nov 20, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reasonable.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 20, 2026
Merged via the queue into master with commit 612d09f Nov 20, 2026
195 checks passed
@alexey-milovidov
alexey-milovidov deleted the query-result-cache-distributed-plan branch November 20, 2026 16:51
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 20, 2026
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-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants