Repository navigation
Not a fix: "Not-ready Set" exception when buildOrderedSetInplace fails - #102192
alexey-milovidov wants to merge 156 commits into
Conversation
`FutureSetFromSubquery::buildOrderedSetInplace` (called during primary key analysis for IN subquery optimization) calls `build()` which destructively moves the `source` plan out. If the in-place build then fails silently (e.g. due to subquery timeout with `result_overflow_mode = 'break'`), the source plan is lost and the set remains not-created. Later, `DelayedCreatingSetsStep::makePlansForSets` calls `build()` again, but `source` is null so it returns nullptr. No set-building plan is created in the pipeline, and `FunctionIn` throws "Not-ready Set is passed as the second argument". This was observed in the stress test (TSan) with parallel replicas settings, where `considerEnablingParallelReplicas` triggers `selectRangesToRead` which calls `buildOrderedSetInplace` for primary key analysis. The fix adds a rebuild callback to `FutureSetFromSubquery` that can recreate the source plan from a saved query tree clone. If `buildOrderedSetInplace` fails, it uses this callback to restore the source so that the normal pipeline-based set building in `makePlansForSets` can still work. https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=d0432097aed783bd35054dce2edcefe0c4e5122c&name_0=MasterCI&name_1=Stress%20test%20%28amd_tsan%29 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
The change looks doubtful. While the root cause analysis (destructive Also, the reproducing conditions (stress test with TSan, intermittent) make it hard to verify the fix directly. The test added here covers the GLOBAL NOT IN + parallel replicas scenario but may not trigger the exact race condition. |
|
Workflow [PR], commit [d8e5e78] Summary: ✅
AI ReviewSummaryReviewed head Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings; remaining CI results are pending. |
|
The test does not reproduce the issue. It only checks functional correctness of GLOBAL NOT IN with parallel replicas. The actual bug requires |
|
The |
The bugfix validation job flagged that `04095_global_not_in_parallel_replicas`
passed on master without the fix ("Failed to reproduce the bug"). The original
query only exercised functional correctness of `GLOBAL NOT IN` with parallel
replicas and never hit the silent-failure path in `buildOrderedSetInplace` that
the PR fixes.
Add the `prepared_sets_build_ordered_set_inplace_fail` failpoint at the exact
site where `set->isCreated()` is checked in `FutureSetFromSubquery::buildOrderedSetInplace`.
When the failpoint is active, `build()` is still allowed to consume the source
plan (matching the natural timeout-with-`overflow_mode='break'` path), and the
function then returns `nullptr` as if the set build had silently failed.
The test now queries on the primary-key column (`idx`) so `KeyCondition` actually
calls `buildOrderedSetInplace` during primary-key analysis, enables the
failpoint, and runs the `GLOBAL IN` / `GLOBAL NOT IN` queries. On unfixed master
this path throws "Not-ready Set is passed as the second argument"; with the
`setRebuildSourceCallback` restoration in `Planner` and `PreparedSets`, the
rebuild succeeds and the query returns the expected result.
Also merge master and update the `GlobalPlannerContext` constructor call in the
rebuild callback to match the new 4-argument signature that landed on master.
Tagged `no-parallel` because the failpoint is global.
#102192
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`buildOrderedSetInplace` previously relied on `build()` to destructively move the `source` plan out, then on a `RebuildSourceCallback` to recreate it from a query-tree clone if the in-place build silently failed (e.g. subquery timeout with `overflow_mode = 'break'`). That callback ran a brand-new `Planner` to reconstitute work we had just thrown away. Run the in-place pipeline against `source->clone()` instead. The original `source` survives a failed in-place build, so `DelayedCreatingSetsStep::makePlansForSets` can build the set as usual and `FunctionIn` no longer throws "Not-ready Set is passed as the second argument". On success we drop `source` since pipeline-based building is no longer needed. This removes the `RebuildSourceCallback` machinery from `PreparedSets` and the matching registration in `Planner.cpp`. The failpoint `prepared_sets_build_ordered_set_inplace_fail` and the regression test `04095_global_not_in_parallel_replicas` exercise the same scenario. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…t be cloned Many `IQueryPlanStep` subclasses do not implement `clone` (only ~15 of ~85 step types do, including `UnionStep`, `LimitStep`, `SortingStep`, etc). The previous commit added `source->clone()` so that the original source plan would survive a silent in-place build failure, but `std::make_unique<QueryPlan>(source->clone())` then throws `NOT_IMPLEMENTED` for any subquery whose plan contains an unimplemented step, breaking unrelated queries that previously worked, e.g. `select count() from t1 where c1 in (select 'BBBBBB' union all select null)` in `01518_select_in_null` failed with "Cannot clone Union plan step. (NOT_IMPLEMENTED)" (the subquery's `UnionStep`). Catch `NOT_IMPLEMENTED` from `clone` and return `nullptr` from `buildOrderedSetInplace` in that case. The primary key index optimization is then skipped for that subquery, but the source plan is left untouched, so `DelayedCreatingSetsStep::makePlansForSets` can build the set later via the normal pipeline path. Other exceptions still propagate. Failures fixed: `01518_select_in_null`, `02949_parallel_replicas_in_subquery`, `02875_merge_engine_set_index`, and many other tests that combine `IN`-subqueries with non-cloneable plan steps. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102192&sha=df3318c6e12376575c32003ad1ffa8d429eadc09&name_0=PR
…arallel-replicas # Conflicts: # src/Common/FailPoint.cpp
…test failpoint When `source->clone()` throws `NOT_IMPLEMENTED` (many `IQueryPlanStep` subclasses do not implement `clone`), the previous fallback was to skip the in-place build entirely. That disabled primary key analysis for any `IN` subquery whose source plan contained a non-clonable step, breaking tests like `00562_in_subquery_merge_tree`, `01700_system_zookeeper_path_in`, `03578_kv_in_type_casts`, `03928_materialized_cte_index`, `03991_set_variant_low_cardinality_in_global_in`, and others. Fall back to the original behavior instead: consume `source` directly. This preserves in-place set building (and primary key analysis) for plans without clone support, at the cost of not being able to recover from a silent in-place build failure for those plans. For plans that do support `clone`, the safer recovery path remains. Also move the `prepared_sets_build_ordered_set_inplace_fail` failpoint from `buildOrderedSetInplace` (where it fired after `executor.execute` and only forced a nullptr return without making `set->isCreated()` stay false) into `CreatingSetsTransform::generate`, where it skips `finishInsert`. This makes the failpoint reproduce the actual bug path: `isCreated()` stays false, `buildOrderedSetInplace` returns nullptr, and `DelayedCreatingSetsStep::makePlansForSets` is exercised. Switch the failpoint to `ONCE` so the deferred build can complete normally on the second `CreatingSetsTransform` pass. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…arallel-replicas # Conflicts: # src/Common/FailPoint.cpp
`buildOrderedSetInplace` now clones the source plan instead of consuming it, so that `DelayedCreatingSetsStep::makePlansForSets` can fall back to building the set from the preserved source if the in-place attempt fails silently (e.g. due to subquery timeout with `overflow_mode = 'break'`). Cloning allocates new step indices via `getNextPlanStepIndex`, so the unique IDs in this test are shifted: the cloned `ReadFromSystemNumbers` becomes `ReadFromSystemNumbers_19` (was `_9`), and the explicitly-added `CreatingSetStep` adds one more index, shifting subsequent steps by one (`CreatingSet_19` -> `CreatingSet_20`, `Expression_21` -> `Expression_22`, `CreatingSets_22` -> `CreatingSets_23`). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102192&sha=07be2e19d084046e90036c607acb39b02880918f&name_0=PR&name_1=Fast%20test PR: #102192 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The cloned-source path in `FutureSetFromSubquery::buildOrderedSetInplace` preserves `source` when the in-place build fails silently, so the same `FutureSetFromSubquery` can re-enter `buildOrderedSetInplace` on a later call (different call sites include `KeyCondition`, MergeTree skip indexes, `ConditionSelectivityEstimator`, virtual column predicate pushdown, etc.). `Set::fillSetElements` appends empty columns to `set_elements` without clearing, so calling it twice would leave `set_elements.size() > keys_size` and the next insertion path would throw `LOGICAL_ERROR` from `Set::appendSetElements`. Match the pattern in `FutureSetFromTuple::buildOrderedSetInplace` and skip the call when `hasExplicitSetElements` is already true. Reported-by: clickhouse-gh in code review on PR PR: #102192 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ion3` After merging master, `optimizeLazyMaterialization3` called `QueryPlan::extractSubplan` with the old two-argument signature, while this branch made it take the plan that owns the nodes so the subplan inherits its execution limits and resources. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…l test The analyzer stores an `IN` subquery source with a `JoinStepLogical`, which becomes a physical `JoinStep` only during optimization, after `buildOrderedSetInplace` clones the plan, and the old analyzer is removed, so no SQL query reaches the physical clone. `gtest_join_step_clone` builds a `JoinStep` over a `HashJoin` directly, clones it before execution, and checks that the clone has its own join state (the original stays empty after the clone runs, and both produce the same rows) and, after the same swap `optimizeJoinLegacy` performs, that the clone keeps the swapped build side. Negative controls (not committed): a shallow `JoinPtr` copy fails both tests, and building the cloned join with the unswapped header order fails the swap test with `Not found column lk in block`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master added the same `clone` implementations to `FractionalLimitStep`, `FractionalOffsetStep`, `NegativeLimitStep`, `NegativeOffsetStep` and `NegativeLimitByStep`, so the merge left two declarations and two definitions of each. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master made reads from `numbers` serializable (`7e6defb7e36`), so the `numbers(50) GROUP BY number` set source is distributed now and caches nothing, which failed the last check of the test in the Fast test: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=102192&sha=latest&name_0=PR&name_1=Fast%20test #102192 A read from a `Memory` table is not serializable, so it still builds the set locally. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Automated continue-pr pass (2026-10-22), pushed
|
# Conflicts: # src/Processors/QueryPlan/QueryPlan.cpp
|
🕵 Automated continue-pr pass (2026-10-26), pushed
|
# Conflicts: # src/Processors/QueryPlan/Optimizations/optimizeTree.cpp
`master` replaced `JoinStep::keep_left_read_in_order` with `left_pipeline_order` and removed the matching constructor argument, and `HashJoin` now requires a `HashJoinBuildLayout`. Re-apply the left order requirement in `clone` the same way `setJoin` does, drop the removed argument from the gtest, and build the test join with `HashJoin::create`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Processors/QueryPlan/ReadFromQueryResultCacheStep.h
…05366` `master` now rejects a query whose subquery sets a different `parallel_replicas_plan_based` than the outer query (`checkParallelReplicasImplementationOfSubqueries`), so the escape attempt in `05366_query_result_cache_subquery_plan_based_parallel_replicas` cannot run at all any more. The test still shows that the subquery cache cannot be used this way. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=102192&sha=2690535fd97e6fbe6636649a079111a68a03dbf4&name_0=PR&name_1=Fast%20test PR: #102192 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
What is this PR doing exactly? It looks like it should be split up into at least five smaller PRs. |
|
The original problem is fixed in another PR, and now this PR only fixes some flaws in the code base - fixes that could also prevented the same bug. Yes, there are a few independent ones. I will split. |
|
Split into smaller PRs, as suggested by the review:
They are independent of each other and all based on |
Split out of ClickHouse#102192. `ExtractColumnsStep` did not implement `clone`, so an `IN` subquery whose source plan contains it made `FutureSetFromSubquery::buildOrderedSetInplace` take the destructive fallback introduced in ClickHouse#107924. Also add the regression tests for the "Not-ready Set is passed as the second argument" exception fixed by ClickHouse#107924, using the `prepared_sets_build_ordered_set_inplace_fail` failpoint: the original parallel replicas reproducer and a `WITH FILL` subquery source plan. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Split out of ClickHouse#102192. `StreamInQueryResultCacheStep` and `ReadFromQueryResultCacheStep` hold node-local state (a `QueryResultCacheWriter`, or the cached chunks) with no serialized representation. A logical plan built for parallel replicas with `serialize_query_plan = 1` (`createRemotePlanForParallelReplicas`) is shipped to the replicas, so `query_cache_for_subqueries = 1` failed the whole query with `Method serialize is not implemented for StreamInQueryResultCache`. Plan-based parallel replicas serialize a fragment of the local plan, including `IN` subquery set plans; a fragment holding a cache step is kept local, so the cache would silently disable parallel replicas and make the remote/local decision depend on cache contents. The Planner no longer adds the cache steps in either case. The cache is still populated and read by the plan the initiator executes itself. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Split out of ClickHouse#102192. With `query_cache_for_subqueries = 1` an `IN` subquery plan contains `StreamInQueryResultCacheStep` (write path) or is replaced by `ReadFromQueryResultCacheStep` (cache hit). Neither implemented `clone`, so `FutureSetFromSubquery::buildOrderedSetInplace` took the destructive fallback (see ClickHouse#107924), where a silent in-place build failure still leads to the "Not-ready Set is passed as the second argument" exception. - `StreamInQueryResultCacheStep::clone` gives the clone its own copy of the `QueryResultCacheWriter`. - The `QueryResultCacheWriter` copy now carries over `query_start_time`, so `query_cache_min_query_duration` is not measured from the clone point. On the successful in-place build path the copy is the only writer that is finalized. - `ReadFromQueryResultCacheStep` keeps its `SourceFromChunks` and clones them via the new `SourceFromChunks::clone`, which shares the immutable columns. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The real bug is in : and consume the source before they know whether the set was actually created. If the in-place path stops early, the delayed build path loses the subquery and sees an empty set. Store a query-plan rebuild callback for analyzer and old-analyzer paths, use a temporary while building in place, and restore the source plan for the fallback path when the in-place attempt does not finish. Add a failpoint-based regression test that covers both and . Ref: ClickHouse#102192
…rces Split out of ClickHouse#102192. The member `QueryPlan::extractSubplan(Node *)` already copies `max_threads`, `concurrency_control` and the resource holder into the extracted plan, but the static `QueryPlan::extractSubplan(Node *, Nodes &)` used by plan optimizations (`tryConvertJoinToIn`, lazy materialization) did not. A subplan extracted there may be executed after the outer plan has been consumed into a pipeline (e.g. the right side of a `JOIN` converted to `IN` is built later as a set), so it ran with the default thread fan-out, without concurrency control, and without holding the table locks, storage holders and interpreter contexts of the source plan. The static overload now takes the source plan, which `Optimization::ExtraSettings` carries as `source_plan`. The fragment that `applyParallelReplicas` cuts with `cloneSubtree` also gets the thread cap and concurrency control of its plan. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Split out of ClickHouse#102192. `IN` subqueries whose plans contain a `JoinStep` took the destructive fallback of `FutureSetFromSubquery::buildOrderedSetInplace` (see ClickHouse#107924), where a silent in-place build failure still leads to the "Not-ready Set is passed as the second argument" exception. `JoinStep::clone` deep-clones the `IJoin` (respecting `swap_streams`) for the algorithms that support `IJoin::clone`: `HashJoin`, `ConcurrentHashJoin`, `ConstantJoin` and `FullSortingMergeJoin`. Other algorithms throw `NOT_IMPLEMENTED` and keep the fallback; widening `IJoin::isCloneSupported` would also enable join swapping and outer-to-inner conversion for them. Document why `FilledJoinStep` and `JoinStepLogicalLookup` stay non-clonable. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Split out of ClickHouse#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]>
Related: #107924
FutureSetFromSubquery::buildOrderedSetInplace(the speculative set build run during primary key analysis forINsubqueries) used to consume the subquerysourceplan up front. If the in-place build then failed silently (e.g. due to subquery timeout withtimeout_overflow_mode = 'break', where the executor stops without throwing and without settingis_created), the set remained permanently unbuilt andFunctionInthrew "Not-ready Set is passed as the second argument".The core fix — running the in-place pipeline against a clone of the source plan so that
DelayedCreatingSetsStep::makePlansForSetscan still build the set after a silent failure — has meanwhile been merged in #107924, which falls back to the original destructive build when the source plan contains a step that does not implementIQueryPlanStep::clone. After merging master, this PR carries the remaining hardening on top of #107924:cloneimplementations for eleven more query-plan steps:JoinStep,FillingStep,ExtractColumnsStep,FractionalLimitStep,FractionalOffsetStep,MergingAggregatedStep,NegativeLimitStep,NegativeLimitByStep,NegativeOffsetStep,StreamInQueryResultCacheStep,ReadFromQueryResultCacheStep.INsubqueries whose plans contain these steps (e.g.ORDER BY ... WITH FILL, joins planned asJoinStep, subqueries going through the query result cache) previously took the destructive fallback, where a silent in-place failure still reproduces the "Not-ready Set" exception; with clone support they take the non-destructive path and recover.JoinStep::clonecovers only the join algorithms whoseIJoinimplementation supports cloning:HashJoin,ConcurrentHashJoin,ConstantJoinandFullSortingMergeJoin.JoinSwitcher(join_algorithm = 'auto'),SpillingHashJoin,MergeJoin/PartialMergeJoinandGraceHashJoinkeep the pre-existing destructive fallback:IJoin::isCloneSupportedalso gatesoptimizeJoin,convertOuterJoinToInnerJoinandQueryPipelineBuilder, so widening it would silently enable join swapping and outer-to-inner conversion for never-validated stateful spilling algorithms. This limitation is documented at the throw site, and04649_not_ready_set_with_non_clonable_join_algorithmspins that those algorithms still produce correct results (theNOT_IMPLEMENTEDstays internal).FilledJoinStep(StorageJoinand dictionary joins) andJoinStepLogicalLookup(direct key-value joins) intentionally remain non-clonable as well: they wrap live storage-backed join state with no safe copy semantics (IJoin::cloneconstructs an empty join rather than copying the filled state). The constraint is documented at both classes.QueryResultCacheWriter(which is whatStreamInQueryResultCacheStep::clonedoes) now carries over both the original'squery_start_timeand itsskip_insertdecision. On the successful in-place build path the copy is the only writer that is ever finalized, so otherwisequery_cache_min_query_durationwould be measured from the clone point and an already cache-resident key would be buffered into a throwaway buffer instead of being skipped. Pinned by04652_query_result_cache_subquery_clone_min_query_durationand04653_query_result_cache_subquery_clone_skip_insert.QueryPlan::clonenow preservesmax_threadsandconcurrency_control, so a pipeline built from a cloned plan runs under the same resource contract as the original instead of defaulting tomax_threads == 0with concurrency control disabled.serialize_query_plan = 1, seecreateRemotePlanForParallelReplicas), whileStreamInQueryResultCacheStepandReadFromQueryResultCacheStephold node-local state (aQueryResultCacheWriter, or the cached chunks) that has no serialized representation. Before this,query_cache_for_subqueries = 1together with parallel replicas andserialize_query_plan = 1failed the whole query withMethod serialize is not implemented for StreamInQueryResultCache. The cache is still populated and read by the plan the initiator executes itself.prepared_sets_build_ordered_set_inplace_failfailpoint:04095_global_not_in_parallel_replicas(the original parallel-replicas reproducer),04492_not_ready_set_with_fill_subquery(aWITH FILLsubquery source plan),04550_not_ready_set_with_join_subquery,04648_not_ready_set_with_query_result_cache_subquery(both the cache write and the cache read path) and04649_not_ready_set_with_non_clonable_join_algorithms.The original failure was observed in the Stress test (amd_tsan) on master, where
considerEnablingParallelReplicastriggersselectRangesToRead, which callsbuildOrderedSetInplacefor primary key analysis.Note on the changelog category: the "Not-ready Set" exception is a
LOGICAL_ERROR, so reproducing it on the unfixed build aborts the server on the sanitizer builds that the per-arch Bugfix validation jobs run on, and the validation harness deliberately treats a mid-run server death as inconclusive rather than as a reproduced bug. Automated bugfix validation is therefore structurally impossible for this fix, and the user-visible bug fix for the common plan shapes already shipped with #107924; the remaining hardening here is classified as an Improvement.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Extend the non-destructive speculative in-place set build for
INsubqueries (introduced in #107924) to more query-plan shapes:cloneis implemented for eleven more query-plan steps, including clone-supported joins viaJoinStep,ORDER BY ... WITH FILLviaFillingStep, and the query result cache steps. Such subqueries now preserve the original source plan and can recover from a silent in-place build failure instead of throwing "Not-ready Set is passed as the second argument". A cloned query plan now preservesmax_threadsandconcurrency_controlof the original plan. Also fixedMethod serialize is not implemented for StreamInQueryResultCachewhenquery_cache_for_subqueries = 1is used together with parallel replicas andserialize_query_plan = 1.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/102192]