Skip to content

Build the PREWHERE and row-level filter sets when a query is planned to FetchColumns - #118359

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/build-prewhere-sets-at-fetch-columns-stage
Sep 13, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/build-prewhere-sets-at-fetch-columns-stage

Conversation

@groeneai

@groeneai groeneai commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #96886

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

Fixed Not-ready Set is passed as the second argument for function 'globalIn' when a PREWHERE or row-level filter expression containing an IN subquery is evaluated by a query planned to the FetchColumns stage, for example a shard query behind Merge over Distributed, or clickhouse-client --stage fetch_columns.

Description

Planner::buildPlanForQueryNode returned early when to_stage == FetchColumns, and that return preceded both the useful_sets construction and the sole call of addBuildSubqueriesForSetsStepIfNeeded. setQueryPlan, reached only from inside that builder, is the only filler of FutureSetFromSubquery::source, so a FetchColumns planner run could never attach a set source: no DelayedCreatingSetsStep is added and the reader threads abort in FunctionIn::executeImpl (in.cpp:155) below MergeTreeRangeReader::executePrewhereActionsAndFilterColumns. A read at that stage still evaluates PREWHERE and 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_sets construction above the early return and calls the existing builder inside it, under the same !only_analyze gate. The adjacent addBuildSubqueriesForMaterializedCTEsIfNeeded is deliberately left alone: a set subquery over a materialized CTE already works there.

Reachable two ways: a Merge whose child column does not convert order-preservingly falls back to FetchColumns and a Distributed child forwards that stage to the shard (reported failure, also on master); or clickhouse-client --stage fetch_columns, with no Merge or Distributed.

Every asserted line of the new test aborts an unfixed server with that message and those frames ('globalIn' for the PREWHERE arms, 'in' for the row-policy one), and each count separates a filtered read from an unfiltered one. The arms cover the shard route, the prefer_localhost_replica = 1 local 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

  • Merged into: 26.9.1.1429 (included in 26.9 and later)

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
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent reviewer and a second model read this change cold before publication, over 4 rounds.
The final round raised nothing.

❌ Blockers: none in the fix. One was raised against the description's serialize_query_plan
claim and disagreed with on the second model's own control; the claim has since been removed anyway
(third item below).

⚠️ Majors, all test-strength, all fixed before publication:

  • The asserted counts did not discriminate a filtered read from an unfiltered one, because every key
    was in the set, so an always-true PREWHERE mutant passed. Every set is now a strict subset of the
    keys present; widening one back reddens the arm with 16 against 8.
  • The row-level filter carrier named in the changelog entry had no coverage. The first attempt
    concluded it was untestable from a stateless .sql, because a policy predicate is re-resolved on
    the shard, where the test's database is not current, so an unqualified table name cannot resolve.
    That holds for every spelling naming a user table, but not for numbers, which needs no
    qualification. The arm is now in the test, mutation-proven against both a widened policy and no
    policy at all.
  • A serialize_query_plan = 1 arm added mid-review asserted nothing about serialization and has been
    removed rather than left in place. Both shards of test_cluster_two_shards_localhost are the same
    local server, so at prefer_localhost_replica = 1 each takes emplace_local_stream, whose
    createLocalPlan call leaves build_logical_plan false, and serialize_query_plan is read only on
    the emplace_remote_stream side. It reddened on master for the ordinary reason and would have
    stayed green if plan serialization regressed.

💡 Noted, not blocking:

  • The plan-serializing producer has no arm, in either direction. Reaching it needs
    serialize_query_plan = 1 together with prefer_localhost_replica = 0, and that pair hits a
    pre-existing analyzer failure to resolve __table1.k, identical on master and on this branch
    (Return column names, not analyzer identifiers, from a Distributed read at FetchColumns #113413). prefer_localhost_replica = 0 on its own is the shipped arm and passes. The fix is keyed
    on the processing stage rather than on how the query reached the server, so it applies there too,
    but that is reasoning and not a measurement.
  • The DESCRIBE line pins the merged header type, which is what forces the FetchColumns
    fallback today, not the processing stage itself. If that computation were ever narrowed to the
    columns a query needs, the guard would stay green while the test stopped exercising this branch. No
    stateless .sql can assert the shard's stage, so this is recorded rather than worked around.
  • A row policy whose predicate subqueries a table is unusable through a Distributed/Merge read
    (UNKNOWN_TABLE on the shard). Pre-existing, unrelated to this site, not raised.

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4cfb88a]

