Skip to content

Lazy materialization for the Memory engine - #123788

Merged
alexey-milovidov merged 23 commits into
masterfrom
memory-lazy-materialization
Oct 22, 2026
Merged

alexey-milovidov merged 23 commits into
masterfrom
memory-lazy-materialization

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 4, 2026 •

Copy link
Copy Markdown
Member

Lazy materialization for the Memory engine. For ORDER BY ... LIMIT n, the columns that are not needed for filtering and sorting are read only for the n rows that survive the LIMIT. This already works for MergeTree, Parquet files and object storage.

This PR includes the commits of #123787 (TopN dynamic filtering for Memory), because both change ReadFromMemoryStorageStep. Only the last commit and the merge are new.

How it works:

  • ReadFromMemoryStorageStep::keepOnlyRequiredColumnsAndCreateLazyReadStep removes the deferred columns from the main read. Columns used by the in-source filters stay in the main read: the row policy, the PREWHERE steps and the TopN filter.
  • The main read produces __global_row_index: the number of the row in the storage snapshot (the rows of the preceding blocks plus the row in its block). Both branches read the same immutable snapshot, so the number identifies the row without a registry.
  • The lazy branch (LazilyReadFromMemoryStorage) creates its readers at run time, when LazyMaterializingTransform starts pulling, as LazyReadFromFileSource does. With compress = true every block decompresses each deferred column as a whole, and the result rows usually come from different blocks. So the blocks are split into contiguous ranges, read by parallel sources, and their chunks are passed on in order. A first sequential version made Q24 2x slower instead of faster.
  • Lazy materialization is not used for the delayed reads of GLOBAL subqueries, which take the blocks only when they start.
  • With partial_result_on_first_cancel, the readers of the lazy branch, created after the first cancel, keep reading the deferred columns of the rows already selected. The same is fixed for MergeTree, whose lazy readers stopped on it, and LazyMaterializingTransform threw Number of rows in lazy chunk 0 does not match number of offsets 5 (found by the stress tests of the private CI, which run 05427_memory_lazy_materialization_partial_result with Memory replaced by MergeTree).

ClickBench Q24 SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10, local 10M-row subset of hits (Memory SETTINGS compress = true), 96 threads, best of 5 runs:

lazy materialization off on
TopN filter off 0.089 s 0.048 s
TopN filter on 0.073 s 0.048 s

Q25–Q27 are unchanged (6–8 ms).

Related: #123787
Related: ClickHouse/ClickBench#1590

Changelog category (leave one):

  • Performance Improvement

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

Lazy materialization is supported for Memory tables: for ORDER BY ... LIMIT n queries, the columns that are not needed for filtering and sorting are read only for the rows in the result.

🤖 Generated with Claude Code


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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2b31637]

Summary: ✅


AI Review

Summary

The remaining changes harden lazy materialization by keeping block-dependent expressions and default-expression dependencies in the main branch, guarding shadowed columns, accounting for deferred reads, and preserving deferred columns during partial-result cancellation for Memory and MergeTree. At 2b31637925b, all prior findings are addressed and no new actionable issues were identified. The focused regression tests pass in the Fast test report.

Final Verdict

Status: ✅ Approve

@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 Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

One query was flagged: clickbench Q20 improved by -42.7% (220 ms to 126 ms), and its CPU time fell from about 2898 ms to 1527 ms, so the speedup comes from less work. The size of the change locks the verdict as an improvement. Still, the diff does not explain it well. Most of this PR adds lazy materialization for Memory-table reads. The only change that reaches MergeTree queries is a check that keeps stateful or non-deterministic functions out of the lazy branch, and that only applies to ORDER BY ... LIMIT plans. The likelier cause is a difference between the PR's merge base and the baseline build, so confirm the base commit before crediting the PR with the Q20 speedup.

clickbench

🟢 1 improved

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 126 -42.7% <0.0001 cpu: -42.7% with CPU time nearly halved, so the work really changed. This PR mainly adds lazy materialization for Memory tables, which a MergeTree query without ORDER BY ... LIMIT does not use. Check the base commit before crediting the PR.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 26cd7450-98ef-455a-a8cb-a337c6a14042
  • MIRAI run: 3ba95ab6-0e90-47f0-ad79-5e6365492ad6
  • PR check IDs:
    • clickbench_118647_1791949172
    • clickbench_118653_1791949172
    • clickbench_118678_1791949172
    • tpch_adapted_1_official_118712_1791949172
    • tpch_adapted_1_official_118735_1791949172
    • tpch_adapted_1_official_118754_1791949172

