Skip to content

Columns cache: zero-copy reads and writes, server-owned memory - #124449

Merged
alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
Algunenano:columns-cache-zero-copy
Oct 21, 2026
Merged

alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
Algunenano:columns-cache-zero-copy

Conversation

@Algunenano

@Algunenano Algunenano commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

The columns cache (#96844) copied every column it served and every column it stored. On a machine whose memory bandwidth is the limit, that copy cost as much as decompressing the column, so with 32 threads a cached scan of hits was barely faster than an uncached one (SearchPhrase: 0.049 s against 0.051 s), a cached UserID scan was slower (0.020 s against 0.014 s), and the run that filled the cache was 2.5x slower than an uncached one.

Changes:

  • A block whose rows are exactly one cache entry is served as the cached column itself. IMergeTreeReader::readRows gets a shared_columns argument for such columns, as immutable ColumnPtr, so res_columns stays uniquely owned; appending to a shared column copies it explicitly.
  • Blocks and read tasks are aligned with the stripes of the cache: the read pool cuts tasks at stripe boundaries, and a block ends at the stripe boundary closest to its size. A stripe that is served from the cache, or that the cache admits for writing, is read whole even if preferred_block_size_bytes asks for less, since the cache holds those rows anyway. Previously nearly every block straddled two entries (3/4 of the ranges at 16 threads, 7/8 at 32), so even fully cached blocks were assembled from copies.
  • A block read from disk that is exactly one stripe is stored as the entry, shared with the read, instead of being copied into it.
  • The memory of the cache is now the server's: when an entry is admitted, its memory is taken off the query and the user that read it (new MemoryTracker::handOverToServer, with IColumn::sizeOfObject to count the column objects exactly), the bookkeeping of the cache is allocated and released under MemoryTrackerBlockerInThread, and a column that a query still holds when its entry is evicted is parked and released as the server's once the query drops it. Before, a query that filled the cache was charged for all of it until it ended (a 1.45 GiB peak for a scan of one column, now 108 MiB), could fail max_memory_usage on data it no longer held, and an evicted entry was credited to whichever query released it. The drift settled at the end of a filling query goes from 1.5 GB to 0.
  • Stripe alignment applies only to parts the cache can hold (not to projection parts or tables without a UUID), and the admission of a stripe is decided once, before the read is sized, so a stripe the cache rejects keeps the requested block size.

Results on ClickBench hits (AMD Ryzen 9 7950X3D, one wide part, ZSTD(3)), median of 21 runs:

Query, cache on 32 threads, before / after 8 cores pinned, 16 threads, before / after
SELECT count() FROM hits WHERE NOT ignore(SearchPhrase) 0.050 s / 0.005 s (10x) 0.053 s / 0.003 s (17x)
SELECT count() FROM hits WHERE NOT ignore(UserID) 0.020 s / 0.003 s (6.7x) 0.021 s / 0.003 s (7x)
SELECT count() FROM hits WHERE NOT ignore(EventTime) 0.010 s / 0.003 s (3.3x) 0.011 s / 0.003 s (3.7x)
First run, filling the cache, SearchPhrase 0.170 s / 0.094 s (1.8x) 0.246 s / 0.133 s (1.8x)
17 narrow columns (cache off: 0.50 s) 0.214 s / 0.006 s (36x)

Reads with the cache off are unchanged. Results are identical with the cache off and on, checked by hashing the columns read.

Known limits, documented in the code and accepted: a LowCardinality dictionary shared by several entries is handed over once per entry, which undercounts the query (not its user) by up to that many dictionaries while it runs; a subcolumn a query keeps past the eviction of its entry is credited to that query; and a stripe read whole can still be rejected by the cache (too large for a shard, budget used up), leaving one block larger than preferred_block_size_bytes.

cc @alexey-milovidov

Related: #96844
Related: #123890

Changelog category (leave one):

  • Experimental Feature

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

The columns cache (use_columns_cache) serves and stores whole cached columns without copying them, and aligns read blocks with its entries: on ClickBench, a cached scan of SearchPhrase is 10x faster with 32 threads and the run that fills the cache 1.8x faster. The memory of the cache now belongs to the server: a query that fills the cache is no longer charged for it, so it no longer fails max_memory_usage with data it no longer holds.


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

Version info

  • Merged into: 26.11.1.373-master (included in 26.11 and later)

Algunenano and others added 8 commits October 7, 2026 14:38
`ColumnsCache::numberOfShards` uses `std::clamp`, which compiled only because every
includer happened to pull `<algorithm>` in first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When the rows a block needs from a column are exactly one entry of the columns cache, the
result column is the cached column itself instead of a copy of it. Such a column is returned
through a new `shared_columns` argument of `IMergeTreeReader::readRows`, as an immutable
`ColumnPtr`, so `res_columns` stays uniquely owned: rows appended to a column that was served
shared go to an explicit copy of it, and the cache entry is never modified.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The read pool cut ranges at arbitrary marks and blocks ended wherever `max_block_size`
rounded up to whole granules fell, so nearly every block served from the columns cache
straddled two entries and was assembled from copies of both. With the cache on, the per-thread
and per-task cuts now end at stripe boundaries, and a block ends at the stripe boundary closest
to its size. A stripe that is served from the cache, or written to it, is read whole even when
`preferred_block_size_bytes` asks for less, since the cache holds those rows anyway. Blocks
served from the cache are then whole entries, which are not copied.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The run that filled the columns cache copied every column it read into the entry. A block that
is a whole stripe, read from the part into empty result columns, is now stored as it is: the
result columns become the entries and are returned to the read through `shared_columns`, so
the cache and the read share them and neither modifies them. Other blocks are still
accumulated into a copy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The entries of the columns cache were charged to the query that read them until it ended, so a
query that filled the cache could exceed `max_memory_usage` with data it no longer held, and an
entry released by another query was credited to that query. When the cache admits an entry, its
memory is now taken off the query and its user and stays with the server, the bookkeeping of the
cache is allocated and released as the server's, and a column that a query still holds when its
entry goes away is kept until the query drops it and then released as the server's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The read pool cut the tasks of every wide part at stripe boundaries while the columns cache was on,
including the parts the reader never caches: those of tables without a UUID and projection parts.
For them the aligned cuts only changed the boundaries of the tasks and of their blocks. The
condition now lives in one place, `canUseColumnsCacheForPart`, used by the reader and the pool.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A block was extended to a whole stripe whenever the write budget allowed it, and the admission
check came only when the stripe was written. While the cache churns and admits few stripes, most
of those blocks were larger than `preferred_block_size_bytes` asks for, for nothing. The reader
now decides the admission of a stripe once, when it sizes the block, and uses the same decision
when it writes the stripe; a stripe the cache does not admit is read in blocks of the requested size.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Three cases the accounting and the stripe-sized reads of the columns cache do not cover, why each is
accepted, and what it costs: a dictionary shared by several entries is handed over once per entry, a
subcolumn a query keeps past the eviction of its entry is credited to that query, and a stripe read
whole for the cache can still be rejected, leaving a block larger than `preferred_block_size_bytes`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Algunenano Algunenano added the pr-performance Pull request with some performance improvements label Oct 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [40fd145]

Summary: ✅


AI Review

Summary

PR #124449, reviewed at 40fd145d0f2f8d3a390e5a53884790ca73cceac1, shares whole columns-cache entries with reads, aligns read boundaries with cache stripes, and transfers admitted memory to the server. The current code addresses the three prior findings. No new actionable findings remain; the supplied benchmarks and focused stateless regressions support the main claims.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or configured build was available, so tests and benchmarks were not independently rerun. Runtime validation relies on the reported measurements and CI results; a build and execution of the added stateless tests would close this gap.
Final Verdict

Status: ✅ Approve. No new inline comments or changes to existing review threads are needed.

@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 7, 2026
Algunenano and others added 3 commits October 7, 2026 18:44
`sizeOfObject` is declared in the mock `IColumn` of the `COW` examples, which `COWHelper`
now overrides; a dead initial store in `MergeTreeReadPool::fillPerThreadInfo` is gone;
and the shared and the owned columns are moved into the result in separate branches,
since a conditional between `MutablePtr` and `ColumnPtr` copies instead of moving.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The alignment of blocks with the stripes was done once per call of `startReadingChain`, so when
the block went on into the next mark range of the task, that range was not aligned, and its
blocks could straddle two entries of the columns cache and be copied instead of shared.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The fill query reads whole stripes, about 8 MB each with the rows the test had, and holds one
until the cache takes it over; on object storage that, with the read buffers, reached the 20 MB
limit the test sets. The rows are narrower now, so a stripe is about 3 MB and the query peaks at
about 10 MB on S3 and 5 MB on a local disk, still caching about 40 MB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/MergeTree/ColumnsCache.cpp Resolved
Algunenano and others added 2 commits October 8, 2026 18:55
A block was extended to a whole stripe of the columns cache whenever the stripe was cached or
going to be written, even when the read had asked for far fewer rows: with a `LIMIT`, which lowers
`max_block_size`, or an explicit small `max_block_size`. The read then produced up to 2048 rows
where a `LIMIT 3` read 256, and with `max_block_size = 1` a block of a whole stripe made
`sleepEachRow` exceed its limit. The extension now stays within twice `max_block_size`, as the
rest of the alignment does; only `preferred_block_size_bytes` can still be exceeded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`setMany` inserted the entries and then checked with `contains` which of them the cache kept, but
a concurrent write of the same stripe could replace an entry in between: the key was present, the
entry was not, and its memory was handed over to the server and counted against the write budget
anyway. The insertion and the check now happen under one lock of the shard, in
`CacheBase::setAndContains`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: c67781ad-a49c-41be-addb-e4e0de0cf292
  • MIRAI run: d5846208-39d4-4292-a2d1-990a7a1ee863
  • PR check IDs:
    • clickbench_576584_1791566117
    • clickbench_576596_1791566117
    • clickbench_576602_1791566117
    • tpch_adapted_1_official_576608_1791566117
    • tpch_adapted_1_official_576640_1791566117
    • tpch_adapted_1_official_576654_1791566118

…hard

A concurrent write of the same stripe could replace the entry between the
residency check and the hand-over, so the query gave up the charge for a column
only it still held. Flip `owned_by_server` in the same critical section as the
insertion and the residency check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 40fd145d0f2f8d3a390e5a53884790ca73cceac1 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

Algunenano and others added 4 commits October 14, 2026 20:05
The first reader of a chain decided alone how its blocks align with the stripes of
the columns cache. A `MergeTreeReaderIndex` in front (a skip index evaluated on data
read, lazy materialization) turned the alignment off, so cached rereads were served
by copying again. A PREWHERE reader whose columns were cached read a whole stripe
even when the main reader read the rest of the row from disk, making a block of up
to twice `max_block_size` rows regardless of `preferred_block_size_bytes`.

The chain now passes the readers that read columns to `startReadingChain`: they agree
on the stripes, and a stripe is read whole only if every one of them can.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Storages/MergeTree/MergeTreeReadersChain.cpp
@alexey-milovidov alexey-milovidov self-assigned this Oct 20, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 21, 2026
Merged via the queue into ClickHouse:master with commit d320d8e Oct 21, 2026
351 of 353 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 21, 2026
alexey-milovidov added a commit that referenced this pull request Oct 21, 2026
The test checked the change that kept the columns cache copies of a read off the
memory trackers of the query. Since #124449
the memory of an entry is handed over from the query to the server when the
cache admits it, and the read is aligned with the stripes of the cache, so a
query is charged for up to a stripe until then, by design. That change is
superseded and was removed in the merge of `master`; the test went with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Oct 22, 2026
…dinated_read

The test compares `RuntimeDataflowStatisticsInputBytes` of two runs exactly.
Since ClickHouse#124449 a read with writes to the columns cache enabled widens a block
to the whole cache stripe only when the cache admits the stripe, and
admission is random once the cache churns. The two runs then read the same
occurrence in a different number of blocks, and the estimate has per-block
terms (the default slot of a Sparse column, per-block truncation of the
compressed estimate), so it differed by a few bytes:

    input bytes 3030317 vs 3030311, SelectedBytes 6739030 vs 6739014
    (8 vs 7 blocks of the 300000-row read, Sparse columns)

Failing job (master f0ea53c, Stateless tests (amd_asan_ubsan, distributed
plan, parallel)):
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=f0ea53c7542388926542d1f871c3659e8de4f2f7&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29

Pin the cache off for the session, the same as the other AutoPR estimation
tests (b045107). A body SET rather than a random-settings limits line,
because fixed --settings profiles bypass the limits line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bdeitte pushed a commit to bdeitte/ClickHouse that referenced this pull request Oct 23, 2026
The columns cache held a whole column of a `Parquet` row group per entry. A row
group is read in row subgroups of the block size, so the reader copied every
subgroup it decoded into the column being written to the cache, and copied every
subgroup it served from the cache out of the cached column. A query that wrote to
the cache was slower than one without it and took several times the memory, which
mattered most for a `clickhouse-local` that reads a file once and exits.

Now an entry holds a chunk of 65536 rows of a column of a row group, and a row group
that uses the cache is read in its chunks, whatever the block size settings, the
same as `MergeTree` parts are read in the stripes of the cache since
ClickHouse#124449:

- A row subgroup that decodes a whole chunk writes the decoded column itself to the
  cache, shared with the result of the read. It is charged to the query, and its
  memory is handed over to the server when the cache admits it.
- A row subgroup that is a whole chunk served from the cache gets the column of the
  cache itself. A filtered subgroup copies only the rows that pass, as before.
- A chunk is written on its own, so a row group that is read only in part (by the
  column index) still writes its whole chunks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
rorylshanks added a commit to rorylshanks/ClickHouse that referenced this pull request Nov 4, 2026
`IMergeTreeReader::readRows` takes a `shared_columns` argument since
ClickHouse#124449: a column served from
the columns cache comes back there instead of in `res_columns`. The per-mark
reads of the `jsonPathValues` dynamic fallback in `MergeTreeReaderTextIndex`
still used the old signature, so the build failed after merging `master`.
Pass the shared columns and take a column from them when the reader did not
fill the mutable one, as the whole-range fallback read above already does.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114613&sha=e6b2c2eaa9444798c6f6f290531d55938446fd86&name_0=PR&name_1=Build%20(arm_tidy%2C%203%2F4)
PR: ClickHouse#114613

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E5v7QTSR65LdYnQEv9HJVu
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-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.

3 participants