Summary: ✅


AI Review

Summary

This PR moves set-source attachment ahead of the FetchColumns early return so PREWHERE and row-level filters that contain IN subqueries still receive a runnable set plan on shard/local-fetch executions. After reading the current diff, the touched planner and read-side paths, and the full prior PR discussion, I did not find a remaining correctness issue in the patched behavior or a missing regression test for the scope this PR claims to fix.

Final Verdict

✅ No findings.

LLVM Coverage Report

Measured on commit 4cfb88a.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.10% -0.10%

Changed lines: Changed C/C++ lines covered: 18/18 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, two independent ones, no randomization and no fuzzer. clickhouse client --stage fetch_columns --query "SELECT count() FROM t_local PREWHERE A GLOBAL IN (SELECT A FROM t_local)", and the shipped test's merge() over two type-mismatched Distributed children with prefer_localhost_replica = 0.
b Root cause explained? The to_stage == FetchColumns early return in Planner::buildPlanForQueryNode preceded both the useful_sets construction and the sole call of addBuildSubqueriesForSetsStepIfNeeded. setQueryPlan is the only filler of FutureSetFromSubquery::source and is reached only from that builder, so such a run never attaches a source, the in-place builders no-op silently, and the reader throws at in.cpp:155 below MergeTreeRangeReader::executePrewhereActionsAndFilterColumns.
c Fix matches root cause? Yes. The fix is at the site that decides whether the source is attached; in.cpp, the in-place builders and SetsSerialization are all consumers of that decision, so guarding any of them would be a symptom guard.
d Test intent preserved / new tests added? New 05099_prewhere_global_in_fetch_columns_stage.{sql,reference}, covering both set carriers the reader evaluates: PREWHERE, and a row-level filter whose predicate holds the only set in the query. A pinned DESCRIBE TABLE guards the stage trigger against silent loss and a control line passes without the fix. Every asserted count discriminates a filtered read from an unfiltered one, shown by mutation: widening the row policy, or removing it, turns the expected 8 into 16. No existing test weakened, no assertion widened.
e Both directions demonstrated? Yes. On master the test reports server died with Not-ready Set ... 'globalIn', in.cpp:155, MergeTreeRangeReader.cpp:1785; with the fix it passes. Reverting only the hoisted call and keeping the move reproduces the failure, so the call is what fixes it, and with the fix the shard reads emit the four Creating set lines that are absent on master.
f Fix is general across code paths? One root cause: the early return is the single site deciding whether a set source is attached, so every route below it is covered - the query arriving over TCP, createLocalPlan and --stage fetch_columns - as are all three carriers, PREWHERE, the row-level filter and the join-tree plan's own sets. The whole useful_sets initialization moves, not only the filter loop, so the join-tree sets are not dropped. The shipped test asserts the TCP route, the createLocalPlan route and both reader-evaluated carriers, each reddening on master and passing with the fix. The plan-serializing producer deliberately has no arm: reaching it needs serialize_query_plan = 1 together with prefer_localhost_replica = 0, and that pair hits a pre-existing analyzer failure to resolve __table1.k, identical on both trees (#113413), so no arm there could distinguish them. (prefer_localhost_replica = 0 on its own is the shipped TCP arm and passes; it is the pair that fails.) This restores parity with the old analyzer, which adds the step unconditionally.
g Fix generalizes across inputs (params/datatypes/wrappers)? The defect is a missing plan pointer, so it is type- and value-independent and a datatype matrix would be enumeration. Measured instead across the axes that change the plan: prefer_localhost_replica 0 and 1 (both shipped as assertions), optimize_read_in_order, GLOBAL IN vs IN (both reproduce, in the query and in a policy predicate), a CTE feeding the set, and one vs two merge() children. serialize_query_plan is not an axis on this fixture: on the local route it is never read, and paired with prefer_localhost_replica = 0 it hits the pre-existing failure noted in (f).
h Backward compatible? (maintainer-approved exception only) Yes. No new or changed setting, no default change, no serialized-format change, so no SettingsChangesHistory.cpp entry is needed. DelayedCreatingSetsStep preserves the header and is skipped by plan serialization. Behaviour changes only from throwing to working.
i Invariants and contracts preserved? useful_sets is still read only after both filter-action setters have run, and both have exactly one caller each, before the early return. collectSets has already run. The three statements the move crosses never receive or mutate useful_sets. The !only_analyze gate is preserved verbatim, so the analyze-only path is unchanged and still masked by in.cpp:151.

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @novikd, could you review this? Planner::buildPlanForQueryNode returned early at to_stage == FetchColumns, before the sole call that attaches a plan to a set subquery, so a PREWHERE or row-level filter carrying an IN subquery reached the reader with a not-ready set and threw a logical error. This hoists the useful_sets construction above that return and calls the existing builder there under the same !only_analyze gate, restoring parity with the old analyzer.

@zlareb1

zlareb1 commented Sep 6, 2026

Copy link
Copy Markdown
Member

TL;DR: the fix looks sound (checked the FetchColumns consumers — StorageMerge, Distributed local plan, parallel replicas, mutations, StorageBuffer — for double application or shape breakage: none). One factual note on the PR description's parity claim.

The old analyzer does not actually handle this shape: with allow_experimental_analyzer = 0, clickhouse local --stage fetch_columns and SELECT k FROM t PREWHERE k IN (SELECT number FROM numbers(2)) returns zero rows with exit code 0, while the literal form PREWHERE k IN (0, 1) returns the expected rows (verified on a 26.9 build). So pre-fix the new analyzer threw Not-ready Set loudly and the old analyzer silently dropped all rows for the same query. That is pre-existing and the old analyzer is deprecated, so nothing to do in this PR — just flagging it since the description presents the old-analyzer behavior as the reference.

Also seconding the in-body note about #114955: whichever PR merges second should drop the now-redundant set attachment in resolveStorages.cpp — with both in, the replan path builds duplicate set-building steps (harmless but dead weight).

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed on my own build, and the description is corrected.

Re-measured your arm rather than transcribing it (table t with k = 0..3, --stage fetch_columns, 26.9.1.1 debug):

analyzer predicate master this branch
allow_experimental_analyzer = 0 k IN (SELECT number FROM numbers(2)) 0 rows, exit 0 0 rows, exit 0
allow_experimental_analyzer = 0 k IN (0, 1) 0, 1 0, 1
default k IN (SELECT number FROM numbers(2)) Not-ready Set (aborts, debug build) 0, 1

Dropping --stage makes the old analyzer return 0, 1, so the silent drop is specific to that stage, and it is identical before and after this change.

One thing sharper than "zero rows": k NOT IN (SELECT number FROM numbers(2)) returns zero rows there too, where 2, 3 is correct, while PREWHERE (k IN (SELECT number FROM numbers(2))) OR 1 returns all four. So the subquery term evaluates false for every row rather than the set coming back empty, which would have made NOT IN true for all rows. Worth noting because the old path attaches its sets unconditionally (InterpreterSelectQuery.cpp:2428 sits outside the to_stage > FetchColumns gate), so its wrongness is a different defect from the missing attachment fixed here. I am not raising it separately, since the path is deprecated and it is out of scope here.

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 addBuildSubqueriesForTableFilterSets call in resolveStorages.cpp, and I will drop it in whichever of the two lands second. It is a plain deletion: the only difference between the two attachments is set_options.ignore_rename_columns = false, and that field is inert for a set subplan, because SelectQueryOptions::subquery() forces to_stage = Complete while the flag is read only under till_stage == FetchColumns (PlannerJoinTree.cpp:2844).

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
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4cfb88a79 with master 7b90949ea (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 19 s compile time in total, 7 of them have a recent master baseline.

Job report

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.
@alexey-milovidov alexey-milovidov self-assigned this Sep 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 13, 2026
Merged via the queue into ClickHouse:master with commit 9fcf3db Sep 13, 2026
174 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
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 returns

▶ Run on ClickHouse Fiddle

Results:

  • Reproduces on: 26.8, 26.7, 26.6, 26.3
  • Does not reproduce on: master
  • Tested versions: master, 26.8, 26.7, 26.6, 26.3
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.8, 26.7, 26.6, 26.3.

CC component owner: @KochetovNicolai @novikd

Analysis metadata

comp-query-analyzer · Severity P2 · Finding phase_d_pr118359

  • Verified against master build 1e93c0a25f17 (aarch64)
Introducing change: not identified
  • No clean release baseline found and no lower bound established — source-build bisect is required to pin the introducing PR (not yet performed).
  • Walked 6 release(s) below the supported window: still reproduces down to 25.8.
  • Secondary components: comp-testing

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 27, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

5 participants