Skip to content

Fix "Not-ready Set" exception by making in-place set build non-destructive - #107924

Merged
alexey-milovidov merged 12 commits into
masterfrom
fix-not-ready-set-inplace-build
Jul 11, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
fix-not-ready-set-inplace-build

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Related: #102192
Related: #107619
Related: #104130
Related: #102803
Related: #102981

FutureSetFromSubquery::buildOrderedSetInplace is a speculative build run during primary key / skip index analysis for an IN subquery (KeyCondition, ReadFromMergeTree::selectRangesToRead, including the considerEnablingParallelReplicas estimation path). It built the set through the destructive build, which moves the subquery source plan out of the future-set; constructing a pipeline then consumes it.

If the in-place pipeline stops without creating the set — a subquery timeout with overflow_mode = 'break', or any early stop that skips CreatingSetsTransform::generate and therefore Set::finishInsert — buildOrderedSetInplace returns nullptr, but source has already been consumed. The authoritative deferred build (DelayedCreatingSetsStep::makePlansForSets) then finds source == nullptr, attaches no set-building step to the pipeline, and FunctionIn throws Not-ready Set is passed as the second argument when the query runs.

Fix. Run the in-place pipeline against a clone of source (via the existing QueryPlan::clone) and keep the original intact, resetting it only after the set is actually created. The speculative pipeline builds into a temporary Set that is published into the canonical set_and_key only once it is fully created, so a partial prefix of rows from an interrupted build never leaks into the set that the deferred build reuses (which would otherwise corrupt the result of a non-deterministic subquery such as one using rand). The speculative build no longer shares its result through PreparedSetsCache, so a silent failure cannot poison the key for the deferred build.

Some source steps cannot be cloned — most notably ReadFromPreparedSource, which wraps an already-materialized, single-use Pipe (dictionary, many system table, and remote reads go through it). For a non-clonable source the code falls back to the original destructive build, so primary key analysis is still performed for such subqueries exactly as before; only the rare silent-failure case stays unrecoverable there, which is no worse than the previous behavior (the deferred build throws, it does not reuse a partial set). Trivial clone overrides are added for the common query plan steps so the safe non-destructive path is taken for ordinary subquery shapes. The physical JoinStep is deliberately left without clone: stored source plans are logical (joins are JoinStepLogical, already clonable), so join subqueries take the destructive fallback instead of a fragile deep-clone of IJoin.

A ONCE failpoint prepared_sets_build_ordered_set_inplace_fail is added to CreatingSetsTransform::generate (it skips finishInsert), so the regression test 04489_not_ready_set_inplace_build exercises the silent-failure path deterministically.

This is an alternative to #102192. That PR adds a 33-line JoinStep::clone that deep-clones IJoin and changes behavior for the other clone consumers; this PR drops that deep-clone, builds the speculative set into a temporary set so an interrupted build cannot corrupt the canonical set, and keeps the speculative build out of PreparedSetsCache.

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):

Fix the Not-ready Set is passed as the second argument exception that could occur when building an IN subquery set during primary key analysis failed silently (for example, a subquery timeout with overflow_mode = 'break'), leaving the set permanently unbuilt for the query pipeline.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.802 (included in 26.7 and later)

…ctive

`FutureSetFromSubquery::buildOrderedSetInplace` is a speculative build run
during primary key / skip index analysis for an `IN` subquery. It built the
set through the destructive `build`, which moves the subquery `source` plan
out of the future-set; building a pipeline then consumes it.

If the in-place pipeline stops without creating the set (e.g. a subquery
timeout with `overflow_mode = 'break'`, or any early stop that skips
`CreatingSetsTransform::generate` and therefore `Set::finishInsert`),
`buildOrderedSetInplace` returns `nullptr`, but `source` has already been
consumed. The authoritative deferred build
(`DelayedCreatingSetsStep::makePlansForSets`) then finds `source == nullptr`,
attaches no set-building step to the pipeline, and `FunctionIn` throws
"Not-ready Set is passed as the second argument" when the query runs.

