Skip to content

Enable the columns cache by default - #123890

Open
alexey-milovidov wants to merge 81 commits into
masterfrom
enable-columns-cache-by-default
Open

alexey-milovidov wants to merge 81 commits into
masterfrom
enable-columns-cache-by-default

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Enable the columns cache (#96844) by default: use_columns_cache is now on by default and moves from the EXPERIMENTAL tier to production. The sub-settings enable_reads_from_columns_cache and enable_writes_to_columns_cache were already on, so with this change the cache is used for wide parts of MergeTree tables in Atomic and Replicated databases without any configuration. Since #124531 the same setting also caches the columns of Parquet files read by the file, s3, azureBlobStorage table functions and engines and by data lake tables, so those are cached by default as well. The server sizes it to columns_cache_size_to_ram_ratio of the available memory unless columns_cache_size is set, and it gives memory back under pressure. compatibility with 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_bytes asks for instead of returning a whole stripe of 65536 rows as one block (this made map_subcolumns_prewhere slower with the cache), and a Parquet row 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):

  • Performance Improvement

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

The columns cache, which keeps deserialized columns of wide MergeTree parts in memory, is now enabled by default (setting use_columns_cache). It saves decompression and deserialization for repeated reads of hot data. Set use_columns_cache = 0 or compatibility to a version before 26.11 to disable it.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code


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

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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0f16e53]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) FAIL
05512_parquet_metadata_cache_offset_index FAIL cidb
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb
Performance Comparison (amd_release, master_head, 1/6) FAIL Performance dashboard
columns_cache_prewhere_gaps #1 FAIL dashboard
columns_cache_prewhere_gaps #2 FAIL dashboard
columns_cache_prewhere_gaps #0 FAIL dashboard
set_index_check_in_range #0 FAIL dashboard
Performance Comparison (arm_release, master_head, 3/8) FAIL Performance dashboard
partial_merge_join #1 FAIL dashboard
array_join #9 FAIL dashboard
array_join #10 FAIL dashboard
promql_set_operator_presence_mask #2 unstable query history
Performance Comparison (arm_release, master_head, 6/8) FAIL Performance dashboard
lazy_materialization_final_limit #1 FAIL dashboard
columns_cache_prewhere_gaps #2 FAIL dashboard
columns_cache_prewhere_gaps #0 FAIL dashboard
columns_cache_prewhere_gaps #1 FAIL dashboard
aggregation_single_level_result_fanout #2 FAIL dashboard
aggregation_single_level_result_fanout #0 FAIL dashboard
lazy_materialization_final_limit #0 FAIL dashboard
primary_key_analysis_wholly_matching_ranges #0 FAIL dashboard
promql_selector_id_range_row_cost #2 FAIL dashboard
lazy_materialization_final_limit #2 FAIL dashboard
1 more test cases not shown
Performance Comparison (amd_release, master_head, 2/6) ERROR
Performance Comparison (amd_release, master_head, 3/6) ERROR
Performance Comparison (amd_release, master_head, 4/6) ERROR
Performance Comparison (amd_release, master_head, 5/6) ERROR
Performance Comparison (amd_release, master_head, 6/6) ERROR

AI Review

Summary

The 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

Performance Improvement is appropriate and requires a changelog entry. The entry describes the benefit, but its compatibility boundary is stale: the setting history and regression test now use 26.12, while the description and changelog still say 26.11. The entry also understates the affected formats and part types. Suggested replacement:

The columns cache is now enabled by default for MergeTree parts and supported Parquet reads, avoiding repeated decompression and deserialization of hot data. Set use_columns_cache = 0 or compatibility to a version before 26.12 to retain the previous default.

Update the compatibility boundary in the introductory description as well.

Findings

