Skip to content

Restore PREWHERE inputs needed by the sorting key when reading by layers - #112664

Merged
alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-112402-join-shard-prewhere-sorting-key
Sep 6, 2026
Merged

alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-112402-join-shard-prewhere-sorting-key

Conversation

@groeneai

@groeneai groeneai commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #112402
Related: #112031

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

Fixes NOT_FOUND_COLUMN_IN_BLOCK when query_plan_join_shard_by_pk_ranges = 1 is combined with join_algorithm = 'full_sorting_merge' and a join input is filtered on a sorting-key column that is not the join key and is not selected. Closes #112402.

Description

ReadFromMergeTree::readByLayers reads each PK-range layer in sorting-key order and applies the sorting-key expression as an ExpressionTransform. It adds the sorting-key columns to the set read from disk, but never re-adds them to the outputs of the PREWHERE or row-level-filter DAG. A sorting-key column used only by the filter and absent from the join output is legitimately pruned there, and PREWHERE runs first, so the column is gone when the transform needs it.

Both sibling sites applying a sorting expression over a possibly-prewhered read (spreadMarkRangesAmongStreamsWithOrder, spreadMarkRangesAmongStreamsFinal) already call restorePrewhereInputs. readByLayers did not inherit the guard.

restorePrewhereInputs combined its two restores with ||, which short-circuits: once the row-level-filter restore returned true, the PREWHERE restore was skipped. A row policy on one sorting-key column plus a filter on another prunes a column from each DAG, so both must be visited. That is now |=. A bare column condition needs one more step: the column is then the filter column, which is erased by name after the DAG runs, so its remove-filter flag is cleared instead. Each change was mutation-tested separately and is load-bearing.

The optimization is preserved, not disabled (EXPLAIN actions = 1 still reports Sharding), and the restored columns never reach the step's declared output: the pipe-to-step header conversion in initializePipeline drops them. The readByLayers hunk needs query_plan_join_shard_by_pk_ranges = 1; the helper changes also apply at its three sibling call sites, where they can only widen which columns survive a filter, never narrow, and that same conversion drops a surplus one.

#112031's missing-column reproducer is the same defect and clears identically. That issue also documents a max_threads > 1 variant failing a pipeline-port check instead; that is a distinct defect, fixed by #109393, so #112031 is linked as Related rather than closed.

Validation

New test 05099_join_shard_by_pk_prewhere_sorting_key, 24 labelled cells: 20 compare the sharded result against an unsharded oracle so a silent wrong result also fails, and the other four guard the output header and the plan shape with no row policy, with one, and with a bare-column one.

Carriers confirmed failing before and passing after: filter on a non-join sorting-key column at any key position, on either join side, on both sides at once, via explicit PREWHERE including a bare column condition at any key position, under INNER/LEFT/RIGHT/FULL, with a row policy on another sorting-key column, with a LowCardinality key column, with an expression sorting key, and #112031's correlated EXISTS under OR.

Controls unchanged: non-key column filter, a bare filter on a non-key column, join-key filter, filtered column kept in the output, and no filter. Every non-throwing cell matched its oracle byte-for-byte before the change too, so there were no silent wrong results.

Randomized runs of the new test: 50/50 pass with the fix. On an unpatched build of the same commit the test failed 50/50, every failure the same Code: 10, so no random settings draw makes the defect cells vacuous; that arm was measured before the later rounds added further cells, each later defect cell of which was measured to fail un-randomized on the pre-fix build (the later control and plan-shape cells are source-fix-independent by design). 02354_read_in_order_prewhere plus the 12 other tests covering this setting and the sibling guard all pass.


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

Version info

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

groeneai and others added 11 commits July 29, 2026 08:47
With query_plan_join_shard_by_pk_ranges = 1 and join_algorithm =
'full_sorting_merge', a valid query failed at pipeline-build time:

  Code: 10. DB::Exception: Not found column c: in block a UInt32, b UInt32.
  (NOT_FOUND_COLUMN_IN_BLOCK)

ReadFromMergeTree::readByLayers reads each PK-range layer in sorting-key order
and applies the sorting-key expression as an ExpressionTransform. It adds the
sorting-key columns to the list of columns read from disk, but never re-adds
them to the outputs of the PREWHERE or row-level-filter DAG. When a sorting-key
column is consumed only by the filter and is absent from the join output, those
actions legitimately prune it. PREWHERE runs before the sorting expression, so
the column is already gone by the time the transform needs it.

Both sibling sites that apply a sorting expression over a possibly-prewhered
read (spreadMarkRangesAmongStreamsWithOrder and
spreadMarkRangesAmongStreamsFinal) already call restorePrewhereInputs;
readByLayers is newer and did not inherit the guard. Add the same call there.

restorePrewhereInputs itself combined the two restores with ||, which
short-circuits: once the row-level-filter restore returned true, the PREWHERE
restore was skipped. A table with a row policy on one sorting-key column and a
filter on another has both DAGs pruning a different column, so both must be
visited. Use |= instead.

The optimization is preserved rather than disabled, and the restored columns do
not reach the step header: they are dropped by the existing conversion in
initializePipeline.

Closes: ClickHouse#112402
Closes: ClickHouse#112031
…line

Three test-only follow-ups from review.

Pin enable_analyzer and allow_experimental_correlated_subqueries. The
correlated EXISTS cell cannot resolve under the old analyzer, which rewrites
EXISTS into a subquery with no outer scope, so the correlated references do not
bind. Two routes ran the file that way: the dedicated old-analyzer jobs, and
the compatibility randomization in stress, where the analyzer flip sits in the
24.3 block and the correlated-subquery flip in 25.4. A session SET rather than
a no-old-analyzer tag, because applyCompatibilitySetting skips settings already
changed manually, so the SET defends both routes while a tag would cover only
the dedicated job and would make the test vanish from that lane. Verified: the
file passes unchanged normally and under compatibility 24.2 and 25.3, and with
the pins removed under 24.2 it fails with UNKNOWN_IDENTIFIER and the sharding
assertion flips to 0. The test runner's setting randomizer does not touch this
axis, so the 50/50 run could not have covered it.

Add a pipeline-building no-leak assertion. DESCRIBE resolves only the sample
block, so it cannot observe the pipeline-time conversion that drops the
restored columns. EXPLAIN PIPELINE builds the real pipeline. The predicate is
anchored on the unindented Header: row, the top-level one: the restored columns
legitimately appear in the read-stage headers, so an unanchored pattern would
be permanently false. Verified discriminating: the shipped form prints 1, the
same predicate on a column that is present prints 0.

Correct the opening comment, which claimed every query threw before the fix and
that every cell used a hash oracle. The control cells did not throw, and the
header and plan-shape cells are not comparisons. Also record which identifiers
in the correlated cell are correlated: only i.s = o.s is, while the unqualified
v >= n binds to the inner table, confirmed from the query tree source ids.

Co-Authored-By: Claude Fable 5 <[email protected]>
… test

Round-2 review findings, all in the test file. The source fix is unchanged.

Nothing verified that the fixed branch was entered: its gate is a PREWHERE or
row-level filter plus a read-in-order read, and the only plan guard checked
sharding. If the PREWHERE move or read-in-order silently declined, both arms of
every oracle cell returned the same correct rows and the test passed green while
the changed code never ran. The plan guard now asserts all three markers, and
pins the EXPLAIN renderer: `explain_query_plan_default` flipped to `pretty` in
26.7, so `compatibility` randomization switches the read-type spelling and an
unpinned assertion silently stops matching.

The outer-join cells did not execute the kinds they were labelled with.
`query_plan_convert_outer_join_to_inner_join` defaults to true and a filter on
the non-preserved side is null-rejecting, so LEFT ran as INNER and FULL as
RIGHT. The setting is now pinned, and because a filter on the non-preserved side
can no longer be pushed into the read once the kind is genuinely outer, those
two cells filter a side the join preserves instead. Both throw before the fix.

The no-leak cell asserted the wrong header and its anchor saw only the first
column, since continuation lines carry no `Header` token. It now asserts that no
plan step declares a restored column, with the column-pruning optimization
pinned because it otherwise keeps the filtered column on every step above the
read whether or not sharding applies.
…e pipeline

The columns are consumed and dropped by the sorting expression they were
restored to feed, one processor above the read, so nothing they touch is
observable at the plan level. The comment above the DESCRIBE cell now names the
header that cell actually asserts.
Pin query_plan_remove_unused_columns = 1 at session level. At 0 the
optimizePrewhere source-output pruning short-circuits, so the filtered
sorting-key column is never removed from the read output and there is
nothing to restore: 9 of the 12 defect cells then silently return 1 on
an unfixed build instead of throwing NOT_FOUND_COLUMN_IN_BLOCK. The
setting flipped to true only in 25.12, and stress randomizes
compatibility over draws that mostly predate that, so the vacuity is
reachable in CI. A pass/fail run cannot detect it because the cells also
pass on the fixed build at 0.

Tighten the plan-shape guard from > 0 to = 2 on both the PREWHERE and
the read-type markers. The restore is gated per read step and this query
has two of them, so > 0 still passed if one step silently stopped
reading in order.

Delete the rfmt step header cell. EXPLAIN header = 1 prints the declared
step header, which is fixed in the ReadFromMergeTree constructor and is
not a function of the restore, so the cell cannot redden for any change
here: it is a constant, not a guard. Three successively narrower
assertion shapes were each structurally evaded. The remaining oracle
comparisons and the plan-shape guard are the coverage.

Correct the in-diff comment: the restored columns are removed by the
sorting expression they exist to feed, one processor above the read, not
by the pipe-to-step header conversion. Inverting either conversion
predicate changes nothing observable. Comment-only, so the object file
is bit-identical.

Drop allow_suspicious_low_cardinality_types from the LowCardinality
table's storage clause. It is a session setting, and validateDataType
accepts LowCardinality(String) unconditionally, so it guarded nothing.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
… the restored columns

The comment above the restorePrewhereInputs call in readByLayers claimed the
restored sorting-key columns are consumed by the sorting expression and so never
reach the step header. That is not what happens.

The sorting-key expression is built by KeyDescription::getKeyFromAST with
ExpressionAnalyzer::getActions(false); with add_aliases false, getActionsDAG
re-adds every source column to the required set before removeUnusedActions, so
the source columns are outputs of that DAG. ActionsDAG::updateHeader
independently re-inserts any header column that was not bound to a DAG input.
Either route means the sorting ExpressionTransform emits the restored columns
rather than dropping them. EXPLAIN PIPELINE header = 1 confirms it: the restored
columns appear on the MergeTreeSelect, the sorting ExpressionTransform and the
layer-range filter alike. They are dropped one level higher, where
initializePipeline converts the pipe header to the step header.

The conclusion the comment exists to support is unchanged and still measured:
the restored columns do not reach the step's declared output, DESCRIBE of the
reproducer returns exactly one column, and the plan shape is the same. Only the
stated reason was wrong.

Comment-only change. ReadFromMergeTree.cpp.o is md5-identical across the reword.
The row-policy cell is a result comparison, so it could not observe the row
policy, the PREWHERE move, the sharding or the in-order read silently
declining on that path; and its policy predicate `b < 1000` excludes 0 of the
fixture's 2000 rows, so the policy's own effect was invisible to it. That is
the same vacuity class the existing `plan shape` cell exists to close, just
never extended over the row-policy path, which is the one path where both
DAGs exist and the row-level restore is exercised.

Pin the plan while the policy is active. `Row level filter` is asserted at 4,
not the 2 predicted when the change was specified: both read steps of the
self-join carry the policy, each printing a name and a column line, while the
PREWHERE-moved filter applies to one step only. Exact counts rather than
`> 0`, since the restore is gated per read step. Measured discriminating in
both directions: commenting out the policy drops the count to 0 and reddens
this cell alone, leaving the existing `plan shape` cell green. Counts are
stable over 12 runs and across both values of
`query_plan_remove_unused_columns`, so no pin is needed on this cell.

Also scope the `output header` comment. `DESCRIBE` resolves the analysis-time
sample block and never builds a pipeline, so that cell cannot observe the
pipeline-time conversion; it pins the step's advertised contract. Four review
rounds read it as a leak detector, which it is not. The comment now names what
it does not cover and where the pipeline-time property is covered instead: a
leaked column trips the arity check in `OutputPort::pushData`, a plain
`if (...) throw` rather than a `chassert`, so it fires in release builds too.

Test-only. No source change, and the read step's object file is untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ded for

The cell filtered r.c, a bare identifier that appears both in the sorting key's
output names and among the expression's required input columns, so it passed
whichever of the two the fix read. Filtering r.b instead, which appears only
inside multiply(b, 2), makes the cell fail when the restore set is built from
KeyDescription::column_names rather than from the key expression's inputs.
Measured on one mutant binary: the r.b form reddens with NOT_FOUND_COLUMN_IN_BLOCK
and the old r.c form still passes.

The LowCardinality cell's comment claimed the restore avoided a removeNullable
strip. There is no such call on this path; restoreDAGInputs matches inputs by
result_name and inspects no types. The comment now names that mechanism.

Also backtick the two literal names in the new readByLayers comment, per the
repository convention. Comment-only, so the object file is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Restoring a pruned sorting-key column by adding it back to the filter DAG
outputs is not enough when the condition is a bare physical column: that
column is then also the filter column, and it is erased by name after the
DAG runs. `restorePrewhereInputs` now clears the remove-filter flag for
that one case instead, covering the PREWHERE DAG and the row-level one.
The data path keeps the real values for the surviving rows, so nothing has
to be substituted.

The flag is only cleared for the filter column itself, so a computed filter
column such as `equals(c, 94)` keeps being removed and no `UInt8` leaks into
the pipe header. The other users of the restore primitive are unchanged.

Verified with a bare `PREWHERE` on a sorting-key column at two key
positions and with a row policy whose predicate is a bare column: all three
threw `NOT_FOUND_COLUMN_IN_BLOCK` before this commit and now match an
unsharded oracle.
The `bare row policy col` cell compared results only, and under this fixture
the policy excludes no row of the joined set: every row with `b = 0` has
`a = 0`, while `r.c = 94` restricts the join to `a = 44`. The digest was
therefore identical with and without the policy, so the cell also passed if
the policy, the PREWHERE move, the sharding or the in-order read silently
declined. Add a plan-shape guard while the bare policy is active, mirroring
the one already present for the `b < 1000` policy, and correct the comment
that claimed the oracle compared a filtered result.

Measured: the guard reads 1 with the policy and 0 without it, which is the
liveness the old cell lacked. Removing the policy leaves `bare row policy
col` at 1 and moves only the new cell.

The `control bare PREWHERE non-key` cell ran `PREWHERE d != ''`, so its
filter column was the computed `notEmpty(d)` node rather than a bare input.
`ok2` has no non-key numeric column and a `String` can never be a bare filter
because `canBeUsedInBooleanContext` is false for it, so the control now uses
its own table with a non-key `UInt32` column. The plan dump confirms the
filter column is the bare input.

Co-Authored-By: Claude Fable 5 <[email protected]>
The comment above the control bare PREWHERE non-key cell claimed the cell shows
that a bare filter on a non-key column keeps being removed and does not start
leaking into the header. It cannot show that, for two independent reasons, both
measured on the shipping build.

The restore is passed the sorting-key columns only, so restoreFilterDAGInputs
skips a non-key column at its inputs.contains check before it can reach the
flag-clearing branch: nk04652 orders by (a, b, c) and the control filters on e,
which is not in that set, and e appears nowhere in EXPLAIN PIPELINE header = 1
for the control query.

Even an over-broad clear is absorbed before anything can see it. The pipe to
step header conversion in initializePipeline narrows the read to its declared
output, so a surplus kept filter column is dropped exactly as the restored
sorting-key columns are. Measured three ways: the restored b and c each occur 96
times across FilterSortedStreamByRange and ExpressionTransform yet the topmost
ExpressionTransform inside (ReadFromMergeTree) emits only a; the round-7
over-broad mutation is reachable and still breaks no cell; and an expression key
ORDER BY (a, b * 2, c) with a bare PREWHERE b, where the flag clear does fire,
also narrows to a with the kept b and multiply(b, 2) both gone.

The cell stays: it is the only coverage for a bare filter on a non-key column
through the sharded read-in-order path, with an oracle comparison, and it does
exercise that path (Sharding 1, Prewhere filter 2, ReadType: InOrder 2). Only
the claim above it was too strong.

Comment-only change. src/ is untouched, the reference is byte-identical and the
Build ID stays 25f139083c68537ad648061091f534216b923827.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (10 Gate B rounds, 9 fix rounds): click to expand

Before publishing I ran an independent cold code review plus 10 rounds of a second-model
adversarial gate on this change (22 findings). Each finding was verified against the source or a
measurement before being accepted or rejected; nothing was accepted on assertion alone. The last
round returned no blockers and no majors. Recorded here so a human reviewer can see what was
already checked.

Resolved this round

❌ Closes: #112031 was wrong and would have auto-closed a live defect. Issue #112031 carries
a second reproducer in a comment: with max_threads = 8 the same two settings fail
Code: 49 Join is supported only for pipelines with one output port, got 7 and 1 instead of the
missing-column exception. That abort reproduces on the exact binary this PR was validated with, and
its mechanism is unrelated to this change: the stream-count mismatch is rejected in
QueryPipelineBuilder::joinPipelinesYShaped, reached because JoinStep::updatePipeline declines
sharding when the two sides' stream counts differ, whereas this PR restores filter-DAG outputs in
ReadFromMergeTree::readByLayers. That half is fixed by #109393, which replaces exactly that
throw. #112031 is therefore linked as Related, and only its missing-column reproducer is claimed
here.

⚠️ Helper blast radius, verified rather than assumed. restorePrewhereInputs changed from
add-only to also clearing a remove-filter flag, and all four of its call sites inherit that. I
confirmed the "can only widen, never narrow" claim holds: the mutation happens during
initializePipeline, after the step's declared output header is fixed and after plan
serialization, so no declared header, EXPLAIN output or remote header can observe a cleared flag;
and a surplus kept filter column is dropped by the same name-matched header conversion that drops
the restored columns. Only the filter column itself is exempted, so a computed filter column keeps
being removed. Now stated in the description.

Noted, not changed

💡 One test comment is stronger than the code warrants: it says either prewhere setting at 0
makes every assertion below vacuous. The move-to-prewhere pass only relocates a WHERE, so the
cells using an explicit PREWHERE still exercise the fix at 0, and the plan-shape guards fail
rather than pass vacuously because they require the Prewhere filter markers. The pins themselves
are correct and load-bearing; only the justifying sentence over-reaches. Happy to reword it if you
would like it precise.

Earlier rounds hardened the test rather than the fix: exact plan-shape counts instead of
> 0 so a silently declining plan cannot make the result cells vacuous, both prewhere settings
pinned, the analyzer and outer-join-conversion settings pinned so the labelled join kind is the
executed one, per-cell oracles so a silent wrong result fails too, and two mechanism claims in
comments corrected after measurement showed the restored columns are dropped by the header
conversion rather than by the sorting expression.

Session id: cron:clickhouse-review-slot-11:20260730-202600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local --path=$(mktemp -d) -q "<issue #112402 reproducer verbatim>" throws Code: 10 ... Not found column c: in block a UInt32, b UInt32 on every run (5/5, and 50/50 under the randomized harness, every failure carrying that same error code). #112031's reproducer throws identically with the same stack.
b Root cause explained? readByLayers adds the sorting-key columns to the set read from disk but never re-adds them to the outputs of the PREWHERE / row-level-filter DAG. PREWHERE prunes a sorting-key column consumed only by the filter, runs before the sorting ExpressionTransform that readByLayers adds to the pipe, and ActionsDAG::updateHeader then throws because the block no longer carries it. Confirmed by stack trace, and by EXPLAIN actions = 1 showing the reading step's Output: a next to Prewhere filter column: c = 94.
c Fix matches root cause? Yes. It restores the pruned DAG inputs via the repo's existing restorePrewhereInputs primitive, at the reading step that owns the invariant. Both sibling sites already do this; readByLayers is newer and did not inherit the guard. No bound widened, no tag added, no optimization disabled.
d Test intent preserved / new tests added? New test 04652_join_shard_by_pk_prewhere_sorting_key, 24 labelled cells: 20 compare a sharded result against an unsharded oracle, three guard the plan shape (twice with a row policy active, once for each policy shape, since a result comparison cannot see the policy declining and neither policy predicate excludes any row of the joined result), one is a DESCRIBE header check. Each plan guard was measured live: it reads 1 with its policy active and 0 without it. The result cells compare the sharded result against an unsharded oracle (hash where the algorithm can change) rather than only asserting "no exception", so a future silent wrong result also fails; the rest are header and plan-shape guards. The analyzer and correlated-subquery settings are pinned with session SETs: the old-analyzer route (dedicated jobs, and compatibility randomization in stress) cannot resolve the correlated cell, and that axis is absent from the test runner's setting randomizer. No existing test weakened.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Unpatched build of the same commit (74a068f272dde63c / 1e02e0d0fc5a80b9): the test fails with Code: 10. Patched build (0318e0f4209419c4): passes. The shipped test reddens all 12 of its defect cells on the unpatched build, 50 of 50 randomized runs, every failure carrying Code: 10. Mutation A (revert only the readByLayers hunk) reddens every defect cell of the discriminator matrix; mutation B (revert only |= to ||) reddens exactly the row-policy cell and leaves the rest green, so both changes are load-bearing. A third mutation substitutes the wrong accessor, getSortingKey().column_names (key output names) for getSortingKey().expression->getRequiredColumnsWithTypes() (the expression's inputs): it reddens exactly the expression-sorting-key cell, so that cell pins the accessor choice rather than merely the presence of an expression key. Restoring the fix restored the carrier file byte-for-byte, with zero mutation markers left behind. A later round added the bare-filter-column fix and three more defect cells: on the pre-fix build (65f37bfd18ff1154) each throws Code: 10 un-randomized and on the fixed build (25f139083c68537a) each matches its unsharded oracle. A fourth mutation makes only the flag-clearing branch inert and, measured per cell, reddens exactly those three and no other, all 19 earlier cells staying green. A fifth mutation clears the flag unconditionally (ignoring the filter-column name test) and breaks nothing: an instrumented build shows that branch IS reached on a real cell, but the header conversion that already drops the restored sorting-key columns absorbs the extra kept filter column, so result and plan are identical; that is reported rather than papered over with a cell that would be vacuous. A sixth mutation removes the bare row policy's CREATE: it moves only the new bare row policy plan shape cell, 1 to 0, while bare row policy col stays at 1. That is the measurement showing the result-only cell was vacuous on this path and the plan guard is what covers it.
f Fix is general across code paths? Yes. Four sites apply a sorting expression over a possibly-prewhered read: spreadMarkRangesAmongStreamsWithOrder (restores at :1449), spreadMarkRangesAmongStreamsFinal (restores at :1946), the intersecting/non-intersecting split (gated off entirely when either filter exists), and readByLayers (the gap, fixed here). Fixed at the reading step, not guarded at the throw site. Both join sides and all four join kinds go through the same code, so one hunk covers them; verified for each. The outer-join cells pin query_plan_convert_outer_join_to_inner_join = 0 and filter a side the join preserves, because otherwise a null-rejecting filter rewrites LEFT to INNER and FULL to RIGHT, and a filter on the non-preserved side never becomes PREWHERE.
g Fix generalizes across inputs? Yes. Verified carriers, each failing before and passing after: sorting-key column at position 2, 3 and 4 of the key; LowCardinality(String), Nullable(UInt32) and LowCardinality(Nullable(String)) key columns; DateTime key; an expression sorting key (ORDER BY (a, b * 2, c), filtered on the expression's own input b so the cell distinguishes the input names from the key output names); key arity 2 and 4; row policy instead of WHERE; explicit PREWHERE; and a bare column as the whole filter condition, which is the one shape where the restored column is also the filter column and is therefore erased again by name after the DAG runs, covered for both PREWHERE (at two key positions) and a row policy, with a genuinely bare filter on a NON-key column as the control that the removal flag is only cleared for a column the sorting key needs. That control needs its own table: ok2 has no non-key numeric column, and a String can never be a bare filter because canBeUsedInBooleanContext is false for it (PREWHERE d is Code: 59), so the earlier PREWHERE d != '' spelling made the filter column the computed notEmpty(d) node and never reached the bare-input case its label claimed. The plan dump now shows Prewhere filter column: e with no wrapper. The restore set comes from the sorting key expression's required columns, so it is wrapper- and expression-agnostic by construction rather than by enumeration. Empty result and no-filter cases unchanged.
h Backward compatible? Yes. No setting default changed, no new setting, no serialization or format change, no new validation, no public signature change, so no SettingsChangesHistory.cpp entry is owed. query_plan_join_shard_by_pk_ranges already defaults to false, and the readByLayers hunk is reachable only under it: AnalysisResult::split_parts has one writer (optimizeJoinByShards.cpp:294, run only under optimizeTree.cpp:679's check of that setting) and readByLayers one caller guarded on a non-empty layer list. The |= correction is in a shared helper and so is not gated by that setting; see row (i) for why it is behaviour-preserving except where it restores strictly more. Only queries that currently throw change behavior.
i Invariants and contracts preserved? The invariant restored is exactly the one the sibling site documents: every column the sorting-key expression requires must survive the PREWHERE / row-level-filter stage of a read-in-order read. Verified the restored extras do not leak: DESCRIBE of the reproducer returns exactly d String, a full SELECT * over the join returns exactly its 8 expected columns, and no plan step declares either restored column. EXPLAIN PIPELINE header = 1 shows the restored columns surviving the sorting ExpressionTransform (the sorting-key expression is built with getActions(false), so it keeps its source columns) and being dropped at the pipe-to-step header conversion in initializePipeline, which is why the step's declared output is unchanged. The |= change is in a shared helper, so it also reaches its three other call sites (:1449, :1946, :3559). Enumerating the 16 combinations of (each filter present) x (each restore's result): the return value is identical in all 16, and the only behavioural delta is the two cells where both filters are present and the row-level restore succeeds, in which the prewhere DAG is now restored as well. So it can only widen which DAGs are visited, never narrow, and restoreDAGInputs re-adds only inputs the DAG already has, so no new column is read at any site. 02354_read_in_order_prewhere has no row policy, so it exercises only the unchanged half of that enumeration. EXPLAIN actions = 1 still reports Sharding, so the optimization is preserved rather than disabled.

Session id: cron:clickhouse-impl-slot-41:20260729-111100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @nickitat, could you review this? With query_plan_join_shard_by_pk_ranges = 1, ReadFromMergeTree::readByLayers applies the sorting-key expression to each PK-range layer but never re-adds the sorting-key columns to the PREWHERE outputs, so a sorting-key column used only by the filter is pruned before the transform needs it and the read fails with NOT_FOUND_COLUMN_IN_BLOCK; both sibling read-in-order sites already restore those inputs.

@yariks5s yariks5s self-assigned this Jul 30, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4e9371b]

Summary: ✅


AI Review

Summary

This PR restores sorting-key inputs that PREWHERE / row-level filtering can prune before readByLayers applies the sorting expression, and it extends the shared restore helper to handle both filter DAGs and bare filter columns. I reviewed the merged-head diff, the current ReadFromMergeTree code paths, the added regression test, and the prior PR discussion, and I did not find any new blocker or major issue in the current code.

Missing context / blind spots
  • ⚠️ Full CI on commit 4e9371b7bc59c3762fb1a3755f3e644fbea04a87 was still in progress during this review; Style check and Fast test were already green, but the remaining build / sanitizer lanes are still the last external validation step.
Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 4e9371b.

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

Changed lines: Changed C/C++ lines covered: 29/29 (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 Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0ecf40f

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix
task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

CI is fully finished on this head: 174 check-runs, 0 queued or in progress, Finish Workflow
and Config Workflow both success, and more than 20 minutes have passed since the last check
completed.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / STID 4488-4a91 logical error Join is supported only for pipelines with one output port #109393 (mine, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / STID 4488-4a91 same, got 14 and 1 #109393 (mine, open)
Stress test (amd_tsan) / STID 4488-4a91 same, got 1 and 2 #109393 (mine, open)
Stress test (arm_msan) / STID 4488-4a91 same, got 2 and 1 #109393 (mine, open)

All four reds are one signature reported by four jobs. It is not caused by this PR:
the diff here touches only src/Processors/QueryPlan/ReadFromMergeTree.cpp and has zero
changes to stream-count or join-pipeline code (getNumStreams, resize,
joinPipelinesYShaped, QueryPipelineBuilder). CIDB over 45 days puts the family at
30 hits total: 25 across 24 unrelated pull requests, 4 here, and one on the 26.6
release branch. First seen 2026-06-17, so it predates this branch.

#109393 is the fixing PR: it removes exactly this throw in
QueryPipelineBuilder::joinPipelinesYShaped and merges each side back into a single sorted
stream with a MergingSortedTransform keyed by the join keys when the two sides' stream
counts diverge. Its regression test
04501_full_sorting_merge_join_shard_stream_divergence.sql pins the same
query_plan_join_shard_by_pk_ranges plus full_sorting_merge shape the fuzzer queries here
hit.

Session id: cron:our-pr-ci-monitor:20260731-040000

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Dear @yariks5s, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

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 Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
alexey-milovidov and others added 2 commits September 6, 2026 08:08
…ng master

The 04652 prefix is now shared by 58 tests on master; the branch is
37 days old, so take the next free number. The table and row-policy
names inside the test follow the new number.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (2026-09-06) into the branch. All four CI reds on the previous head were the single Join is supported only for pipelines with one output port logical error, which is fixed by #109393, merged into master on 2026-09-05; the merge pulls that fix in. The test is renumbered from 04652 to 05099 (the old prefix now collides with 58 tests on master); its table and row-policy names follow. Locally the renumbered test passes with and without randomized settings on the merged head, and the incremental build is clean.

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4e9371b7b 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, 26 s compile time in total, 7 of them have a recent master baseline.

Job report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 6, 2026
Merged via the queue into ClickHouse:master with commit 227cd9a Sep 6, 2026
175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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.

query_plan_join_shard_by_pk_ranges + full_sorting_merge: NOT_FOUND_COLUMN_IN_BLOCK when the right side filters on a non-join sort-key column

4 participants