Fix: run the in-place pipeline against a clone of `source` (via the existing
`QueryPlan::clone`) and keep the original intact, resetting it only after the
set is actually created. If a step in the plan does not support `clone`
(`NOT_IMPLEMENTED`), skip the in-place optimization and return `nullptr`
*without* consuming `source` — fail-close, so the deferred build can always
rebuild the set. This makes the exception impossible for every plan shape;
losing primary key analysis for a non-clonable subquery only costs
performance. The speculative build no longer shares its result through
`PreparedSetsCache`, so a silent failure cannot poison the key for the
deferred build.

Trivial `clone` overrides are added for the common query plan steps so the
optimization is preserved for ordinary subquery shapes. The physical
`JoinStep` is deliberately left without `clone`: stored source plans are
logical (joins are `JoinStepLogical`, already clonable), so join subqueries
take the safe fallback instead of a fragile deep-clone of `IJoin`.

A `ONCE` failpoint `prepared_sets_build_ordered_set_inplace_fail` is added to
`CreatingSetsTransform::generate` (skips `finishInsert`) so the regression
test `04357_not_ready_set_inplace_build` exercises the silent-failure path
deterministically.

This is an alternative to #102192
that follows the fail-close principle (its `NOT_IMPLEMENTED` fallback consumed
`source`, leaving the bug latent) and drops the risky `JoinStep` deep-clone.

Related: #102192
Related: #107619
Related: #104130
Related: #102803
Related: #102981

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9685248]

Summary: ✅


AI Review

Summary

This PR fixes the silent-failure Not-ready Set path by running speculative IN-subquery builds against a cloned QueryPlan and by publishing only a fully created temporary Set. That direction looks correct, but the current head still regresses the speculative build's execution contract: the clone drops the subquery's thread cap and concurrency-control flag, so the analysis-time pipeline can now run wider than the real execution plan. I would not approve until that is preserved.

Findings

⚠️ Majors

  • [src/Interpreters/PreparedSets.cpp:503] The non-destructive path clones only the plan nodes, so it loses the QueryPlan-level max_threads and concurrency_control already attached to the original subquery. QueryPlan::buildQueryPipeline applies those fields when building the source pipeline (src/Processors/QueryPlan/QueryPlan.cpp:259-275), and the interpreters set them on the original plan (src/Interpreters/InterpreterSelectQuery.cpp:2924-2927, src/Interpreters/InterpreterSelectQueryAnalyzer.cpp:408). As a result, the speculative in-place build can fan out with the default stream count and without concurrency control even when the authoritative runtime build would have been capped, which is an operational regression on large IN subqueries.
    Suggested fix: right after plan = std::make_unique<QueryPlan>(source->clone());, copy source->getMaxThreads() and source->getConcurrencyControl() onto plan.
Final Verdict

Status: ⚠️ Request changes
Minimum required action: preserve the original subquery plan's max_threads and concurrency_control on the cloned speculative plan before building the pipeline.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 18, 2026
Comment thread src/Interpreters/PreparedSets.cpp Resolved
… to destructive build for non-clonable sources

The previous version skipped the in-place optimization entirely (returning
`nullptr`) whenever a source step did not support `clone`. That regressed
primary key / skip index pruning for every subquery whose source is not
clonable — most notably `ReadFromPreparedSource`, which wraps an
already-materialized, single-use `Pipe` (dictionary, many system table, and
remote reads go through it). It broke the EXPLAIN-based pruning tests
`03302_analyzer_distributed_filter_push_down`,
`04202_inverse_dictionary_lookup_pruning_key_condition`,
`03928_materialized_cte_index`, `03928_materialized_cte_index_2`,
`01700_system_zookeeper_path_in`, `02859_replicated_db_name_zookeeper`, and
`01064_incremental_streaming_from_2_src_with_feedback`.

For a non-clonable source, fall back to the original destructive `build`
instead, so primary key analysis is still performed for such subqueries
exactly as before; only the rare silent-failure case stays unrecoverable
there, which is no worse than the previous behavior (the deferred build throws
`Not-ready Set is passed as the second argument`, it does not reuse a partial
set). Clonable sources still take the safe non-destructive path.

