Skip to content

Columns Cache - #96844

Merged
alexey-milovidov merged 377 commits into
masterfrom
columns-cache
Oct 4, 2026
Merged

alexey-milovidov merged 377 commits into
masterfrom
columns-cache

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Feb 13, 2026 •

Copy link
Copy Markdown
Member

Implement the deserialized columns cache that keeps columns in memory. In comparison to the uncompressed cache, this saves time on deserialization and copying.

Closes: #82335

The feature is off by default and gated behind the EXPERIMENTAL setting use_columns_cache. When it is on, the BETA settings enable_reads_from_columns_cache and enable_writes_to_columns_cache turn the reads and the writes on and off, and columns_cache_max_bytes_to_write_to_cache and columns_cache_max_estimated_bytes_to_write_to_cache keep a single large scan from displacing the cache: the estimate is made in uncompressed bytes - the unit the cache is bounded in - and the whole query is charged for its selected mark ranges before any task is handed out, so a query that cannot fit writes nothing at all. The size and the eviction policy of the cache are server settings: columns_cache_size, columns_cache_size_to_ram_ratio, columns_cache_size_ratio, and columns_cache_policy. When columns_cache_size is absent from the configuration, the cache is sized to columns_cache_size_to_ram_ratio (0.1) of the memory available to the server rather than to a fixed default, so it is above the working set of a real query on a large machine and below it on a small one.

The cache identifies its entries by table UUID, so it is active only for tables in databases that assign UUIDs (Atomic and Replicated); MergeTree tables in databases without UUIDs - legacy Ordinary databases, and Shared databases, the default in ClickHouse Cloud - have a nil UUID and silently ignore the setting. Only wide parts are cached: reads of compact parts neither populate the cache nor are served from it.

An entry holds a stripe of consecutive granules of one column of one part - about 65536 rows, one block of a read, cut the same way for every read of the part - and a read is served from the cache granule by granule and column by column: the granules whose entries are there come from the cache, the others are read from the part, whatever the mark ranges of the read task are. An entry holds a contiguous run of the granules of its stripe: the whole stripe after a full scan, the granules a filtered read touched otherwise, and the runs written by different reads are merged when they overlap or touch. This is what makes the entries reusable across queries. The ranges a task reads depend on the number of threads, on the primary key analysis, on the query condition cache (which prunes marks on the second run of a query) and on PREWHERE (whose readers skip rows and read their ranges in pieces), so entries bound to task ranges were found again only by a read with exactly the same ranges, and the entries of any other read of the same data displaced them; in the ClickBench concurrency test that gave a steady-state hit rate of 10-40% and a 13% loss of throughput. Entries per granule fixed that but cost a lookup and a copy per granule, which for a narrow column is more than decompressing it, and the lookups of a thread per core serialized on one mutex: the large machines lost 2-3x on cheap queries. The stripes bring the fixed cost per row down by the size of the stripe, the cache is split into 16 shards like the userspace page cache, and the key is a 128-bit identity of the column of the part plus the stripe number, so a lookup allocates and hashes nothing. On a 96-core machine a warm scan of two narrow columns over 100M rows takes 5 ms against 14 ms without the cache (17 ms with entries per granule), writing the cache costs 7% instead of 4x, and the ClickBench concurrency test on a 30M-row table runs at 1.3-1.5x the throughput of the plain read at a 99% hit rate.

The cache gives its memory back when the server is short of it. Its size counts against max_server_memory_usage like the memory of the queries does, so a cache of a tenth of the memory pushed concurrent queries over the limit on small machines (an error ratio of 0.5 in the ClickBench concurrency test on 32 GB machines), where they succeeded with the cache off. Like the userspace page cache, the size in effect is now lowered to what fits next to the peak memory usage of everything else - on every tick of the memory worker, and synchronously when an allocation is about to exceed the limit, before a query is stopped for it - and raised back towards columns_cache_size once that usage subsides; columns_cache_free_memory_ratio and columns_cache_history_window_ms control it. A cache that is smaller than the working set of the queries does not pay for writes that are evicted before any read finds them either: while most admitted entries go unused, the admission probability is halved, down to 1/64, and doubled back while they are used.

The cache is bounded by the memory its entries retain rather than by the logical size of their rows: an entry is charged the allocated size of its column, which for a LowCardinality column includes the dictionary it keeps alive, and the accumulated copy is shrunk to its rows before it is admitted so the reservation is not charged for the life of the entry. A read whose first range the cache can serve as a whole and without touching a single stream of the range also skips the read-ahead of that range, so a hit on object storage spends no requests on data it will not read; a range that is served from the cache but still reads a partially read column from the part - a Nested member re-added by an ALTER - is prefetched as any other range is.

system.columns_cache lists the entries and reports that same retained size, SYSTEM DROP COLUMNS CACHE drops them, and the ColumnsCacheHits and ColumnsCacheMisses profile events count the granules of columns served from the cache and read from disk.

Changelog category (leave one):

  • Experimental Feature

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

Add an experimental columns cache that keeps deserialized columns of wide MergeTree parts in memory, one entry per stripe of granules of a column. In comparison to the uncompressed cache, this saves time on deserialization and copying. It is enabled by the experimental setting use_columns_cache, with enable_reads_from_columns_cache and enable_writes_to_columns_cache as beta sub-settings, and it applies to tables in databases that assign UUIDs (Atomic and Replicated). The cache gives its memory back to the queries when the server is short of it.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

  • Merged into: 26.10.1.1500-master (included in 26.10 and later)

@alexey-milovidov
alexey-milovidov marked this pull request as draft February 13, 2026 21:01
@clickhouse-gh

clickhouse-gh Bot commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d2c296]

