Repository navigation
Columns cache: zero-copy reads and writes, server-owned memory - #124449
Conversation
`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]>
|
Workflow [PR], commit [40fd145] Summary: ✅
AI ReviewSummaryPR #124449, reviewed at Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline comments or changes to existing review threads are needed. |
`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]>
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]>
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
…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]>
Build profile diff (arm_release)Commit See the job log for details. |
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
d320d8e
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]>
…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]>
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]>
`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
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
hitswas barely faster than an uncached one (SearchPhrase: 0.049 s against 0.051 s), a cachedUserIDscan 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:
IMergeTreeReader::readRowsgets ashared_columnsargument for such columns, as immutableColumnPtr, sores_columnsstays uniquely owned; appending to a shared column copies it explicitly.preferred_block_size_bytesasks 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.MemoryTracker::handOverToServer, withIColumn::sizeOfObjectto count the column objects exactly), the bookkeeping of the cache is allocated and released underMemoryTrackerBlockerInThread, 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 failmax_memory_usageon 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.Results on ClickBench
hits(AMD Ryzen 9 7950X3D, one wide part,ZSTD(3)), median of 21 runs:SELECT count() FROM hits WHERE NOT ignore(SearchPhrase)SELECT count() FROM hits WHERE NOT ignore(UserID)SELECT count() FROM hits WHERE NOT ignore(EventTime)SearchPhraseReads 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
LowCardinalitydictionary 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 thanpreferred_block_size_bytes.cc @alexey-milovidov
Related: #96844
Related: #123890
Changelog category (leave one):
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 ofSearchPhraseis 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 failsmax_memory_usagewith data it no longer holds.Workflow [PR]
Sync PR [sync-upstream/pr/124449]
Version info
26.11.1.373-master(included in26.11and later)