Also address the review comment that the speculative build mutated the
canonical `set_and_key->set` before the build was committed: with
`overflow_mode = 'break'` the pipeline can stop after
`CreatingSetsTransform::consume` has inserted a prefix of rows but before
`Set::finishInsert`, leaving partial rows in the set that the deferred build
reuses — corrupting the result of a non-deterministic subquery such as one
using `rand`. The non-destructive path now builds into a temporary `Set` and
publishes it into `set_and_key` only after `isCreated()`, so an interrupted
build never leaks partial rows into the canonical set.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/PreparedSets.cpp Resolved
…committed speculative build

The non-destructive path gave the speculative `CreatingSetsTransform` the real
`GLOBAL IN` `external_table`. `CreatingSetsTransform::consume` writes each block
to that table before `generate` / `finishInsert`, so a pass stopped by
`timeout_overflow_mode = 'break'` (or the failpoint) would leave a prefix of
rows in the temporary table; the deferred build then appends a second
evaluation, and remote shards would see the failed prefix plus the real build
while the local `Set` contains only the real build.

Keep `external_table` null on the temporary `SetAndKey` so the speculative
pipeline never touches the real table, and populate it from the committed set
afterwards via `buildExternalTableFromInplaceSet` (the same path
`setExternalTable` uses), only once `isCreated()` is true. The deferred build is
then skipped, so this is the single, atomic population of the table. On the
destructive fallback the external table is still written by `build`'s
`CreatingSetsTransform`, exactly as before.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/PreparedSets.cpp Resolved
Comment thread src/Interpreters/PreparedSets.cpp Resolved
alexey-milovidov and others added 2 commits June 19, 2026 21:58
The non-destructive in-place set build added by this PR (cloning `source`
instead of consuming it) left the `GLOBAL IN` / `GLOBAL JOIN` external table
untouched during `FutureSetFromSubquery::buildOrderedSetInplace` and repopulated
it from the committed set afterwards via `buildExternalTableFromInplaceSet`. That
broke two things:

- The network transfer limits `max_rows_to_transfer` / `max_bytes_to_transfer`
  are enforced in `CreatingSetsTransform::consume` only while streaming rows into
  the external table. With the table left empty during the speculative build the
  check never fired, so queries that must fail with `SET_SIZE_LIMIT_EXCEEDED`
  succeeded silently. This is the regression caught by
  `04204_global_in_join_max_rows_to_transfer_103333` under the old analyzer.
- `Set::insertFromColumns` drops the explicit set elements once
  `use_index_for_in_with_subqueries_max_values` is exceeded, so rebuilding the
  external table from the set elements would lose rows.

Restrict the non-destructive path to subqueries without an external table. The
`GLOBAL IN` / `GLOBAL JOIN` case now uses the destructive `build`, exactly as
before this PR: it streams the subquery output into the external table during the
pipeline run and enforces the transfer limits there. The `Not-ready Set` fix is
retained for the common local `IN` case.

Also document why `DelayedCreatingSetsStep` (added to the source plan by a nested
`IN`) is intentionally left non-clonable: it holds the inner subqueries by shared
pointer and building it consumes their `source`, so a shallow clone would consume
the inner sources and mutate the canonical inner sets anyway, giving no real
preservation; that shape takes the destructive fallback, no worse than before.

Tests: renumber `04357_not_ready_set_inplace_build` to `04401` (the `04357`
prefix now collides with a test merged to master), extend it with a nested `IN`
case, and add `04402_global_in_set_max_values_external_table` covering `GLOBAL IN`
with a small `use_index_for_in_with_subqueries_max_values`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed d3cc487 (on top of a clean master merge) to address the AI Review ❌ Block and the failing 04204_global_in_join_max_rows_to_transfer_103333 (it was failing under the old analyzer: the query that must throw SET_SIZE_LIMIT_EXCEEDED succeeded silently).

Root cause. The non-destructive in-place build left the GLOBAL IN / GLOBAL JOIN external table empty during the speculative pass and repopulated it afterwards from the committed set via buildExternalTableFromInplaceSet. But the network transfer limits (max_rows_to_transfer / max_bytes_to_transfer) are enforced in CreatingSetsTransform::consume only while streaming rows into the external table — with the table empty during the build, the check never fired. The same approach also lost rows whenever use_index_for_in_with_subqueries_max_values was exceeded and Set::insertFromColumns dropped the explicit set elements.

