Skip to content

Fix Not-ready Set exception when IN subquery is moved to PREWHERE - #100375

Merged
fm4v merged 36 commits into
masterfrom
fix-in-subquery-prewhere-not-ready-set
May 9, 2026
Merged

fm4v merged 36 commits into
masterfrom
fix-in-subquery-prewhere-not-ready-set

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 22, 2026 •

Copy link
Copy Markdown
Member

Linked issues

When optimizePrewhere moves a filter condition containing IN (subquery) from WHERE to PREWHERE, the set for the subquery may not have been built yet. buildSetsForDAG was only called in applyFilters, which runs before the PREWHERE optimization. After optimizePrewhere moves the condition via updatePrewhereInfo, the set remains unbuilt and causes a "Not-ready Set is passed" exception (LOGICAL_ERROR) during MergeTree data reading.

The fix calls buildSetsForDAG in ReadFromMergeTree::updatePrewhereInfo so that any sets in newly-assigned PREWHERE actions are built synchronously, matching the existing pattern already used in applyFilters.

Reproduces with a query that combines UNION ALL, a window function, and IN (subquery) on a MergeTree table with multiple parts — the IN condition gets moved to PREWHERE, but its set was never built.

Fixes #100318

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 "Not-ready Set" exception when a filter with IN (subquery) is moved to PREWHERE by the query optimizer.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.465
  • Backported to: 26.4.3.5, 26.3.11.7, 26.2.19.9

When `optimizePrewhere` moves a filter condition containing `IN (subquery)`
from WHERE to PREWHERE, the set for the subquery may not have been built yet.
`buildSetsForDAG` was only called in `applyFilters`, which runs before the
PREWHERE optimization. After `optimizePrewhere` moves the condition, the set
remains unbuilt and causes a "Not-ready Set is passed" exception during
MergeTree data reading.

Fix by calling `buildSetsForDAG` in `ReadFromMergeTree::updatePrewhereInfo`
so that any sets in newly-assigned PREWHERE actions are built synchronously.

Fixes #100318

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

clickhouse-gh Bot commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [72c3892]

Summary: ✅


AI Review

Summary

This PR fixes a real correctness issue where IN (subquery) conditions moved to PREWHERE could hit a Not-ready Set exception, and it adds safeguards/tests around GLOBAL IN handling so those sets are not forced through an unsafe synchronous build path. The final state is coherent across optimizer logic, set-building behavior, and regression coverage, with no additional blocker or major issue found.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 22, 2026
alexey-milovidov and others added 4 commits March 22, 2026 19:16
When `optimizePrewhere` moves a filter with `GLOBAL IN (subquery)` to
PREWHERE, the synchronous `buildSetsForDAG` call in `updatePrewhereInfo`
would build the set before `ReadFromRemote` had a chance to attach an
external table via `setExternalTable`. This caused a LOGICAL_ERROR:
"Trying to attach external table to a ready set without explicit elements".

Add `buildSetsForDAGExcludingGlobalIn` that skips sets used as arguments
to `globalIn`/`globalNotIn` functions. Those sets will be built later by
the pipeline-level `CreatingSetsTransform` after external tables are set up.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Storages/VirtualColumnUtils.cpp Resolved
alexey-milovidov and others added 2 commits March 29, 2026 00:26
- Update `02967_parallel_replicas_joins_and_analyzer` reference: remove
  `CreatingSet` steps that no longer appear in EXPLAIN output because
  sets for IN subqueries are now built synchronously in `updatePrewhereInfo`.

- Update `03800_autopr_reuse_index_analysis` reference: adjust
  `IndexAnalysisRounds` counts that increased because the parallel replicas
  plan now also builds sets via `buildSetsForDAGExcludingGlobalIn`, causing
  additional index analysis passes for IN subqueries.

- Address review feedback: extend GLOBAL IN exclusion in
  `buildSetsForDAGExcludingGlobalIn` to also skip `globalNullIn` and
  `globalNotNullIn` (null-aware GLOBAL IN variants used with
  `transform_null_in`), which also require external table attachment.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 5 commits March 30, 2026 03:18
Extract `functionIsGlobalInOperator` helper in `misc.h` and use it in
`buildSetsForDAGExcludingGlobalIn` instead of hardcoded string comparisons.

Add a dedicated test for `GLOBAL IN` moved to PREWHERE with
`transform_null_in = 1` to cover null-aware global variants
(`globalNullIn`/`globalNotNullIn`).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…collision

GLOBAL IN sets are populated via external tables attached by `ReadFromRemote`
and cannot be built synchronously during PREWHERE evaluation. Instead of
trying to skip them in `buildSetsForDAGExcludingGlobalIn` (which leaves the
sets unbuilt and causes "Not-ready Set" errors), prevent the optimizer from
moving GLOBAL IN conditions to PREWHERE in the first place via `cannotBeMoved`.

Also rename `04068_global_in_subquery_prewhere` to `04070_global_in_subquery_prewhere`
to avoid collision with `04068_constant_fold_union_intersect` from master.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Since `globalIn`/`globalNotIn` conditions are now prevented from
being moved to PREWHERE, the WHERE step in EXPLAIN output changes
from `Expression` to `Filter` for GLOBAL IN queries (the filter
remains in WHERE instead of being absorbed by PREWHERE).

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

Copy link
Copy Markdown
Member Author

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The flaky check failure is fixed in #102148, let's update the branch.

alexey-milovidov and others added 5 commits April 23, 2026 22:12
… pushdown

When `updatePrewhereInfo` built IN-subquery sets synchronously via
`buildSetInplace`, the resulting `Set` had `isCreated()==true` but no
explicit elements. Subsequent primary-key and skip-index analysis in
`KeyCondition` / `MergeTreeIndexSet` / bloom-filter / text-index
conditions uses `FutureSetFromSubquery::buildOrderedSetInplace`, which
early-returns `nullptr` on a created-but-empty set — so the set cannot
be used for index filtering and the table is scanned fully.

This manifested on parallel-replicas shards with
`parallel_replicas_local_plan=1` and
`parallel_replicas_index_analysis_only_on_coordinator=1`, where
`ReadFromMergeTree::selectRangesToReadImpl` skips local index analysis
(so `KeyCondition`'s ordered build never runs first) and our unordered
build wins the race. Local `IN (subquery)` queries then lost PK /
skip-index pruning, causing `TOO_MANY_ROWS` failures in
`01583_const_column_in_set_index`, `01585_use_index_for_global_in` and
inflated `ReadCompressedBytes` in
`03801_autopr_input_bytes_estimation_query_with_subqueries`.

Fix: prefer `buildOrderedSetInplace` in `buildSetsForDAGExcludingGlobalIn`,
falling back to `buildSetInplace` only when `use_index_for_in_with_subqueries`
is disabled (in which case the ordered path returns `nullptr` without
building, so we still need the unordered build to satisfy the original
"Not-ready Set" fix).
`04060_explain_pretty_joins_sets`: now that `buildSetsForDAGExcludingGlobalIn`
also builds the non-PK side of `b IN subquery1 AND a IN subquery2`, the
`CreatingSets` step has a single `ReadFromMergeTree` child, with no
remaining `CreatingSet` for `subquery1` (the set is already populated).

`03800_autopr_reuse_index_analysis`: pin `query_plan_optimize_prewhere = 1`
on queries 3, 4, 5. Without the pin, randomized CI runs that flip
`query_plan_optimize_prewhere = 0` skip `optimizePrewhere` (and therefore
the synchronous `buildSetsForDAGExcludingGlobalIn` call), producing fewer
`IndexAnalysisRounds` than the reference expects.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100375&sha=8085f6c1d87be999ed8573d5f67a2618cc1ea61e

PR: #100375

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
fm4v added a commit that referenced this pull request May 9, 2026
…ot-ready-set

Fix Not-ready Set exception when IN subquery is moved to PREWHERE

(cherry picked from commit 0f0e7dd)
fm4v added a commit that referenced this pull request May 9, 2026
…ot-ready-set

Fix Not-ready Set exception when IN subquery is moved to PREWHERE

(cherry picked from commit 0f0e7dd)
robot-ch-test-poll3 added a commit that referenced this pull request May 9, 2026
Cherry pick #100375 to 26.2: Fix Not-ready Set exception when IN subquery is moved to PREWHERE
robot-clickhouse added a commit that referenced this pull request May 9, 2026
robot-ch-test-poll3 added a commit that referenced this pull request May 9, 2026
Cherry pick #100375 to 26.3: Fix Not-ready Set exception when IN subquery is moved to PREWHERE
robot-clickhouse added a commit that referenced this pull request May 9, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label May 9, 2026
alexey-milovidov added a commit that referenced this pull request May 18, 2026
…ex_granularity (#104162)

Random settings limit only had an upper bound on `index_granularity` and no
limits on `index_granularity_bytes`. With no lower bound, the test runner
randomized `index_granularity` down to 27 (and `index_granularity_bytes` can
be as low as 1024), producing 7400+ granules over the 200K-row table.

The 300s client timeout fired while `ALTER TABLE test MODIFY COLUMN json JSON
SETTINGS mutations_sync=1` rewrote all parts. Each granule contributes
per-mark overhead that compounds with MSan + WasmEdge slowdown plus parallel
CI contention.

CIDB shows the same failure across 3 unrelated runs in 30 days (PR #100947,
master 76e37f1, PR #100375), all in
`Stateless tests (amd_msan, WasmEdge, parallel, 1/2)`, all with
`index_granularity` in {27, 18, 28}.

Locally measured (debug build, 200K rows, JSON `ALTER MODIFY`):
- default `index_granularity=8192`           24 granules, 0.21s
- failing  `index_granularity=27`           7408 granules, 1.62s
- pathological `index_granularity_bytes=1024` 7408 granules, 1.62s
- proposed floor `index_granularity=100, bytes=10000` 2001 granules, 0.59s

Mirrors the limits already used by the source test
`03246_alter_from_string_to_json.gen.sql` from which 03381 was derived.

Per @alexey-milovidov's request on
#100375 (comment)...

Co-authored-by: Groene AI <[email protected]>
Co-authored-by: Alexey Milovidov <[email protected]>
@watson-ch watson-ch Bot added v25.12-must-backport v25.8-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels May 19, 2026
@watson-ch

watson-ch Bot commented May 19, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/ClickHouse/clickhouse-core-incidents/issues/1079

Labels added:

  • v25.8-must-backport
  • v25.12-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

@robot-ch-test-poll2 robot-ch-test-poll2 added pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore labels May 19, 2026
azat pushed a commit to azat/ClickHouse that referenced this pull request Jun 16, 2026
… partitioned tables

A SELECT over a MergeTree table with a PARTITION BY key threw
"Not-ready Set is passed as the second argument for function 'in'"
(LOGICAL_ERROR) when an IN/NOT IN subquery was used inside a larger
expression rather than as a top-level filter conjunct, for example:

    SELECT c0 FROM t WHERE (c0 IN (SELECT ...)) != 0;

ReadFromMergeTree::applyFilters builds IN-subquery sets synchronously for
the PREWHERE and row-level-filter DAGs (the latter was the fix for ClickHouse#100375),
but not for the index/partition-pruning DAG. KeyCondition only builds sets
for top-level IN atoms, so when the IN is wrapped in an expression the set is
never prepared and is then executed unbuilt during PartitionPruner key
analysis, raising the LOGICAL_ERROR.

Build the sets for the index filter DAG as well, using the existing
buildSetsForDAGExcludingGlobalIn helper. It prefers the ordered build (so the
set retains explicit elements that KeyCondition needs for primary-key and
skip-index analysis) and excludes GLOBAL IN, whose sets must be populated by
ReadFromRemote first. The call is placed after buildIndexes (so KeyCondition's
ordered builds for top-level key INs run first) and before the PREWHERE builds
(so a ColumnSet shared with PREWHERE keeps its explicit elements). This is the
partition-pruning counterpart of the PREWHERE fix in ClickHouse#100375.

Closes: ClickHouse#107503

Co-Authored-By: Claude Opus 4.8 <[email protected]>
yonas pushed a commit to yonasBSD/ClickHouse that referenced this pull request Jun 20, 2026
nullIn / notNullIn on a not-ready IN-subquery set inside an ANY JOIN
filter used to abort with LOGICAL_ERROR "Not-ready Set is passed as
the second argument for function 'nullIn'" during the plan-time
dry-run in convertAnyJoinToSemiOrAntiJoin (STID 0250-4409). The crash
path is the dry-run evaluation in filterResultForMatchedRows reaching
FunctionIn::executeImpl on a future set whose Set is not yet built.

The bug is already fixed on master by ClickHouse#100375 (dagContainsNonReadySet
guard in filterResultForMatchedRows) together with the dry-run guard in
FunctionIn::executeImpl. This adds a deterministic stateless test that
covers the nullIn / notNullIn variants and the INTERSECT ALL shape from
the original fuzzer query, which the existing 04305 / 04310 tests (plain
in / globalIn / notIn) do not exercise.

Verified by reverting both guards locally: all four queries abort with
the exact STID 0250-4409 error; with master HEAD they run clean and
return the expected rows.

Closes: ClickHouse#104130

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v25.12-must-backport v26.2-must-backport v26.3-must-backport v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FunctionIn_Aborted

7 participants