Skip to content

Do not evaluate a potentially throwing PREWHERE condition ahead of its guard - #111954

Merged
fm4v merged 19 commits into
ClickHouse:masterfrom
groeneai:fix/prewhere-subcolumn-guard-throwing-expression
Sep 27, 2026
Merged

fm4v merged 19 commits into
ClickHouse:masterfrom
groeneai:fix/prewhere-subcolumn-guard-throwing-expression

Conversation

@groeneai

@groeneai groeneai commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111879
Closes: #121909
Closes: #121910
Closes: #115178
Related: #107988

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN and CANNOT_PARSE_TEXT when a PREWHERE guard predicate and a throwing expression, such as a CAST or toUInt64(substring(...)), end up in the same read step: either because they read subcolumns of the same column, for example a JSON or Map column, 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, 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. Adding more IS NOT NULL guards 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 > 0 filter"); this change closes the adjacent case, which the same reasoning covers.

Fix, in tryBuildPrewhereSteps:

  • Propagate a may_throw flag through the existing fillRequiredColumns DFS, using IFunctionBase::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 as addDays(String, ...). Master also carries IFunction::canThrow, which the comparison functions override type-awarely and which a node reaches through FunctionToFunctionBaseAdaptor::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 as NO_COMMON_TYPE; against a const string it raises CANNOT_PARSE_DATE even on an empty table with no guard, so no step boundary prevents it; enum-to-string and cross-scale decimal comparisons do not throw.
  • A condition that may throw always starts a new read step, so every condition already in the group is evaluated before it.
  • Force need_filter = true on the step immediately preceding such a boundary. A boundary alone is not sufficient: a non-final step's need_filter is just query_plan_merge_filters and ReadResult::optimize applies a step filter on its own only when fewer than 60% of the rows pass. Without this, a guard that keeps most rows, or query_plan_merge_filters = 0, would leave the throwing step reading rejected rows.
  • Read the columns of a condition that is split out only because it may throw (it reads the same storage columns as the step before it) in the first step of that run. Reading is safe, only the evaluation has to wait for the filter, so the later steps read nothing and just evaluate their condition on the filtered rows. Without this, every such step deserialized the storage column again, for example the whole Map once 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).
  • Flatten nested conjunctions before grouping. The splitter used to take the children of the top-level and verbatim, so an inner and counted as one atomic condition and its guard and throwing predicate stayed together. optimizePrewhere builds exactly that shape, and(existing_prewhere, and(guard, throwing)), when it merges a moved WHERE into an existing PREWHERE under optimize_prewhere_after_pushdown. The flattening preserves the original order, which both the boundary logic and a user written PREWHERE depend on.

Conditions that cannot throw are still grouped, so the redundant-read optimization from #107988 is preserved for the shapes it targets. arrayElement, tupleElement and the comparison functions all report false, so the query shapes in tests/performance/map_subcolumns_prewhere.xml keep 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 startsWith or LIKE over Map keys, now get a step per condition where master grouped them. Because their keys are read by the first step of the run, the Map is still deserialized once; what remains is the forced filter materialization between the steps. The two shapes are in tests/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 the Map.

The Parquet reader also calls tryBuildPrewhereSteps now, and adds every split step with a filter regardless of the step's need_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: with enable_join_runtime_filters = 1 the filter's key computation is merged into the probe side's own DAG and moved into PrewhereInfo, which has no re-split, so a guarded CAST or toUInt64(substring(...)) lands in the guard's step. That is four value-asserting shapes, two enable_join_runtime_filters = 0 controls, and one plan assertion per route that the Runtime filters annotation under the probe side ReadFromMergeTree names the guarded expression as the filter key, so those arms cannot silently stop covering the route. A companion .sh test asserts the grouping itself through the RowsReadByPrewhereReaders profile event, that flattening a non-throwing nested conjunction still leaves one step, and that a run of throwing conditions over one Map reads the Map once (RowsReadByPrewhereReaders equals the table's rows, and ReadCompressedBytes stays below twice that of the grouped query).

The flat WHERE form of the different-columns case is deliberately not asserted: MergeTreeWhereOptimizer orders moved conditions by estimated column size, so a throwing condition can legitimately become the first step. That is equally true on master, so a flat WHERE carries no evaluation order contract; a user written PREWHERE does, and that is the form the test pins.

Not covered: the two further runtime filter symptoms in #121909 (comment) (CAST in the SELECT list of a FINAL subquery, and the table-less parseDateTime query) do not go through PREWHERE at all. There the guarded expression is a non-filter output of a FilterStep whose DAG is evaluated as a whole before filtering, so they need a separate fix.


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

Version info

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

groeneai and others added 6 commits July 25, 2026 22:59
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 5 rounds, 7 findings total;
2 blockers and 4 majors raised and fixed before publication, 1 nit noted below). Every
finding was adjudicated against the code; the fix rounds are the commits in this PR.

# Sev Finding Verdict Evidence / action
1 ❌ A may-throw condition starting a new step is not enough: a non-final step's need_filter is only query_plan_merge_filters, and ReadResult::optimize applies a step filter on its own only when fewer than 60% of rows pass, so the throwing step still sees rejected rows AGREE — fixed @ ccb7abc, 1e835e6 need_filter = true is now forced on the step preceding every may-throw group, independently of query_plan_merge_filters. A 90%-pass-guard case reproduces the hole on the base binary and is pinned in the test; reverting the clause makes it fail again
2 ❌ The splitter took the children of the top-level and verbatim, so a nested and(existing, and(guard, throwing)) counted as one atomic condition and the guard stayed in the throwing step AGREE — fixed @ c3d243d Conjunctions are flattened left to right before grouping. optimizePrewhere builds exactly that shape when a moved WHERE merges into an existing PREWHERE; the new case throws CANNOT_PARSE_TEXT on the base binary at both query_plan_merge_filters values
3 ⚠️ The predicate reports true for merely expensive functions, so conjunctions of startsWith/LIKE split where master grouped them AGREE — measured and disclosed Quantified in the description: 16 conjuncts over one Map go from 1 step to 16, ~5x wall clock, SelectedMarks unchanged. The committed performance test uses comparisons, which report false, so it keeps 1 step
4 ⚠️ The predicate also has false negatives, which the comment did not state AGREE — fixed @ 1e835e6 The comment now names the false-negative direction with addDays(String, ...) as the example and points at the canThrow TODO
5 ⚠️ RowsReadByPrewhereReaders = 100000 cannot distinguish a correct one-group split from the splitter declining and falling back to a single step, so two assertions passed for the wrong reason AGREE — fixed @ c82344f Reshaped to counts no fallback can produce (300000 for three steps). Every asserted value was measured, not predicted, and mutation-tested: reverting the flattening makes the nested assertion fail
6 ⚠️ The read-step test's assertions depend on the subcolumn rewrite, which is analyzer-only, so they silently evaluate to 0 in the old-analyzer job AGREE — fixed @ ed0ba2a enable_analyzer 1 pinned in the client options the measured queries already carry. Verified in both directions on an old-analyzer server
7 💡 The justification comment attributes canThrow to IFunctionBase and findLazyExecutedNodes to ExpressionActions; both names are wrong AGREE — noted, not blocking Correct: canThrow is declared on IExecutableFunction (IFunction.h), with the delegating override and its TODO in FunctionToExecutableFunctionAdaptor (IFunctionAdaptors.h); findLazyExecutedNodes is file-local in ExpressionActions.cpp. Both symbols are findable by bare name in the files the comment already names, and every substantive claim in that comment was re-verified as correct, so this is left as a wording nit rather than another round

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20260726-131501

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on pristine base 693a303c10174: the issue query over a 500k-row JSON table throws Code: 349 CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN. Reduced to 100k rows in 04630_prewhere_subcolumn_guard_throwing_expression, which fails on the base build and passes with the fix.
b Root cause explained? All conditions of one PREWHERE read step are evaluated on the same unfiltered block, and the step filter is applied only afterwards (MergeTreeRangeReader.cpp), so nothing filters between conditions inside a step. Since #107988 MergeTreeWhereOptimizer::analyzeImpl groups conjuncts by their physical storage column, so payload.longitude IS NOT NULL and pointInPolygon(CAST(tuple(payload.longitude, payload.latitude), 'Point'), ...) both resolve to {payload}, arrive adjacent, and tryBuildPrewhereSteps merges them into one step combined with and(). Short circuit cannot help: the CAST chain is a prewhere DAG output (the outer query needs latitude/longitude), and used_in_result disables lazy execution. So the CAST runs on the NULL rows the guard would have removed.
c Fix matches root cause? Yes, it restores the missing safety condition at the layer that owns step boundaries. A condition that may throw no longer shares a step with a preceding condition, and the preceding step is forced to materialize its filter. No ifNull widening, no catching 349, no disabling the #107988 grouping.
d Test intent preserved / new tests added? Two new tests. 04630_prewhere_subcolumn_guard_throwing_expression (17 assertions, tagged no-random-merge-tree-settings) covers JSON and Map subcolumns, same and mixed storage columns, guard selectivity on both sides of the 60% threshold, and query_plan_merge_filters 1 and 0, plus a nested conjunction case (PREWHERE pre = 1 with a same-Map WHERE guard merged in under optimize_prewhere_after_pushdown = 1, at both query_plan_merge_filters values). 04631_prewhere_subcolumn_guard_read_steps.sh asserts the #107988 optimization still fires by counting read steps through ProfileEvents['RowsReadByPrewhereReaders'], the same technique 03143_prewhere_profile_events.sh uses: 100000 for four grouped Map conditions, more than 100000 once the throwing condition gets its own step, exactly 300000 for a three step plan where a condition on another column interleaves two Map conditions (a count no single step plan can produce), 100000 for a nested conjunction over one Map that must stay grouped, and exactly 300000 for a nested conjunction whose conditions read different columns, which reads 200000 unless the nested conjunction is flattened. Every asserted count was measured and cross-checked against the splitter's own PREWHERE condition was split into N steps log. No existing test was modified or weakened.
e Both directions demonstrated? Yes, with Build-ID-verified binaries throughout. Base 4e04387da97085ed: the JSON cases, allow_reorder_prewhere_conditions=0, the 90%-pass variant, and the mixed-storage PREWHERE at query_plan_merge_filters=0 all throw (Code: 349 / Code: 6); the whole test file FAILS. Fixed 80934294df192fe2: all return the expected counts and the file passes, 100/100 under the runner's full setting randomization. The nested conjunction case throws Code: 6 CANNOT_PARSE_TEXT on the base and returns 45000 3375000 with the fix, at both query_plan_merge_filters values. Two mutation binaries keep each half of the fix isolated as load-bearing rather than inferred: with the forced-need_filter clause deleted, 04630 still FAILS (Code: 6, the query_plan_merge_filters = 0 case); with the nested-conjunction flatten reverted, 04631 FAILS on the read step count (200000 instead of 300000).
f Fix is general across code paths? Fixed in tryBuildPrewhereSteps, the single function that decides step boundaries, so it covers the WHERE-to-PREWHERE path, user written PREWHERE, allow_reorder_prewhere_conditions=0, and the Parquet v3 reader which calls the same splitter. The sibling hazard (non-adjacent grouping) was already handled by 7572613; this closes the adjacent case, and the condition list is now the flattened conjunction so an optimizer built nested and (optimizePrewhere merging a moved WHERE into an existing PREWHERE) is grouped condition by condition instead of as one opaque unit. The single-step fallback (enable_multiple_prewhere_read_steps=0) evaluates the original DAG unchanged and is pre-existing behavior, not part of this regression.
g Fix generalizes across inputs (params/datatypes/wrappers)? The new predicate is per function, not per type, so the strip-all-wrappers hazard does not apply. Verified anyway across JSON dynamic subcolumns, Map(String, String), Map(String, LowCardinality(String)), guard and throwing condition on the same and on different physical columns, with query_plan_merge_filters 1 and 0, with guard selectivity both below and above the 60% threshold, at boundaries (empty table, 1 row all rejected, 2 rows one passing), and across conjunction shapes (flat and nested, the latter both throwing and all non throwing). One negative result is worth stating: a flat WHERE a AND b carries no evaluation-order guarantee, because MergeTreeWhereOptimizer orders the conditions it moves by estimated column size, so a throwing condition can legitimately become the first step. That shape throws on master too and is not asserted; only a user written PREWHERE, which does preserve order, is.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default change, no new setting, no serialization or format change, so no SettingsChangesHistory.cpp entry. The only behavior change is that a query which used to throw now returns the correct result, plus possibly one additional read step for the affected query shape.
i Invariants and contracts preserved? Invariant established: a condition that can throw is never evaluated on rows a preceding PREWHERE condition rejects. It needs both halves, and both are implemented: a step boundary, and need_filter=true on the preceding step (a boundary alone is insufficient because ReadResult::optimize applies a step filter on its own only when fewer than 60% of rows pass, and a non-final step's need_filter is otherwise just query_plan_merge_filters). The splitter's own contract that the step chain is equivalent to the original DAG is unchanged: only grouping and filter materialization change, never the conditions or the outputs. The Parquet reader consumes each step's actions and passes its own needs_filter, so the forced need_filter does not change which steps it registers (verified in Parquet/Reader.cpp).

Session id: cron:clickhouse-impl-slot-7:20260726-100300

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3e2bd49]

