Repository navigation
Build the PREWHERE and row-level filter sets when a query is planned to FetchColumns - #118359
Conversation
Planner::buildPlanForQueryNode returned early when to_stage == FetchColumns, and that early return preceded both the useful_sets construction and the sole call of addBuildSubqueriesForSetsStepIfNeeded. setQueryPlan is the only thing that ever fills FutureSetFromSubquery::source, and it is reached only from inside that builder, so a planner run at that stage could never attach a set source: the in-place builders no-op silently, no DelayedCreatingSetsStep is added, and the reader threads abort in FunctionIn::executeImpl (in.cpp:155) below MergeTreeRangeReader::executePrewhereActionsAndFilterColumns with "Not-ready Set is passed as the second argument for function 'globalIn'". A read at FetchColumns still evaluates PREWHERE and row-level filter expressions itself, so the sets they reference are genuinely needed there. The old analyzer adds the step unconditionally in InterpreterSelectQuery, so this restores parity rather than adding a special case. Moving the whole useful_sets initialization (not just the filter loop) also keeps join_tree_query_plan.useful_sets, which the early return dropped. The move is inert on the existing path: setPrewhereFilterActions and setRowLevelFilterActions have one caller each and both run before the early return, collectSets has already run, and the three statements the move crosses (PlannerQueryProcessingInfo, QueryAnalysisResult, buildExpressionAnalysisResult) never receive or mutate useful_sets. The !only_analyze gate is preserved, so the analyze-only path stays masked by the dry_run branch in in.cpp. The stage is reachable without any Merge or Distributed table, via clickhouse-client --stage fetch_columns. The regression test uses the shape with CI provenance instead: a Merge whose child column does not convert order-preservingly falls back to FetchColumns, and a Distributed child then forwards that stage to the shard, which plans the whole query there. Related: ClickHouse#96886
Every set in the test was the full key range 0..3, so each asserted count() was the same number whether the PREWHERE was applied or ignored entirely: an always-true predicate satisfied the reference. Restricting each set to k < 2 while the tables hold 0..3 makes the counts 8/8/4 instead of 16/16/8, so the assertions now fail if the set is built but the predicate is not applied. Verified by mutation: widening the sets back to the full key range reddens the test with 16 against the expected 8. The single-table control keeps returning its value on an unfixed build, so it still isolates the processing stage rather than merge plus GLOBAL IN.
A row policy is the reader's other set carrier, and it had no assertion: the shipped arms all carried the set in the query's own PREWHERE. The policy predicate holds the only set in its arm, and its PREWHERE k < 4 matches every row, so the asserted count is decided by the policy alone: 8 of the 16 rows the merge sees, against 16 with no policy. An earlier attempt at this arm failed because every spelling named a user table, and a policy predicate is re-resolved on the shard, where the test's database is not current, so the name could not resolve (Code: 60). Reading the numbers table function needs no database qualification and resolves identically on every node. The arm aborts an unfixed server in FunctionIn::executeImpl (in.cpp:155) below MergeTreeRangeReader::executePrewhereActionsAndFilterColumns, for function 'in'. Widening the policy to admit every key, or removing it, reddens the test with 16 against the expected 8. Related: ClickHouse#96886
Internal second-model reviewAn independent reviewer and a second model read this change cold before publication, over 4 rounds. ❌ Blockers: none in the fix. One was raised against the description's
💡 Noted, not blocking:
|
|
Workflow [PR], commit [4cfb88a] Summary: ✅
AI ReviewSummaryThis PR moves set-source attachment ahead of the Final Verdict✅ No findings. LLVM Coverage ReportMeasured on commit 4cfb88a.
Changed lines: Changed C/C++ lines covered: 18/18 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
|
|
cc @yakov-olkhovskiy @novikd, could you review this? |
|
TL;DR: the fix looks sound (checked the FetchColumns consumers — The old analyzer does not actually handle this shape: with Also seconding the in-body note about #114955: whichever PR merges second should drop the now-redundant set attachment in |
|
Confirmed on my own build, and the description is corrected. Re-measured your arm rather than transcribing it (table
Dropping One thing sharper than "zero rows": The description now reads "The old analyzer is no reference here: at that stage it silently returns no rows for the same query." My earlier reviewer cc comment on this PR carries the same wrong claim, and I am correcting it here rather than editing it away. On #114955, which is also mine: the redundant piece is the |
The distributed-plan test flavour sets serialize_query_plan = 1 for the whole job, and in that flavour every query over a Merge whose Distributed child is read at FetchColumns fails before it reaches any set: Code: 8. Cannot find column `__table1.k` in source stream, there are only columns: [] That path is broken on master independently of this change. Measured on the merge-base binary with prefer_localhost_replica = 0 and serialize_query_plan = 1: a set-free SELECT count() ... PREWHERE k < 4 over the same shape fails with the identical message, and so does the test's own query, so neither the sets this test covers nor the planner change here is involved. PR ClickHouse#113413 fixes that path. The pin does not weaken the test in that flavour: with it in place the merge-base binary still dies on "Not-ready Set is passed as the second argument for function 'globalIn'" (Functions/in.cpp:155 below MergeTreeRangeReader.cpp:1785) while this branch returns the expected counts, and six randomized runs pass with the flavour off. Related: ClickHouse#96886
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 19 s compile time in total, 7 of them have a recent master baseline. |
The `old analyzer` job flavour installs tests/config/users.d/analyzer.xml, which sets `allow_experimental_analyzer = 0` for the default profile, and the test then reddens deterministically there: every count collapses to 0 while the DESCRIBE lines and the single-table control still match. Measured through the runner in a sandbox with that profile installed, on the merge base (build id ef193c1ff55c08ec) and on this branch (08a658d25a2a84ae), with `prefer_localhost_replica = 0`: arm base this branch bare count(), no PREWHERE Code 8 Code 8 set-free PREWHERE k < 4 0 0 PREWHERE k IN (0, 1) 0 0 PREWHERE k GLOBAL IN (SELECT ...) 0 0 WHERE k GLOBAL IN (SELECT ...) 8 8 one Distributed table, PREWHERE GLOBAL IN 4 4 The old analyzer therefore cannot execute any PREWHERE over a `Merge` whose `Distributed` child is read at `FetchColumns`: it drops every row with no set in the query at all, and a bare `count()` over the same shape fails with THERE_IS_NO_COLUMN. Both results are identical on the two trees, so neither is introduced by this change, and neither is reachable by it: the planner it touches only runs with the analyzer enabled. Pinning the setting rather than tagging the test `no-old-analyzer` keeps it running on those jobs, which also carry s3 storage and Replicated databases. The pin does not weaken it: with the pin in place and the same profile installed, the merge-base binary still fails this test, with `Not-ready Set is passed as the second argument for function 'globalIn'` at Functions/in.cpp:155 in the server log. This branch passes 1 + 6 randomized runs under that profile, and 20 out of 20 randomized runs with the profile off.
Reproducer-- any query planned to FetchColumns; simplest route is the client's own --stage
-- clickhouse-client --stage fetch_columns
SET enable_analyzer = 1;
CREATE TABLE t_fc (k UInt64, v UInt64) ENGINE = MergeTree ORDER BY k;
INSERT INTO t_fc SELECT number, number FROM numbers(4);
SELECT count() FROM t_fc PREWHERE k IN (SELECT number FROM numbers(2));
-- 23.8 .. 26.8: Code: 49. DB::Exception: Not-ready Set is passed as the second
-- argument for function 'in' ... While executing MergeTreeSelect. (LOGICAL_ERROR)
-- 26.9+ (fixed): 0\n1 -- the PREWHERE-filtered k column, which is what this stage returnsResults:
Backport the fix to CC component owner: @KochetovNicolai @novikd Analysis metadata
Introducing change: not identified
|
Master now builds the sets of a table's PREWHERE and row-level filters when the planner stops at `FetchColumns` (ClickHouse#118359), which is what this branch's `addBuildSubqueriesForTableFilterSets` did for the re-planned read. Drop that duplicate. The planner builds those sets with `SelectQueryOptions::subquery()` of the read's own options, and that copy kept `ignore_rename_columns`. The read that `resolveStorages` plans again sets it so its output matches the shipped plan by source column name, and the set's subquery then renamed its own read back as well, failing with `NOT_FOUND_COLUMN_IN_BLOCK` (`Not found column __table1.number`). A subquery is consumed through column identifiers, so reset the flag in `subquery()`, like the other flags that describe only the read they were set for. This also hits master without this branch: a `Merge` table with an `IN (SELECT ...)` row policy, read through `Distributed` with `serialize_query_plan = 1` and `prefer_localhost_replica = 0`, failed the same way on a master build (`f272e3a3`), because `resolveStorages` plans a `Merge` read again with the same flag. 04908 gets an arm for it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #96886
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
Not-ready Set is passed as the second argument for function 'globalIn'when aPREWHEREor row-level filter expression containing anINsubquery is evaluated by a query planned to theFetchColumnsstage, for example a shard query behindMergeoverDistributed, orclickhouse-client --stage fetch_columns.Description
Planner::buildPlanForQueryNodereturned early whento_stage == FetchColumns, and that return preceded both theuseful_setsconstruction and the sole call ofaddBuildSubqueriesForSetsStepIfNeeded.setQueryPlan, reached only from inside that builder, is the only filler ofFutureSetFromSubquery::source, so aFetchColumnsplanner run could never attach a set source: noDelayedCreatingSetsStepis added and the reader threads abort inFunctionIn::executeImpl(in.cpp:155) belowMergeTreeRangeReader::executePrewhereActionsAndFilterColumns. A read at that stage still evaluatesPREWHEREand row-level filters itself, so those sets are needed there. The old analyzer is no reference here: at that stage it silently returns no rows for the same query.This moves the
useful_setsconstruction above the early return and calls the existing builder inside it, under the same!only_analyzegate. The adjacentaddBuildSubqueriesForMaterializedCTEsIfNeededis deliberately left alone: a set subquery over a materialized CTE already works there.Reachable two ways: a
Mergewhose child column does not convert order-preservingly falls back toFetchColumnsand aDistributedchild forwards that stage to the shard (reported failure, also on master); orclickhouse-client --stage fetch_columns, with noMergeorDistributed.Every asserted line of the new test aborts an unfixed server with that message and those frames (
'globalIn'for thePREWHEREarms,'in'for the row-policy one), and each count separates a filtered read from an unfiltered one. The arms cover the shard route, theprefer_localhost_replica = 1local plan, and a row policy as the reader's other set carrier; a single-table control passes on both trees, keeping the test keyed on the stage. A serial, randomization-free A/B over 145 related tests is identical on both trees.#114955 adds the same attachment in
resolveStorages.cpp, on the serialized-plan route and only when a row policy is re-planned there, so whichever merges second drops a now-redundant call.Workflow [PR]
Sync PR [sync-upstream/pr/118359]
Version info
26.9.1.1429(included in26.9and later)