Repository navigation
Lazy materialization for the Memory engine - #123788
Conversation
|
Workflow [PR], commit [2b31637] Summary: ✅
AI ReviewSummaryThe 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 Final VerdictStatus: ✅ Approve |
|
📊 Cloud Performance Report 🟢 AI verdict: 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)
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
|
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]>
The test checks the `EXPLAIN` output, and `ReadFromMemoryStorage` now prints `TopN filter column` when the randomized setting is enabled. 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]>
…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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes7 object files changed (+38.50 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units12 translation units recompiled, 69 s compile time in total, 11 of them have a recent master baseline. |
…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]>
…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]>
|
🕵 @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 ( |
|
Acknowledged. I'm investigating the |
|
Fix: #124417 (test-only).
|
# 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]>
…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]>
|
🕵 @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 ( |
…oryBlocksSource` Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged the latest The previous red checks (the three |
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
|
🕵 Merged the latest What remains in this PR is the follow-up review fixes:
The build passes. All |
|
🕵 The only red check was |
|
🕵 The only red check was |
…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]>
…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]>
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]>
|
🕵 The "CH Inc sync" stress tests failed with @groeneai, investigate the other failure of the sync PR, |
|
Acknowledged. I'm investigating the 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 |
|
@alexey-milovidov To find the cause I need the result of the last The reference diff alone does not show it. The test pipes both stdout and stderr of that query into The one private-only difference I can see on this path: FileLog keeps its read offsets on the first disk of the In the same PR I will also bound this test's |
Lazy materialization for the
Memoryengine. ForORDER BY ... LIMIT n, the columns that are not needed for filtering and sorting are read only for thenrows that survive theLIMIT. This already works forMergeTree, Parquet files and object storage.This PR includes the commits of #123787 (TopN dynamic filtering for
Memory), because both changeReadFromMemoryStorageStep. Only the last commit and the merge are new.How it works:
ReadFromMemoryStorageStep::keepOnlyRequiredColumnsAndCreateLazyReadStepremoves the deferred columns from the main read. Columns used by the in-source filters stay in the main read: the row policy, thePREWHEREsteps and the TopN filter.__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.LazilyReadFromMemoryStorage) creates its readers at run time, whenLazyMaterializingTransformstarts pulling, asLazyReadFromFileSourcedoes. Withcompress = trueevery 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.GLOBALsubqueries, which take the blocks only when they start.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 forMergeTree, whose lazy readers stopped on it, andLazyMaterializingTransformthrewNumber of rows in lazy chunk 0 does not match number of offsets 5(found by the stress tests of the private CI, which run05427_memory_lazy_materialization_partial_resultwithMemoryreplaced byMergeTree).ClickBench Q24
SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10, local 10M-row subset ofhits(Memory SETTINGS compress = true), 96 threads, best of 5 runs:Q25–Q27 are unchanged (6–8 ms).
Related: #123787
Related: ClickHouse/ClickBench#1590
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Lazy materialization is supported for
Memorytables: forORDER BY ... LIMIT nqueries, 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
26.11.1.570-master(included in26.11and later)