Summary: ✅


AI Review

Summary

This PR fixes the main PREWHERE step-splitting hazard and makes the new read-ahead optimization safe around pending MODIFY COLUMN, masking policies, and runtime-filter carriers. The remaining problems are both in the new may_throw classifier: the branch still leaves real same-storage PREWHERE shapes where a throwing predicate stays in the guard's read step, so the advertised "guard before thrower" invariant is not fully restored.

Findings
❌ Blockers
  • [src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp:92] may_throw is still derived only from isSuitableForShortCircuitArgumentsExecution, so it misses the existing canThrow overrides on FunctionComparison / FunctionsNullSafeCmp. Those comparison nodes are still treated as non-throwing here even though mixed-scale DateTime64 / Time64 / Decimal comparisons can raise DECIMAL_OVERFLOW (src/Functions/FunctionsComparison.h:804-818, 1778-1787, tests/queries/0_stateless/04510_optimize_and_compare_chain_comparison_domains.sql:63-83). Put one of those comparisons behind a guard over the same Tuple / JSON / other shared storage column and tryBuildPrewhereSteps will still group it into the guard's step, so the comparison is evaluated on rows the guard should have discarded. Suggested fix: when node->function_base is a FunctionToFunctionBaseAdaptor, consult the wrapped IFunction::canThrow and fall back to isSuitableForShortCircuitArgumentsExecution only for other IFunctionBase implementations.
