Repository navigation
Query condition cache for the Memory engine - #123798
Conversation
For `ORDER BY ... LIMIT n` over a `Memory` table, the columns that are not needed for filtering and sorting are now read only for the `n` rows that survive the `LIMIT`, like for `MergeTree`, Parquet files and object storage. The main read produces `__global_row_index`, the number of the row in the storage snapshot, which both branches share. The lazy branch reads the rows block by block; with `compress = true` every block decompresses each deferred column as a whole, so the blocks are split into contiguous ranges read by parallel sources, whose chunks are passed on in order. Co-Authored-By: Claude Opus 5.5 <[email protected]>
An entry describes one block of the table, split into granules of 8192 rows, and records the granules where no row satisfies a condition. The source skips such blocks and granules. There are two kinds of entries: - PREWHERE, which the source evaluates itself. The source writes the entries when nothing else (a row policy, the TopN threshold) has removed rows before PREWHERE. - The filter of the query pushed down to the read, with the same key as for `MergeTree`. The `FilterTransform` of the `WHERE` filter writes the entries from the `MarkRangesInfo` of the chunks, which the source attaches when it has removed no rows itself. The new `MarkRangesInfo::rows_per_mark` lets `FilterTransform` also record the granules without matches of a partially filtered chunk. A block is identified by a generation of the table data and its number in the generation. Appending blocks and removing the oldest ones (`max_rows_to_keep`) keep the generation; any other change of the data (a mutation, `TRUNCATE`) starts a new one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [d958f80] Summary: ✅
AI ReviewSummaryAdds query condition caching and lazy materialization for Findings❌ Blockers
Final VerdictStatus: ❌ Block. Incorporate the predicate hashing fix and verify that different lambda bodies cannot share cached exclusions through either |
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds lazy materialization and query condition cache support for the Memory table engine. Outside the Memory read step, the only changes are an extra type check in the lazy-materialization and query-condition-cache plan optimizations, so MergeTree query plans are unchanged. The only two flagged results are ClickBench Q33 (-14.1%) and Q34 (-13.1%). Both are filter-free GROUP BY aggregations on the MergeTree hits table, have noisy histories, and have source medians inside master's recent range, so both are downgraded to not sure. Neither benchmark reads from Memory tables, so this run shows no performance effect from the PR, either positive or negative. clickbenchFlagged queries (2 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]>
…` column The mask of the rows passing the `PREWHERE` steps is taken from the filter column as is, so for `PREWHERE k` over a `UInt8` column it holds the values of `k`, not only 0 and 1. The writer of the cache searched for the byte 1 and recorded the granules whose passing rows had other values as having no matches, so the next query with the same condition returned no rows. Check for any non-zero byte. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123798&sha=c8036a384db97af5266d2948262b8820ab612a9b&name_0=PR&name_1=Fast%20test PR: #123798 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…of insert parallelism `05289_memory_prewhere_multiple_steps` compares the bytes read with one and with several `PREWHERE` steps. The benefit of the steps is in the block where the first condition removes all rows, and the query condition cache skips that block in both queries, so disable the cache there. `05321_memory_lazy_materialization` orders by `rowNumberInAllBlocks`, which follows the order of the blocks. A parallel `INSERT ... SELECT FROM numbers` can store them in a different order, so insert with a single thread. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123798&sha=c8036a384db97af5266d2948262b8820ab612a9b&name_0=PR&name_1=Fast%20test PR: #123798 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 sizes10 object files changed (+226.04 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 units479 translation units recompiled, 4699 s compile time in total, 479 of them have a recent master baseline. |
…`WHERE` `FilterStep` evaluates a conjunction by a chain of `FilterTransform`s, one per atom, all with the same key of the query condition cache. The atoms after the first one got the chunks of a `Memory` table with `MarkRangesInfo::rows_per_mark` set, although the previous atoms had already removed rows, and threw the `LOGICAL_ERROR` "The chunk with N rows does not consist of M marks of 8192 rows for the query condition cache". Now a `FilterTransform` that removes some rows of a chunk clears `rows_per_mark` in a copy of its `MarkRangesInfo`. Recording a whole chunk without matches stays as it was: the rows removed before are removed by the other atoms of the same condition. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123798&sha=ea7a69562089a32962e96b922ac732279f5c5a62&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 #123798 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…AULT` column `Memory` does not evaluate the default expression for the blocks inserted before `ALTER TABLE ADD COLUMN`: the query itself sees the default of the type there, which is the same value the in-source TopN filter compares, so the filter is correct for such a column. Pin it with a test comparing the results with and without the filter. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ped by the filter entry The source of a `Memory` table starts from the granules allowed by both the `PREWHERE` entry and the entry of the filter pushed down to the read. The granules skipped by the latter were never evaluated by `PREWHERE`, but were recorded as having no rows satisfying it, so a later query with the same `PREWHERE` could miss rows. Skip those granules when writing the `PREWHERE` entry. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # tests/queries/0_stateless/04077_materialized_cte_union.sql # tests/queries/0_stateless/05320_memory_top_k_dynamic_filter.reference # tests/queries/0_stateless/05320_memory_top_k_dynamic_filter.sql
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123798&sha=63301ba67e515b2ab98c35f56fe09c97f0ebb768&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%205%2F6%29 ( |
|
Acknowledged. I'm investigating the Preliminary data (
This run is the same shape (reference |
|
Fix: #124741 (test-only, one line in The slow runs come from code layout, not from a code change. The fixture data has an exact 8 KiB period, so each 64 KiB block is one ~56 KiB LZ4 match and the merge is dominated by LZ4's The PR changes the data to repeat each of 1024 random hashes 8 times. LZ4 still wins every block, and all 9 builds land within 3% of the median (0.56-0.58 s). Both sides of the comparison use the PR's checked-out XML, so this PR picks it up with the next master merge after it lands. |
|
🕵 @groeneai, thanks for tracing the AST fuzzer mismatch to the lambda key in the query condition cache. #122966 fixes it, and this PR will pick it up with a master merge after that one lands. Pushed 71e4f21:
|
|
🕵 The only red check, It is unrelated to this PR: the same job times out for 80+ PRs per day since 2026-10-09, and the slowest tests in this run are The branch was merged with master on 2026-10-10; there are no unresolved review threads. |
…ion-cache Resolve the conflict in `ReadFromMemoryStorageStep.cpp`: `master` added filling of missing `Nested` members with the array sizes of their siblings (`findSizesSource`, `fillColumnsMissingFromBlock`) as members of `MemorySource`. They are moved to free functions taking `nested_arrays`, so that the lazy branch of lazy materialization (`LazyReadFromMemoryBlocksSource`) fills missing columns the same way.
…`nested_arrays` Co-Authored-By: Claude Opus 5.5 <[email protected]>
…terialization of `Memory` Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cache of `Memory` as read The granules that the query condition cache eliminates are never scanned, so reporting them in the progress made them count against `max_rows_to_read`, `read_overflow_mode = 'break'` and `READ_ROWS` quotas, letting `use_query_condition_cache` change the result of a query. Report only the scanned rows, as `MergeTree` does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…re not counted as read Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123798&sha=latest&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel) ( |
|
Yes, #125195 is the fix for this one. The error is byte-identical (query 14,
|
… row-set-dependent filters The granules skipped by the query condition cache are removed before `PREWHERE` and the row policy run. If either of them has a stateful or non-deterministic function, such as `rowNumberInBlock` or `blockSize`, it sees a different set of rows, and a warmed cache changes the result: e.g. `PREWHERE rowNumberInBlock() = 1 WHERE k = 8192` matches `k = 8192` after the first granule is skipped. Do not consult or write the cache for such queries, the same as the top-K filter is not used for them. #123798 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123798&sha=735aeea6d79fcc5dc76707db8a1295176f953006&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%201%2F4%29 ( |
|
This is fixed by #125448 (mine), merged 2026-10-13 01:47 UTC. This run tested 735aeea merged into master b137629 (2026-10-12 22:29 UTC), which does not contain the fix. It is the #125448 mechanism: All 25 master failures since 2026-10-12 are on 22 commits without the fix. The 22 master commits that contain it have 108 passing runs of this test and no failures. The 20 PR failures since the merge all come from workflows dispatched before it (the latest at 01:42 UTC), so they tested a master without the fix. |
|
🕵 Thanks @groeneai. I merged |
…ndition cache key An `ALTER` of the columns keeps the stored blocks and their generation, but can change the values read from them: a `Nested` subcolumn missing in the blocks takes its array sizes from the stored siblings, and the read casts to the changed type (e.g. `JSON(SKIP a)`). Hash the columns of the metadata snapshot of the query into the block identity, so an entry is used only with the same columns it was written with, including by in-flight readers. #123798 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
The query condition cache (
use_query_condition_cache) for theMemoryengine.This PR includes the commits of #123788 (lazy materialization), because both change
ReadFromMemoryStorageStep. The TopN filtering of #123787 is already merged intomaster.An entry describes one block of a
Memorytable, split into granules of 8192 rows. It records the granules where no row satisfies a condition, and the source skips such blocks and granules without evaluating the condition on them. There are two kinds of entries:Memorysource evaluates itself. The source writes these entries only when nothing else removed rows before PREWHERE: not a row policy, not the TopN threshold.filter_actions_dag), with the same key as forMergeTree. TheFilterTransformof theWHEREfilter writes these entries, using theMarkRangesInfothat the source attaches to its chunks when it has removed no rows itself.updateQueryConditionCachetags the filter step only if just row-preserving expression steps lie between it and the read (noarrayJoin).FilterTransformpreviously recorded only chunks that were filtered out completely, which is useless withMemory's ~65k–83k-row blocks. The newMarkRangesInfo::rows_per_markdeclares that the chunk holds the rows of its marks in order, with a fixed number of rows per mark. With it,FilterTransformalso records the granules without matches of a partially filtered chunk.MergeTreedoesn't set it, so nothing changes there. My first attempt, splitting every block into per-granule chunks, madeWHERE AdvEngineID <> 03x slower.Stale entries: a block is identified by the table UUID, a generation of the table data, and the block's number within the generation. Appending blocks and dropping the oldest ones (
max_rows_to_keepand friends) keep the generation and advance the numbers. Any other change of the data (a mutation,TRUNCATE) constructs a newBlocksWithCounts, which takes a new generation. The test05322_memory_query_condition_cachecovers these cases, and I checked that it fails if the block numbering ignores removed blocks.ClickBench on a local 10M-row subset of
hits, single thread, best of 5, cache off → on:compress = trueWHERE UserID = 435090932899640449count() WHERE URL LIKE '%google%'URL LIKE '%google%' AND SearchPhrase <> ''SELECT * ... URL LIKE '%google%' ORDER BY EventTime LIMIT 10Q2 and Q8 are unchanged, and the other queries show no overhead. With all three PRs together, compared with master on the same machine and 16 threads, Q22 and Q24 are about 3x faster, and the geometric mean of the 43 queries is 0.96.
Limitation: with
compress = true, a block decompresses each column as a whole, so skipping granules inside a block saves only the evaluation of the condition, not the decompression. Q21 and Q24 are bound by decompressingURL. Getting MergeTree's times on them would needMemoryto compress columns in chunks of about 1 MB that can be decompressed separately. Simply storing smaller blocks doubles the memory (5.2 GB instead of 2.6 GB of compressed data for 8192-row blocks).Related: #123787
Related: #123788
Related: ClickHouse/ClickBench#1590
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The query condition cache works for
Memorytables: the granules of 8192 rows where no row satisfies the condition of a query are recorded, and later queries with the same condition skip them.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/123798]
Version info
26.11.1.13-master(included in26.11and later)