⚠️ Majors

  • src/Storages/MergeTree/MergeTreeReadPool.cpp:73: Stripe alignment remains enabled for reads that cannot populate the cache. With 2247 marks and eight threads, 256-mark stripes pass the alignment threshold. The compact-part write estimate subsequently disables writes, leaving repeated cache misses and expensive mark-range initialization. Historical AMD CI measured 94.4 → 279.9 ms; the 2026-11-21 measurement after the mark-walk optimization still reports 205 → 373 ms, versus a 1.01 ratio at 16 threads, where alignment is skipped. The relevant conditions remain in the current code. Finalize write eligibility before choosing alignment and skip it when writes are inhibited and no entries can be served. The dashboard conservatively labels the historical result “suspect” because raw repeated samples are unavailable; its history checks support the slowdown, and the later paired measurement and source trace independently support the mechanism. Exact-head confirmation remains outstanding.

  • src/Storages/MergeTree/MergeTreeReaderWide.cpp:954: Cache population can still exhaust a streaming query's memory budget. [dismissed by author -- https://github.com/Enable the columns cache by default #123890#discussion_r4324257393] The earlier fix was deliberately reverted, as explained in the 2026-10-21 discussion. The accumulator still grows under the query tracker until admission transfers ownership: a stripe of 65536 one-KiB strings can exceed a 50 MB query limit despite small output blocks and ample server-cache capacity. The new block-size guard does not bound this accumulator. This remains a default-on compatibility tradeoff; no new inline comment or reopening.

  • src/Core/Settings.cpp:1051: One-shot clickhouse-local reads still populate a cache discarded on exit. [dismissed by author -- https://github.com/Enable the columns cache by default #123890#discussion_r4331134456] Disabling the automatic cache there was deliberately reverted. LocalServer::processConfig still creates the RAM-sized cache, so zero-copy admission retains decoded columns and causes additional page faults without reuse. The post-zero-copy measurements report a 1.137 time ratio and higher RSS. The mechanism remains; no new inline comment or reopening.

💡 Nits

  • PR description/changelog: correct the compatibility boundary and scope using the replacement above.
Missing context / blind spots
  • ⚠️ Reviewed PR head 0f16e53c22a9 using pinned source files where the local CI merge differs. No local build or test binaries are available, so this run performed source and artifact review without executing tests.
  • ⚠️ The latest available performance dashboard candidate is 0d5d90b4d840 from 2026-11-14; its 43 slowdown rows and 1120 speedup rows predate the latest fixes. Current Praktika performance reports contain no completed query measurements. Completed measurements on the reviewed head would close this gap; historical ratios are not presented as current-head timings.
Tests
  • ⚠️ Run compact_part_subcolumns Repair subtree2 #1 with max_threads = 8, an empty columns cache, and the default write-estimate budget, toggling use_columns_cache in one current binary. Record time, user CPU, and cache hits/misses. The existing small-read regression exercises a different alignment boundary.
Final Verdict

Status: ⚠️ Request changes

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.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 4, 2026
Comment thread src/Core/Settings.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0f16e53c2 with master 841a49bef (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

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

Job report

alexey-milovidov and others added 2 commits October 5, 2026 19:19
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]>
Comment thread src/Core/Settings.cpp Resolved
alexey-milovidov and others added 2 commits October 6, 2026 13:21
…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]>
Comment thread src/Core/Settings.cpp Resolved
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 32 queries analysed

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 34 not_sure 1092 974 -10.8% <0.0001 cache: The -10.8% comes with an 11% CPU drop, which fits skipping decompression and deserialization of the heavy column this query groups on. Master's baseline for Q34 is unstable, so it stays not_sure.

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: 32073d9e-dbed-4309-8d47-27e6f554594e
  • MIRAI run: 1ad65f2c-e5e7-4770-bf91-bc07fd46a49f
  • PR check IDs:
    • clickbench_427740_1791490612
    • clickbench_427746_1791490612
    • clickbench_427752_1791490612
    • tpch_adapted_1_official_427763_1791490612
    • tpch_adapted_1_official_427775_1791490613
    • tpch_adapted_1_official_427842_1791490613

Comment thread src/Core/Settings.cpp Resolved
…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]>
Comment thread src/Core/Settings.cpp Resolved
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]>
Comment thread src/Storages/MergeTree/ColumnsCache.cpp Resolved
…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]>
Comment thread src/Storages/MergeTree/ColumnsCache.cpp Resolved
alexey-milovidov and others added 2 commits October 16, 2026 12:01
…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]>
@Avogar

Avogar commented Oct 16, 2026

Copy link
Copy Markdown
Member

Please wait for #126298, it's a blocker.

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed 4c25108e6f49. The merge was clean, clickhouse builds, and 05325_use_columns_cache_compatibility and 05479_merge_tree_small_read_streams_columns_cache pass locally.

