Repository navigation
Enable the columns cache by default - #123890
alexey-milovidov wants to merge 81 commits into
Conversation
Turn `use_columns_cache` on by default and move it from the `EXPERIMENTAL` tier to production. `compatibility` with versions before 26.11 restores the previous behavior. Related: #96844 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [0f16e53] Summary: ❌
AI ReviewSummaryThe PR enables the columns cache by default in 26.12, promotes it from experimental status, fixes cache bookkeeping and memory reclamation, and adjusts read sizing and tests. Historical measurements demonstrate substantial warm-read benefits, but compact-part reads still retain unnecessary stripe alignment when cache writes are disabled. Request changes for that remaining performance concern. Two previously raised, deliberately accepted tradeoffs remain documented below; their threads are not reopened. PR Metadata
Update the compatibility boundary in the introductory description as well. Findings
💡 Nits
Missing context / blind spots
Tests
Final VerdictStatus: Address or disprove the compact-part alignment regression with the focused current-head measurement. Correct the compatibility guidance to 26.12. Previously accepted tradeoffs remain summary-only findings. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units698 translation units recompiled, 5132 s compile time in total, 698 of them have a recent master baseline. |
With `use_columns_cache` enabled by default, warm reads in these tests are served from the columns cache, so the page cache and the remote prefetch they check are never reached: `03553_prefetch_buffer_size` saw zero prefetched bytes for `test_1` (populated by reading it in the `INSERT SELECT`s), and `test_page_cache` / `test_reader_executor_populates_and_serves_page_cache` saw no `PageCacheHits` on the warm read. Turn the columns cache off for the queries under test. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123890&sha=latest&name_0=PR PR: #123890 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cache` Co-Authored-By: Claude Opus 5.5 <[email protected]>
…when_reading_from_cache` With `use_columns_cache` on by default, the measured query could be served from the columns cache, and the checks of the filesystem cache read path would pass without exercising it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…base engine `05055_columns_cache_database_engines` documents that `Shared` tables keep a nil UUID and the columns cache is ignored for them, like `Ordinary`. Update the `use_columns_cache` setting description and the `system.columns_cache` table description to only name `Atomic` and `Replicated`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report
This PR turns on use_columns_cache by default, so every MergeTree read in ClickBench and TPC-H now goes through the deserialized columns cache. Only two queries moved, both faster. Q34 (-10.8%) used about 11% less CPU, which fits the cache skipping decompression and deserialization, but master's baseline for it is unstable, so it stays not_sure. Q31 (-16.5%) is still inside master's current range and its CPU barely changed, so it stays no_change. Because the change reaches every query, the lack of wider gains suggests the cache was rarely hit in these runs; check that before reading this as a measured win or a sign of no overhead. clickbenchFlagged 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
|
…tial_segment` The test checks that the second read of the same granules promotes the filesystem cache segments. With `use_columns_cache` enabled by default, the second read is served from the columns cache and does not touch the filesystem cache, so nothing is promoted. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123890&sha=976f72423f3be21d3cc15eb2ab877ccee2a563e2&name_0=PR #123890 Co-Authored-By: Claude Opus 5.5 <[email protected]>
An operation of `ColumnsCache` allocates under the mutex of a shard or `index_mutex`: the snapshot of `dump` for `system.columns_cache`, the nodes of the hash tables in `setMany`, the stamps in `getInvalidationGeneration`. If such an allocation exceeds the global memory limit, `MemoryTracker` calls `ColumnsCache::autoResize`, which takes the mutexes of the shards for `sizeInBytes` and for eviction, and `index_mutex` in `onEntryRemoval`, so the thread deadlocked on the mutex it already held. Count the operations of the cache in progress in the thread, and make `autoResize` do nothing while there is one: the allocation is left to the other means of `MemoryTracker`, stopping a query or the exception. Addresses the review comment in #123890 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…to the columns cache With `use_columns_cache` and `enable_writes_to_columns_cache`, the readers did not apply `apply_string_filters_during_scan` to any part, and `MergeTreeWhereOptimizer` did not move conditions to PREWHERE for it, although only a wide part of a table with a UUID, not a projection part, can be written to the cache. A compact part, or a table in an `Ordinary` database, lost the filter with no possible use of the cache. Decide by the actual eligibility: `isColumnsCachePossibleForPart` is shared by `IMergeTreeReader` and `MergeTreeReaderWide`, and the optimizer gets `ReadFromMergeTree::mayWriteToColumnsCache` for the parts it reads. `05326_string_filters_move_to_prewhere_applicability` now forces wide parts, so that its columns cache case does not depend on the randomized part type. Addresses the review comment in #123890 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ackTrace::tryResolveAddress` #126039 changed `StackTrace::tryResolveAddress` to return `ResolvedAddress` by value, with a null address for an address that does not resolve, while `formatStackTrace` in `gtest_functions_stress.cpp`, added in parallel, used it as an optional. `unit_tests_dbms` does not compile on `master` since then. Print the resolved address like `writeResolvedAddress` in `SignalHandlers.cpp` does: `<unknown>` for an address that does not resolve, and the name of the object for an address in a shared library. https://github.com/ClickHouse/ClickHouse/actions/runs/38884911247/job/116920919005 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ot tracked With a sanitizer, `operator new` is the one of the sanitizer runtime and does not go through `MemoryTracker`, so the allocation under the mutex of a shard never exceeds the limit and the test had nothing to check. Probe that a plain `operator new` fails at the limit before registering the cache, and skip the test otherwise. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123890&sha=ae7e0f75376571fd03a222761a46f4bd9db372c2&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%29 #123890 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Please wait for #126298, it's a blocker. |
…neligible_parts` The test checks `StringValueFilterValuesChecked` in the `system.query_log` entry of the query, which does not reliably include the reads of the queries to the replicas. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123890&sha=fe0be4cfde990bd7f58d6af66c06b917dc456880&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29 #123890 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Both constructors called `getColumnsCacheIfEnabled` three times: for the write policy, for the schema identity and for `owned_columns_cache`. The helper checks the current effective cache size, which `autoResize` changes under memory pressure, so a pool could keep a non-null cache while its reader settings had no write budget state and the default schema identity. Declare `owned_columns_cache` before `reader_settings` and derive both reader-settings adjustments from that single snapshot. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged On
A few slowdowns were reported in the shards that finished:
I could not reproduce the two biggest ones on this build with a local server. Getting the perf check green needs a decision about the harness. Either keep the cache off in the perf comparison and measure its effect separately, or accept the timeouts or adjust profiling for this PR. Disabling the cache in more individual perf tests would not be enough. I did not change this. |
|
None of the four slowdowns looks like memory pressure. In the perf archives of
I reproduced the first two mechanisms on a fresh server. The patch below fixes the top-K one. Top-K over a cached Parquet file. A row group gives back its top-K admission as soon as it has been read ( Fresh server on a 4-vCPU ARM host with 30 GiB and its default 3.3 GB columns cache; master
With the patch, both queries are faster with the cache than without it (15 vs 25 ms and 48 vs 81 ms). The cache-off rows are from runs without the cache. In the runs that mixed both modes, #0 without the cache came out at 1.09 [1.01, 1.17]; neither the cache-off runs nor master against itself (0.98 [0.91, 1.05]) reproduce that. A read without the cache takes the same path as before: the added release at delivery finds nothing left to release. Ten top-K variants ( Patch (on master d88a8f1, applies to 4c25108)--- a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp
+++ b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp
@@ -423,8 +423,10 @@
{
for (auto & c : row_group.columns)
clearColumnChunk(c, diff);
- release_top_k_admission = true;
}
+ /// A row group with subgroups usually released its top-K admission when they were read, see
+ /// `finishRowSubgroupStage`; one whose top-K sort column is in the columns cache releases it here.
+ release_top_k_admission = true;
/// All subgroups are delivered (or there are none), so nothing forms columns from
/// the cached ones any more. Don't keep the columns alive after the cache evicts them.
row_group.cached_columns.clear();
@@ -719,6 +721,15 @@
if (*advanced_ptr == row_group.subgroups.size())
{
+ /// When the top-K sort column is served from the columns cache, the row group is read in almost no
+ /// time: the filter on that column needs no reading or decoding, and the other columns are read only
+ /// for the rows that pass it. If it released its top-K admission now, the next row groups would start
+ /// before the sorting has seen any of its rows, and all of them would be checked against the threshold
+ /// of the first few, so a file in the cache would be read almost whole. It holds the admission until
+ /// it is delivered instead, see `ReadStage::Deallocated` in `finishRowGroupStage`.
+ const bool top_k_column_from_cache = reader.top_k_primitive_idx.has_value()
+ && row_group.columns.at(*reader.top_k_primitive_idx).served_from_cache;
+
/// If we've read (not necessarily delivered) all subgroups, we can deallocate things
/// like dictionary page and offset index. Clear all columns (including PREWHERE-only),
/// since we scheduled ColumnData prefetches for all of them and must release the memory.
@@ -727,7 +738,8 @@
reader.flushColumnsCacheWrites(row_group);
- releaseTopKAdmission(row_group_idx, diff);
+ if (!top_k_column_from_cache)
+ releaseTopKAdmission(row_group_idx, diff);
}
}
}
I didn't look into So these are effects of the new default, not noise from the runner. With the cache off in the comparison, they would not show up. |
TopN dynamic filtering checks a row group against the threshold before reading it. A row group served from the columns cache is ready almost at once, so all of them pass that check while the sorting transforms are still sorting the first chunks and the threshold is loose: with the cache, `ParquetTopKSkippedRowGroups` dropped from about 160 to 3 of 209 row groups and the query read five times more rows. Check the threshold once more when delivering a chunk: by then it reflects everything delivered before, and the check costs nothing. https://performance.ci.clickhouse.com/runs/pr-123890-0f4e0e78cb42e31fef159ff3e74a0eec321c772a ClickHouse#123890 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…olumns `MergeTreeReaderStreamAllOfMultipleColumns::estimateMarkRangeBytes` estimated the bytes to read for every column of the part separately, at about a dozen `getMark` calls per column and mark. A compact part with substream marks has a column per substream, and a `JSON` column with many paths has thousands of them (7025 for `t_json_2` of the `compact_part_subcolumns` perf test). So `MergeTreeReaderStream::init` cost the number of marks of the first task times the number of substreams: with one thread, `SELECT data.a0 FROM t_json_2` spent 2.3 s of its CPU there. Longer tasks make it worse, and the stripe alignment of the columns cache gives longer tasks, which made that query 3x slower with the cache on. The stream reads all columns, and the columns of a stripe lie together in the file, so the estimate now walks whole stripes. A stripe ends where `getStartOfNextStripeMark` says it does. This costs O(marks), and the sum is also accurate now: each tiny substream used to count its shared compressed block again, so a range of 25 KB was estimated at 175 MB. Measured with `SELECT data.a0 FROM t_json_2` (median of 5): 2.34 s -> 0.90 s with `max_threads = 1`, 0.216 s -> 0.182 s with the default number of threads, and with the columns cache on and `max_threads = 8`, 0.566 s -> 0.278 s. https://performance.ci.clickhouse.com/runs/pr-123890-0d5d90b4d8401b30eb4ac3bd711d80f25f62b8f2 Related: ClickHouse#123890 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e-by-default Conflicts in `ReadFromMergeTree`: `master` added `min_marks_per_task_at_read_end` to `ReadFromMergeTree::read` next to the `align_tasks_to_columns_cache_stripes` parameter of this branch. Both are kept. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Fixes the `modernize-use-nodiscard` error of the `arm_tidy` build: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123890&sha=4c25108e6f49358316ee169c37f40578b9ff8bfc&name_0=PR&name_1=Build%20%28arm_tidy%2C%203%2F4%29 #123890 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ns cache until it is delivered A row group gives back its top-K admission as soon as it has been read, which lets the next row group start and be checked against the threshold. When the sort column comes from the columns cache, a row group is read in almost no time, so the admissions ran ahead of the sorting and nearly every row group was checked against the threshold of the first few: a cached file was read almost whole (`parquet_top_k_threshold_streams` was up to 3.9 times slower with `use_columns_cache`). Such a row group now holds its admission until it is delivered. Row groups read from the file are unchanged. The patch and the measurements are by snelheidai: #123890 (comment) Co-Authored-By: Claude Fable 5.2 <[email protected]>
…e columns cache A block that is a whole stripe of the columns cache (65536 rows) shares the columns of the cache, so `MergeTreeRangeReader` read such a stripe as one block even when `preferred_block_size_bytes` asked for a granule. For wide rows that block is tens of megabytes, and the functions over it work out of the CPU cache. In `map_subcolumns_prewhere` #0 and #4 the read is negligible and all the time is in `arrayElement` over a `Map` of 16 keys: without the cache it ran on 611 blocks of a granule, with the cache on 79 blocks of 27 MB, which was confirmed as +39.5% and +33.3% in the performance comparison: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123890&sha=0d5d90b4d8401b30eb4ac3bd711d80f25f62b8f2&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%201%2F6%29 #123890 A stripe is now read whole only if it is at most 4 times the rows the read asked for. A read of wider rows keeps its block size and copies the rows from the cache. Measured on a 96-core ARM host, same binary, warm, medians of 20 runs, `use_columns_cache` 0 and 1: - `map_subcolumns_prewhere` #0, 16 threads: user CPU 2585 and 2643 ms before, 2574 and 2340 ms after; time 172 and 184 ms before, 168 and 164 ms after. - `map_subcolumns_prewhere` #4, 16 threads: user CPU 2693 and 2695 ms before, 2651 and 2376 ms after; time 181 and 192 ms before, 179 and 172 ms after. The memory of the query with the cache went from 388 MiB to 158 MiB (#0). With a cache of 6.4 GB, as on the 64 GB runner, `has_any_constant_string_needles` #4 gets 82 hits and evicts nothing after the first run (60 ms, and 165 ms without the cache). Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged @snelheidai, thank you for the analysis. What this push does about the four slowdowns:
Also fixed the Local test results on this head: of the stateless tests that mention the columns cache or top-K, 183 pass against a server with the 100 MB cache of the test config. The rest fail only for what my bare server lacks (clusters, Keeper, S3, access storage), none with a different result. Still open, and needs a human decision: the |
|
#131707 makes this walk cheaper, and this head has it from
The alignment cannot pay off for this query, because the cache never stores Two changes would address this:
|
The current version is 26.12 after the merge of master, so the style check requires the change of the default to be recorded under it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| { | ||
| columns_cache_stripe_marks.assign(parts_ranges.size(), 0); | ||
| if (owned_columns_cache && (reader_settings.enable_columns_cache_reads || reader_settings.enable_columns_cache_writes)) | ||
| if (pool_settings.align_tasks_to_columns_cache_stripes && owned_columns_cache |
There was a problem hiding this comment.
[Major] Avoid stripe-aligned tasks when the read cannot populate the cache
This still enables task alignment before commitColumnsCacheWriteEstimate decides whether writes are allowed. For compact_part_subcolumns #1 at max_threads = 8, the 2247 selected marks give 281 marks per thread, so the 256-mark stripes pass this check. The estimate then charges all 21.6 GB of the compact parts and disables writes with a normal-sized cache. With no cached entries, every run pays for the larger tasks without obtaining a cache hit; initializing the compact reader repeatedly estimates ranges across its 7025 substreams.
The 2026-11-14 AMD result was 94.4 → 279.9 ms, and its CPU profile concentrates the extra work in mark-range estimation. That predates the mark-walk optimization, but the 2026-11-21 follow-up still measures 205 → 373 ms after that optimization over 15 paired runs. At 16 threads the stripes exceed the per-thread share, alignment is skipped, and the ratio is 1.01. The current code retains this path; the new block-size guard cannot help when the budget already forbids writing a whole stripe.
Please decide write eligibility before enabling alignment, and skip alignment when writes are inhibited and the part has no entries to serve. Verify the existing query at eight threads with use_columns_cache off/on in the same current binary; the small-read test does not exercise this boundary.
|
With the cache on, The patch below cuts only whole granules when the step's reader uses the cache, by passing Master a7735de with
In the interleaved run, the other queries had already cached Q38's cut granules on master too, so there the patch only makes Q38 serve and filter whole granules from the cache. The patch's condition ( Patch (MergeTreeRangeReader.cpp)diff --git a/src/Storages/MergeTree/MergeTreeRangeReader.cpp b/src/Storages/MergeTree/MergeTreeRangeReader.cpp
index a6bf50c548ea..8f6b1d0545a4 100644
--- a/src/Storages/MergeTree/MergeTreeRangeReader.cpp
+++ b/src/Storages/MergeTree/MergeTreeRangeReader.cpp
@@ -679,6 +679,15 @@ void MergeTreeRangeReader::ReadResult::applyFilter(const FilterWithCachedCount &
LOG_TEST(log, "ReadResult::applyFilter() num_rows after: {}", num_rows);
}
+/// The columns cache holds only granules read to their end. A granule that a read cuts after the last row the
+/// filter kept is never written to it, so every later read of the range reads that granule from the part again.
+/// When the reader uses the cache, cut only whole granules: the rows after the last kept one are read and
+/// filtered out like the others.
+static bool canCutIncompleteGranules(bool can_read_incomplete_granules, const IMergeTreeReader & reader)
+{
+ return can_read_incomplete_granules && reader.getColumnsCacheStripeMarks() == 0;
+}
+
void MergeTreeRangeReader::ReadResult::optimize(const FilterWithCachedCount & current_filter, bool can_read_incomplete_granules_, bool must_apply_filter)
{
checkInternalConsistency();
@@ -1359,7 +1368,7 @@ MergeTreeRangeReader::ReadResult MergeTreeRangeReader::startReadingChain(
{
auto current_filter = FilterWithCachedCount(result.columns.front());
result.columns.clear();
- result.optimize(current_filter, can_read_incomplete_granules, merge_tree_reader->mustApplyFilter());
+ result.optimize(current_filter, canCutIncompleteGranules(can_read_incomplete_granules, *merge_tree_reader), merge_tree_reader->mustApplyFilter());
}
else
{
@@ -1854,7 +1863,7 @@ void MergeTreeRangeReader::executePrewhereActionsAndFilterColumns(ReadResult & r
}
/// No later step re-evaluates the candidates, so the filter must not be left in final_filter.
- result.optimize(current_filter, can_read_incomplete_granules, /*must_apply_filter=*/ true);
+ result.optimize(current_filter, canCutIncompleteGranules(can_read_incomplete_granules, *merge_tree_reader), /*must_apply_filter=*/ true);
}
if (!prewhere_info || prewhere_info->type == PrewhereExprStep::None)
@@ -1963,7 +1972,7 @@ void MergeTreeRangeReader::executePrewhereActionsAndFilterColumns(ReadResult & r
const size_t rows_before_prewhere_filter
= result.final_filter.present() ? result.final_filter.countBytesInFilter() : result.num_rows;
- result.optimize(current_filter, can_read_incomplete_granules, false);
+ result.optimize(current_filter, canCutIncompleteGranules(can_read_incomplete_granules, *merge_tree_reader), false);
/// Null when predicate_statistics_sample_rate = 0 (default). Counts the rows that passed all steps so far.
if (performance_counters)
performance_counters->rows_passed_filter += result.final_filter.present() ? result.final_filter.countBytesInFilter() : result.num_rows; |
Enable the columns cache (#96844) by default:
use_columns_cacheis now on by default and moves from theEXPERIMENTALtier to production. The sub-settingsenable_reads_from_columns_cacheandenable_writes_to_columns_cachewere already on, so with this change the cache is used for wide parts ofMergeTreetables inAtomicandReplicateddatabases without any configuration. Since #124531 the same setting also caches the columns ofParquetfiles read by thefile,s3,azureBlobStoragetable functions and engines and by data lake tables, so those are cached by default as well. The server sizes it tocolumns_cache_size_to_ram_ratioof the available memory unlesscolumns_cache_sizeis set, and it gives memory back under pressure.compatibilitywith versions before 26.11 restores the previous behavior.To make the default safe for wide rows, a read through the cache now keeps the block size that
preferred_block_size_bytesasks for instead of returning a whole stripe of 65536 rows as one block (this mademap_subcolumns_prewhereslower with the cache), and aParquetrow group whose top-K sort column comes from the cache keeps its top-K admission until it is delivered (without this, a cached file was read almost whole by a top-K query).This is meant to be merged after the 26.10 release.
Related: #96844
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The columns cache, which keeps deserialized columns of wide
MergeTreeparts in memory, is now enabled by default (settinguse_columns_cache). It saves decompression and deserialization for repeated reads of hot data. Setuse_columns_cache = 0orcompatibilityto a version before 26.11 to disable it.Documentation entry for user-facing changes
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/123890]