Skip to content

Preserve execution limits and resources in derived QueryPlans - #109722

Merged
alexey-milovidov merged 42 commits into
ClickHouse:masterfrom
groeneai:fix-not-ready-set-settings
Aug 30, 2026
Merged

alexey-milovidov merged 42 commits into
ClickHouse:masterfrom
groeneai:fix-not-ready-set-settings

Conversation

@groeneai

@groeneai groeneai commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107619
Related: #107924

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Preserve execution limits and resource lifetimes when deriving QueryPlan instances for internal query execution.

Description

The non-destructive in-place set-build fix from #107924 is already on master; this follow-up fixes the remaining QueryPlan propagation and lifetime invariants.

QueryPlan::clone and QueryPlan::extractSubplan previously copied or moved only the node tree. The derived plan consequently lost its max_threads, concurrency_control, and QueryPlanResourceHolder state. QueryPlan::unitePlans also discarded concurrency_control when joining child plans. This change preserves those plan-level execution caps and shared resource handles, and adds focused unit coverage for clone, extractSubplan, and both child orders of unitePlans.

The HTTP make_distributed_plan set-build behavior described in the remaining review thread is intentionally out of scope: it is a pre-existing QueryPlan::convertToDistributed boundary unrelated to this follow-up, and the native protocol re-applies concurrency control after pipeline construction.


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

Version info

  • Backported to: 26.8.16.40

…lace set build

QueryPlan::clone copies only the node tree, not the plan-level max_threads /
concurrency_control. The speculative buildOrderedSetInplace pass therefore ran
with the default thread fan-out and without concurrency control, instead of the
caps the authoritative runtime build honors. Carry them over to the cloned plan.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SYSTEM ENABLE FAILPOINT prepared_sets_build_ordered_set_inplace_fail fires once inside CreatingSetsTransform::generate and skips finishInsert, reproducing the silent in-place build failure on every run (test 04489).
b Root cause explained? buildOrderedSetInplace did auto plan = std::move(source); if the in-place pipeline stopped without setting is_created (timeout overflow_mode='break', or any stop skipping Set::finishInsert), the consumed source left the set unbuilt and FunctionIn threw "Not-ready Set".
c Fix matches root cause? Yes. In-place pipeline runs against a clone of source into a temporary Set, publishing only on isCreated(); source is preserved so DelayedCreatingSetsStep::makePlansForSets can build later. The additional commit preserves max_threads/concurrency_control on the clone (QueryPlan::clone copies only nodes).
d Test intent preserved / new tests added? New tests 04489 (failpoint repro) + 04490 (GLOBAL IN external-table max-values). No existing test weakened.
e Demonstrated both directions? Yes. Failpoint reproduces the crash on the pre-fix path; with the full fix test 04489 returns 500/500/250/250 matching the reference.
f Fix general, not narrow patch? Yes. Fix is at the chokepoint buildOrderedSetInplace (all IN-family index-analysis paths); clonable QueryPlan steps get clone() overrides; non-clonable sources and GLOBAL IN external tables keep the pre-PR destructive path (no regression).
g Generalizes across inputs/wrappers? Yes. Covers plain IN, nested IN (destructive fallback via DelayedCreatingSetsStep), MATERIALIZED-CTE-backed IN (DelayedMaterializingCTEsStep fallback), and GLOBAL IN external table (destructive, transfer limits enforced).
h Backward compatible? Yes. No setting default / format / wire change. Adds a debug-only failpoint. Non-clonable and GLOBAL-IN shapes behave exactly as before.
i Invariants / contracts preserved? Yes. Canonical set_and_key->set is mutated only on committed build; speculative temp set is not shared via PreparedSetsCache; source-plan resources kept alive until after the speculative pipeline is destroyed (source.reset() scoping); fillSetElements called once.

Session id: cron:clickhouse-worker-slot-2:20260707-214000

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @KochetovNicolai — could you review? This carries @alexey-milovidov's non-destructive in-place set build (#107924, all public checks green) plus the one open review item on PreparedSets.cpp: preserving the subquery's max_threads / concurrency_control on the cloned speculative plan (QueryPlan::clone copies only nodes). Fixes the chronic "Not-ready Set" logical error (#107619).

@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3856bdc]

Summary: ✅


