Skip to content

Not a fix: "Not-ready Set" exception when buildOrderedSetInplace fails - #102192

Closed
alexey-milovidov wants to merge 156 commits into
masterfrom
fix-not-ready-set-parallel-replicas
Closed

alexey-milovidov wants to merge 156 commits into
masterfrom
fix-not-ready-set-parallel-replicas

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Related: #107924

FutureSetFromSubquery::buildOrderedSetInplace (the speculative set build run during primary key analysis for IN subqueries) used to consume the subquery source plan up front. If the in-place build then failed silently (e.g. due to subquery timeout with timeout_overflow_mode = 'break', where the executor stops without throwing and without setting is_created), the set remained permanently unbuilt and FunctionIn threw "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::makePlansForSets can 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 implement IQueryPlanStep::clone. After merging master, this PR carries the remaining hardening on top of #107924:

  • clone implementations for eleven more query-plan steps: JoinStep, FillingStep, ExtractColumnsStep, FractionalLimitStep, FractionalOffsetStep, MergingAggregatedStep, NegativeLimitStep, NegativeLimitByStep, NegativeOffsetStep, StreamInQueryResultCacheStep, ReadFromQueryResultCacheStep. IN subqueries whose plans contain these steps (e.g. ORDER BY ... WITH FILL, joins planned as JoinStep, 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::clone covers only the join algorithms whose IJoin implementation supports cloning: HashJoin, ConcurrentHashJoin, ConstantJoin and FullSortingMergeJoin. JoinSwitcher (join_algorithm = 'auto'), SpillingHashJoin, MergeJoin / PartialMergeJoin and GraceHashJoin keep the pre-existing destructive fallback: IJoin::isCloneSupported also gates optimizeJoin, convertOuterJoinToInnerJoin and QueryPipelineBuilder, 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, and 04649_not_ready_set_with_non_clonable_join_algorithms pins that those algorithms still produce correct results (the NOT_IMPLEMENTED stays internal).
  • FilledJoinStep (StorageJoin and dictionary joins) and JoinStepLogicalLookup (direct key-value joins) intentionally remain non-clonable as well: they wrap live storage-backed join state with no safe copy semantics (IJoin::clone constructs an empty join rather than copying the filled state). The constraint is documented at both classes.
  • Copying a QueryResultCacheWriter (which is what StreamInQueryResultCacheStep::clone does) now carries over both the original's query_start_time and its skip_insert decision. On the successful in-place build path the copy is the only writer that is ever finalized, so otherwise query_cache_min_query_duration would be measured from the clone point and an already cache-resident key would be buffered into a throwaway buffer instead of being skipped. Pinned by 04652_query_result_cache_subquery_clone_min_query_duration and 04653_query_result_cache_subquery_clone_skip_insert.
  • QueryPlan::clone now preserves max_threads and concurrency_control, so a pipeline built from a cloned plan runs under the same resource contract as the original instead of defaulting to max_threads == 0 with concurrency control disabled.
  • The Planner no longer plants query result cache steps into a logical plan. A logical plan is not executed where it is built: it is serialized and shipped to another node (parallel replicas with serialize_query_plan = 1, see createRemotePlanForParallelReplicas), while StreamInQueryResultCacheStep and ReadFromQueryResultCacheStep hold node-local state (a QueryResultCacheWriter, or the cached chunks) that has no serialized representation. Before this, query_cache_for_subqueries = 1 together with parallel replicas and serialize_query_plan = 1 failed the whole query with Method serialize is not implemented for StreamInQueryResultCache. The cache is still populated and read by the plan the initiator executes itself.
  • Regression tests using the prepared_sets_build_ordered_set_inplace_fail failpoint: 04095_global_not_in_parallel_replicas (the original parallel-replicas reproducer), 04492_not_ready_set_with_fill_subquery (a WITH FILL subquery 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) and 04649_not_ready_set_with_non_clonable_join_algorithms.

The original failure was observed in the Stress test (amd_tsan) on master, where considerEnablingParallelReplicas triggers selectRangesToRead, which calls buildOrderedSetInplace for 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):

  • Improvement

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 IN subqueries (introduced in #107924) to more query-plan shapes: clone is implemented for eleven more query-plan steps, including clone-supported joins via JoinStep, ORDER BY ... WITH FILL via FillingStep, 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 preserves max_threads and concurrency_control of the original plan. Also fixed Method serialize is not implemented for StreamInQueryResultCache when query_cache_for_subqueries = 1 is used together with parallel replicas and serialize_query_plan = 1.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

`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]>
@alexey-milovidov
alexey-milovidov marked this pull request as draft April 9, 2026 08:31
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The change looks doubtful. While the root cause analysis (destructive build() in buildOrderedSetInplace leaving the set permanently unbuilt on failure) seems correct, the fix introduces complexity — a callback with a captured query tree clone and a full Planner rebuild. There may be a simpler approach, such as making build() non-destructive or preventing buildOrderedSetInplace from consuming the source when it cannot guarantee success.

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.

@clickhouse-gh

clickhouse-gh Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d8e5e78]

Summary: ✅


AI Review

Summary

Reviewed head d8e5e78adf0b50e7f77c98bd730e5f518880776b. The PR extends independent cloning of IN-subquery plans, preserves resources and execution limits in extracted subplans, and prevents node-local query-cache state from reaching serialized plan fragments. Prior findings are addressed or covered by the explicitly narrowed contract. No actionable findings remain.

Missing context / blind spots
  • ⚠️ Full CI on this head is still running. Fast test and Style check passed; targeted stateless and unit jobs remain pending. Runtime validation relies on the submitted regression tests and the documented earlier A/B runs; completion of those jobs would close this gap. No local build or tests were run.
Final Verdict

Status: ✅ Approve. No new inline findings; remaining CI results are pending.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 9, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The test does not reproduce the issue. It only checks functional correctness of GLOBAL NOT IN with parallel replicas. The actual bug requires buildOrderedSetInplace to fail after build() has already consumed the source plan (e.g. due to subquery timeout with result_overflow_mode = 'break'). This only happens under load in stress tests. A proper reproducer would need a FailPoint to force the failure path at PreparedSets.cpp:359.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Fast test (arm_darwin) failure is unrelated to this PR — the fix is in #102184.

alexey-milovidov and others added 3 commits April 24, 2026 07:39
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]>
@alexey-milovidov
alexey-milovidov marked this pull request as ready for review April 26, 2026 10:46
Comment thread src/Interpreters/PreparedSets.cpp Resolved
@alexey-milovidov
alexey-milovidov marked this pull request as draft April 26, 2026 10:48
`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
alexey-milovidov and others added 2 commits April 28, 2026 20:55
…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]>
Comment thread src/Interpreters/PreparedSets.cpp Resolved
alexey-milovidov and others added 2 commits April 29, 2026 11:55
…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]>
Comment thread src/Interpreters/PreparedSets.cpp Resolved
alexey-milovidov and others added 2 commits May 2, 2026 21:46
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]>
alexey-milovidov and others added 5 commits October 20, 2026 06:50
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Automated continue-pr pass (2026-10-22), pushed 1b7879df..8f8661b2:

  1. Merged master. Master added identical clone implementations to FractionalLimitStep, FractionalOffsetStep, NegativeLimitStep, NegativeOffsetStep and NegativeLimitByStep, so the PR's duplicates were removed (these files drop out of the PR diff). ninja clickhouse and gtest_join_step_clone.cpp.o build.
  2. Fast test failure of 05029_make_distributed_plan_in_subquery_query_cache_set_source: master made reads from numbers serializable (7e6defb7e36), so the 'cannot be distributed' case over numbers(50) GROUP BY number was distributed and cached nothing. The test now uses a Memory table, whose read is not serializable; verified locally against the reference.
  3. The open review thread on JoinStep::clone was answered on 2026-10-20 with the plan-level test gtest_join_step_clone.cpp; no new feedback since.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Automated continue-pr pass (2026-10-26), pushed 69dcbddd..d8b8e005:

  1. The only CI failure on 69dcbddd was Upgrade check (amd_release): use_query_condition_cache_for_time_conditions was missing from the settings changes history. This is unrelated to the PR and is fixed on master by Keep use_query_condition_cache_for_time_conditions experimental and disabled on master, as in 26.10 #127687, so I merged master (no conflicts). The diff against master has not changed, and the translation units the PR touches still compile.
  2. There are no unresolved review threads.

