Repository navigation
Preserve execution limits and resources in derived QueryPlans - #109722
Conversation
…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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260707-214000 |
|
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 |
|
Workflow [PR], commit [3856bdc] Summary: ✅
AI ReviewSummaryThis PR correctly restores Findings
Tests
Final VerdictLLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 201/212 (94.81%) · Uncovered code |
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]>
|
Good call. Moved the fix from the single caller into the
On the two sibling callers you flagged — I checked both, and inheriting the caps is correct (and safe) for them too:
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-3:20260707-230500 |
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]>
|
Fixed in 3177ac0: Safety at the boundary: every Pre-PR validation gate (click to expand)
Local: |
CI finish ledger — 3177ac0Every 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
All CI checks pass. The Session id: cron:our-pr-ci-monitor:20260708-043000 |
CI finish ledger — 3177ac0Every failure below has an owner. Only
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
CI finish ledger — 618eb03Every 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
Not PR-caused: this PR only carries Session id: cron:our-pr-ci-monitor:20260711-163000 |
…ettings # Conflicts: # tests/queries/0_stateless/03269_explain_unique_ids.reference
CI finish ledger — 51bcc93Every 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.
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
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.
|
🕵 Merged current The gate The new test 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 |
`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.
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
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 = 2Results:
Backport the fix to CC component owner: @alexey-milovidov @KochetovNicolai Analysis metadata
Introducing change: not identified
|
Backport #109722 to 26.8: Preserve execution limits and resources in derived QueryPlans
…ources in derived QueryPlans
Related: #107619
Related: #107924
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Preserve execution limits and resource lifetimes when deriving
QueryPlaninstances for internal query execution.Description
The non-destructive in-place set-build fix from #107924 is already on
master; this follow-up fixes the remainingQueryPlanpropagation and lifetime invariants.QueryPlan::cloneandQueryPlan::extractSubplanpreviously copied or moved only the node tree. The derived plan consequently lost itsmax_threads,concurrency_control, andQueryPlanResourceHolderstate.QueryPlan::unitePlansalso discardedconcurrency_controlwhen joining child plans. This change preserves those plan-level execution caps and shared resource handles, and adds focused unit coverage forclone,extractSubplan, and both child orders ofunitePlans.The HTTP
make_distributed_planset-build behavior described in the remaining review thread is intentionally out of scope: it is a pre-existingQueryPlan::convertToDistributedboundary 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
26.8.16.40