AI Review

Summary

This PR correctly restores QueryPlan execution-limit/resource propagation across clone, the member extractSubplan, unitePlans, replaceNodeWithPlan, and ordinary distributed-plan serialization/fallback. I still see two major gaps on the current head: the JOIN -> IN rewrite still manufactures a standalone set-build plan without the owning plan's execution caps, and the plan-based parallel-replicas path still loses rolling-upgrade compatibility on the 9 -> 10 query-plan-version bump.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/convertJoinToIn.cpp:262-268, src/Processors/QueryPlan/QueryPlan.cpp:1139-1179] [dismissed by author -- https://github.com/Preserve execution limits and resources in derived QueryPlans #109722#discussion_r3573960863] The JOIN -> IN rewrite still builds the RHS FutureSetFromSubquery from QueryPlan::extractSubplan(Node *, Nodes &), and that overload still returns a fresh plan with max_threads = 0 and concurrency_control = false. FutureSetFromSubquery::build / buildOrderedSetInplace then execute that plan later without any caller-side reapply, so this opt-in rewrite remains outside the execution-limit contract the rest of the PR restores.
    Suggested fix: thread the owning plan's max_threads / concurrency_control into this extraction path before wrapping it in FutureSetFromSubquery (for example by extending Optimization::ExtraSettings, or by adding a cloneSubtree(..., source_plan)-style helper for this standalone RHS plan).

  • [src/Core/ProtocolDefines.h:101-106, src/Interpreters/ClusterProxy/executeQuery.cpp:1092-1095, src/QueryPipeline/RemoteQueryExecutor.cpp:179-205] [dismissed by author -- https://github.com/Preserve execution limits and resources in derived QueryPlans #109722#discussion_r3817364348] parallel_replicas_plan_based = 1 still loses rolling-upgrade compatibility on this 9 -> 10 query-plan-version bump. executeQueryWithParallelReplicas pre-serializes one fragment at the current version, while the ConnectionPoolPtr RemoteQueryExecutor constructor rejects any replica below DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_PARALLEL_REPLICAS, and that minimum is defined as the current DBMS_QUERY_PLAN_SERIALIZATION_VERSION. So this PR still makes every version-9 replica unusable on the plan-based parallel-replicas path, and the new SQL fallback never gets a chance to run because those replicas are discarded before sendQueryUnlocked.
    Suggested fix: either add a compatibility path for plan-based parallel replicas, or keep the cached fragment on a version-9 layout whenever max_threads == 0 && !concurrency_control, so a mixed 10/9 rollout does not silently lose replicas or fail the query.

Tests
  • ⚠️ The new QueryPlanExecutionLimits gtests still do not cover the static extractSubplan(Node *, Nodes &) carrier that feeds JOIN -> IN. A focused test should enable query_plan_convert_join_to_in = 1 and assert that the resulting FutureSetFromSubquery source plan keeps the outer plan's max_threads / use_concurrency_control.
  • ⚠️ The added 05038_query_plan_limits_hedged_sql_fallback test only exercises the ordinary distributed hedged fallback on a same-version cluster. It does not cover the mixed-version parallel_replicas_plan_based path where version-9 replicas are still filtered out before fallback; proving that path needs a 10/9 integration harness.
Final Verdict

⚠️ Needs changes before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 201/212 (94.81%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 7, 2026
Comment thread src/Interpreters/PreparedSets.cpp Resolved
QueryPlan::clone copies only the node tree, not the plan-level max_threads /
concurrency_control. Move the carry-over of those limits into clone() itself so
every cloned plan preserves the source plan's execution caps, rather than fixing
only the speculative set-build caller. This also covers the direct-join lookup
clones (PlannerJoinTree, DirectJoinMergeTreeEntity), which otherwise ran with
the default thread fan-out and no concurrency control.

max_threads only ever imposes a cap (limitMaxThreads runs only when non-zero), so
copying it into a clone can never increase a plan's fan-out.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Good call. Moved the fix from the single caller into the QueryPlan::clone boundary itself, so the contract "a cloned plan preserves its execution limits" holds for every clone site. Pushed as 7b3c030.

QueryPlan::clone() now copies max_threads / concurrency_control onto the result (they are plain plan-level members, not part of the node tree that cloneInplace walks). I removed the caller-side carry-over in FutureSetFromSubquery::buildOrderedSetInplace since it is now redundant.

On the two sibling callers you flagged — I checked both, and inheriting the caps is correct (and safe) for them too:

  • There are exactly three QueryPlan::clone() call sites in the tree: PreparedSets.cpp:503, PlannerJoinTree.cpp:2193 (right_query_plan.clone() → the direct-join lookup plan), and DirectJoinMergeTreeEntity.cpp:176 (lookup_plan.clone() → the per-batch executed lookup plan).
  • The direct-join source plan (right_query_plan) already gets max_threads / use_concurrency_control from the same planner path (buildQueryPlanForTableExpression, PlannerJoinTree.cpp:1850-1852) that every other table-expression plan uses. So honoring those caps in the clones is consistent with how the plan would run outside the direct-join path, not a new policy.
  • Direction of effect: max_threads can only ever impose a cap — QueryPlan::buildQueryPipeline applies limitMaxThreads(max_threads) only when max_threads != 0 (QueryPlan.cpp:257), and max_threads defaults to 0. So carrying it into a clone can never increase fan-out; it can only bring an uncapped clone down to the query's configured limit. concurrency_control likewise just enables the existing control. There is no caller for which this is a regression — the previous behavior (uncapped, no concurrency control) was the unintended one.
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The Not-ready-Set exception this PR fixes is deterministically reproduced by the failpoint test 04489_not_ready_set_inplace_build (passes locally). The dropped-caps behavior is a plan-property invariant verified by code inspection of the three clone sites + buildQueryPipeline; it is not a test-failure symptom.
b Root cause explained? QueryPlan::clone() delegates to cloneInplace, which copies only the node tree; the plan-level max_threads / concurrency_control members are not copied. Any cloned plan therefore executes with max_threads == 0 (no limitMaxThreads) and concurrency_control == false, regardless of what the source plan carried.
c Fix matches root cause? Yes — the missing copy is added exactly where the loss happens (clone()), so the property holds for all clone sites rather than one caller.
d Test intent preserved / new tests added? Existing regression tests (04489_not_ready_set_inplace_build, 04490_...) unchanged and still pass. No behavior-observable-from-SQL change to add a new test for: the fix only restores the intended thread cap on cloned plans (a resource property, not a result).
e Both directions demonstrated? Before: clone() leaves max_threads == 0 / concurrency_control == false (verified in the pre-fix cloneInplace). After: clone() copies both; the Not-ready-Set suite (04489, 02156, 02841_not_ready_set_join_on) passes on a Build-ID-verified binary.
f Fix is general across code paths? Yes — this is precisely the generalization requested: the fix now covers all three QueryPlan::clone() callers (speculative set build + both direct-join clones) instead of one.
g Fix generalizes across inputs? N/A — the two copied members are a size_t and a bool; there are no datatype/wrapper variants. All plan shapes are covered because the copy is unconditional in clone().
h Backward compatible? Yes — no setting default, wire/disk format, or validation change. It only restores the execution caps a cloned plan was always meant to honor; the prior uncapped behavior was the unintended one.
i Invariants and contracts preserved? Yes — clone()'s intended postcondition is "an equivalent plan"; copying the plan-level limits strengthens that. max_threads only ever imposes a cap (limitMaxThreads runs only when non-zero), so no clone can gain more fan-out than it had; it can only be brought down to the source's configured limit. No lock/ownership/structure invariant is touched.

Session id: cron:clickhouse-worker-slot-3:20260707-230500

Comment thread src/Processors/QueryPlan/QueryPlan.cpp Resolved
clone() copied the execution limits (max_threads, concurrency_control) but
not the plan-level resource holder. The direct-join lookup clone path
(PlannerJoinTree -> DirectJoinMergeTreeEntity) reads MergeTree parts through
the cloned plan, so it must keep the source plan's storage holders and table
locks alive. append copies the shared handles, so ownership is only shared,
never moved out of the source.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in 3177ac0: QueryPlan::clone() now also carries the resource holder onto the clone (result.resources.append(resources);), so all three clone sites (PreparedSets.cpp:503, PlannerJoinTree.cpp:2193, DirectJoinMergeTreeEntity.cpp:176) preserve the source plan's table locks / interpreter contexts / storage holders alongside max_threads / concurrency_control. The direct-join lookup path is exactly the beneficiary you named.

Safety at the boundary: every QueryPlanResourceHolder member is a shared-ownership handle (shared_ptr, RWLockImpl::LockHolder), and append inserts copies via const & (the same call already backing operator=(&&)). So clone() only ever shares ownership with the source, never moves out of it: it is strictly a lifetime extension for the clone, correct and safe for all three callers.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? No standalone crash repro. This is a lifetime invariant, not a wrong-result bug; in the current call graph the source right plan (moved into JoinStepLogicalLookup::child_plan) usually outlives the getByKeys-time clone, masking the missing holders. The fix restores the contract rather than fixing an observed crash.
b Root cause explained? clone() copied the node tree + (post-fix) the scalar exec limits, but not resources. buildQueryPipeline attaches only the executed plan's resources (QueryPlan.cpp:268), so a cloned+executed plan lost the source's table locks / storage holders / interpreter contexts.
c Fix matches root cause? Yes: copy resources at the clone() contract boundary, same place the scalar caps are copied.
d Test intent preserved / new tests? No test change. Existing not-ready-set + direct-join suites are the coverage; a deterministic lifetime-drop test is not achievable given (a).
e Demonstrated both directions? No (per a) - no deterministic failing case to toggle. The change is safe-by-construction (shared-handle copy).
f General, not a narrow patch? Yes: fixed at the boundary, covering all 3 clone sites rather than one caller.
g Generalizes across inputs? N/A - not input-shape dependent; append copies every holder member uniformly.
h Backward compatible? Yes: no format/setting/wire change; only extends clone lifetime semantics.
i Invariants preserved? Yes: append copies shared handles via const &, never moves out of the source, so no double-ownership or lifetime shortening on either the source or the clone.

Local: 04489_not_ready_set_inplace_build, 02156_storage_merge_prewhere_not_ready_set_bug, 02841_not_ready_set_join_on, and the full *direct_join* suite (6 tests) PASS on the rebuilt binary.

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3177ac0

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
CH Inc sync — CH Inc sync (private, not actionable)

All CI checks pass. The 04490_global_in_set_max_values_external_table FAIL rows under Bugfix validation (functional tests, amd64/aarch64) are the expected master-side behavior of the bugfix-validation harness (the new regression test must fail on master HEAD and pass on the PR) — both Bugfix validation checks are green.

Session id: cron:our-pr-ci-monitor:20260708-043000

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3177ac0

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
CH Inc sync private ClickHouse Inc sync CH Inc sync (private, not actionable by us)

Bugfix validation (functional, amd64 + aarch64) is green on this head. All other checks pass.

Session id: cron:our-pr-ci-monitor:20260708-050000

…ettings

# Conflicts:
#	tests/queries/0_stateless/03269_explain_unique_ids.reference
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 618eb03

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, parallel, 2/3) / Server died + Unknown error crash (chronic trunk, 8 master + 19 unrelated PRs / 30d) #109747 (ours, open) — 03915_exchange_tables_race.sh EXCHANGE TABLES type-swap → multiply LOGICAL_ERROR abort in ActionsDAG partial eval
Bugfix validation (functional tests, amd64/aarch64) / 04490_global_in_set_max_values_external_table expected harness behavior (regression test fails on master HEAD, passes on PR) — both Bugfix checks are green N/A — not a failure

Not PR-caused: this PR only carries max_threads/concurrency_control/QueryPlanResourceHolder onto QueryPlan::clone, unrelated to the coverage-batch server crash.

Session id: cron:our-pr-ci-monitor:20260711-163000

…ettings

# Conflicts:
#	tests/queries/0_stateless/03269_explain_unique_ids.reference
Comment thread src/Processors/QueryPlan/QueryPlan.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 51bcc93

Every failure below has an owner. This PR's diff (QueryPlan::clone concurrency-control forwarding) does not touch any failing code path — no failure is PR-caused.

Check / test Reason Owner / fixing PR
Stateless (amd_asan_ubsan/amd_debug/amd_msan/amd_tsan/arm_binary, sequential) / 02346_text_index_bug108519_qcc_skip_index flaky (randomized statistics) #110260 (ours, merged 2026-07-13 15:05Z) — this build predates the merge
Stateless (amd_tsan, s3, sequential) / Scraping system tables infra (minio_audit_logs dump 600s timeout) a fix task is created (investigating at full effort — fixing-PR link to follow here)
Integration tests (amd_asan_ubsan old analyzer 3/6; amd_tsan 3/6) / test_replicated_database/test.py::test_replicated_table_structure_alter flaky (Replicated-DB DDL-recovery race, trunk) #110030 (ours, open)
Upgrade check (amd_release) / Cannot parse test_results.tsv (missing result file) infra (harness crash, 1 PR / 0 master) a fix task is created (investigating at full effort — fixing-PR link to follow here)
Finish Workflow / Post Hooks infra (Config Workflow Pre/Post Hooks spike, 78 PRs/7d) a fix task is moved to pending (investigating at full effort — fixing-PR link to follow here)
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260713-190000

/// Preserve the plan-level execution limits. They are not part of the node tree, so cloneInplace
/// does not copy them; without this a cloned plan runs with the default thread fan-out and no
/// concurrency control instead of the caps the source plan carries.
result.max_threads = max_threads;

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.

Moving the carry-over into QueryPlan::clone fixes the three clone callers, but the same plan-equivalence contract is still broken on QueryPlan::extractSubplan. Both overloads at QueryPlan.cpp:1019-1099 build a fresh QueryPlan with default max_threads / concurrency_control, and we later execute plans produced that way in at least optimizePlanForExists (src/Planner/Utils.cpp:774) and the join-to-IN rewrite (src/Processors/QueryPlan/Optimizations/convertJoinToIn.cpp:224).

So after this PR, cloned plans respect the query caps, but extracted subplans still run with the default fan-out and no concurrency control. If the contract is "a derived subplan preserves the source plan's execution limits", this needs the same treatment on the extractSubplan boundary (or the sibling callers updated explicitly), otherwise the fix remains incomplete.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed for the member overload. QueryPlan::extractSubplan(Node *) now carries max_threads / concurrency_control / resources onto the extracted subplan (pushed fbe771c). That is the overload behind the two callers you named: optimizePlanForExists (Planner/Utils.cpp:774), reached from evaluateScalarSubqueryIfNeeded and PlannerCorrelatedSubqueries. Extra confirmation the drop was real: evaluateScalarSubqueryIfNeeded.cpp:264 was hand-setting setConcurrencyControl after the extraction to paper over it; that is now redundant.

The convertJoinToIn.cpp:224 caller goes through the OTHER overload, static extractSubplan(Node *, Nodes &), which has no source QueryPlan instance to inherit from (it splices from a free Nodes &). There is nothing to carry over at that boundary; giving it the caps would mean threading them in through the optimization ExtraSettings, a separate change out of scope here. Left unchanged.

Direction of effect is the same as the clone fix: max_threads only ever caps (limitMaxThreads applies only when non-zero, default 0), so this can never increase fan-out for any caller, only restore the query's configured cap. resources.append copies shared handles, so ownership is only shared, never moved out.

Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? No standalone crash repro. Contract/perf invariant (dropped caps), not a crash. Exercised both extractSubplan paths on a local debug server (EXISTS-correlated via optimizePlanForExists; JOIN->IN via the static overload): correct results, no regression.
b Root cause explained? The member extractSubplan(Node *) built the new plan with default max_threads=0 / concurrency_control=false / empty resources; splice moves only the node tree, so extracted subplans that are later executed ran with default fan-out, no concurrency control, and without the source resource holders.
c Fix matches root cause? Copies max_threads / concurrency_control and resources.append(resources) onto the extracted subplan, exactly the members splice omits. Same treatment already applied to clone().
d Test intent preserved / new tests? No test weakened. Behavior is a limits/lifetime carry-over with no result change; existing correlated-subquery and not-ready-set suites still pass.
e Demonstrated both directions? Partial: no deterministic crash to gate on (source plan usually outlives the extracted subplan in the current call graph, masking the drop). Fix is safe-by-construction (cap-only + shared-handle copy).
f Fix is general, not a narrow patch? Both extractSubplan overloads reviewed. Member overload fixed (has a source to inherit from). Static overload has no source instance; documented why it is left unchanged rather than blindly threading caps through settings.
g Generalizes across inputs? N/A (limits/resource carry-over, not input-dependent codegen).
h Backward compatible? Yes. Cap-only change cannot increase fan-out; no format/setting/default change.
i Invariants preserved? Yes. resources.append copies shared_ptr / lock handles (never moves out of source); node-tree splice semantics unchanged.

Session id: cron:clickhouse-worker-slot-1:20260714-012100

The member extractSubplan(Node *) overload built the extracted subplan with
default max_threads/concurrency_control and an empty resource holder. Callers
that execute the extracted subplan (optimizePlanForExists in Planner/Utils.cpp,
via evaluateScalarSubqueryIfNeeded and PlannerCorrelatedSubqueries) then ran it
with the default thread fan-out and no concurrency control, and without the
source plan's resource holders kept alive. This is the same plan-equivalence
contract already restored for QueryPlan::clone(); apply it at the extractSubplan
boundary too.

The static extractSubplan(Node *, Nodes &) overload has no source QueryPlan
instance to inherit caps from (nodes are spliced from a free Nodes list), so it
is left unchanged; the convertJoinToIn caller would have to thread caps through
its settings, which is out of scope for this fix.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Processors/QueryPlan/QueryPlan.cpp Resolved
unitePlans already carries max_threads (via max) and resources from its
child plans but dropped concurrency_control, so a united plan ran with
concurrency_control=false even when a child had it enabled. The correlated
subquery decorrelation path (PlannerCorrelatedSubqueries) feeds the extracted
subplan into unitePlans, so it lost the query's concurrency control.

OR concurrency_control from all children, mirroring the max_threads merge.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The `pr-bugfix` merge gate (`new_tests_check.py`) requires at least one
per-arch Bugfix validation job to reproduce the bug on master. The PR's
only functional-test change so far was a compatibility tweak to
`04653_merging_aggregated_deserialized_thread_count`, which passes on
master, so every per-arch job reported "Bug does not reproduce" and
`Finish Workflow` stayed red on head cccd836.

The new test `05038_query_plan_limits_hedged_sql_fallback` pins behavior
that exists only with this PR: a distributed query with
`serialize_query_plan = 1` over hedged connections falls back to sending
SQL when the plan carries non-default execution limits and a later hedge
could select a replica whose query-plan serialization version is
unverified (plan-level `max_threads` / `concurrency_control` are only
serialized since plan serialization version 10). On master the fallback
does not exist, so the firing oracle reads 0 and the test fails there -
exactly what Bugfix validation needs. A control query with hedged
connections off pins that the fallback stays silent when every connected
replica is verified.

This also adds the same-version-testable half of the mixed-version
coverage the AI review asked for.

Verified locally against the branch build: the test passes, and all 8
`QueryPlanExecutionLimits` gtests pass after merging current master.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (conflict-free) and fixed the deterministic Finish Workflow red, pushed as db09168637c6.

The gate new_tests_check.py requires a pr-bugfix PR's changed functional tests to reproduce the bug on master on at least one arch. This PR's only functional-test change was the compatibility tweak to 04653_merging_aggregated_deserialized_thread_count, which passes on master, so all four per-arch Bugfix validation jobs reported "Bug does not reproduce - N/A" and the gate failed on cccd8364.

The new test 05038_query_plan_limits_hedged_sql_fallback pins behavior introduced by this PR, so it fails on master and passes here: with serialize_query_plan = 1, non-default plan-level execution limits, and hedged connections whose later hedge could select an unverified replica, the initiator logs and takes the SQL fallback (RemoteQueryExecutor::sendQueryUnlocked); a control query with use_hedged_requests = 0 pins that the plan is still shipped and the fallback stays silent when every connected replica is verified. This is also the same-version-testable half of the rolling-upgrade coverage the AI review asked for.

Verified locally on the branch build: the new test passes (and fails by construction on master, where the fallback message does not exist), and all 8 QueryPlanExecutionLimits gtests pass after the merge.

Comment thread src/Client/HedgedConnectionsFactory.h Resolved
`HedgedConnections` is compiled only under `OS_LINUX`, so on Darwin
`use_hedged_requests = 1` silently degrades to ordinary connections and the
initiator never logs `Sending query as SQL because a replica does not support
query-plan serialization version`. The new test therefore failed in
`Fast test (arm_darwin)`; tag it `no-darwin`.
`HedgedConnections::supportsQueryPlanSerializationVersion` only walked the
replicas already published into `offset_states`, plus `maySelectUnverifiedReplica`
for the pools that were never dialled. An established replica that is usable but
not up to date increments `entries_count` and returns `CANNOT_CHOOSE` without ever
becoming ready, so it is invisible to both terms while `setBestUsableReplica` can
still hand it out on a later hedge when
`fallback_to_stale_replicas_for_distributed_queries` is on. Shipping the plan to
such a replica could then throw from `QueryPlan::serialize` on a version-9 peer.

Add `HedgedConnectionsFactory::maySelectReplicaBelowQueryPlanSerializationVersion`,
which additionally scans the established, usable, not-ready entries the factory
still holds, and use it as the gate.
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: a821a587-ebba-4b0d-9d5a-0d75c43d032b
  • MIRAI run: 4151a7c0-3f05-48ef-a896-b107ee791518
  • PR check IDs:
    • clickbench_384531_1788047830
    • clickbench_384544_1788047830
    • clickbench_384550_1788047830
    • tpch_adapted_1_official_384556_1788047830
    • tpch_adapted_1_official_384587_1788047830
    • tpch_adapted_1_official_384601_1788047830

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 30, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 30, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 30, 2026
Merged via the queue into ClickHouse:master with commit 97b6e9a Aug 30, 2026
180 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 30, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
-- Needs a server (reads system.query_log). 8 separate INSERTs = 8 parts.
CREATE TABLE t (a UInt64) ENGINE = MergeTree ORDER BY a;
CREATE TABLE s (a UInt64) ENGINE = MergeTree ORDER BY a;
SYSTEM STOP MERGES s;
INSERT INTO t SELECT number FROM numbers(1000);
INSERT INTO s SELECT number + 100000 FROM numbers(20000);
INSERT INTO s SELECT number + 200000 FROM numbers(20000);
INSERT INTO s SELECT number + 300000 FROM numbers(20000);
INSERT INTO s SELECT number + 400000 FROM numbers(20000);
INSERT INTO s SELECT number + 500000 FROM numbers(20000);
INSERT INTO s SELECT number + 600000 FROM numbers(20000);
INSERT INTO s SELECT number + 700000 FROM numbers(20000);
INSERT INTO s SELECT number + 800000 FROM numbers(20000);

SELECT count() FROM t WHERE a IN (SELECT a FROM s)
SETTINGS max_threads = 1, use_index_for_in_with_subqueries = 1, log_comment = 'set_build';

SELECT count() FROM t WHERE a IN (SELECT a FROM s)
SETTINGS max_threads = 1, use_index_for_in_with_subqueries = 0, log_comment = 'baseline';

SYSTEM FLUSH LOGS query_log;

SELECT log_comment, peak_threads_usage
FROM system.query_log
WHERE log_comment IN ('set_build', 'baseline') AND type = 'QueryFinish'
ORDER BY event_time_microseconds;

-- 26.7.5.10: set_build = 10, baseline = 2  (one thread per part, max_threads=1 ignored)
-- 26.6.3.62 and older, and this PR's build: set_build = 2, baseline = 2

Results:

  • Reproduces on: 26.7
  • Does not reproduce on: 26.6, 26.5, 26.3, 25.8
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 clean
  • Fix merged on master (not re-verified: tested master build predates this PR's merge — a clean verdict is not attributable to the fix). The releases listed above still have the bug and need the backport.

Backport the fix to 26.7.

CC component owner: @alexey-milovidov @KochetovNicolai

Analysis metadata

comp-query-execution · Severity P2 · Finding phase_d_pr109722

  • Could not test: master
Introducing change: not identified
  • Secondary components: comp-protocols, comp-testing

@robot-clickhouse robot-clickhouse added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Oct 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 3, 2026
Backport #109722 to 26.8: Preserve execution limits and resources in derived QueryPlans
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors groeneai-origin-unknown PR origin: unclassified (legacy task) pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

IN (subquery) set built from a cloned plan ignores max_threads: about 1600 threads and MEMORY_LIMIT_EXCEEDED (26.6 -> 26.8)

7 participants