Summary: ✅


AI Review

Summary

This PR adds a deserialized columns cache for wide MergeTree reads, including invalidation on schema/part lifecycle changes, per-query write budgeting, memory-pressure resizing, and system.columns_cache introspection. After re-checking the current head and prior discussion, I do not see a remaining correctness, concurrency, or performance blocker in the implementation. The only issue I still found is in the PR metadata: the body and changelog entry still describe Shared databases as excluded, while the current docs/code describe the cache as available for UUID-bearing tables there as well.

PR Metadata
  • 💡 Changelog category is correct: Experimental Feature.
  • 💡 Changelog entry is required and mostly good, but the supported-surface text is stale. The PR body and changelog entry still say the cache applies only to Atomic / Replicated and that Shared databases have nil UUIDs, which does not match src/Core/Settings.cpp:973 and docs/reference/system-tables/columns_cache.mdx:17.
  • 💡 Suggested replacement sentence for both places: It applies to wide parts of tables with UUIDs, including Atomic, Replicated, and Shared databases; legacy Ordinary databases remain excluded.
Final Verdict
  • ✅ No remaining code-level blocker found in the current head.
  • 💡 Please update the PR body and changelog entry so the user-facing contract matches the current implementation.

LLVM Coverage Report

Measured on commit 5d2c296.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.20% +0.10%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 1473/1560 (94.42%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Feb 13, 2026
Comment thread ci/jobs/fast_test.py Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Also, let's set it to 2 GiB in the default server configuration, so it will be easier to selectively enable it in production.

alexey-milovidov added a commit that referenced this pull request Feb 13, 2026
- Add settings to SettingsChangesHistory.cpp to fix 02995_new_settings_history test
- Add SYSTEM DROP COLUMNS CACHE privilege to fix 01271_show_privileges test
- Improve system.columns_cache schema:
  * Add database and table columns for better usability
  * Simplify column names: part_name -> part, column_name -> column
- Expand caching to support partial granule reads:
  * Now serves subset reads: if cached [a, b), can serve [a', b') where a' >= a and b' <= b
  * Calculate proper offset within cached blocks for subset extraction
- Standardize naming: deserialized_columns_cache -> columns_cache throughout codebase
- Move logger from static variable to class member in MergeTreeReaderWide
- Set default columns_cache_size to 2 GiB for easier production enablement
- Re-enable cache in 03917_columns_cache_edge_cases test (Nullable issue resolved)
- Update test reference files for new schema

All changes address PR #96844 review comments.

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
@alexey-milovidov
alexey-milovidov force-pushed the columns-cache branch 2 times, most recently from d16b47c to d90a646 Compare February 14, 2026 01:58
Comment thread metadata/default.sql Resolved
Comment thread src/Storages/MergeTree/ColumnsCache.h Resolved
Comment thread src/Storages/MergeTree/ColumnsCache.h Resolved
alexey-milovidov added a commit that referenced this pull request Mar 14, 2026
…rwrite collisions

Address review feedback on PR #96844:

1. Fix stale `interval_index` entries: when LRU/SLRU eviction removes a cache
   entry, the corresponding `interval_index` entry was never cleaned up.
   Now `getIntersecting` and `getAllEntries` lazily remove stale entries
   (entries present in the index but evicted from the cache).

2. Fix overwrite collisions: `interval_index` is keyed by `row_begin`, so
   inserting a new entry with the same `row_begin` but different `row_end`
   would overwrite the previous index entry, orphaning the old cache entry.
   Now `set` detects this case and removes the old cache entry first.

3. Move columns cache settings from version 26.2 to 26.3 in
   `SettingsChangesHistory.cpp` to fix the 02995_new_settings_history test.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Storages/MergeTree/ColumnsCache.h Resolved
Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
Comment thread .claude/skills/continue-pr/SKILL.md Resolved
Comment thread src/Storages/MergeTree/ColumnsCache.cpp Resolved
Comment thread src/Storages/MergeTree/ColumnsCache.h Resolved
Comment thread src/Common/IMemoryReleasableCache.h Resolved
alexey-milovidov and others added 3 commits October 3, 2026 16:19
Conflicts:
- ci/jobs/scripts/docs/autogenerate/test_system_table_pages.py: removed on master, accept the deletion.
- src/Storages/MergeTree/MergeTreeData.cpp: keep includes from both sides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he limit

Address review: a value of `0` for `columns_cache_max_bytes_to_write_to_cache` and
`columns_cache_max_estimated_bytes_to_write_to_cache` means half of the current size limit of
the columns cache, which `ColumnsCache::autoResize` lowers under memory pressure. Both were
snapshotted when the read pool was created, so a long query kept the pre-shrink allowance.
Now the runtime budget is resolved on every check in `MergeTreeReaderWide::canWriteToColumnsCache`,
and the estimate budget when the staged estimate is charged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ns cache

Address review: only legacy `Ordinary` databases leave tables without a UUID.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
return static_cast<double>(getUncompressedSizeOfColumns(part, columns, settings)) / static_cast<double>(total_marks);
}

/// Mirror the cache-write eligibility predicate in `MergeTreeReaderWide::readRows`: only wide parts

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

We should reconsider this in follow-ups:

  • why don't support projections?
  • why don't support compact parts?

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Approved, finally.

alexey-milovidov and others added 3 commits October 4, 2026 00:41
# Conflicts:
#	tests/queries/0_stateless/00933_test_fix_extra_seek_on_compressed_cache.sh
Comment thread src/Storages/MergeTree/ColumnsCache.cpp Resolved
Comment thread src/Common/IMemoryReleasableCache.cpp Resolved
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-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-experimental Experimental Feature pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cache for deserialized columns

5 participants