Repository navigation
Read all statistics of a data part at once - #126621
alexey-milovidov wants to merge 29 commits into
Conversation
The statistics of a part are small (`statistics.packed` is at most a few hundred KB with the default `basic, uniq_v2`), so read the whole file in one go, parse the packed index from the buffer and deserialize the statistics of all columns. Previously, the first load of a part read the index of the archive and then one entry per required column: 1 + number of columns small random reads per part, which adds up on a cold disk. Legacy parts with separate `statistics_<col>.stats` files are loaded entirely as well. The statistics cache holds one entry per part instead of one per part and column. This removes the per-part `PackedFilesReader` and its mutex, the per-column probing of files, the per-column cache keys, the column loop in `removeStatisticsFromCache`, the incremental bookkeeping of `getEstimates` (the estimates are complete after the first load) together with its `required_columns` argument and `StatisticsPartPruner::getRequiredColumns`. `loadStatistics` still filters the result by `required_columns` (keeping the parent column for `<col>.null`), so that the selectivity estimator merges only the statistics it needs. The on-disk format is unchanged. Related: ClickHouse/ClickBench#2047 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [2e93832] Summary: ❌
AI Review
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units345 translation units recompiled, 3409 s compile time in total, 345 of them have a recent master baseline. |
Now that the statistics of all columns of a part are loaded at once, the per-column overhead of loading them matters. Profiling the first load of a part with 100 columns showed: - `StatisticsUniqV2` got its aggregate function from `AggregateFunctionFactory` for every column, and allocated a 4 KiB `Arena` for its small state, which `uniqCombined64` does not use. The aggregate function is now obtained once per data type and shared, and the state is allocated directly. `allocatedBytes` uses the size of the deserialized state instead of serializing it. - `StatisticsBasic` created a column to find the default value of its type. It is now computed once per data type. - The descriptions of the statistics cloned their ASTs on move and created them twice during deserialization. - The estimates of a part included the cardinality of every column, which is computed from the HyperLogLog counters with `long double` arithmetic. Only `system.parts_columns` uses it, so it computes the cardinality from the statistics on demand instead. - The buffer for the whole statistics file was zero-filled before reading. The weight of a `uniq_v2` statistics cache entry no longer includes an arena, so the expectation of `05394_statistics_cache_weight` is updated. Related: ClickHouse/ClickBench#2047 Co-Authored-By: Claude Opus 5.5 <[email protected]>
| throw Exception(ErrorCodes::CORRUPTED_DATA, "File {} is out of bounds of {} in part {}", filename, packed_file, name); | ||
|
|
||
| ReadBufferFromMemory file_buf(data.data() + file_offset.offset, file_offset.size); | ||
| deserialize(file_buf, filename, packed_file); |
There was a problem hiding this comment.
Every query needing any statistics now decompresses and constructs the statistics of every stored column here, including when getEstimates only needs one column for part pruning. With the default automatic statistics, this makes a sparse-column query's first load proportional to the entire table width; eviction repeats that cost when the working set exceeds statistics_cache_size.
The updated PR description already reports 20–40 ms for the 100-column/30-part case versus 0.8–2.4 ms on master with warm page cache and cold statistics, and no measured cold-disk improvement. Although those measurements are noisy, they do not establish the promised performance benefit or an acceptable cost for ordinary wide-table queries. Cache the packed bytes once and deserialize requested columns lazily, and provide controlled before/after query measurements for the target storage and sparse-column workload before making this unconditional.
There was a problem hiding this comment.
🕵 Not changing this in this PR: loading all columns of a part at once is the point of the change, not a side effect. A part's statistics file is small (a few hundred KB at most with the default basic, uniq_v2), so the cost that dominates on cold storage is the number of round trips (1 + number of columns per part before), not the bytes. Caching the packed bytes and deserializing lazily would bring back the per-column bookkeeping this PR removes (per-column state inside the cache cell, its synchronization, and the incremental getEstimates logic), and it would charge the raw bytes plus the deserialized objects to the cache.
The CPU cost of deserializing the unused columns was reduced in the second commit (about 7 µs per column), and the cache cell is now weighted with the map nodes and names, so eviction accounts for it. A follow-up commit also makes the filter by required_columns probe the requested names instead of scanning all columns, so a cache hit no longer costs time proportional to the table width.
Whether the remaining first-load CPU cost on very wide tables with a warm page cache is acceptable versus the cold-storage latency win is a judgement call for the human reviewer; I'm leaving this thread open for that.
There was a problem hiding this comment.
🕵 Update after the measurement in the latest PR comment (snelheidai, 2026-11-01): on latency-bound EBS (4 vCPU, 3000 IOPS), head 195598a is slower than master on cold runs. It is 1.66× on MIN/MAX(EventDate) answered from statistics and 1.15× on a filtered query. LoadedStatisticsMicroseconds is 52.9 ms vs 14.6 ms. Reads drop from 3 to 1 per part, but deserializing all ~105 columns costs more than the round trips saved. That contradicts the premise in my previous reply, so this concern is confirmed.
The fix the measurement points to is the one suggested here: one read per part, keep the packed bytes in the cache cell, and deserialize only the requested columns. It is not a mechanical change:
- The cache cell needs per-column lazily populated state with its own synchronization.
CacheBasefixes an entry's weight on insertion. Either the weight covers only the raw bytes, which under-counts the deserialized objects, or an entry has to be re-inserted when it grows.05394_statistics_cache_weightpins down the current weighting.getEstimatescurrently builds the estimates of all columns, so part pruning would again need per-column estimate memoization (the bookkeeping this PR removed).
Rework the PR into that design or close it in favor of #126625 / #126627? Leaving this for a human decision. CI on the current head is green and the branch is up to date with master.
There was a problem hiding this comment.
🕵 snelheidai remeasured the current head on 2026-11-08 and it confirms this concern. On cold EBS, with #126627 merged, queries that still load statistics are slower with this PR. MIN/MAX(EventDate) answered from statistics is 1.74× slower, and part pruning for AdvEngineID <> 0 is 1.27× slower. LoadedStatisticsMicroseconds is ~55 ms vs 1.6–14.7 ms on master. A lazy per-column variant could recover at most master's own cold loading cost. So the choice is still between reworking into lazy per-column deserialization of cached packed bytes and closing this PR. That decision needs a human, so I'm leaving this thread open.
`statisticsTypeToString` throws a `LOGICAL_ERROR` for a type unknown to this build, so the description must not be created before checking that the type is registered. Otherwise a part written by a newer build with a new statistics type could not be loaded, although `V4` length-prefixes every statistic exactly to allow skipping it. Add a gtest for that. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…map nodes `loadStatistics` is called for every part on every query, so look up the required columns in the cached statistics of the part instead of scanning all of its columns. The weight of a cache entry now includes the nodes of the map and the buffers of the column names, which are retained by the entry too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The caches of default values (`StatisticsBasic`) and aggregate functions (`StatisticsUniqV2`) outlive the tables. Do not cache large default values (e.g. of a wide `FixedString`), and clear the caches when they hold too many types, so schema churn does not retain memory forever. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Storages/Statistics/tests/gtest_stats.cpp
…g a description The test came from master and calls `tryCreateSingle` with a `StatisticsType`, while this PR changed it to take a `SingleStatisticsDescription`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cise the statistics cache The second query was pruned by the memoized per-part estimates without going through the statistics cache, so it did not test that the statistics of other columns are already cached. Disable statistics-based part pruning and use two `AND` predicates so that both queries request the statistics through `loadStatistics` to reorder the `PREWHERE` conditions, and assert that the second query hits the cache and loads nothing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…o-parallel` The test asserts that the statistics stay in the server-wide statistics cache between two queries. A concurrent test dropping a table without UUID (e.g. in an `Ordinary` database) clears all caches of the server, including the statistics cache, as in `05227_statistics_cache_per_part` and `05320_statistics_cache_prewarm`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126621&sha=ef468aaf9eab24c9994deabf88ca69aa32af2ad4&name_0=PR&name_1=Stress%20test%20%28arm_release%29 ( The |
|
This is the bug #122707 fixes. When an #122707 makes the Azure parser accept trailing The same failure reached master today (Stress test (arm_asan_ubsan) on 733ba530) and 3 other unrelated PRs since 2026-09-28. |
Resolve the conflicts with #126625, which loads the statistics of parts in parallel and added `tryLoadStatisticsFromCache` and `tryGetEstimatesFromMemory` on top of the per-column statistics cache. Adapt them to the cache with one entry per part of this PR: `tryGetStatisticsFromCache` probes the entry of the part, and `filterStatistics` (shared with `loadStatistics`) picks the requested columns. `getEstimates` and `tryGetEstimatesFromMemory` take no columns, as the estimates of all columns are memoized at once. Update the reference of `05407_statistics_parallel_load`: a cold part now counts one `StatisticsCacheMisses` instead of one per column. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Thanks @groeneai. The Merged master in 023de1c to resolve the conflicts with #126625 (parallel loading of statistics). |
|
🕵 Merged master. The remaining CI failures are unrelated to this PR:
@groeneai, please get #127676 merged so this oracle mismatch stops showing up. |
|
@alexey-milovidov I merged master into #127676 (6269f2d) to pick up #127687. That PR fixes the only failure on #127676's previous head: The #127676 has no review yet and I can't merge it, so it needs an approval. Could you review it? |
Resolve the conflict in `MergeTreeDataSelectExecutor::filterPartsByStatistics`: keep the shared `EstimatesPtr` of the whole part from this PR, and master's skipping of parts with pending alters and its check that the stored column type matches the current metadata. Since the shared estimates must not be modified, they are copied only when a column has to be removed. Restore `StatisticsPartPruner::getRequiredColumns`, which master now uses for the type check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
On the latency-bound EBS case from the description (4 vCPU, reads capped at 3000 IOPS and 120 MiB/s), head 195598a is slower than master on cold runs:
PR/master on the table with statistics (paired ratio, 95% CI): Q6, The PR does save reads (one per part instead of three, about the same bytes), but at 4 threads deserializing all ~105 columns costs more than the reads it saves. Master still pays for statistics on a cold start: Q42 is 1.21× [1.14, 1.28] slower than without them (Q36 +1–2%, Q41 not significant), with planning at ~14 ms instead of ~1.6 ms. Disabling only one of Setupr7g.xlarge (Graviton3, 4 vCPU, |
Conflict resolution: - `IMergeTreeDataPart::areStatisticsCached` (new on master, used to count only the parts whose statistics would be loaded) is reimplemented for the single cache entry per part: the part's statistics are cached, or the part has no statistics files at all (since all statistics of a part are read at once, a part with any statistics reads its file). - `MergeTreeDataSelectExecutor::filterPartsByStatistics`: take master's restructuring (parts with estimates in memory are decided upfront, deferred parts, exceptions propagate) and keep the shared `EstimatesPtr` of this PR, copied only when a column has to be removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…arks_per_part_to_load_statistics` Master now skips loading statistics when the primary key leaves fewer than `min_marks_per_part_to_load_statistics` (64 by default) marks to read per part. The test table has a single mark, so the statistics were not used at all. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged master in 4bac237 to resolve the conflicts with the statistics small-read skipping on master (
The statistics tests pass locally. The open thread about eager deserialization still needs a human decision: the measurement from snelheidai (2026-11-01) shows this head is slower than master on cold EBS. Either rework to lazy per-column deserialization from cached packed bytes, or close in favor of #126625 / #126627. |
|
Remeasured the current head (7cf879a) against the master it merged (7b5f2bf) on the same cold EBS setup as the earlier measurement. With #126627, neither build loads statistics for Q41 and Q42 any more, so the earlier Q42 difference is gone. Queries that load statistics on a cold start remain slower with this PR:
PR/master on the table with statistics (paired ratio, 95% CI): Q6 ( The most a lazy per-column variant could recover here is master's cold cost of loading statistics: 4.5 ms on Q7 (1.12× [1.07, 1.18] vs the table without statistics) and 77 ms on Q19 (1.02×); Q6 is answered from statistics in 12 ms instead of a 39.5 ms read. Master's Q42 is 3 ms slower on the table with statistics although nothing is loaded there: planning takes 3.4 ms instead of 1.7 ms. SetupSame protocol as before: r7g.xlarge (Graviton3, 4 vCPU, |
…ames `getColumnDefaultField` and the `collectors` cache in `StatisticsUniqV2` outlive the tables, and their size was bounded only by the number of types and (for the defaults) by the size of the default value. A type name can be large, e.g. an `Enum16` with thousands of long labels, and the aggregate function retained by `collectors` owns its argument type. Types with a name longer than 256 bytes are no longer cached, so both caches retain at most 10000 small entries. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pushed c7bb118, which addresses the latest bot review about retained memory: statistics helpers are no longer cached for types whose name is longer than 256 bytes (e.g. an Thanks @snelheidai for the remeasurement of 7cf879a (2026-11-08). It confirms that queries which load statistics on a cold start are still slower with this PR (Q6 1.74×, Q7 1.27×), and that lazy per-column loading could recover at most master's own cold loading cost. The remaining open thread asks whether to rework this PR into lazy per-column deserialization or to close it. That needs a human decision. The only red CI check was |
# Conflicts: # src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp # src/Storages/Statistics/StatisticsBasic.cpp
# Conflicts: # src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp
|
🕵 Merged |
…mator` before allocating A serialized medium set (hash table) of `uniqCombined` / `uniqCombined64` (also used by `uniq_v2` statistics) was read with only the generic `100'000'000'000` limit, so a few corrupted bytes such as `02 80 80 80 80 04` requested a multi-GiB hash table buffer before failing on truncated data. The writer never keeps more than `medium_set_size_max` elements in the medium set, so `HashTable::read` now takes a maximum size, and `CombinedCardinalityEstimator::read` passes `medium_set_size_max`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The medium-set bound in 830c6f8 (reply) also rejects valid
Master reads such states. With 830c6f8 they fail with SELECT finalizeAggregation(CAST(CAST(uniqCombinedState(18)(toString(number)) AS String)
AS AggregateFunction(uniqCombined, String))) FROM numbers(5000);Without 830c6f8 this returns 4998 (a HyperLogLog estimate); with it, the new check rejects the state (5000 > 4096). A bound of |
Conflicts: `IMergeTreeDataPart.h` keeps the PR's statistics loading API; `getPathForCacheKey` is now public on master, so the private declaration is dropped. `Statistics.h` keeps the PR's `isRegistered` and `tryCreateSingle` taking a description, with master's `[[nodiscard]]`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…adable The bound added in 830c6f8 rejected valid states: older servers kept more elements in the medium set of a default-precision state than the current writer (16384 up to 18.14, 8192 until 2019, while the current limit for `String` is 4096), so queries and merges reading such states would fail with `TOO_LARGE_ARRAY_SIZE`. The bound is now `4 * medium_set_size_max`, which accepts every earlier writer and still caps the allocation. The test now reads a precision-18 `String` state as a default-precision one (same layout as a legacy state), and checks the new bound. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged Thanks @snelheidai for the table of historical medium-set sizes: the bound is now The remaining open thread is the design question of reworking this PR into lazy per-column deserialization of cached packed bytes or closing it in favor of #126625 / #126627. It needs a human decision, so it stays open. |
# Conflicts: # src/Storages/Statistics/tests/gtest_stats.cpp
|
🕵 Merged The only red check was |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=4 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
|
🕵 Merged The only red check is |
| { | ||
| const auto & all_columns = getColumnsDescription(); | ||
| CompressedReadBuffer compressed_buf(in); | ||
| if (auto stats = ColumnStatistics::deserialize(compressed_buf, column_desc->type)) |
There was a problem hiding this comment.
[Blocker] Validate countmin dimensions before the sketch allocates
Eagerly loading every column also reaches an unchecked allocation in StatisticsCountMinSketch::deserialize. Take a valid 16-byte empty sketch, preserve its header and seed hash, set bytes 8–11 to 2^29 buckets and byte 12 to one hash, and retain the outer size of 16. This passes the accepted-size check. The pinned sketch reader constructs its counter array before checking the empty flag; its constructor zero-fills num_hashes * num_buckets counters of type UInt64, so these bytes request 4 GiB. ClickHouse checks for the expected 7 hashes and 2718 buckets only after that allocation (StatisticsCountMinSketch.cpp:133–137).
This existing decoder defect now affects queries whose requested columns do not include the damaged countmin column. Cache loading disables query/user memory limits, so a tiny malformed member can exhaust server memory before its dimensions are rejected; the outer statistics length and packed-member bounds do not prevent it.
Validate the serialized dimensions before calling Sketch::deserialize, and add an empty-sketch regression case with oversized dimensions that is rejected before allocating the counter array.
| files_to_load.emplace_back(std::move(filename), column_desc); | ||
| }; | ||
| /// The archive is small, so it is read entirely in one go instead of reading its index and then every file. | ||
| PODArray<char> data(packed_checksum->second.file_size); |
There was a problem hiding this comment.
[Blocker] Bound the whole-archive allocation before reading statistics.packed
packed_checksum->second.file_size now drives a contiguous PODArray<char> allocation of the entire archive before any validation. That size comes from part metadata, so a malformed part can set statistics.packed to multi-GiB and make a statistics cache miss request that much RAM before readStrict reaches EOF or readIndex rejects the contents. getStatistics wraps cache fills in MemoryTrackerBlockerInThread, so this allocation is outside query/user limits. The previous code streamed the archive index and then the requested member(s), so it never had this unconditional whole-file allocation on the hot query path.
Please either keep the archive streamed or reject oversized archives before constructing data, with a regression test for an inflated statistics.packed size in metadata.
false
Read all statistics of a data part at once and cache them as one entry per part.
The statistics file of a part is expected to be small: with the default auto statistics
basic, uniq_v2,statistics.packedis at most a few hundred KB per part. So the first load of a part now reads the whole file in one go (its size is known fromchecksums), parses the packed index from the buffer withPackedFilesReader::readIndex, and deserializes the statistics of all columns. Before, it read the index of the archive and then one entry per required column, so 1 + number of columns small random reads per part, sequentially, part by part. On a cold disk (the ClickBench cold run) that latency adds up. Legacy parts that store separatestatistics_<col>.statsfiles are loaded entirely too, so both layouts produce the same per-part object.The statistics cache now holds one entry per part instead of one per part and column. It is still bounded by
statistics_cache_sizeand weighted by retained memory. This allows removing a lot of code:PackedFilesReaderand its mutex;.nullspecial case (loadStatisticskeeps the statistics of the parent column for<col>.nullwhen it filters its result byrequired_columns, so the selectivity estimator still merges only the columns it needs);removeStatisticsFromCache;getEstimates(estimates_loaded_columns,estimates_complete), and itsrequired_columnsargument. (StatisticsPartPruner::getRequiredColumnsstays: master now uses it to drop the estimates of columns whose stored type differs from the current metadata, and the shared estimates are copied only in that case.)Prewarming (
prewarm_statistics_cache) is now the same operation as a query load. The on-disk format is unchanged.Effect: one read per part instead of 1 + number of columns. Test changes:
05394_statistics_cache_weightnow expects 10 cache cells for 10 parts (one per part) instead of 20 (one per part and column). The new test05407_statistics_load_all_columns_at_oncechecks that once a query has loaded the statistics of one column, a query that needs other columns reads nothing from disk.The second commit makes loading the statistics of all columns cheaper, based on profiling the first load of a part with 100 columns:
StatisticsUniqV2gets itsuniqCombined64aggregate function once per data type instead of fromAggregateFunctionFactoryfor every column, and no longer allocates a 4 KiBArenafor its small state, whichuniqCombined64does not use;StatisticsBasiccomputes the default value of a type once per type instead of creating a column for every statistics object;SingleStatisticsDescriptionno longer clones its AST on move, and the deserializer creates the description once;long doublearithmetic for every column. Onlysystem.parts_columnsuses it, so it is now computed from the statistics there, on demand;Measurements, taken locally on a heavily loaded shared machine (NVMe, other builds and benchmarks running), so they are noisy. The table has 100
UInt64columns and 30 parts, andstatistics.packedis about 300 KB per part.LoadedStatisticsMicrosecondsis summed over the 30 parts:CompressedReadBuffersetup (about 40%), creating the statistics objects (about 20%), deserializing the HyperLogLog counters, and copying the 300 KB file from the page cache.So for wide tables, this approach does not win locally, either warm or cold. A win would require a latency-bound disk such as EBS, where one 300 KB read is cheaper than three small random reads. The target of well under 0.3 ms per part is not met. Getting there would need lazy deserialization: read the file once, but deserialize a column only when it is first needed.
The expectation of
05394_statistics_cache_weightis updated, because auniq_v2entry no longer retains an arena.Status: draft. The PR is kept as a draft because it does not pay off:
Options for this PR:
uniqCombined64obtained once per data type, noArenaper column, no cardinality in the estimates.Tests locally: 136 of 143 statistics-related tests pass; the other 7 fail only because of the local server configuration (missing
test.hits,system.predicate_statistics_log,process_query_plan_packet, a stateless worker cluster, and atext_logmessage).Related: ClickHouse/ClickBench#2047
Related: #126625
Related: #126627
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The statistics of all columns of a
MergeTreedata part are read from disk at once, with one read per part instead of one per column, and are cached as one entry per part.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/126621]