⚠️ Majors
  • [src/Storages/MergeTree/MergeTreeSplitPrewhereIntoReadSteps.cpp:92] [dismissed by author -- https://github.com/Do not evaluate a potentially throwing PREWHERE condition ahead of its guard #111954#discussion_r3652805519] The current classifier still has the FunctionDateOrDateTimeAddInterval false negative that the comment itself calls out. FunctionDateOrDateTimeAddInterval::isSuitableForShortCircuitArgumentsExecution is hard-coded to false (src/Functions/FunctionDateOrDateTimeAddInterval.h:1015), so PREWHERE tags['safe'] != '' AND addDays(tags['ts'], 1) > ... over the same Map / JSON / Tuple storage column is still grouped into one step and still evaluates addDays on rejected rows. Documenting that limitation is helpful, but it still leaves a real guard-bypass repro in the exact code path this PR is trying to harden. Suggested fix: either use a real canThrow signal here as above, or narrow the PR contract and coverage so it no longer claims to protect potentially throwing PREWHERE conditions in general.
Final Verdict

Not ready: the step-splitting and read-ahead plumbing look sound, but the surviving may_throw false negatives mean there are still PREWHERE shapes that evaluate a throwing predicate before its guard.

LLVM Coverage Report

Measured on commit 3e2bd49.

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 26, 2026
/// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

groeneai and others added 2 commits July 26, 2026 15:57
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

addDays false negative. Correct, and it reproduces. FunctionDateOrDateTimeAddInterval does hard-code isSuitableForShortCircuitArgumentsExecution to false (FunctionDateOrDateTimeAddInterval.h:996), and addDays(String, ...) parses per row via parseDateTime64BestEffort (:99-101). Your exact shape throws on this branch:

PREWHERE tags['safe'] != '' AND addDays(tags['ts'], 1) > toDateTime('2019-01-01')
-> Code: 41 CANNOT_PARSE_DATETIME ... FUNCTION addDays(tags.key_ts :: 1, ...)

It also throws with a byte-identical error on a current master build (Build ID a45998f2e6fe1165 vs this branch's b69b5fdf819c1af4), so this is pre-existing behaviour rather than something the change introduces or regresses. The classifier's false-negative direction is stated at the call site and in the description, naming this function family specifically. Closing it needs the dedicated canThrow oracle that IFunctionAdaptors.h:31 already carries a TODO for, which means auditing every function class, so it is a separate change.

Expensive-but-safe predicates as step boundaries. Also correct: FunctionStartsEndsWith.h:94-96 and FunctionsStringSearch.h:141 both return true. Taking the two asks separately.

A narrower predicate: I do not see a robust one to switch to. canThrow has exactly one override and it forwards to isSuitableForShortCircuitArgumentsExecution (IFunctionAdaptors.h:32), and IFunction.h:319-322 documents that predicate as "throws OR is computationally heavy", so the imprecision is by construction rather than an oversight in how I am calling it. A name or return-type allowlist that exempts startsWith and LIKE would key on an incidental property instead of a robust one, and it would be silently wrong the moment a listed function grows a throwing path. The precedent points the same way: 7572613 hit this hazard in the same function and accepted extra reads by reverting non-adjacent grouping rather than narrowing the predicate. Correctness first, and the oracle removes the cost properly.

A performance test: agreed, and added. tests/performance/map_subcolumns_prewhere.xml now carries the two regressed shapes (16 startsWith and 16 LIKE conjuncts over one Map in an explicit PREWHERE) next to the != '' shape from #107988 that stays in a single step, so the grouped and split costs sit side by side and the Performance Comparison check reports the number instead of it living only in prose. Measured on a 200k-row Wide part with send_logs_level=test: master groups all three shapes into 1 step; this branch keeps != '' at 1 step and splits startsWith and LIKE into 16. Both binaries return 111040 rows for the new shapes, so the predicates filter and the split is cost-only.

I also corrected the class names in the justification comment: canThrow is on IExecutableFunction (IFunction.h:134) with the delegation in FunctionToExecutableFunctionAdaptor, and findLazyExecutedNodes is a file-local static in ExpressionActions.cpp, not a member of ExpressionActions.

Pushed as 6b2ad13. Both regression tests pass on the rebuilt binary (Build ID b69b5fdf819c1af4).

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

The Stateless tests (amd_asan_ubsan, flaky check) failure on 6b2ad13 was my new test
04630_prewhere_subcolumn_guard_throwing_expression straddling the 180s per-run limit: 150s to
224s across the 50 runs, so it passed or failed on runner jitter alone. Fixed in 0bec62c.

The job's own query_log localised the cost to two queries. The two INSERTs that cast to JSON
averaged 73.6s and 70.3s of the ~160s of query time, while the equally sized Map INSERT beside
them took 1.4s. The cast to JSON is roughly 50x more CPU per row (ASan, 100000 rows: 0.74s CPU
versus the Map INSERT's 0.24s; in CI it reached ~10.4s user+system).

Row count alone was not the cause, which is why I did not simply tag the test long. The flaky
check runs 50 iterations with 8 workers on a 9 core runner, so 8 copies compete for cores:
OSCPUWaitMicroseconds averaged 38.6s and 31.5s on those two INSERTs, i.e. the query was runnable
but had no core. The first, uncontended run of the same query in the same job took 1.1s. On an idle
ASan server that INSERT takes about 1s under the default profile, under CI's memory profiler
profile, and under each randomized setting group that could plausibly matter.

So only the two JSON fixtures shrink, 100000 to 10000 rows. Every modulus is unchanged, so each
guard keeps its selectivity: 2/3 of rows carry coordinates in the first table, and 90% pass the
guard in the second, still above the 60% threshold at which a read step applies its filter
unprompted. The expected counts were regenerated, not hand edited. The Map fixtures are untouched
because they are already cheap.

No assertion was weakened, and I checked that rather than assuming it. The seven statements that
fail on pristine master are exactly the same seven, with the same error codes, before and after the
shrink. EXPLAIN actions = 1 confirms the throwing CAST(..., '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 1.58s worst case. Total query CPU for the file drops 5.4x on ASan, 0.59s to 0.11s.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0bec62c

CI is fully finished on this head (174 checks, Finish Workflow green). No failure is caused by this
PR: every red check below is an existing trunk defect, and each one has an owner.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_tsan) / Block structure mismatch in after optimization liftUpUnion (STID 0993-23fd) logical error, tryLiftUpUnion pushes a parent step past a union that coerces a diverging aggregate-state branch #110745 (ours, open)
Stress test (arm_asan_ubsan) / Reading from materialized CTE 'ct' before its materialization completed - DelayedPortsProcessor gate is missing (STID 2467-2c2d) logical error on a fuzzed nested-materialized-CTE query inside viewExplain #110428 (ours, open) covers the self-named set-operation shape of this error; the nested shape seen here is still being investigated at full effort, and its fixing-PR link will be posted here
Stateless tests (arm_binary, parallel) / 04357_distributed_alias_same_expression un-merged GROUP BY groups on a Distributed table over duplicate ALIAS columns: the reference expects 300 300 2, the run returned 300 300 1 twice, i.e. one group per shard with a split count(). The run drew group_by_two_level_threshold_bytes = 1 and distributed_aggregation_memory_efficient = 1, which forces the two-level path #108855 (ours, open)

The Stateless tests (amd_asan_ubsan, flaky check) failure on the previous head (6b2ad13) was mine and
is fixed in this PR at 0bec62c; all four flaky-check jobs are green here.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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:

  1. 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 block LOGICAL_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 pin enable_analyzer = 1, so neither covers the cell this would newly enable.
  2. Different subsystem, and this PR is v26.6-must-backport. Its diff is MergeTreeSplitPrewhereIntoReadSteps.cpp plus tests.
  3. Reader.cpp has 9 open PRs against it, and Added Parquet Shredded VARIANT Support to ParquetReaderv3 #102499 restructures preparePrewhere itself, 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.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5f8d896

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.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / Logical error: Bad cast from type A to B (STID 4350-5ca2) + Server died crash in MergeTreeDataPartWriterOnDisk::initColumnsSubstreamsIfNeeded on the mutation path, reached from MutateTask. Trunk defect, unrelated to this diff (which only touches PREWHERE step splitting); the same signature is live on master and across unrelated PRs #112501 (external, merged 2026-08-05T13:08:56Z)
Build (arm_release) / Post Hooks infra: build-profile telemetry INSERT fails against the CI logs cluster (non-gating hook; the enclosing check reports success, so it is invisible to the check-runs API) #113409 (external, open)

The Server died line and the Bad cast line are one event, not two.

Note on the first row: this build predates the fix. #112501 merged at 13:08:56Z, while this head
was built from a master merge pushed at 11:44:56Z; I confirmed the fix is absent at this head by
content probe (its regression test 04653_mutation_rewrite_stale_part_column_type.sql is 404 at
this commit and present at the merge commit and on master). I am not merging master to pick it up,
because the current head is a maintainer-pushed master merge, not mine; the fix will arrive with
the next such merge.

Session id: cron:our-pr-ci-monitor:20260805-170000

Avogar added a commit that referenced this pull request Aug 13, 2026
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]>
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fast test was red on b7feb136 because 04631's split steps assertion rests on a premise that does not hold: a prewhere step whose reader has no columns does not count its rows. MergeTreeRangeReader::continueReadingChain returns at MergeTreeRangeReader.cpp:1479-1481 (merge_tree_reader->getColumns().empty()) before updatePerformanceCounters, so the throwing query reads exactly 100000, not more.

The same blindness had quietly weakened grouped steps, nested grouped steps and read ahead bytes: with the columns read ahead, a one step plan and an N step run over one storage column produce the same row count and the same byte count, so those lines passed for plans they were written to reject. 57f5771e asserts the step count MergeTreeSelectProcessor reports at TEST level in each of them and keeps the read volume checks; the reference file is unchanged. Mutation checked: removing the may-throw split reports 1 step instead of 2 and 4, removing the read ahead turns the same two lines red on their row and byte halves, and 50/50 runs are green.

One thing to decide before this merges. "Reading is safe" does not hold for a column with a pending, unmaterialised MODIFY COLUMN: the conversion is applied to the whole block the reader returns, before the step filter. A/B on your head, one tree, only inputs_read_ahead differing:

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;
  • head as pushed: 2 steps, step 0 inputs payload.safe.size and payload.val, Code: 6 ... Cannot parse string 'bad' as UInt64 ... while executing 'FUNCTION _CAST(payload.val :: 0, 'UInt64'_String ...)'
  • same tree, only inputs_read_ahead disabled: 2 steps, step 0 inputs payload.safe.size, returns 3266
  • control with the guard on a different storage column, so the read ahead does not apply: 3266 on both binaries

Not a regression against a release: a one step plan over the same storage column throws identically, measured both with enable_multiple_prewhere_read_steps = 0 and with the comparison spelled without toUInt64 so it is not a boundary at all. So this is a case the pre-read-ahead shape of this PR happened to cover and the read ahead gives up, not something that worked in 26.x. I left the splitter alone: whether to make the read ahead conversion aware is a call about your optimization, and alter conversions are a per part property while inputs_read_ahead is computed once per query.

I also corrected the one sentence in the description that described the old test mechanism and the RowsReadByPrewhereReaders premise. Nothing else in the body changed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 57f5771

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.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) CI infrastructure, not a test result: the targeted test-selection step read-timed-out against play.clickhouse.com (Read timed out. (read timeout=60)), and ci/jobs/functional_tests.py:867 converts any selection exception into a job-level ERROR, so the job stopped before running a single test a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Stateless tests (arm_asan_ubsan, targeted) same selection step, same read timeout, same job-level ERROR with 0 tests run a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Finish Workflow / Post Hooks (new_tests_check.py) consequence of the two rows above: both Bugfix validation (functional tests, amd64 and aarch64) arms report DROPPED (Dropped due to previous failure [Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted)]), and the hook validates a bug fix only when at least one per-arch arm reports OK or XFAIL a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Mergeable Check rollup of the rows above a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
PR praktika aggregator rollup of the same rows a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