alexey-milovidov and others added 4 commits November 4, 2026 03:17
# 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]>
@rschu1ze

rschu1ze commented Nov 9, 2026

Copy link
Copy Markdown
Member

What is this PR doing exactly? It looks like it should be split up into at least five smaller PRs.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

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.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Split into smaller PRs, as suggested by the review:

  1. Add ExtractColumnsStep::clone and "Not-ready Set" regression tests #130373 - ExtractColumnsStep::clone and the "Not-ready Set" regression tests for Fix "Not-ready Set" exception by making in-place set build non-destructive #107924
  2. Implement JoinStep::clone #130374 - JoinStep::clone
  3. Implement clone for the query result cache steps #130375 - clone for the query result cache steps (and the QueryResultCacheWriter copy fix)
  4. Do not use the subquery query result cache in plans shipped to replicas #130376 - no subquery query result cache steps in plans shipped to parallel replicas
  5. Make the subquery query result cache safe under make_distributed_plan #130377 - subquery query result cache under make_distributed_plan
  6. Let subplans extracted by plan optimizations inherit limits and resources #130378 - subplans extracted by plan optimizations inherit limits and resources

They are independent of each other and all based on master. The applyParallelReplicas thread cap hunk was dropped: QueryPlan::cloneSubtree already does it on master.

alexey-milovidov added a commit to melvynator/ClickHouse that referenced this pull request Nov 10, 2026
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]>
Blargian pushed a commit to Blargian/ClickHouse that referenced this pull request Nov 10, 2026
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]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 14, 2026
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]>
PedroTadim pushed a commit to hsusul/ClickHouse that referenced this pull request Nov 18, 2026
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
subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 18, 2026
…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]>
m7kss1 pushed a commit to m7kss1/ClickHouse that referenced this pull request Nov 20, 2026
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]>
perfloop-agent pushed a commit to perfloop-oss/ClickHouse that referenced this pull request Nov 20, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants