Repository navigation
Conversation
…s guard All conditions of one PREWHERE read step are evaluated on the same unfiltered block, and the step filter is applied only afterwards, so a guard condition cannot protect a later condition placed in the same step. Since ClickHouse#107988 MergeTreeWhereOptimizer groups conditions by their physical storage column, so a guard such as `payload.longitude IS NOT NULL` and a throwing predicate over `payload.latitude` arrive adjacent and tryBuildPrewhereSteps merges them into one step. The throwing expression then runs on the rows the guard rejects, which fails the query with CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN. Short circuit does not help because the conversion is a prewhere DAG output, and adding more IS NOT NULL guards does not help either since they are hoisted into the same step. Commit 7572613 already reverted non-adjacent merging for the same hazard. The comment it left behind claimed adjacent-only merging was safe precisely because the WHERE optimizer makes such conditions adjacent; this is the counterexample, so the comment is corrected. The fix propagates a may_throw flag through the existing fillRequiredColumns DFS, using the same isSuitableForShortCircuitArgumentsExecution predicate the short circuit machinery uses. A condition that may throw always starts a new read step, and the step preceding such a boundary is forced to materialize its filter: a boundary alone is not enough, because a non-final step's need_filter is otherwise just query_plan_merge_filters, and ReadResult::optimize applies a step filter on its own only when fewer than 60% of the rows pass. Conditions that cannot throw are still grouped, so the redundant read optimization from ClickHouse#107988 is preserved; the read step counts for the query shapes in tests/performance/map_subcolumns_prewhere.xml are unchanged. Closes ClickHouse#111879
The previous commit only recorded the boundary when the may-throw condition read the same physical storage columns as the group before it. A may-throw condition on different columns started a new step, but its predecessor kept need_filter = query_plan_merge_filters, and ReadResult::optimize applies a step filter on its own only when fewer than 60% of the rows pass. So with query_plan_merge_filters = 0, or a guard that keeps most rows, the throwing condition still saw the rows its predecessor rejected. That is exactly the shape the comment above the grouping loop promises is safe. A boundary is now recorded whenever a may-throw condition starts a step and another step already exists, regardless of which columns the two steps read. Test changes: The three Map cases were vacuous. toUInt64(tags['val']) >= 0 is folded away in full, because a UInt64 is unconditionally >= 0, so the throwing conversion was never planned. Changed to > 50. Added a mixed storage column case, as a user written PREWHERE only. A flat WHERE gives no evaluation order guarantee: MergeTreeWhereOptimizer orders the conditions it moves by estimated column size, so under a sparse serialization threshold that makes the guard column sparse, the throwing condition is ordered first and becomes the first step, with nothing before it to filter. That shape throws on master too. The sparse serialization threshold is now pinned on every table so no case can go vacuous under CI randomization. Added 04631_prewhere_subcolumn_guard_read_steps.sh, which counts read steps through ProfileEvents['RowsReadByPrewhereReaders'] the way 03143_prewhere_profile_events.sh does, to assert that non-throwing Map conditions still share one step. The 04630 EXPLAIN assertion cannot tell grouping from the single step fallback, so its label was narrowed to the subcolumn rewrite it does prove. The reused predicate is documented as imprecise in both directions. It also reports true for merely expensive functions: a PREWHERE of 16 startsWith(tags['kN'], ...) conjuncts over one Map now splits into 16 steps instead of 1, costing about 5x wall clock on a 2M row table. The committed perf test uses != '' comparisons, which report false, and is unaffected.
tryBuildPrewhereSteps took the children of the outer AND verbatim, so a nested conjunction was one atomic condition. optimizePrewhere builds exactly that shape, and(existing_prewhere, and(guard, throwing)), when a moved WHERE is merged into an existing PREWHERE under optimize_prewhere_after_pushdown. The inner AND reports may_throw as a unit, so its guard and its throwing predicate landed in the same read step, evaluated on the same unfiltered block, which is the failure the preceding commits fix for the flat case. The conjunction is now flattened recursively before grouping. The flatten appends children left to right, because the step boundaries and the evaluation order promised for a user written PREWHERE both depend on the original order. ActionsDAG::extractConjunctionAtoms is not reused for this reason: it walks with a stack and reverses sibling order. Flattening only ever produces more, and finer, conditions, so a nested conjunction of conditions that cannot throw still collapses into one step, which the read step counter in the .sh test asserts. Regression coverage: a nested PREWHERE case in 04630 (default and with query_plan_merge_filters = 0), a grouping preservation assertion in 04631, and the merge tree randomization tag on 04630.
The two equality assertions passed for reasons other than the property they
named, so neither would have failed if the property broke.
RowsReadByPrewhereReaders = 100000 cannot tell a correct one group split from
the splitter declining and falling back to a single step: the fallback builds
one step, hence one non main range reader, reading the same 100000 rows.
The nested conjunction assertion measured 100000 whether or not the conjunction
was flattened, because all three of its conditions were on one Map and ended up
in one group either way. It was added to guard the flattening and did not.
Two constant 1 UInt8 columns are added to t_steps_group. They filter nothing, so
they only change how conditions are grouped into steps. With them:
- a user written PREWHERE that interleaves a condition on another column
between two Map conditions reads 300000, a count neither the single step
fallback (100000) nor a merge of the two non adjacent Map conditions
(200000) can produce;
- a nested conjunction whose two conditions read different columns reads
300000 when it is flattened and 200000 when it is not.
Both counts were measured, not predicted, and cross checked against the
splitter's own "PREWHERE condition was split into N steps" log. Reverting
flattenConjunction to condition_root.children makes the second assertion fail,
which is what the assertion is for.
The condition originally prescribed for the nested case (gate = 1 AND
tags['k1'] != '') is not discriminating: QueryPlanOptimizePrewhere orders the
conditions it moves by estimated column size, so the Map condition is placed
first and merges back into the Map group, giving 200000 in both worlds.
ratio_of_defaults_for_sparse_serialization is pinned on both tables, as in
04630: a Sparse gate column would change the MergeTreeWhereOptimizer ordering.
The test asserts exact RowsReadByPrewhereReaders values read from the initiator's system.query_log row. Those counters are reported by whichever replica actually reads the marks, and the coordinator does not collect all of them, so the assertions are not meaningful when the reading is distributed. At the current fixture size the test happens to pass: the table has 14 marks and chooseSegmentSize() clamps the mark segment to 128 granules, so the whole table is a single segment awarded to the local replica. That is incidental. Denying the initiator the local plan (parallel_replicas_local_plan = 0, which the test runner randomizes) makes the counter land on a remote replica and the assertions read 0, and the same happens if the fixture ever grows past one segment or index_granularity is lowered. Co-Authored-By: Claude Fable 5 <[email protected]>
04631 measures how PREWHERE conditions are grouped into read steps through RowsReadByPrewhereReaders. It relies on optimize_functions_to_subcolumns rewriting tags['k0'] to the tags.key_k0 subcolumn so conditions over one physical column can group into a single step, and that rewrite exists only as an analyzer query tree pass (FunctionToSubcolumnsPass). The old analyzer functional test jobs set enable_analyzer to 0 in the default server profile, so the rewrite never happens and two of the five assertions evaluate to 0. That comes from the server profile, not the client randomizer, so no-random-settings does not cover it. Pin enable_analyzer in the client options the measured queries already carry, which keeps the coverage in those jobs instead of skipping the test there. 04630 asserts that exactly one plan line names both the first and the last rewritten subcolumn. Under parallel replicas ReadFromRemote embeds the entire remote query text in the step description, so that step matches the filter on its own and the count is 2. Pin enable_parallel_replicas on that one EXPLAIN subquery to keep the plan local; every other assertion in the file is a row count or an absence of error and stays meaningful under distributed reading, so the rest of the file keeps its parallel replicas coverage. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 5 rounds, 7 findings total;
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260726-131501 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260726-100300 |
|
cc @Avogar @hanfei1991 — could you review this? Since #107988 the PREWHERE splitter groups conjuncts by physical storage column, so a guard and a throwing expression over two subcolumns of one JSON/Map column land in the same read step and the throwing one runs on the rows the guard rejects. This makes a may-throw condition start a new step and forces the preceding step to materialize its filter, and it flattens nested conjunctions so a WHERE merged into an existing PREWHERE is grouped condition by condition. Avogar: tagging you because you authored #107988 and its partial revert 7572613, which fixed the non-adjacent half of exactly this hazard. |
|
Workflow [PR], commit [3e2bd49] Summary: ✅
AI ReviewSummaryThis PR fixes the main PREWHERE step-splitting hazard and makes the new read-ahead optimization safe around pending Findings❌ Blockers
|
| Metric | Baseline | Current | Δ |
|---|---|---|---|
| Lines | 88.20% | 88.20% | +0.00% |
| Functions | 91.70% | 91.70% | +0.00% |
| Branches | 79.50% | 79.50% | +0.00% |
Changed lines: Changed C/C++ lines covered: 118/120 (98.33%) · Uncovered code
| /// functions, and false for some functions that do throw while parsing row values (for example | ||
| /// addDays(String, ...) via FunctionDateOrDateTimeAddInterval). There is no sound can-throw | ||
| /// oracle in the tree yet, see the TODO on IFunctionBase::canThrow in IFunctionAdaptors.h. | ||
| if (!node_info.may_throw && node->type == ActionsDAG::ActionType::FUNCTION && node->function_base |
There was a problem hiding this comment.
The may_throw classifier is still a known false negative for FunctionDateOrDateTimeAddInterval: that family hard-codes isSuitableForShortCircuitArgumentsExecution = false in FunctionDateOrDateTimeAddInterval.h:996, even though addDays(String, ...) and similar calls can still throw while parsing row values.
That means a PREWHERE like tags['safe'] != '' AND addDays(tags['ts'], 1) > today() over the same Map or JSON column will still be grouped into one step here and evaluate addDays on rows the guard should have filtered out. So the PR still does not restore the "potentially throwing condition runs after its guard" invariant for that function family.
The read step splitter ends a step at every condition that reports true from isSuitableForShortCircuitArgumentsExecution, which is the only can-throw signal available in the tree today. That predicate is documented as "throws OR is computationally heavy", so conditions that are merely expensive, such as startsWith and LIKE, also become step boundaries and each one then deserializes the same Map data again. The PR description measured this on 16 conjuncts over one Map column, 1 step before and 16 after. Encode both shapes as performance queries next to the `!= ''` shape from ClickHouse#107988 that stays in a single step, so the cost is reported by the Performance Comparison check instead of living only in prose, and so a future change to the boundary predicate shows up as a measured difference. Verified on two Build-ID-checked binaries over a 200k row Wide part: master (a45998f2e6fe1165) groups all three shapes into 1 step; this branch (80934294df192fe2) keeps `!= ''` at 1 step and splits startsWith and LIKE into 16. Both binaries return 111040 rows for the two new shapes, so the split changes cost only. Co-Authored-By: Claude Fable 5 <[email protected]>
The comment attributed canThrow to IFunctionBase and findLazyExecutedNodes to ExpressionActions. canThrow is declared on IExecutableFunction (IFunction.h:134) and the delegation to isSuitableForShortCircuitArgumentsExecution lives in FunctionToExecutableFunctionAdaptor (IFunctionAdaptors.h:32); findLazyExecutedNodes is a file-local static in ExpressionActions.cpp and is absent from the header. Comment only, no behaviour change. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Both findings are accurate on the source facts, and I checked each one before acting. One is a pre-existing limitation this change already documents; the other asked for two things, and I took the actionable one.
It also throws with a byte-identical error on a current master build (Build ID Expensive-but-safe predicates as step boundaries. Also correct: A narrower predicate: I do not see a robust one to switch to. A performance test: agreed, and added. I also corrected the class names in the justification comment: Pushed as 6b2ad13. Both regression tests pass on the rebuilt binary (Build ID |
The flaky check marks a run over 180s as a failure, and this test straddled the limit on amd_asan_ubsan: 150s to 224s across the 50 runs, so it passed or failed on runner jitter alone. The job's own query_log shows the cost is concentrated in two queries. The two INSERTs that cast to JSON averaged 73.6s and 70.3s of the roughly 160s of query time, while the equally sized Map INSERT next to them took 1.4s. The cast to JSON is about 50 times more CPU per row: on an ASan build the 100000 row JSON INSERT burns 0.74s of CPU against the Map INSERT's 0.24s, and in CI it reached about 10.4s of user plus system time. Two factors combine. The per-row cost is the first. The second is that the flaky check runs the test 50 times with 8 workers on a 9 core runner, so 8 copies compete for cores: OSCPUWaitMicroseconds averages 38.6s and 31.5s on those two INSERTs, meaning the query was runnable but had no core. The very first, uncontended run of the same query in the same job took 1.1s. Row count alone is therefore not the problem, and neither are the randomized settings: on an idle ASan server the 100000 row JSON INSERT takes about 1s under the default profile, under CI's memory profiler profile, and under each of the randomized setting groups that could plausibly matter. Only the two JSON fixtures shrink, from 100000 to 10000 rows. Every modulus is unchanged, so each guard keeps its selectivity: 2/3 of the rows carry coordinates in the first table and 90% pass the guard in the second, which is still above the 60% threshold at which a read step applies its filter without being asked. The expected counts scale accordingly and were regenerated, not edited by hand. The Map fixtures are left alone because they are already cheap. Verified on three servers, each with buildId() checked against the binary: the seven statements that fail on pristine master are exactly the same seven, with the same error codes, before and after the shrink, so no assertion went vacuous; EXPLAIN actions=1 confirms the throwing CAST to Point still survives into the PREWHERE at 10000 rows and the part is still Wide; 50 randomized runs of both tests pass 100/100 with a worst case of 1.58s. Total query CPU for the file drops 5.4x on ASan, from 0.59s to 0.11s.
|
The The job's own Row count alone was not the cause, which is why I did not simply tag the test So only the two No assertion was weakened, and I checked that rather than assuming it. The seven statements that |
CI finish ledger — 0bec62cCI is fully finished on this head (174 checks, Finish Workflow green). No failure is caused by this
The Session id: cron:our-pr-ci-monitor:20260726-230000 |
| .need_filter = force_short_circuit_execution, | ||
| /// A step that precedes a may_throw condition must materialize its filter, so that | ||
| /// the throwing condition is not evaluated on the rows this step rejects. | ||
| .need_filter = force_short_circuit_execution || groups_requiring_filtered_input.contains(step_index + 1), |
There was a problem hiding this comment.
The new need_filter boundary only helps readers that actually invoke tryBuildPrewhereSteps. Parquet::Reader::preparePrewhere still guards that call with if (needs_filter) (src/Processors/Formats/Impl/Parquet/Reader.cpp:1212-1219), so an explicit PREWHERE gate = 1 AND toUInt64(tags['val']) > 50 WHERE 1 arrives there with prewhere_info->need_filter = false (src/Interpreters/InterpreterSelectQuery.cpp:1099-1101) and falls back to one unsplit step at Reader.cpp:1273.
That step executes both predicates on the same unfiltered block and returns before any filter is applied (Reader.cpp:3268, Reader.cpp:3284-3285), so the conversion still runs on rows the guard should have discarded. This still violates the new "guard before thrower" invariant for the Parquet path. Can we make the Parquet reader use the split steps even when the final PREWHERE filter is merged downstream, and honor the per-step filtering state for the intermediate guard step?
There was a problem hiding this comment.
The finding is real and all five citations are exact on this head. I verified it, implemented the remedy, measured it, and am still not shipping it here. Reasoning, with the measurements:
It reproduces, but only with the old analyzer. The example as written is not a carrier: gate and tags are different storage columns, so the split fires for an unrelated reason and the query returns a result on both binaries. Porting the actual #111879 shape to Parquet (Nullable coordinates, guard lon IS NOT NULL, thrower CAST(tuple(lon, lat), 'Point')) gives:
enable_analyzer |
trailing WHERE 1 |
pristine master | this branch |
|---|---|---|---|
| 1 | no | 13333 | 13333 |
| 1 | yes | 13333 | 13333 |
| 0 | no | 13333 | 13333 |
| 0 | yes | Code: 349 |
Code: 349 |
Deterministic 3/3 per binary. Only the last cell throws, because PlannerJoinTree.cpp:1745 sets need_filter = true unconditionally while InterpreterSelectQuery.cpp:1099-1101 sets it only when there is no WHERE. enable_analyzer defaults to true. Controls: the thrower alone does throw on this branch, and the committed 04630 test throws Code: 349 on pristine master and passes here, so the two binaries genuinely differ and the fix works on the path it claims.
It is pre-existing. The error text is md5-identical (17c95ec24c23ffd0…) on pristine master and on this branch. This PR's diff is 6 files, none under src/Processors/, and greps 0 for Parquet|needs_filter|preparePrewhere (control: the same diff greps 1 for need_filter). The if (needs_filter) guard is 954bf143d38aa74 from #107059, an ancestor of this PR's merge-base. MergeTree is clean in all 8 cells of the same matrix, so the gap is Parquet-specific and orthogonal to the splitter change.
I built the remedy and it works. With if (needs_filter) removed, the carrier returns 13333, and all 6 in-tree Parquet PREWHERE tests plus a 10-shape old-analyzer sweep are byte-identical to this branch. Three reasons it does not belong here:
- Fix NOT_FOUND_COLUMN_IN_BLOCK in the native Parquet V3 reader prewhere handling #107059's commit message records that this exact combination previously tripped an
Unexpected column in sample blockLOGICAL_ERROR, reachable only via the old analyzer, and that it therefore carries no regression test. I could not construct that error in 16 probes, so removing the guard is unproven in the direction that matters rather than proven safe. Both of Fix NOT_FOUND_COLUMN_IN_BLOCK in the native Parquet V3 reader prewhere handling #107059's tests pinenable_analyzer = 1, so neither covers the cell this would newly enable. - Different subsystem, and this PR is
v26.6-must-backport. Its diff isMergeTreeSplitPrewhereIntoReadSteps.cppplus tests. Reader.cpphas 9 open PRs against it, and Added Parquet Shredded VARIANT Support to ParquetReaderv3 #102499 restructurespreparePrewhereitself, so a change here would conflict.
The gap is already stated in the description ("hard-coded false for the Parquet reader"), which I re-verified: the split path passes literal true per step at Reader.cpp:1267, the single-step fallback passes needs_filter at :1273. I am leaving it disclosed rather than widening this PR, since closing it properly means either a dedicated canThrow oracle or reworking the Parquet reader's cross-step column addressing, both of which want their own change.
CI finish ledger — 5f8d896Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The Note on the first row: this build predates the fix. #112501 merged at 13:08:56Z, while this head Session id: cron:our-pr-ci-monitor:20260805-170000 |
With the `m['key']` -> Map key subcolumn rewrite disabled by default there is no reason to group PREWHERE conditions by physical storage column: without the rewrite all `m['kN']` conditions reference the same column, so grouping by the exact column set already places them into one read step. Restore the pre-#107988 grouping in `MergeTreeWhereOptimizer` and `tryBuildPrewhereSteps`. This also fixes the `CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN` regression from #107988: storage-column grouping merged a guard condition and a throwing expression over subcolumns of the same column into one read step, and every condition of a step is evaluated on the unfiltered block, so the throwing expression ran on rows the guard had rejected. Verified with the repro from #111879 on pre-built binaries: master before #107988 returns a result, master with #107988 throws, and this branch returns a result again. Improving subcolumn read sharing in PREWHERE is left for a separate change that does not need backporting. Tests: - 04815: regression test for the `JSON` subcolumn guard with a throwing `CAST(tuple, 'Point')`. - 04814: pin `optimize_map_element_to_subcolumn`, it is randomized in CI, so the test cannot rely on the default value. - `map_subcolumns_prewhere` performance test: drop the setting opt-in so it measures the default path. Closes: #111879 Related: #107988 Related: #111954 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Dear @Avogar, 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. |
|
The same blindness had quietly weakened One thing to decide before this merges. "Reading is safe" does not hold for a column with a pending, unmaterialised CREATE TABLE t (id UInt64, payload Tuple(safe String, val String)) ENGINE = MergeTree ORDER BY id
SETTINGS min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;
INSERT INTO t SELECT number, tuple(if(number % 3 = 0, '', 'y'), if(number % 3 = 0, 'bad', toString(number % 100))) FROM numbers(10000);
ALTER TABLE t MODIFY COLUMN payload Tuple(safe String, val UInt64) SETTINGS mutations_sync = 0;
SELECT count() FROM t PREWHERE payload.safe != '' AND toUInt64(payload.val) > 50;
Not a regression against a release: a one step plan over the same storage column throws identically, measured both with I also corrected the one sentence in the description that described the old test mechanism and the |
CI finish ledger - 57f5771Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Breadth, so the job ERROR is not read as specific to this pull request: the same Nothing else failed at this head: 48 checks green, 118 skipped, and the only CIDB FAIL row outside the job-level ERRORs above is the Session id: cron:our-pr-ci-monitor:20260924-220033 |
The read ahead of a later step's columns assumed that reading a column cannot throw. It can: the reader converts a column from the type a part stores (a pending `MODIFY COLUMN`) and fills a column a part lacks from its default expression on the whole block it reads, before any step filter. So a guard over the same storage column no longer protected a conversion such as `String` to `UInt64` of a `Tuple` element. `ReadFromMergeTree` now enables the read ahead per query only when every part stores every storage column PREWHERE reads with the table's type, and there are no on-the-fly mutations or masking policies. Otherwise the run of steps reads each column in the step that evaluates it, as before the read ahead. The decision is carried by `MergeTreeReaderSettings::read_ahead_prewhere_columns`, so the pool and the processors build the same steps. Projection index readers never read ahead. ClickHouse#111954 (comment)
The loop variable `name` shadowed the static `ReadFromMergeTree::name`, which broke the build. https://s3.amazonaws.com/clickhouse-test-reports/PRs/111954/d5b160b54dab22b00acf98c1d04b0ac0f43343ff/pr/fast_test/job.log
`StorageMergeTree::alter` waits for the `MODIFY COLUMN` mutation under `alter_sync`, not `mutations_sync`, and a `SETTINGS` clause after `MODIFY COLUMN` is parsed as column settings, so the `ALTER` threw the mutation's parse error. https://s3.amazonaws.com/clickhouse-test-reports/PRs/111954/483fba085989d4ad212d6b364a9e7a38d06d0efc/pr/fast_test/job.log
The fixture only needs strings that are not numbers, so `cityHash64` does the same. The result with runtime filters off is unchanged (`2501 2501`) and master still throws `CANNOT_PARSE_TEXT` with them on. Failed in `Stateless tests (amd_fips_release, meta in keeper, s3 storage, OpenSSL FIPS, parallel)` of ClickHouse/clickhouse-private#65962 with `Function MD5 is not available in FIPS mode`.
This branch has no `may_throw` in `MergeTreeSplitPrewhereIntoReadSteps` (from #111954), no `hasObservableSideEffects` and no `is_runtime_filter`. Keep the split step as it is here, and port the rest: `isExpensive` for the AI functions and their adaptors, and the `MergeTreeWhereOptimizer` changes that put expensive conditions in their own group and move them to PREWHERE after all other conditions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This branch has no `may_throw` in `MergeTreeSplitPrewhereIntoReadSteps` (from #111954), no `is_runtime_filter`, and none of the lambda body trait helpers (`allLambdaBodyFunctions`, `isLambdaBodyStateful` and the others). Keep the split step as it is here, and port the rest: `isExpensive` for the AI functions and their adaptors, with a standalone `isLambdaBodyExpensive` for lambdas, and the `MergeTreeWhereOptimizer` changes that put expensive conditions in their own group and move them to PREWHERE after all other conditions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n its subcolumn Since ClickHouse#107988, tryBuildPrewhereSteps groups adjacent PREWHERE conditions by the storage column they read, so that the keys of one Map, each of which reads the whole Map, share one read step (ClickHouse#107912). The resolution was type-blind: `j.kind` and `j`, two JSON paths, a Tuple element and the whole Tuple, `m.size0` and `m.key_k1`, and keys of two Maps nested in one Tuple all resolved to one storage column. A cheap subcolumn condition was then merged with an expensive condition on the rest of the column, which read the whole column for every row. On master a may-throw `toString(j)` gets its own step (ClickHouse#111954), but its read-ahead, keyed on the same comparison, reads `j` in step 0 anyway. Key each input by the storage column and the substreams cache key of its subcolumn path instead. A Map key subcolumn drops its trailing MapKeyValue, so it keys as the Map that owns it (`(m, "")` at the top level, as before; `(c, "%2Eleft")` for a Map inside a Tuple, so two sibling Maps no longer share a step). The pair is used rather than a concatenated string because the path rendering escapes tuple dots. MergeTreeWhereOptimizer keeps grouping by storage column: that keeps a guard ahead of a throwing condition on the same column. So with the expensive condition written first the order is still kept. Closes ClickHouse#124535 Co-Authored-By: Claude Opus 5.5 <[email protected]>
… them Since ClickHouse#111954 the PREWHERE read step splitter gives a condition its own step, and makes the step before it filter, whenever any of its functions reports `isSuitableForShortCircuitArgumentsExecution` (or `isExpensive`), so that a condition that may throw never runs on the rows a preceding guard rejects. `startsWith`/`endsWith` and `like`/`ilike` answer `true` there unconditionally ("worth evaluating lazily"), although they cannot throw on a `String` with a constant needle. `m['a1'] = 'v1' AND startsWith(m['a2'], 'p-')` was therefore split into two steps, with a forced filter copying the whole `Map` between them (ClickHouse#131717: 1.17x on a synthetic query, 2.03x on the original one). A flagged condition now shares the step when the sound oracle `IFunctionBase::canThrow` proves that no function in it can throw and none is expensive (`prewhereConditionCannotThrow`, used by `tryBuildPrewhereSteps` and by the guard grouping of `MergeTreeWhereOptimizer`). The whole condition is checked, not only its root, so a cheap throwing descendant still keeps the split. The functions of the reported condition describe `canThrowIfKnown`: - `startsWith`/`endsWith` family: cannot throw when both arguments are `String`/`FixedString` (the `Array` form converts to a common type). - `[not]like`/`[not]ilike`: cannot throw for a `String`/`FixedString` haystack and a constant pattern that builds; an `Enum` haystack, an ESCAPE argument, a non-constant or an invalid pattern may throw. - `arrayElement` on a `Map`: a lookup returns the default value for a missing key; it may throw only for `Enum` keys (a string key is converted to them). This only removes splits. `NOT startsWith(...)` keeps its split, `not` does not describe `canThrowIfKnown`. Closes ClickHouse#131717 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #111879
Closes: #121909
Closes: #121910
Closes: #115178
Related: #107988
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
CANNOT_INSERT_NULL_IN_ORDINARY_COLUMNandCANNOT_PARSE_TEXTwhen aPREWHEREguard predicate and a throwing expression, such as aCASTortoUInt64(substring(...)), end up in the same read step: either because they read subcolumns of the same column, for example aJSONorMapcolumn, or because a JOIN runtime filter's key computation was merged into the guarded subquery. Such a query used to fail because the throwing expression was evaluated on rows the guard had rejected.Description
Closes #111879, closes #121909, closes #121910. Regression from #107988, present from 26.3 and still reproducible on master.
All conditions of one PREWHERE read step are evaluated on the same unfiltered block, and the step filter is applied only afterwards, so a guard condition cannot protect a later condition placed in the same step.
Since #107988,
MergeTreeWhereOptimizergroups conditions by their physical storage column, so a guard such aspayload.longitude IS NOT NULLand a throwing predicate overpayload.latitudearrive adjacent andtryBuildPrewhereStepsmerges them into one step. The throwing expression then runs on the rows the guard rejects. Adding moreIS NOT NULLguards does not help, because they are hoisted into the same step.Commit 7572613 already reverted non-adjacent merging for this exact hazard ("would pull the throwing conversion before the
value > 0filter"); this change closes the adjacent case, which the same reasoning covers.Fix, in
tryBuildPrewhereSteps:may_throwflag through the existingfillRequiredColumnsDFS, usingIFunctionBase::isSuitableForShortCircuitArgumentsExecution, the predicate the short-circuit machinery uses. It answers "throws or is expensive" rather than "throws", so it reports true for merely expensive functions and false for some that throw while parsing row values, such asaddDays(String, ...). Master also carriesIFunction::canThrow, which the comparison functions override type-awarely and which a node reaches throughFunctionToFunctionBaseAdaptor::getFunction(), no header change needed. I did not consume it because the divergence has no read-step consequence I could reach: a date column against a non-const string is rejected asNO_COMMON_TYPE; against a const string it raisesCANNOT_PARSE_DATEeven on an empty table with no guard, so no step boundary prevents it; enum-to-string and cross-scale decimal comparisons do not throw.need_filter = trueon the step immediately preceding such a boundary. A boundary alone is not sufficient: a non-final step'sneed_filteris justquery_plan_merge_filtersandReadResult::optimizeapplies a step filter on its own only when fewer than 60% of the rows pass. Without this, a guard that keeps most rows, orquery_plan_merge_filters = 0, would leave the throwing step reading rejected rows.Maponce per key. The read ahead is enabled per query only when no part needs a read-time conversion or default fill for a column PREWHERE reads, and there are no on-the-fly mutations or masking policies, because those run on the whole block before any step filter (ReadFromMergeTree::canReadPrewhereColumnsAhead).andverbatim, so an innerandcounted as one atomic condition and its guard and throwing predicate stayed together.optimizePrewherebuilds exactly that shape,and(existing_prewhere, and(guard, throwing)), when it merges a movedWHEREinto an existingPREWHEREunderoptimize_prewhere_after_pushdown. The flattening preserves the original order, which both the boundary logic and a user writtenPREWHEREdepend on.Conditions that cannot throw are still grouped, so the redundant-read optimization from #107988 is preserved for the shapes it targets.
arrayElement,tupleElementand the comparison functions all report false, so the query shapes intests/performance/map_subcolumns_prewhere.xmlkeep their read-step counts (16 Map keys in explicit PREWHERE: 1 step; Map keys interleaved with another column: 2 steps; 6 Map keys via WHERE: 1 step).The predicate's imprecision means that conjunctions of merely expensive functions, such as
startsWithorLIKEoverMapkeys, now get a step per condition where master grouped them. Because their keys are read by the first step of the run, theMapis still deserialized once; what remains is the forced filter materialization between the steps. The two shapes are intests/performance/map_subcolumns_prewhere.xml(#6 and #7). Before the read-ahead, the performance check measured them at +2.4x (236 ms to 575 ms on arm), because each of the 16 steps re-read theMap.The Parquet reader also calls
tryBuildPrewhereStepsnow, and adds every split step with a filter regardless of the step'sneed_filter, so the forced filter changes nothing there; only the extra boundaries apply.The regression test covers the JSON repro from the issue, the same shape with both coordinates guarded,
allow_reorder_prewhere_conditions = 0,query_plan_merge_filters = 0, a guard that keeps 90% of the rows, Map subcolumns via both WHERE and a user written PREWHERE, a guard and a throwing condition on different physical columns, a nested conjunction from a WHERE merged into an existing PREWHERE, and an assertion that non-throwing Map conditions are still rewritten to subcolumns. It also covers the JOIN runtime filter route reported in #121909 and #121910: withenable_join_runtime_filters = 1the filter's key computation is merged into the probe side's own DAG and moved intoPrewhereInfo, which has no re-split, so a guardedCASTortoUInt64(substring(...))lands in the guard's step. That is four value-asserting shapes, twoenable_join_runtime_filters = 0controls, and one plan assertion per route that theRuntime filtersannotation under the probe sideReadFromMergeTreenames the guarded expression as the filter key, so those arms cannot silently stop covering the route. A companion.shtest asserts the grouping itself through theRowsReadByPrewhereReadersprofile event, that flattening a non-throwing nested conjunction still leaves one step, and that a run of throwing conditions over oneMapreads theMaponce (RowsReadByPrewhereReadersequals the table's rows, andReadCompressedBytesstays below twice that of the grouped query).The flat
WHEREform of the different-columns case is deliberately not asserted:MergeTreeWhereOptimizerorders moved conditions by estimated column size, so a throwing condition can legitimately become the first step. That is equally true on master, so a flatWHEREcarries no evaluation order contract; a user writtenPREWHEREdoes, and that is the form the test pins.Not covered: the two further runtime filter symptoms in #121909 (comment) (
CASTin the SELECT list of aFINALsubquery, and the table-lessparseDateTimequery) do not go through PREWHERE at all. There the guarded expression is a non-filter output of aFilterStepwhose DAG is evaluated as a whole before filtering, so they need a separate fix.Workflow [PR]
Sync PR [sync-upstream/pr/111954]
Version info
26.10.1.821-master(included in26.10and later)