Fix. Take the non-destructive (clone) path only when there is no external table. The GLOBAL IN / GLOBAL JOIN case now uses the destructive build exactly as before this PR — streaming the external table during the pipeline run and enforcing the transfer limits there — so both the limit and the use_index_for_in_with_subqueries_max_values cases are correct again. The Not-ready Set fix is retained for the common local IN case.

Nested IN (the DelayedCreatingSetsStep Major). Left non-clonable on purpose: it holds the inner subqueries by shared_ptr and building it std::moves their source, so a shallow clone gives no real preservation and would mutate the canonical inner sets during speculation. That shape takes the destructive fallback — identical to pre-PR behavior, no regression. Documented in code and the threads.

Tests.

  • Restored 04204_global_in_join_max_rows_to_transfer_103333 (verified under both analyzers locally).
  • Added 04402_global_in_set_max_values_external_table for GLOBAL IN with a small use_index_for_in_with_subqueries_max_values.
  • Renumbered 04357_not_ready_set_inplace_build → 04401 (the 04357 prefix now collides with 04357_geojson_real_world on master) and extended it with a nested-IN case.

Verified locally against a server built from this branch: 04204, 04401, 04402, 03269_explain_unique_ids, the 02841_not_ready_set_* suite, the set-index tests, and the distributed GLOBAL IN tests all pass.

alexey-milovidov and others added 2 commits June 29, 2026 17:29
…llision

After merging master, many other tests now use the 04401 and 04402
prefixes. Move both regression tests added by this PR
(`not_ready_set_inplace_build` and `global_in_set_max_values_external_table`)
to the next free numbers.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged a clean `master` (the branch was 226 commits behind and the only red checks were flakes). The merge had no conflicts and the net diff is unchanged (34 files, +346/-13); test numbers `04489`/`04490` still do not collide with master (which tops out at `04488`). Re-checked `PreparedSets.cpp`, `CreatingSetsTransform.cpp`, `FailPoint.cpp`, `SortingStep.cpp`, and `TotalsHavingStep.cpp` against the merged tree with -fsyntax-only — all clean (the IQueryPlanStep::clone signature and the TotalsHavingStep members the custom copy constructor enumerates are unchanged on master).

The two non-green checks are both Hung check failed, possible deadlock found (Stress test amd_tsan / arm_tsan), which is the chronic master-wide flake #107941 that the CI report already links — not related to this change. All four review threads are resolved and the AI Review verdict is ✅ Approve; the PR is MERGEABLE, pending requested human reviews.

Comment thread src/Interpreters/PreparedSets.cpp Resolved
Comment thread src/Interpreters/PreparedSets.cpp Resolved
…eline

On the non-destructive (clone) path of `FutureSetFromSubquery::buildOrderedSetInplace`,
the speculative pipeline is built from `source->clone()`. `QueryPlan::clone` copies the
plan nodes only, not the `QueryPlanResourceHolder`, so the cloned plan — and therefore the
pipeline built from it — carries an empty resource holder. The interpreter contexts, storage
holders, and table locks that processors may use implicitly (including in their destructors)
are held only by the original `source`.

Previously `source.reset()` ran while `executor` and `pipeline` were still alive, releasing
those resources before the processors were destroyed. Run the pipeline in its own scope so
the executor and pipeline are destroyed first, and reset `source` only afterwards. On the
destructive fallback `build` moved the resources into `plan`, which already outlives the
scope, so the ordering is correct there too.

Also document that a `MATERIALIZED` CTE referenced by a local `IN` subquery contains a
non-clonable `DelayedMaterializingCTEsStep` and therefore takes the destructive fallback,
identical to the pre-PR behavior for that shape.

This addresses the AI Review lifetime finding on the cloned speculative pipeline.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…t-inplace-build

