Skip to content

Filter PartsSplitter layers on the key columns the sorting expression computed - #120058

Merged
alexey-milovidov merged 7 commits into
masterfrom
fix/parts-splitter-layer-filter-key-columns
Oct 13, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
fix/parts-splitter-layer-filter-key-columns

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

Related: #119385
Related: #117375

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 rows missing from a FINAL query (and from any read split into primary key range layers) when a sorting key expression's result type depends on a session setting, such as ORDER BY CAST(json.b, 'String') read under cast_keep_nullable = 1: the per-layer filter now compares the key values the table itself computed instead of re-evaluating the key expression with the query's settings.


PartsSplitter::buildFilters cloned the sorting key AST into the per-layer border predicate tuple(key) > tuple(border), and applyRangeFilterFromAST resolved it again with the query's ExpressionAnalyzer. When a setting changes the result type of a key expression, the query-side resolution is a different function with different values: for a table created under cast_keep_nullable = 0 with ORDER BY CAST(json.b, 'String'), a row without json.b has the key '', while a session with cast_keep_nullable = 1 evaluates the same expression to NULL. The layer filter was then NULL for that row and FilterSortedStreamByRange dropped it from every layer - a wrong FINAL result. This is the split-ranges counterpart of the read-in-order divergence fixed in #119385.

In CI it surfaced as 05187_read_in_order_key_type_setting_divergence losing its NULL rows whenever the randomized settings paired index_granularity = 1 with merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117375&sha=9e46ee24a0a6d36d1f40aea2f3c12fbb65608268&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 (from #117375, whose change is unrelated - the failure reproduces with enable_join_runtime_filters = 0).

The per-layer filter now refers to the key columns by name, is resolved against the key sample block, and is composed with the table's own key expression (ActionsDAG::merge with primary_key.expression), so it compares exactly the values the layers were split by. Composing with the key expression rather than reading the key columns off the stream header keeps both shapes of caller working: readByLayers and the distributed FINAL lanes in MergeTreeFinalMerge run the sorting expression on the pipe first, while the join-by-shards layers are read without it and carry only the plain table columns. No behaviour change when the types agree.

Test 05217_parts_splitter_layer_filter_key_type_divergence: a ReplacingMergeTree FINAL and a forced split on an ordinary read under the diverged type, each losing the NULL row before the fix, plus a same-type control.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.2246-master (included in 26.10 and later)

…on computed

`PartsSplitter::buildFilters` cloned the sorting key AST into the per-layer
border predicate and `applyRangeFilterFromAST` resolved it again with the
query's `ExpressionAnalyzer`. A key expression whose result type depends on a
session setting - `CAST(json.b, 'String')` is `String` in a table created
under `cast_keep_nullable = 0` and `Nullable(String)` in a session with
`cast_keep_nullable = 1` - then became a different function with different
values: the row whose `json.b` is missing is `''` for the table and `NULL`
for the query, the layer filter `tuple(key) > tuple(border)` evaluated to
`NULL` for it, and `FilterSortedStreamByRange` dropped the row from every
layer. Visible as a wrong `FINAL` result, and in CI as
`05187_read_in_order_key_type_setting_divergence` losing its `NULL` rows
whenever the randomized settings paired `index_granularity = 1` with
`merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability`.

Every caller (`readByLayers`, the distributed `FINAL` lanes in
`MergeTreeFinalMerge`) runs the table's own sorting expression on the pipe
right before the filter, so the key columns are already in the stream under
their `getColumnName` names. The filter now refers to them by name and is
resolved against the stream header instead of the table columns, so it
compares exactly the values the layers were split by.

Test `05217_parts_splitter_layer_filter_key_type_divergence`: a
`ReplacingMergeTree FINAL` and a forced split on an ordinary read under the
diverged type, each losing the `NULL` row before the fix, plus a same-type
control.

Related: #119385
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117375&sha=9e46ee24a0a6d36d1f40aea2f3c12fbb65608268&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 (PR #117375)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [af87518]

Summary: ✅


AI Review

Summary

This PR fixes a real correctness bug in PartsSplitter: the per-layer range predicate no longer re-resolves the key AST in the query context, so session settings such as cast_keep_nullable cannot make the filter compare different values from the ones the table used to split layers. The final shape of the fix is well targeted: buildFilters now binds by key-column name, applyRangeFilterFromAST resolves against primary_key.sample_block, and then composes the predicate with primary_key.expression, which preserves the join-by-shards caller that does not already carry computed key columns in the stream. The new stateless regression test covers both FINAL and forced split reads for the reported divergence. I did not find a remaining correctness or safety issue in the current diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing af8751816 with master 145c4acb0 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 371b23a4b; 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, 12 s compile time in total, 7 of them have a recent master baseline.

Job report

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 16, 2026
The read-side guard in 22ca496 erases the tainted names inside KeyCondition,
which disarms the primary key, partition pruning and the minmax skip index,
because all three build their condition there. The set and Bloom filter
conditions do not go through it: MergeTreeIndexConditionSet builds its own
key_columns map from the index sample block and evaluates the predicate over the
stored granule values, and MergeTreeIndexConditionBloomFilter matches
key_node.getColumnName() against the index header. With a table written under the
server baseline and a query session that deviates, both still prune the only
matching granule:

    CREATE TABLE t (h UInt64, v UInt32,
        INDEX s tupleElement(h3ToGeo(h), 1) TYPE set(100) GRANULARITY 1)
    ENGINE = MergeTree ORDER BY v;
    INSERT INTO t VALUES (608009741498580991, 1);
    INSERT INTO t VALUES (610315033787760639, 2);
    SET h3togeo_lon_lat_result_order = 1;
    SELECT h FROM t WHERE tupleElement(h3ToGeo(h), 1) > 50;
    -- returns nothing; with use_skip_indexes = 0 it returns 610315033787760639

bloom_filter drops the row the same way for equality and IN. Refusing such an
index in the admission loop of buildIndexes covers every family at one site
instead of teaching each of them the same rule, and it makes the minmax coverage
explicit rather than a side effect of that index building a KeyCondition. A
session that agrees with the baseline keeps the index: force_data_skipping_indices
still passes and EXPLAIN indexes still shows Granules: 1/2.

The join runtime filter path needs no equivalent: it registers a filter only for a
bare INPUT column (joinRuntimeFilter.cpp), so an index over an h3ToGeo expression
is never selected there.

05218 grows set and bloom_filter arms in both sessions. Without this change the two
result arms return nothing and the two force_data_skipping_indices arms do not
throw; 49 of 50 randomized runs pass with it, the remaining failure being the
geoToH3 primary-key arm that ClickHouse#120058 fixes.

Co-Authored-By: Claude Opus 5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 16, 2026
The geoToH3 arm of 05218_h3_key_session_order_read_guard asserts that a session
deviating from the stored key still gets the row, so nothing may prune it. When
merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability
is drawn above 0, ReadFromMergeTree turns that plain read into a layered in-order one
(ReadFromMergeTree.cpp:1775-1789); PartsSplitter then clones the primary-key AST
(PartsSplitter.cpp:886) and re-analyzes it in the query session
(applyRangeFilterFromAST, PartsSplitter.cpp:1247), so the layer filter compares
session-computed key values against borders taken from the stored index and drops the
row, whatever the read-side guard does. Only that table is reachable: isSafePrimaryKey
refuses a Float key, which is why the h3ToGeo tables here and 05219 never get split.

Measured on this head. With the injection forced on, the test fails 5/5 with exactly
the CI diff, the row after the geoToH3 label missing; with it at 0 and every other
setting unchanged, 5/5 pass. All six failures on the current head drew a nonzero value
(0.36 to 0.96) and the rerun rates track it: 0.96 gave 153/158, 0.36 gave 23/49. With
the limit in place 100 randomized runs pass and all 7500 of their queries run at the
0.0 default, and misspelling the limit line brings 25 distinct nonzero draws back.

The divergence itself is the PartsSplitter layer filter rather than this guard, and it
does not need the injection to show: a ReplacingMergeTree ORDER BY geoToH3(lat, lon, 5)
read with FINAL under geotoh3_argument_order = 'lon_lat' returns 4 of its 5 rows. That
belongs to ClickHouse#120058, which compares the key values the table already computed instead of
re-resolving the expression, so this test only stops arming the path.
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: d97766c7-0ec8-4dee-9ffe-a53d33b177e9
  • MIRAI run: 8b5db946-e58a-44ab-8a13-95a3a56c7d9a
  • PR check IDs:
    • clickbench_1013640_1791792879
    • clickbench_1013646_1791792879
    • clickbench_1013652_1791792879
    • tpch_adapted_1_official_1013662_1791792879
    • tpch_adapted_1_official_1013675_1791792879
    • tpch_adapted_1_official_1013710_1791792879

alexey-milovidov and others added 6 commits September 19, 2026 14:39
…he stream header

The previous commit assumed every caller of `applyRangeFilterFromAST` runs the
table's sorting expression on the pipe before the filter, so the key columns are
in the stream under their `getColumnName` names. That is true for
`readByLayers`'s merging pipes and for the distributed `FINAL` lanes in
`MergeTreeFinalMerge`, but not for the join-by-shards layers of
`ReadFromMergeTree::readByLayers`: when `reader_settings.read_in_order` is off
the step getter reads with `ReadType::Default` and no `ExpressionTransform`, so
the pipe carries the plain table columns only. Resolving the filter against that
header threw `Missing columns: 'multiply(a, 2)'` in
`03357_join_pk_sharding` with `query_plan_join_shard_by_pk_ranges = 1`.

Keep the filter written in terms of the key column names, but resolve it against
`primary_key.sample_block` and compose the resulting `ActionsDAG` with the
table's own `primary_key.expression`. The key values the filter compares are then
always the ones the table computed - the ones the layer borders came from - for
both shapes of caller, and the required source columns are the same ones the
filter needed before this branch, so nothing new has to be read.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120058&sha=7418b353ca2f92e97efb839bb211b89777a1c30a&name_0=PR (PR #120058)

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Oct 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 13, 2026
Merged via the queue into master with commit 2279ace Oct 13, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/parts-splitter-layer-filter-key-columns branch October 13, 2026 00:59
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 13, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@KochetovNicolai

Copy link
Copy Markdown
Member
  -- tables as in 03357 (tab_m ORDER BY (c + d, b * 2)), lazy materialization off
  SELECT sum(l.a), sum(m.c) FROM tab_l l INNER JOIN tab_m m ON l.a * 2 = m.c + m.d AND l.d = m.a
  SETTINGS enable_join_runtime_filters = 0, max_bytes_before_external_join = 0,
  max_bytes_ratio_before_external_join = 0;
  -- Code: 10. DB::Exception: Not found column b in block
  

clickhouse-gh Bot pushed a commit that referenced this pull request Oct 15, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 125763 120058 Revert "Filter `PartsSplitter` layers on the key columns the sorting expression computed"
Changelog-deleted-entry: 120058 [Bug Fix (user-visible misbehavior in an official stable release)] [section] * Fixed rows missing from a `FINAL` query, and from any read split into primary-key range layers, when a sorting-key expression's result type depends on a session setting, such as `ORDER BY CAST(json.b, 'String')` read under `cast_keep_nullable = 1`. The per-layer filter now compares the key values the table itself computed instead of re-evaluating the key expression with the query's settings. [#120058](#120058) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
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-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.

4 participants