Breadth, so the job ERROR is not read as specific to this pull request: the same Failed to load test selection signature appears 121 times across about 80 distinct pull requests in the 17:00Z to 21:00Z window today (68 rows over 47 PRs in the 18:00Z hour, 47 rows over 29 PRs in the 19:00Z hour), on all three targeted stateless flavours, and 0 times in the preceding 6 days. In the same window the public endpoint answers Quota for user play for 3600s has been exceeded: read_rows = 300002020588/300000000000, and that is the endpoint the selection step queries. Merged #120928, which makes the step wait for a CI database query slot, is already contained in this head (compare reports behind_by=0), so it does not cover the socket read-timeout path and is deliberately not linked as the owner here.

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 Post Hooks row already listed, so no stateless, integration, fuzzer or sanitizer test regressed.

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)
`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`.
@fm4v
fm4v added this pull request to the merge queue Sep 27, 2026
Merged via the queue into ClickHouse:master with commit 80f6567 Sep 27, 2026
172 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 27, 2026
PedroTadim added a commit that referenced this pull request Oct 30, 2026
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]>
PedroTadim added a commit that referenced this pull request Oct 30, 2026
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]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 5, 2026
…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]>
27rohan pushed a commit to 27rohan/ClickHouse that referenced this pull request Nov 18, 2026
… 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]>
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

5 participants