Skip to content

Do not give startsWith and LIKE their own PREWHERE read step - #132112

Merged
fm4v merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/prewhere-starts-with-like-same-step
Nov 18, 2026
Merged

fm4v merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/prewhere-starts-with-like-same-step

Conversation

@groeneai

@groeneai groeneai commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131717
Related: #111954

Changelog category (leave one):

  • Performance Improvement

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

A PREWHERE condition with startsWith or endsWith over a String, or with LIKE or ILIKE with a constant pattern, such as m['a'] = 'x' AND startsWith(m['b'], 'p-'), is evaluated in the same read step as the condition before it again, instead of in a separate step that filters the whole block in between. Such queries over a Map column are about 1.2 times faster.

Description

This fixes a regression from my own #111954. To keep a condition that may throw from running on rows a preceding guard rejects, the PREWHERE step splitter gives it its own step and makes the step before it filter. It decides "may throw" with isSuitableForShortCircuitArgumentsExecution, which startsWith and LIKE answer true for because they are worth evaluating lazily, although they cannot throw on a String with a constant needle. So m1['a1'] = 'v1' AND startsWith(m1['a2'], 'p-') got two steps with a filter of the whole Map between them.

A flagged condition now joins the previous step when IFunctionBase::canThrow proves that none of its functions can throw and none is expensive. The whole condition is checked, not only its root, so startsWith(lower(m['k']), 'x') keeps its split. The guard grouping of MergeTreeWhereOptimizer uses the same check. Three functions describe canThrowIfKnown now: the startsWith/endsWith family on String/FixedString; [not]like/[not]ilike on a String haystack with a constant pattern that builds (an Enum haystack, ESCAPE, a non-constant or invalid pattern still count as throwing); arrayElement on a Map without Enum keys. A Map lookup compared with a constant and startsWith therefore also qualify for the existing reorderings of non-throwing conditions. NOT startsWith(...) keeps its split, not describes nothing. match, position and the rest of FunctionsStringSearch are not described: the reported queries need only these.

Validation: the issue's query goes from 3 steps to 2 with the same result. 04631 gets cases in both directions: the new grouped ones fail on master, and 8 mutations of the change each turn it red. RelWithDebInfo, 4M rows of the issue's table, n=20: startsWith 568 -> 463 ms, LIKE 575 -> 468 ms, the comparison form unchanged (n=30: 454.5 vs 454.5 ms).


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

Version info

  • Merged into: 26.11.1.2664-master (included in 26.11 and later)

groeneai and others added 3 commits November 16, 2026 14:35
… 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]>
…throw

A condition on a sibling subcolumn that cannot throw is no longer grouped
with its guard by physical column, so cost order moves it first, while a
throwing one keeps the written order. EXPLAIN with pretty = 0, because the
pretty form does not print the conjuncts in the order of the steps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fold the Enum haystack note into the LIKE canThrowIfKnown comment, keep master's getArgumentTypesWithConstInfo doc without the stale ExpressionActions line, and shorten the fillRequiredColumns pointer and the prewhereConditionCannotThrow doc to one line each.

Co-Authored-By: Claude Opus 5.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; 1 finding in round 1, 0 in round 2) plus my own review.

# Sev Finding Verdict Evidence / action
1 ❌ arrayElement on a Map is described as unable to throw, but an unsupported key/index type pair (Map(UUID, ...)[257]) throws ILLEGAL_TYPE_OF_ARGUMENT, so guard AND startsWith(uuid_map[257], 'x') could throw on rows the guard rejects DISAGREE executeMap picks the matcher from the column types before reading any row and throws on every block of that pair, rows the guard passes included; the canThrowIfKnown contract excludes errors that depend only on the argument types; master already evaluates uuid_map[257] = 1 in its guard's step
2 ⚠️ The MergeTreeWhereOptimizer guard-grouping change had no test AGREE, fixed in b58d85b 04631 gains two WHERE queries on sibling Tuple subcolumns: startsWith is ordered by cost, a throwing toUInt64 stays behind its guard; reverting only that hunk turns the first one red
3 💡 Case e relies on lower being undescribed noted, not blocking it detects a proof that checks only the root of the condition

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261116-190333

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's table (200k rows), clickhouse local --send_logs_level=test, counting PREWHERE condition was split into N steps: master gives 3 steps for startsWith(m1['a2'], 'p-'), LIKE 'p-%' and LIKE '%p-%' and 2 for the comparison form, at defaults and with the issue's settings, every run.
b Root cause explained? Since #111954 the step splitter treats a condition as "may throw" when a function in it reports isSuitableForShortCircuitArgumentsExecution. startsWith and LIKE report true because they are worth evaluating lazily, not because they can throw, so the condition gets its own step and the step before it must filter the whole Map block.
c Fix matches root cause? Yes. The splitter now asks the sound IFunctionBase::canThrow for every function of the condition, and startsWith/endsWith, the LIKE family and Map arrayElement describe canThrowIfKnown. No setting, tag or bound is changed.
d Test intent preserved / new tests added? 04631 keeps every existing query and reference line, and gains 8 cases: two that must share a step, four that must stay split, and two WHERE queries on sibling Tuple subcolumns. 8 mutations of the change each turn the test red.
e Both directions demonstrated? Yes, on Build-ID-checked servers: master fails exactly the two new grouped lines and the sibling reorder line, the fix passes all lines; repro 3 -> 2 steps with identical results (9473).
f Fix is general across code paths? Both splitters (tryBuildPrewhereSteps and the guard grouping of MergeTreeWhereOptimizer) use one predicate, and the readers that reuse tryBuildPrewhereSteps (MergeTree, Memory, Parquet) are covered. The other canThrow users only gain reorderings for functions that cannot throw; callers that pass no constant column keep true for LIKE.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable and LowCardinality are unwrapped; the Array form of startsWith, an Enum haystack, ESCAPE, non-constant and invalid patterns and Enum-keyed maps stay throwing. Checked: ILIKE, NOT LIKE, endsWith share the step.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change, and results are identical; only step boundaries (and a deferred filter for non-throwing steps) change.
i Invariants and contracts preserved? "A condition that may throw never runs on rows a preceding condition rejects" still holds. A condition is regrouped only when every executed function in it reports canThrow == false, and the new descriptions answer false only where no row value or constant can throw. The LIKE pattern is built with the same createRegexp call that execution uses. A Map lookup returns the default for a missing key, and only the Enum key cast can throw.

Session id: cron:clickhouse-impl-slot-6:20261116-182900

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3d81527]

Summary: ✅


AI Review

Summary

Restores shared PREWHERE read steps for non-throwing startsWith/endsWith and constant-pattern LIKE conditions, while preserving guard boundaries for potentially throwing expressions. Reviewed head 3d815274cbd7f22db3d60863ce51e29a01b00baa; no actionable findings. The focused regression test passes in the Fast test report, and the PR supplies before/after performance measurements. Validation relied on source inspection, recorded CI results, and the supplied measurements; no local build or test run was performed.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 16, 2026

@clickhouse-gh clickhouse-gh Bot left a comment

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.

AI review approves this commit, see the AI Review comment.

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3d815274c with master 088b6f5e4 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

59 translation units recompiled, 386 s compile time in total, 59 of them have a recent master baseline.

Job report

@fm4v
fm4v added this pull request to the merge queue Nov 17, 2026
Merged via the queue into ClickHouse:master with commit 7c15c7e Nov 18, 2026
386 of 387 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 18, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 18, 2026
`05343_lazy_materialization_for_join_padded_side_can_throw` used a comparison of
decimals of different scales as the one that can throw. It cannot: an overflowing
rescale is compared exactly, or ignored without `decimal_check_overflow`, so it is now
computed above the LIMIT. A `UInt64` compared with a `Decimal64` is the comparison that
can throw (`DECIMAL_OVERFLOW` for a value above `Int64`), so it takes its place.

The read-ahead case of `04631_prewhere_subcolumn_guard_read_steps` needs conditions
that may throw. `NOT startsWith(...)` no longer is one once both `not` and `startsWith`
(ClickHouse#132112) are known not to throw, so on a merge with master the four conditions shared
one PREWHERE step. `toUInt64` of a `String` can throw and passes every row there.

The comments of `04893_comparison_can_throw_replicated_columns` said the same about
decimals of different scales. With those classified as safe, no case there could catch
a comparison wrongly classified as safe: the values of its unreferenced row are valid.
A `Decimal128` compared with a `UInt128` that does not fit into `Int128` is added. Lazy
replication needs values wider than 8 bytes and a row joined more than once, and the
hash join is pinned so that the unreferenced row reaches it; with the unsigned case of
`comparisonCanThrow` widened to equal sizes, the case fails 30 of 30 randomized runs
with `DECIMAL_OVERFLOW`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
acking-you added a commit to acking-you/ClickHouse that referenced this pull request Nov 18, 2026
Apply the upstream effective exception check in `appendGroups` for both initial grouping and alias refinement. Preserve constant argument metadata, dynamic-filter separation, cache attribution, and shared reads.

Related: ClickHouse#129445

Related: ClickHouse#132112
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 18, 2026
…rewhere-attribution

Conflict in MergeTreeSplitPrewhereIntoReadSteps.cpp with ClickHouse#132112: keep its
`may_throw` / `prewhereConditionCannotThrow` split rule, drop only
`is_first_unattributed` added by ClickHouse#122380.

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. pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

26.10: startsWith/LIKE on a Map value is split into its own PREWHERE step, filtering the whole Map between steps, ~1.2x slower (side effect of #111954)

4 participants