Fix "Not-ready Set" exception by making in-place set build non-destructive
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 13, 2026
`prepared_sets_build_ordered_set_inplace_fail` was added in ClickHouse#107924 to simulate a
*speculative* in-place set build that stops without creating its set, so that the
runtime deferred build has to recover it. The injection lives in
`CreatingSetsTransform::generate()`, but that transform serves both builds: the
in-place one (`FutureSetFromSubquery::buildSetInplace` / `::buildOrderedSetInplace`)
and the ordinary runtime one under `DelayedCreatingSetsStep`. The failpoint's own
comment asserted the narrow scope, and nothing enforced it: it held only while an
in-place build happened to be the first `generate()` call after the arm.

`SYSTEM ENABLE FAILPOINT` is server-wide and a `ONCE` arm survives until the first
`generate()` call anywhere in the process. When that call belongs to an unrelated
query's runtime build, `generate()` returns before `Set::finishInsert()`, so
`Set::isCreated()` stays false, `FutureSetFromSubquery::get()` returns nullptr, and
`FunctionIn::executeImpl` raises LOGICAL_ERROR from inside an already-running
`FilterTransform`, aborting a debug or sanitizer server. Only the in-place path has
a recovery, so nothing rescues the runtime build. In CI this is armed on purpose by
BuzzHouse and replayed verbatim by the AST fuzzer out of the corpora of
04489_not_ready_set_inplace_build.sql and 04697_shared_set_error_not_inherited.sh,
which is why the abort lands on queries that never asked for a set at all.

Carry the discriminator on the individual set build: `CreatingSetStep` gains
`speculative_build`, threaded through `FutureSetFromSubquery::build()` and set true
only at the three in-place construction sites, and
`CreatingSetsTransform::generate()` consults it before `fiu_do_on`. The check
precedes the injection rather than sitting inside it, because `fiu_fail` on a
`FIU_ONETIME` point consumes the shot: an inside check would let a runtime build
spend the shot and leave the speculative build it was armed for running unfaulted.

The flag deliberately travels on the step and not on `BuildQueryPipelineSettings`.
One settings object serves an entire plan, and `addPlansForSets` splices runtime set
plans in as children of that same plan, so a pipeline-wide flag would also mark
runtime `CreatingSetStep`s nested inside an in-place build's plan, including lazy
FINAL's internal set. That is a narrower version of the same bug. For the same
reason the nested `DelayedCreatingSetsStep` an in-place destructive fallback can
carry expands through `makePlansForSets` with the flag false, so its inner canonical
sets stay classified as runtime and the shot cannot abandon them.

Every new parameter is defaulted, and all five `build()` call sites state their value
explicitly so a future caller has to make the choice rather than inherit it. The
injected state is otherwise byte-identical, which is why 04489 and 04697 pass
unchanged; they remain the live proof that the in-place injection still fires.

Related: ClickHouse#118722

Co-Authored-By: Claude Opus 5 <[email protected]>
alexey-milovidov added a commit to alexey-milovidov/ClickHouse that referenced this pull request Oct 2, 2026
…ause

`master` has since merged and repeatedly extended its own fix for the lost
subquery plan in `FutureSetFromSubquery::buildOrderedSetInplace` (ClickHouse#107924 and
follow-ups: clone-based speculative build, `in_place_build_failure`,
`inplace_build_mutex`, the recoverable-build scope of the
`prepared_sets_build_ordered_set_inplace_fail` failpoint, distributed-plan
support). This branch's alternative implementation (query-plan rebuild
callbacks, the `GLOBAL IN` transfer-limit deferral and the
`hasUnbuiltSubquerySet` guards for synchronous consumers) conflicts with all of
it and can no longer be reconciled without re-implementing those changes.

Conflict resolution: take `master`'s implementation of the in-place set build
(`PreparedSets.{h,cpp}`, `QueryPlan.cpp`, `IQueryPlanStep`, the call sites of
`addFromSubquery`, `MergeTreeData.cpp`, `VirtualColumnUtils`,
`03269_explain_unique_ids.reference`, `ci/defs/darwin.skip`) and drop the tests
that only covered the dropped machinery (`04093` duplicates `master`'s `04489`;
`04401` covered the transfer-limit deferral). The part `master` still lacks,
the `GLOBAL IN` external-table case, is ported on top in the next commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
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]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants