Repository navigation
Restore PREWHERE inputs needed by the sorting key when reading by layers - #112664
alexey-milovidov merged 13 commits into
Conversation
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.
Internal second-model review (10 Gate B rounds, 9 fix rounds): click to expandBefore publishing I ran an independent cold code review plus 10 rounds of a second-model Resolved this round ❌
Noted, not changed 💡 One test comment is stronger than the code warrants: it says either prewhere setting at Earlier rounds hardened the test rather than the fix: exact plan-shape counts instead of Session id: cron:clickhouse-review-slot-11:20260730-202600 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260729-111100 |
|
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. |
|
Workflow [PR], commit [4e9371b] Summary: ✅
AI ReviewSummaryThis PR restores sorting-key inputs that Missing context / blind spots
Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit 4e9371b.
Changed lines: Changed C/C++ lines covered: 29/29 (100.00%) · Uncovered code |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 28/28 (100.00%) · Uncovered code |
CI finish ledger — 0ecf40fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix CI is fully finished on this head: 174 check-runs, 0 queued or in progress,
All four reds are one signature reported by four jobs. It is not caused by this PR: #109393 is the fixing PR: it removes exactly this Session id: cron:our-pr-ci-monitor:20260731-040000 |
|
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. |
…rd-prewhere-sorting-key
…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]>
|
🕵 Merged |
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, 26 s compile time in total, 7 of them have a recent master baseline. |
Closes: #112402
Related: #112031
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes
NOT_FOUND_COLUMN_IN_BLOCKwhenquery_plan_join_shard_by_pk_ranges = 1is combined withjoin_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::readByLayersreads each PK-range layer in sorting-key order and applies the sorting-key expression as anExpressionTransform. 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 callrestorePrewhereInputs.readByLayersdid not inherit the guard.restorePrewhereInputscombined 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 = 1still reportsSharding), and the restored columns never reach the step's declared output: the pipe-to-step header conversion ininitializePipelinedrops them. ThereadByLayershunk needsquery_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 > 1variant failing a pipeline-port check instead; that is a distinct defect, fixed by #109393, so #112031 is linked asRelatedrather 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
PREWHEREincluding a bare column condition at any key position, under INNER/LEFT/RIGHT/FULL, with a row policy on another sorting-key column, with aLowCardinalitykey column, with an expression sorting key, and #112031's correlatedEXISTSunderOR.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_prewhereplus the 12 other tests covering this setting and the sibling guard all pass.Workflow [PR]
Sync PR [sync-upstream/pr/112664]
Version info
26.9.1.845(included in26.9and later)