On 0d5d90b4d840, only Performance Comparison jobs failed. 9 of the 14 master_head shards and all 6 Iceberg shards timed out (7200 s). They are red because of how the harness reacts to this change, not because of errors:

  • Since 0f4e0e7 removed columns_cache_size = 0 from the perf config, the right server answers repeated reads from the cache. The 5 shards that finished show 457 faster queries out of 2483.
  • perf.py profiles each changed query for --profile-seconds 10 on each server and gives it extra runs. Example: leftpad took 6 s on arm 3/8 at 2cf87a532402, before the change, and 78 s now, with 946 profile rows in leftpad-raw.tsv. The Tests stage of arm 5/8 took 49 min at 2cf87a532402 and over 98 min now. tpcds alone went from 97 s to 1096 s.
  • ARM runs the full suite on 8 shards ("Setting default changed"). AMD runs the 49 changed perf tests with all queries (--max-queries 0). Neither fits in the timeout with hundreds of profiled queries.

A few slowdowns were reported in the shards that finished:

  • parquet_top_k_threshold_streams #0: 3.9x
  • has_any_constant_string_needles doc: fix typo #4: 3.7x
  • compact_part_subcolumns Repair subtree2 #1: 3x
  • map_subcolumns_prewhere: about 1.35x

I could not reproduce the two biggest ones on this build with a local server. parquet_top_k_threshold_streams #0 took about 14 ms with use_columns_cache 0 and 1. compact_part_subcolumns #1 took 60-80 ms either way, and compact parts are not cached anyway. They may come from memory pressure on the shared runner, where the right server's cache grows across tests, rather than from the read path.

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.

Comment thread src/Core/Settings.cpp Resolved
@snelheidai

Copy link
Copy Markdown

None of the four slowdowns looks like memory pressure. In the perf archives of 0d5d90b4d840, the right server shows the same metrics run after run. For map_subcolumns_prewhere that is in the review comment above. The other three:

Test, query Right server (cache on), typical run Left server
parquet_top_k_threshold_streams #0 (arm 4/8) 0 row groups skipped by the top-K threshold, all 20 M rows through the filter, 200 cache hits 148–161 skipped, 3.9–5.2 M rows
parquet_top_k_threshold_streams #1 0 skipped, 20 M rows 41–79 skipped, 12–16 M rows
has_any_constant_string_needles #4 (amd 2/6) ColumnsCacheEvictedBytes 846,900,900 (4 entries), 1 hit, 81 misses, 130 k soft page faults, 847 MB decompressed 8 k soft page faults, 847 MB decompressed
has_any_constant_string_needles #3 2 entries (215 MB) evicted per run —
compact_part_subcolumns #1 (amd 1/6) 2247 misses, nothing evicted, 2.36 GB decompressed, 1.38 s user CPU 2.36 GB decompressed, 0.52 s user CPU

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 (finishRowSubgroupStage), which lets the next row group start and be checked against the threshold. When the sort column v comes from the columns cache, a row group is read almost instantly. So admissions run ahead of the sort, and nearly every row group is checked against the threshold of the first few. The cache fills only with row groups that were read, so the number of skipped row groups falls run by run (125, 9, 3 on a fresh server), and the first runs after a restart look normal. The patch makes a row group whose sort column comes from the cache keep its admission until it is delivered. Row groups read from the file are unchanged.

Fresh server on a 4-vCPU ARM host with 30 GiB and its default 3.3 GB columns cache; master d88a8f1234a with and without the patch (ReadManager.cpp is the same in 0d5d90b4d840 and 4c25108e6f49). Medians of interleaved runs (75 pairs with the cache, 100 and 60 without); the ratio is the paired geometric mean with a 95% bootstrap interval:

Query use_columns_cache Master Patched Patched / master Row groups skipped
#0, LIMIT 10 1 30 ms 15 ms 0.46 [0.42, 0.50] 30 → 175
#1, LIMIT 100 1 64 ms 48 ms 0.74 [0.72, 0.76] 0 → 81
#0 0 25 ms 25 ms 0.98 [0.91, 1.07] 151 → 151
#1 0 81 ms 82 ms 1.00 [0.95, 1.05] 21 → 17

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 (LIMIT 10/100/5000, DESC, OFFSET, WHERE, ties, WITH TIES, one thread) return identical results on both builds, with the cache on and off. With use_columns_cache = 1, the server-side Parquet top-K and columns-cache stateless tests also give identical output on both builds: 05317, 05321, 05338, 05361 and 05446 pass, and 05243, 05339 and 05353 fail the same way on master in my setup.

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);
         }
     }
 }

has_any_constant_string_needles #3 and #4. A cache entry holds a stripe of about 65536 rows; for perf_has_any_512 that is about 212 MB of strings. The cache has at most 16 shards, so a shard of the default cache on the 64 GB runner holds roughly 400 MB, and SLRU keeps a probationary entry only if it fits in the space the protected segment leaves (see the comment in ColumnsCache.cpp). An entry that large needs a nearly empty shard. On the runner, all four were dropped right after being written, on every run, after the query had paid for building them (130 k page faults). On the 30 GiB host (12 shards of 275 MB), 2 of the 4 entries are dropped on every run. Its steady state is still faster than without the cache (108 vs 180 ms), but the first run, which writes all four, takes 426 ms. Bounding a stripe by bytes as well as rows would let such columns be cached. Not building an entry its shard cannot keep would at least avoid the cost.

I didn't look into compact_part_subcolumns beyond these metrics: the extra time is CPU on the cache-on read path, with nothing cached or evicted.

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.

subkanthi pushed a commit to subkanthi/ClickHouse that referenced this pull request Nov 18, 2026
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]>
perfloop-agent pushed a commit to perfloop-oss/ClickHouse that referenced this pull request Nov 20, 2026
…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]>
alexey-milovidov and others added 4 commits November 21, 2026 03:08
…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]>
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed 3beb0fb. The merge conflicted in ReadFromMergeTree: master added min_marks_per_task_at_read_end to ReadFromMergeTree::read next to align_tasks_to_columns_cache_stripes of this branch, and both are kept.

@snelheidai, thank you for the analysis. What this push does about the four slowdowns:

  • parquet_top_k_threshold_streams: applied your patch as is in aae18e6. The Parquet columns cache and top-K stateless tests that can run on my local server pass with it, including 05629_parquet_top_k_columns_cache. I did not repeat your timing.
  • map_subcolumns_prewhere #0 and doc: fix typo #4: fixed in 3beb0fb, details and measurements are in the review thread. A read through the cache returned whole stripes of 65536 rows as one block, 27 MB for this Map, instead of the granule that preferred_block_size_bytes asks for.
  • has_any_constant_string_needles BaseDaemon: terminate on double SIGINT #3 and doc: fix typo #4: the same change helps here. With a cache of 6.4 GB (as on the 64 GB runner) doc: fix typo #4 now gets 82 hits, 0 misses and 0 evicted bytes on every run after the first: 60 ms, against 165 ms without the cache. The first run, which writes the cache, takes 552 ms. I did not add a byte bound to the stripe itself.
  • compact_part_subcolumns Repair subtree2 #1: not reproduced and not changed. On my host the query has the same 2247 misses with the cache on, but the same time and user CPU as with it off (24 ms and about 740 ms user at 96 threads, 38 ms and about 528 ms user at 16 threads). This one is still open.

Also fixed the arm_tidy build ([[nodiscard]] on MemoryReleasedInThread::get).

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 Performance Comparison jobs timed out on the previous head because hundreds of queries change with the cache on and each gets profiled. This push does not change that.

@snelheidai

Copy link
Copy Markdown

compact_part_subcolumns #1 depends on max_threads, which is why it did not show up at 16 and 96 threads. The perf comparison runs it with max_threads = 8. With the cache on, MergeTreeReadPool then aligns the read tasks to the 256-mark stripes of these parts, because a thread's share of the 2247 marks is 281 marks; at 16 threads it is 141, and the pool does not align. The first task of each stream becomes a whole stripe, and MergeTreeReaderStream::init walks the marks of all 7025 substreams for every granule of that task. In the right server's CPU profile from the 0d5d90b4d840 run (amd 1/6), init → estimateMarkRangeBytes has 576 of the 866 samples under readGranule, against 35 of 281 on the left server. The decompressed bytes are the same on both.

#131707 makes this walk cheaper, and this head has it from master, but at 8 threads the query is still 1.8x slower with the cache. The head has no build because CI stopped at the style check, so I used master CI builds and set use_columns_cache per query. Nothing on this read path changed between f42be4011797 and the master merged into 3beb0fb. The PR's own align_tasks_to_columns_cache_stripes turns the alignment off only for spread small reads, and in the 0d5d90b4d840 run this read is still aligned: 9–10 read buffers per query on the right server, 14–20 on the left. Setup: a 4-vCPU x86 host, t_json_2 filled as in the test (4 compact parts, 2247 marks), and the cache off and on interleaved in one server for 15 pairs. The table shows medians and the paired time ratio with a 95% bootstrap interval:

Build max_threads Cache off Cache on On / off
e05308f1dd1e, before #131707 8 311 ms, 1192 ms user 1034 ms, 3718 ms user 3.22 [3.06, 3.42]
f42be4011797, #131707 merged 8 205 ms, 782 ms user 373 ms, 1363 ms user 1.81 [1.77, 1.86]
f42be4011797 16 226 ms, 864 ms user 229 ms, 869 ms user 1.01 [0.99, 1.03]

e05308f1dd1e gives 1.01 [0.99, 1.06] at 16 threads as well. On f42be4011797 at 8 threads, estimateMarkRangeBytes still has 3299 of the 7094 CPU samples with the cache on, against 578 of 3697 with it off.

The alignment cannot pay off for this query, because the cache never stores data.a0. The write estimate charges a compact part in full, 21.6 GB uncompressed for these parts. That is more than half of any cache under 43 GB, so writes are off for the whole query and every run has 2247 misses. The data.a0 entries need only 3.6 MB. With columns_cache_max_estimated_bytes_to_write_to_cache = 100000000000, the first run takes 385 ms and the following runs 2 ms each, with all 2247 granules served from the cache.

Two changes would address this:

  • Skip the alignment when the read cannot write to the cache and the cache holds nothing of the part. That should remove the slowdown, as at 16 threads. The pool decides the alignment in its constructor, before the estimate is charged.
  • Charge a compact part only for the columns or subcolumns the query reads. That would let this query use the cache.

alexey-milovidov and others added 2 commits November 22, 2026 19:30
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]>
{
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@snelheidai

Copy link
Copy Markdown

With the cache on, PREWHERE queries keep re-reading granules that the range reader cuts short. ReadResult::optimize stops reading a granule after the last row PREWHERE kept, and the columns cache stores only granules read to their end, so such a granule is read from the part and decompressed by every query. In the wide reader, if that is the last range a reader reads, it also drops the complete granules it had accumulated for that stripe. This hits primary-key ranges that end inside a granule: on a 10-part hits, repeated ClickBench Q38 (CounterID = 62) had 3 cache misses and decompressed 4.80 MB on every run.

The patch below cuts only whole granules when the step's reader uses the cache, by passing can_read_incomplete_granules = false to ReadResult::optimize. Repeated Q38 then has no misses and decompresses nothing. It applies to this PR's head (0f16e53) with line offsets; the head's change in MergeTreeRangeReader.cpp (alignRowsToColumnsCacheStripes) is not on this path.

Master a7735de with use_columns_cache = 1 in both arms; Xeon 8375C pinned to 8 cores + HT, max_threads = 16; 100M-row hits with 12 columns, ZSTD(3), 10 parts (CounterID = 62 is in 4 of them and ends inside a granule in each). Paired runs, durations from query_log, patched/master geometric mean with 95% CI:

Workload Patched / master
Q38 repeated: 11.44 → 7.88 ms, CPU 28 → 23 ms; per run 3 → 0 misses, 4.80 MB → 0 decompressed 0.698 [0.681, 0.715], 8/8 rounds
Q38, Q36 and five URL GROUP BY queries over other CounterID ranges, interleaved two URL queries 0.937 [0.916, 0.959] and 0.971 [0.943, 1.000]; Q36 and the other three within noise; Q38 1.017 [0.998, 1.036]
First query after SYSTEM CLEAR COLUMNS CACHE 1.031 [0.948, 1.121]
Cache off 1.014 [0.994, 1.034]; same code path (getColumnsCacheStripeMarks() is 0)

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 (getColumnsCacheStripeMarks() != 0) also holds for a read that cannot write to the cache (enable_writes_to_columns_cache = 0, or the query is over its write estimate or write budget). Such a read now decodes the rows that used to be cut and does not cache them. I did not measure that case separately; the first-query row reads the same rows. The 493 stateless tests matching columns_cache, condition_cache, prewhere, zero_tail, read_in_order or granul give the same results with and without the patch.

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;

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants