Skip to content

Evaluate PREWHERE over a Memory table in multiple steps - #122604

Merged
alexey-milovidov merged 4 commits into
masterfrom
memory-prewhere-multiple-steps
Oct 2, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
memory-prewhere-multiple-steps

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

PREWHERE over a Memory table (added in #116248) evaluated the whole conjunction as one step. So every column used by any condition was decompressed for every block before anything was filtered. For a compress = true table, a cheap condition on a wide column cancelled the gain. In ClickBench Q37, URL <> '' next to CounterID = 62 made the source decompress the whole URL column, even though CounterID = 62 matches rows in only 18 of 1,229 blocks. This is why the clickhouse-memory entry in ClickHouse/ClickBench#1590 showed no improvement from #116248.

Now the conjunction is split into steps with tryBuildPrewhereSteps, the same code MergeTree uses under enable_multiple_prewhere_read_steps. Each step reads its columns only for the rows that passed the previous steps, and blocks where no row passes are skipped without reading the columns of the later steps. The result is assembled by name in the order of the output header, as in MergeTreeSelectProcessor.

A PREWHERE containing a stateful function (runningConcurrency, rowNumberInBlock, ...) or a function that is non-deterministic in scope of the query (blockSize, rand, ...) stays in a single step. Memory steps filter the block physically, so such a function would otherwise see only the rows that passed the preceding conditions. MergeTree avoids this because its intermediate steps stay unfiltered unless the next condition may throw. 04872_running_concurrency_join_conversion_wrong_results covers this.

ClickBench, 100M rows loaded into Memory SETTINGS compress = true with the benchmark's INSERT ... SELECT FROM file(), aarch64. Same binary, only enable_multiple_prewhere_read_steps toggled. Median of 5 runs, on a heavily loaded shared machine; CPU time comes from UserTimeMicroseconds + SystemTimeMicroseconds.

query CPU, ms (1 / 0) wall, s (1 / 0) bytes read, GB (1 / 0)
Q37 308 / 3608 0.028 / 0.176 0.75 / 10.84
Q38 253 / 3546 0.025 / 0.169 0.73 / 11.29
Q39 218 / 399 0.025 / 0.033 0.75 / 1.34
Q41 195 / 760 0.019 / 0.049 0.63 / 1.81
Q42 199 / 720 0.019 / 0.051 0.63 / 1.81
Q43 129 / 319 0.035 / 0.021 0.32 / 1.01
Q22, Q23, Q24, Q40 within noise

Queries without a conjunction are not affected. A query of this shape is added to tests/performance/memory_prewhere.xml. It is the same change as #123155, which adds the query on its own to give a baseline on master.

Related: #116248
Related: ClickHouse/ClickBench#1590
Related: #123155

Changelog category (leave one):

  • Performance Improvement

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

PREWHERE over a Memory table is evaluated in multiple steps, like for MergeTree (enable_multiple_prewhere_read_steps): the columns of each next condition are read only for the rows that passed the previous ones. For a table with compress = true, a condition on a wide column next to a selective one no longer decompresses that column for every block, which makes such queries up to several times faster.

🤖 Generated with Claude Code


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

Version info

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

alexey-milovidov and others added 2 commits September 28, 2026 01:16
A conjunction in `PREWHERE` is now split into steps with `tryBuildPrewhereSteps`,
like `MergeTreeSelectProcessor` does under `enable_multiple_prewhere_read_steps`.
Each step reads its columns only for the rows that passed the previous steps, so
a condition over a wide column (e.g. `URL <> ''` next to `CounterID = 62`) no
longer decompresses that column for every block of a `compress = true` table.
The result is assembled by name in the order of the output header.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The steps of a `Memory` table filter the block physically, so a stateful
function such as `runningConcurrency` or `rowNumberInBlock` would only see the
rows that passed the preceding conditions (`MergeTree` keeps intermediate steps
unfiltered unless the next condition may throw). This broke
`04872_running_concurrency_join_conversion_wrong_results`.

Also fill the reference of `05289_memory_prewhere_multiple_steps`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f23c323]