alexey-milovidov added a commit that referenced this pull request Oct 5, 2026
For a query like `SELECT json FROM t ORDER BY rowNumberInAllBlocks() LIMIT 2`, all
columns are deferred to the lazy branch and the main branch reads only
`__global_row_index`; `StorageSnapshot::check` rejected the empty list of columns
with `EMPTY_LIST_OF_COLUMNS_QUERIED`. Skip the check in that case, the source
already produces chunks with only the global row index.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123788&sha=807d3dfd0b145cef508c02cb63a93d7e4b7fc6bc&name_0=PR&name_1=Fast%20test
PR: #123788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 5, 2026
alexey-milovidov and others added 2 commits October 6, 2026 03:08
…inserted blocks

The randomized `max_insert_threads` makes the order of blocks of `INSERT ... SELECT`
nondeterministic, so `ORDER BY rowNumberInAllBlocks()` did not always return the rows
with `k` 0, 1, 2. Check instead that the lazily read columns belong to the same row and
that the result matches the one without lazy materialization.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123788&sha=latest&name_0=PR&name_1=Fast%20test
#123788

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

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2b3163792 with master 915c5e7f3 (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.

Object file sizes

7 object files changed (+38.50 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromMemoryStorageStep.cpp.o 499.13 KiB 521.42 KiB +22.29 KiB (+4.47%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

12 translation units recompiled, 69 s compile time in total, 11 of them have a recent master baseline.

Job report

…zyReadFromMemoryBlocksSource`

The lazy branch materializes the deferred columns of each block as a whole
(decompressing them for `compress = true`) and only then picks the requested
rows, but the automatic progress of `ISource` counted only the bytes of the
returned chunk. Report the progress explicitly, like `MemorySource::generateFiltered`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 7, 2026 09:12
…zy materialization

A stateful function (`runningDifference`, `neighbor`, `rowNumberInAllBlocks`) or a function not
deterministic within a query (`rowNumberInBlock`, `blockSize`) depends on the block it runs on.
If lazy materialization moved such a function into the lazy half (which happens when its
argument is a lazily read column), it was calculated on the rows that survived the `LIMIT`
instead of the original blocks, and returned different values. Mark the outputs computed by
such functions as required, so they are calculated before the `LIMIT`.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123788&sha=cde5681628d3adcb5b6eca32a8ccff6f9cfaebc6&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%205%2F6%29 (short_circuit_compact_logical_masks query 0, +21%, arm) and provide a fix in a separate PR. If the fix is already in progress, link it here. The query only reads numbers() and evaluates short-circuit and; this PR only changes lazy materialization and the Memory read step, so it cannot affect that query.

@clickhouse-gh clickhouse-gh Bot added comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... and removed comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... labels Oct 7, 2026
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the short_circuit_compact_logical_masks query 0 report on arm; I'll follow up here with a PR (or my findings) shortly.

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

Fix: #124417 (test-only).

#0 and #1 are the two sparse masks with an exact 64-row period, and on arm their time is bimodal on the same code: since the test was added they moved more than 10% old vs new in 264 and 271 of about 3570 arm runs, while #2..#7 moved in 2-4 and amd in 5-6. On the previous head of this PR the master side was the slow one. The fix selects their rows by intHash32(number) % 64 instead: same 1/64 density and short-circuit path, no period.

alexey-milovidov and others added 2 commits October 7, 2026 22:26
# Conflicts:
#	tests/queries/0_stateless/04077_materialized_cte_union.sql
…column is shadowed

`supportsTopKDynamicFilter` checked the sort column only by name, while the threshold
is computed from the output column and `makeSourceFilter` reads the physical column of
the same name. Require the storage type to match and reject the case when the row-level
filter or `PREWHERE` actions output a computed node with that name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Oct 7, 2026
alexey-milovidov and others added 2 commits October 8, 2026 10:46
…n branch of lazy `Memory` read

If the row-level filter or `PREWHERE` actions output a computed node named like a
physical column, the lazy branch would reread the physical column, and the
expressions above `JoinLazyColumnsStep` could pick the wrong one by name. Keep every
computed output of these actions in the main branch.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123788&sha=2e44d54a3daa526b2fe1727193d969b013ce3e35&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20targeted%29 (test_dictionary_allow_read_expired_keys/test_default_reading.py::test_default_reading) and provide a fix in a separate PR. If the fix is already in progress, link it here. The dictionary_node failed to restart with Code: 57 ... UUID collision ... Cannot parse definition from metadata file store/.../all_asynchronous_insert_..., which looks like the plain_rewritable database-disk issue addressed by #123832; this PR only touches lazy materialization and the Memory read step.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master and addressed the review: the deferred reread in LazyReadFromMemoryBlocksSource now stops on cancellation between blocks. The build passes and 05321_memory_lazy_materialization, 05332_memory_lazy_materialization_block_dependent, 05361_memory_lazy_materialization_default pass locally.

The previous red checks (the three targeted stateless/integration jobs) failed before running any test: CIDB query failed ... play.clickhouse.com ... Connection refused in find_tests.py, an infrastructure outage unrelated to this PR. Thanks @groeneai for #125750 (FIPS fix for 05359_parquet_file_logical_type); 03988_cached_read_big_at was fixed by #125527, now pulled in with this merge.

alexey-milovidov pushed a commit to comino/ClickHouse that referenced this pull request Oct 16, 2026
The test builds the opaque `checksum` string of its Parquet `FILE` tuples
with `MD5`, which throws `SUPPORT_IS_DISABLED` at analysis when OpenSSL
FIPS mode is enabled. The inserts that write the test files then fail and
the whole test fails in the FIPS job, on master too.

`sipHash128` has no OpenSSL dependency and no FIPS check and also returns
`FixedString(16)`, so the value stays a 32-char hex string. The label
prefix is renamed with it. Only the three checksum values in the
reference change. Same substitution as ClickHouse#116023.

Reported on ClickHouse#123788.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Processors/QueryPlan/ReadFromMemoryStorageStep.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master and resolved the conflict in ReadFromMemoryStorageStep.cpp. Most of this PR is already in master through #123798, which was stacked on this branch. The conflict was only the argument order of fillColumnsMissingFromBlock, and I took master's order. For 05321_memory_lazy_materialization I took master's version, which fixes the same insert-order flakiness by inserting with max_threads = 1.

What remains in this PR is the follow-up review fixes:

  • block-dependent functions stay in the main half;
  • columns shadowed by in-source filters, and columns with a DEFAULT expression, stay in the main branch;
  • the TopN filter is not used when the sort column is shadowed;
  • read-progress accounting and cancellation in LazyReadFromMemoryBlocksSource;
  • tests 05332 and 05361.

The build passes. All memory_lazy_materialization and memory_query_condition_cache stateless tests (11 in total) pass locally.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check was CH Inc sync: the private sync PR had a merge conflict in ReadFromMemoryStorageStep.cpp (the same one resolved here on 2026-10-16). I merged the private master and the current head of this PR (10a3c66) into the sync branch, taking this PR's version of the file; the sync diff now matches this PR's diff exactly, and the sync PR is mergeable again. All other CI checks on this PR pass.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check was CH Inc sync ("build failed"). In the private sync PR, every build passed except Build (amd_msan), including Build (arm_msan). amd_msan failed after 260 s on a private-arm-large runner, which looks like an infrastructure problem rather than a compile error in this change. I could not fetch the private job log to confirm. I merged the latest master (clean merge) to start a fresh sync run. The build passes locally, and so do 05321_memory_lazy_materialization, 05332_memory_lazy_materialization_block_dependent and 05361_memory_lazy_materialization_default.

alexey-milovidov and others added 2 commits October 20, 2026 11:09
…esult cancel

With `partial_result_on_first_cancel = 1`, the first cancel propagates
`CancelReason::PartialResult` to the lazy sources created after it, and
`LazyReadFromMemoryBlocksSource` returned no deferred columns for the rows
already selected by the main branch, which led to the `LOGICAL_ERROR`
`Invalid number of columns in chunk pushed to OutputPort`. Ignore this
reason, as `BufferingFromFileSource` does, while keeping other cancellations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 21, 2026
…h set

When `hasAny(Array(String), <constant Array(String)>)` does not build the
needle hash set for a block (fewer than 4 needles, a needle longer than 256
bytes, or a block too small for the set to pay off), it used to fall back to
the generic GatherUtils path. That path makes two virtual calls per row from
the per-row loop of `arrayAllAny` (`ColumnString::structureEquals` from
`sliceHas`, and `ColumnString::compareAt` per element/needle pair).

The speed of that loop turned out to depend on code placement. Three PR builds
of 2026-10-18 (ClickHouse#123788, ClickHouse#100394, ClickHouse#63383; their diffs share no file and none
touches Functions/ or Columns/) ran `has_any_constant_string_needles` queries
ClickHouse#5 and ClickHouse#6 1.2-2.1x slower than the master reference in all three process
lifetimes of their perf job, on three different runners, with md5-identical
machine code for the four functions involved. Across 24 inspected CI builds, a
build is slow exactly when a 64-byte line of `compareAt` or `structureEquals`
coincides with a line of the `arrayAllAny` loop modulo 8 KiB (3/3 slow, 0/21
fast). Reproduced locally with the CI binaries: query ClickHouse#6 takes 1.04-1.35 s on
the three slow builds vs 0.62 s on three fast ones, at equal instruction counts.

Now the declined block compares each element with each needle directly
(`getDataAt` + `memequalSmallAllowOverflow15`, the comparison
`ColumnString::compareAt` makes), in the generic path's order (needles outer,
elements inner, first match wins). The loop has no call left, and it is faster
for every declined shape: on a release build, perf test queries ClickHouse#4-ClickHouse#7 take
0.73-0.91x of the base time and #0-ClickHouse#3 (set path) are unchanged.

Adds perf query ClickHouse#7 for the fewer-than-4-needles branch, the only declined
branch the test did not cover. Non-String columns still use the generic path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits October 22, 2026 07:19
With `partial_result_on_first_cancel`, the first cancel is propagated as
`CancelReason::PartialResult` to every processor, including the readers of the
lazy branch of lazy materialization that `LazyReadFromMergeTreeSource` creates
after the cancellation. `MergeTreeSource` stopped on it, so the lazy branch
returned no rows for the rows already selected by the main branch, and
`LazyMaterializingTransform` threw a `LOGICAL_ERROR`: `Number of rows in lazy
chunk 0 does not match number of offsets 5`.

The same was already fixed for `Memory` in this PR. The private CI runs
`05427_memory_lazy_materialization_partial_result` with `Memory` tables replaced
by `MergeTree` (`--replace-log-memory-with-mergetree`), which hit it in the
stress tests of the sync PR ClickHouse/clickhouse-private#79292

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

With `--replace-log-memory-with-mergetree` the table is a `MergeTree`, which reads
blocks of `max_block_size` rows, so `sleepEachRow` exceeded its limit per block
and the query never started. Also disable parallel replicas, which the random
settings may enable for a `MergeTree` table, so that lazy materialization is used.

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

Copy link
Copy Markdown
Member Author

🕵 The "CH Inc sync" stress tests failed with LazyMaterializingTransform: Number of rows in lazy chunk 0 does not match number of offsets 5. The private CI runs 05427_memory_lazy_materialization_partial_result with Memory replaced by MergeTree. There, the lazy readers of MergeTree stopped on the partial_result_on_first_cancel cancel, which is the same problem this PR already fixed for Memory. I reproduced it locally on a MergeTree table. Fixed in 803c78e and covered by the new test 05443_merge_tree_lazy_materialization_partial_result. 2b31637 makes 05427 usable with MergeTree.

@groeneai, investigate the other failure of the sync PR, 05318_file_log_one_bad_file (CANNOT_PARSE_INPUT_ASSERTION_FAILED, in Stateless tests (amd_debug, meta in keeper, distributed plan, s3 storage, parallel)). It is not related to this PR. Please provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the 05318_file_log_one_bad_file failure in the private Stateless tests (amd_debug, meta in keeper, distributed plan, s3 storage, parallel) run; I'll follow up here with a PR (or my findings) shortly.

The private report is not visible to me. If you can paste the test's reference diff and stderr from it, that shows which arm of the test failed. It has not failed in public CI since #123595 merged (0 of about 60k runs in the last 14 days, including the DBReplicated and distributed plan, s3 storage jobs).

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov To find the cause I need the result of the last SELECT a FROM file_log_sel of that run, the one after printf 'not json\n' >> ..._sel_target.jsonl. If it failed, the server log has an error line for it with (in query: SELECT a FROM file_log_sel). Could you paste the server log lines of this test that contain that, together with the reference diff?

The reference diff alone does not show it. The test pipes both stdout and stderr of that query into grep -o -m1 'CANNOT_PARSE_INPUT_ASSERTION_FAILED', so when that line is missing, the query failed with a different error or did not fail, and the output that would tell which is discarded.

The one private-only difference I can see on this path: FileLog keeps its read offsets on the first disk of the default storage policy (StorageFileLog.cpp:201), and every direct SELECT reads and writes them there. In all public jobs that disk is local.

In the same PR I will also bound this test's system.text_log reads, which hit max_rows_to_read in the sync run you mentioned on #123493.

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

Looks ok.

@alexey-milovidov alexey-milovidov self-assigned this Oct 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 22, 2026
Merged via the queue into master with commit 2660c51 Oct 22, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the memory-lazy-materialization branch October 22, 2026 18:47
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 22, 2026
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.

3 participants