Summary: ✅


AI Review

Summary

This PR teaches Memory reads to split conjunctive PREWHERE filters into multiple in-source steps so later columns are skipped for blocks already eliminated by earlier predicates, and it correctly falls back to a single step when the predicate contains stateful or query-scope non-deterministic functions. I re-checked the only prior bot finding against the current head, verified that the hasNonDeterministicOrStatefulFunctions() guard and the added regression coverage address it, and I do not see remaining contract violations in the current diff.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit f23c323.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... labels Sep 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f23c32309 with master 38fd308a8 (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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 34 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: db343109-6e80-4515-a6a7-3f3efccaf04a
  • MIRAI run: 50f2053c-f2a1-4715-aafb-fd47a8d3923d
  • PR check IDs:
    • clickbench_2821895_1790901954
    • clickbench_2822074_1790901973
    • clickbench_2822187_1790902007
    • tpch_adapted_1_official_2822290_1790902043
    • tpch_adapted_1_official_2822319_1790902045
    • tpch_adapted_1_official_2822494_1790902055

The query added earlier filtered on `s3 != ''` without selecting `s3`, so the
optimizer rewrote the condition to `s3.size != 0`, which reads only the cheap
`size` subcolumn, and the query did not exercise the change (28.4 -> 28.7 ms in
the performance check). Use the same query as
#123155, which selects the column
it filters on, so that the two PRs make an identical change to the file.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…for `Memory`

`Memory` filters the block physically between `PREWHERE` steps, so a function
that is non-deterministic in scope of the query without being stateful, such as
`blockSize` or `blockSerializedSize`, would see only the rows that passed the
preceding conditions and change the result depending on
`enable_multiple_prewhere_read_steps`. Gate the split with
`hasNonDeterministicOrStatefulFunctions` instead of `hasStatefulFunctions`.

Address review: #122604 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Oct 2, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
Merged via the queue into master with commit 13f4a37 Oct 2, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the memory-prewhere-multiple-steps branch October 2, 2026 19:57
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 10, 2026
The master merge resolution of `read_missing_columns` passed `std::move(*column_it)`
into the `ColumnWithTypeAndName` braced initializer, whose only matching constructor
takes `const ColumnPtr &`, so the move was a no-op and `Build (arm_tidy)` failed.
Pass the column directly.

Also correct two comments that the read-time evaluation of `DEFAULT` expressions
made inaccurate. `StorageMemory::supportedPrewhereColumns` claimed the in-source
filter reads the columns of all its steps before running the first one, which no
longer holds since ClickHouse#122604 (each step reads its inputs only for the rows that passed
the previous ones). `supportsTopKDynamicFilter` said the source fills such a column
with the defaults of the type; it now evaluates the expression, and the exclusion is
still needed because the threshold step runs before the row-level security filter:
with it lifted, a user restricted by `USING k = 1` gets `Cannot parse string 'secret'`
from `ORDER BY d LIMIT 1` over `d UInt64 DEFAULT toUInt64(secret)`, quoting a hidden
row. Both exclusions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 20, 2026
Since ClickHouse#116248 and ClickHouse#122604, a WHERE over a `Memory` table is moved to
PREWHERE and split into steps by `tryBuildPrewhereSteps`, so the `Memory`
cases of this test no longer reach the filter-step split they were written
for. With `allow_reorder_prewhere_conditions = 0`, the steps compute
`enabled = 1` (the ON copy) and `toNullable(enabled) = 1` (the WHERE copy)
separately under one column name, and the read fails with
AMBIGUOUS_COLUMN_NAME. Which written order reaches that depends on the
conjunct order, which this PR changes.

That failure is a defect of the PREWHERE split, not of the filter step:
master fails the same way when the ON condition is written first, and
26.8.21.12 fails with `MergeTree` tables. It is left to a separate fix.

Failed run: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122160&sha=4c1aab48fb2eaede08abeddd7e866d076c948214&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29

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

comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants