Skip to content

Read all statistics of a data part at once - #126621

Open
alexey-milovidov wants to merge 29 commits into
masterfrom
stats-read-whole-file
Open

alexey-milovidov wants to merge 29 commits into
masterfrom
stats-read-whole-file

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

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.packed is 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 from checksums), parses the packed index from the buffer with PackedFilesReader::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 separate statistics_<col>.stats files 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_size and weighted by retained memory. This allows removing a lot of code:

  • the per-part PackedFilesReader and its mutex;
  • the per-column probing of statistics files, including the .null special case (loadStatistics keeps the statistics of the parent column for <col>.null when it filters its result by required_columns, so the selectivity estimator still merges only the columns it needs);
  • the per-column cache keys and the column loop in removeStatisticsFromCache;
  • the incremental bookkeeping in getEstimates (estimates_loaded_columns, estimates_complete), and its required_columns argument. (StatisticsPartPruner::getRequiredColumns stays: 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_weight now expects 10 cache cells for 10 parts (one per part) instead of 20 (one per part and column). The new test 05407_statistics_load_all_columns_at_once checks 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:

  • StatisticsUniqV2 gets its uniqCombined64 aggregate function once per data type instead of from AggregateFunctionFactory for every column, and no longer allocates a 4 KiB Arena for its small state, which uniqCombined64 does not use;
  • StatisticsBasic computes the default value of a type once per type instead of creating a column for every statistics object;
  • SingleStatisticsDescription no longer clones its AST on move, and the deserializer creates the description once;
  • the estimates of a part no longer include the cardinality, which is computed from the HyperLogLog counters with long double arithmetic for every column. Only system.parts_columns uses it, so it is now computed from the statistics there, on demand;
  • the buffer for the statistics file is not zero-filled.

Measurements, taken locally on a heavily loaded shared machine (NVMe, other builds and benchmarks running), so they are noisy. The table has 100 UInt64 columns and 30 parts, and statistics.packed is about 300 KB per part. LoadedStatisticsMicroseconds is summed over the 30 parts:

  • warm page cache, cold statistics cache and estimates: master spends 0.8-2.4 ms (it loads only the 1-2 needed columns). The first commit spent 38-70 ms. With the second commit it is 20-40 ms, which is 0.7-1.1 ms per part, about 7 µs per column. What is left is mostly inherent per-column work: LZ4 decompression and checksum of each column's block plus CompressedReadBuffer setup (about 40%), creating the statistics objects (about 20%), deserializing the HyperLogLog counters, and copying the 300 KB file from the page cache.
  • cold (server restart, OS caches dropped): master reads 1.1 MB in 90 small reads and spent 0.03-0.32 s; this PR reads 9.7 MB in 30 reads and spent 0.17-1.4 s on this contended disk.

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_weight is updated, because a uniq_v2 entry no longer retains an arena.

Status: draft. The PR is kept as a draft because it does not pay off:

  • the CPU cost of deserializing every column (about 7 µs per column, mostly decompressing and checksumming each column's block) is inherent to eager loading, so the target of well under 0.3 ms per part is not reachable this way;
  • the file is not that small: with 100 high-cardinality columns it is about 300 KB per part, while a query needs about 30 KB. On EBS (about 125-250 MB/s) one 300 KB read costs about as much as the three small reads it replaces;
  • Load statistics of data parts in parallel #126625 already hides the latency of the small reads by loading the statistics of parts in parallel, and Don't load statistics when the primary key leaves a small read #126627 skips loading statistics when the primary key leaves a small read. Together they cover the ClickBench cold-run regression, so the saving of one read per part matters less.

Options for this PR:

  1. Close it, relying on the two PRs above.
  2. Lazy deserialization: keep one read per part and cache the raw bytes, but deserialize a column only when a query first needs it. This keeps the I/O saving, but brings back a per-column map with a mutex and less exact cache weights, so the code no longer gets simpler.
  3. Keep only the changes that don't change what is loaded, as a refactoring: uniqCombined64 obtained once per data type, no Arena per 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 a text_log message).

Related: ClickHouse/ClickBench#2047
Related: #126625
Related: #126627

Changelog category (leave one):

  • Performance Improvement

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

The statistics of all columns of a MergeTree data 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]

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

clickhouse-gh Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2e93832]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, targeted) FAIL
test_prometheus_protocols/test_compliance.py::test_promql_extended_support FAIL cidb
test_version_update_after_mutation/test.py::test_mutate_and_upgrade FAIL cidb
test_version_update_after_mutation/test.py::test_upgrade_while_mutation FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

⚠️ Review sessions stopped as a cybersecurity risk

The model provider stopped these review sessions as a possible cybersecurity risk:

  • attempt 1: gpt-6.1-sol

This summary comes from a session with gpt-5.4. A session is typically stopped when it reaches a memory-safety finding, and the finding is lost with it, so this review can miss a real defect. Please review the change in detail, and run the review internally with a model that has cyber access.

Summary

This PR replaces per-column statistics cache entries with a single per-part entry and eagerly reads/deserializes every column's statistics on the first miss. The refactoring simplifies the cache path and fixes some older decoder hazards, but the current design is still slower on the target cold-start EBS workload discussed on the PR and it widens malformed-input memory risks, so it is not ready to merge.

PR Metadata
  • Changelog category is not semantically correct in the current state. The PR is marked Performance Improvement, but the discussion measurements on 2026-11-01 and 2026-11-08 show regressions on the workload it targets. Exact replacement if this branch stays exploratory: Not for changelog.
  • Changelog entry is user-readable but misleading for the current branch state because it describes the implementation change as an improvement. Exact replacement with the category above: remove the entry.
Findings

❌ Blockers

  • [src/Storages/MergeTree/IMergeTreeDataPart.cpp:1429] statistics.packed is now allocated as one contiguous buffer from checksums.files["statistics.packed"].file_size before any archive validation. A malformed part can inflate that metadata to GiBs and make a cache miss request that much RAM before readStrict reaches EOF or readIndex rejects the archive. getStatistics disables query/user memory accounting around cache fills, so this becomes an untracked server-wide allocation on the hot query path. Suggested fix: keep the archive streamed, or reject oversized archives before constructing data with a hard bound and a regression test for an inflated statistics.packed size.
  • [src/Storages/Statistics/StatisticsCountMinSketch.cpp:133] Eager whole-part loading now reaches the countmin deserializer even for queries that do not need the affected column. Sketch::deserialize allocates the counter array before ClickHouse checks num_hashes / num_buckets, so a tiny crafted empty sketch can request multi-GiB memory first. Suggested fix: parse and validate the serialized dimensions before calling Sketch::deserialize, and add a regression for an oversized empty sketch.

⚠️ Majors

  • [src/Storages/MergeTree/IMergeTreeDataPart.cpp:1439] The eager-deserialization design still violates the PR's performance contract. The measurements posted on 2026-11-01 and 2026-11-08 show the target cold EBS workload is slower with this branch (MIN/MAX(EventDate) 1.66–1.74x slower, pruning query 1.15–1.27x slower) because deserializing every stored column costs more than the small reads it saves. Suggested fix: rework this into one read per part plus lazy per-column deserialization of cached packed bytes, or close/re-scope the PR in favor of https://github.com/ClickHouse/ClickHouse/pull/126625 and https://github.com/ClickHouse/ClickHouse/pull/126627.
Final Verdict

Status: ❌ Block

  • Bound or eliminate the unconditional whole-statistics.packed allocation on cache miss.
  • Validate countmin dimensions before Sketch::deserialize allocates, with a regression test.
  • Do not merge the eager all-column design as a Performance Improvement while the linked measurements still show regressions on the target workload; either rework it to lazy per-column deserialization or close/re-scope it.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 802e8a27d with master 64893f356 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.87 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.9 s 16.7 s +9.8 s (+141%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 4.1 s 8.7 s +5.2 s (+147%)
Compile time of recompiled translation units

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

Job report

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]>
Comment thread src/Storages/Statistics/Statistics.cpp Resolved
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);

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.

⚠️ Avoid eagerly deserializing unrelated columns on a cache miss

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.

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.

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

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.

🕵 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.
  • CacheBase fixes 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_weight pins down the current weighting.
  • getEstimates currently 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.

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.

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

@alexey-milovidov
alexey-milovidov marked this pull request as draft October 19, 2026 01:56
alexey-milovidov and others added 5 commits October 21, 2026 08:50
`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]>
alexey-milovidov and others added 2 commits October 25, 2026 21:41
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 (Cannot start clickhouse-server: fuzzed AzureBlobStorage tables with partition_strategy = 'none' fail to attach with UNKNOWN_IDENTIFIER) and provide a fix in a separate PR. If the fix is already in progress, link it here. It looks like #122707 covers it.

The Upgrade check failure (use_query_condition_cache_for_time_conditions not in the settings changes history) is unrelated to this PR and should be cleared by the master merge in 5719d76, because master now has that setting's default back at false.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the bug #122707 fixes.

When an AzureBlobStorage table with PARTITION BY resolves to no partition strategy, the server appends partition_strategy = 'none' to the stored engine arguments (since #115277). The Azure argument parser evaluates every engine argument as a constant expression and only knows partition_strategy as a positional argument, so loading the table fails with UNKNOWN_IDENTIFIER. In this job, the restart dies on fuzzed tables like test_7.t_arrayjoin_bf_domain_lc__fuzz_3, stored as AzureBlobStorage(<connection string>, 'clickhouse-tests', 'fuzz_azure_engine_768.arrow', 'Arrow', partition_strategy = 'none').

#122707 makes the Azure parser accept trailing partition_strategy / partition_columns_in_data_file key-value arguments and keep them in the stored definition. Its test does CREATE, DETACH and ATTACH on a table whose stored definition gets partition_strategy = 'none'. I also checked that metadata written by an unfixed server loads at server startup with the fix. CI on its head is green, it merges cleanly with current master, and it has no review yet.

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

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. The AzureBlobStorage / partition_strategy = 'none' stress failure is unrelated to this PR and is tracked by #122707 (still open).

Merged master in 023de1c to resolve the conflicts with #126625 (parallel loading of statistics). tryLoadStatisticsFromCache and tryGetEstimatesFromMemory now probe the single cache entry of a part. The reference of the new 05407_statistics_parallel_load test now expects one StatisticsCacheMisses per cold part instead of one per column. That test, 05407_statistics_load_all_columns_at_once, 05227_statistics_cache_per_part, 05394_statistics_cache_weight and the statistics gtests pass locally.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master. The remaining CI failures are unrelated to this PR:

@groeneai, please get #127676 merged so this oracle mismatch stops showing up.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov I merged master into #127676 (6269f2d) to pick up #127687. That PR fixes the only failure on #127676's previous head: Upgrade check (amd_release), a settings-history mismatch for use_query_condition_cache_for_time_conditions. The PR diff is unchanged, and CI is running again.

The KeeperMap mismatch in this PR's report is covered. On #127676's CI build the query returns the same count as the full scan; master does not.

#127676 has no review yet and I can't merge it, so it needs an approval. Could you review it?

alexey-milovidov and others added 2 commits October 30, 2026 10:33
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]>
@snelheidai

Copy link
Copy Markdown

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:

Cold run, median of 6 Q6 master Q6 PR Q42 master Q42 PR
Latency, table without statistics 37.5 ms 39 ms 54 ms 57 ms
Latency, table with statistics 12 ms 19 ms 65.5 ms 75.5 ms
Physical reads, with statistics 60 20 300 260
LoadedStatisticsMicroseconds (sum over parts) 14.6 ms 52.9 ms 21.2 ms 54.5 ms
QueryPlanOptimizeMicroseconds 9.4 ms 16.5 ms 13.6 ms 19.2 ms

PR/master on the table with statistics (paired ratio, 95% CI): Q6, MIN/MAX(EventDate) answered from statistics, 1.66 [1.59, 1.73]; Q42, CounterID = 62 over two days by minute, 1.15 [1.09, 1.21]; Q36 and Q41 not significant; warm runs unchanged. Without statistics the two builds are within 5%.

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 use_statistics and use_statistics_for_part_pruning does not help, since either loads the same statistics. With max_threads = 16 Q42 planning still takes ~9.5 ms, so #126625 only partly hides the per-part chain of small reads (packed index, then column slices). This suggests keeping one read per part but deserializing only the required columns from that buffer. Not measured: that variant, more cores, larger statistics files and #126627.

Setup

r7g.xlarge (Graviton3, 4 vCPU, max_threads = 4) on EBS; the server runs in a cgroup with io.max riops=3000 rbps=125829120. ClickBench hits as 20 Wide parts of 5M rows (105 columns), and a hard-linked copy with the default basic, uniq_v2 statistics materialized (statistics.packed ≈ 104 KB per part). For each query and build: stop the server, sync, drop caches, start, run three times (cold = first run); 6 rounds in rotated order; queries numbered from 0. Master CI build 24037cf (31 Oct) vs this PR's CI build of 195598a, both stripped and started from tmpfs, no system logs, ProfileEvents from the client, physical reads from the cgroup's io.stat. Results match across builds, apart from the order of tied rows in Q41.

alexey-milovidov and others added 2 commits November 8, 2026 08:31
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master in 4bac237 to resolve the conflicts with the statistics small-read skipping on master (min_marks_per_part_to_load_statistics):

  • IMergeTreeDataPart::areStatisticsCached is reimplemented for the single cache entry per part: it is true when the part's entry is cached or the part has no statistics at all.
  • filterPartsByStatistics takes master's restructuring (parts with estimates in memory decided upfront, deferred parts, exceptions propagate) and keeps the shared EstimatesPtr.
  • 7cf879a sets min_marks_per_part_to_load_statistics = 0 in 05407_statistics_load_all_columns_at_once, whose single-mark table no longer loaded statistics.

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.

@snelheidai

Copy link
Copy Markdown

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:

Cold run, median of 8 Q6 master Q6 PR Q7 master Q7 PR Q42 master Q42 PR
Latency, table without statistics 39.5 ms 40 ms 39 ms 41 ms 53 ms 56 ms
Latency, table with statistics 12 ms 21 ms 43.5 ms 56 ms 56 ms 59 ms
Physical reads, with statistics 60 20 120 100 240 240
LoadedStatisticsMicroseconds (sum over parts) 14.7 ms 55.9 ms 1.6 ms 54.7 ms 0 0

PR/master on the table with statistics (paired ratio, 95% CI): Q6 (MIN/MAX(EventDate), answered from statistics) 1.74 [1.67, 1.80]; Q7 (AdvEngineID <> 0 with GROUP BY, which loads statistics for part pruning) 1.27 [1.24, 1.31]; Q19 (a 3.3 s scan that also loads them) 1.00 [1.00, 1.01]. Q42's 1.05 [1.03, 1.08] matches the difference between the two builds on the table without statistics (1.07 [1.03, 1.12]). Warm runs are unchanged.

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.

Setup

Same protocol as before: r7g.xlarge (Graviton3, 4 vCPU, max_threads = 4) on EBS; the server runs in a cgroup with io.max riops=3000 rbps=125829120. For each query and build: stop the server, sync, drop caches, start, run three times (cold = run 1); 8 rounds in rotated order; queries numbered from 0. The fixture was rebuilt with master 7b5f2bf: ClickBench hits as 20 Wide parts of 5M rows (105 columns), and a hard-linked copy with the default basic, uniq_v2 statistics materialized (statistics.packed ≈ 106 KB per part). Master CI build 7b5f2bf vs this PR's CI build of 7cf879a, both stripped and started from tmpfs, no system logs, ProfileEvents from the client, physical reads from the cgroup's io.stat. Results match across builds, apart from the order of tied rows in Q41. Not measured: more cores and larger statistics files.

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

Copy link
Copy Markdown
Member Author

🕵 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 Enum16 with many long labels).

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 Finish Workflow, blocked by the unresolved-review-threads gate, which also skipped the full CI suite. No test failed.

alexey-milovidov and others added 2 commits November 10, 2026 22:01
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp
#	src/Storages/Statistics/StatisticsBasic.cpp
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp
@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). This update was made automatically.

alexey-milovidov and others added 2 commits November 14, 2026 20:17
…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]>
@snelheidai

Copy link
Copy Markdown

The medium-set bound in 830c6f8 (reply) also rejects valid uniqCombined states written by older servers. They kept more elements in the medium set of a default-precision state than the current writer does:

Server version String arguments Other types
up to 18.14 16384 16384
18.16 until #7222 (October 2019) 8192 8192
since #7222, and the new check 4096 8192

Master reads such states. With 830c6f8 they fail with TOO_LARGE_ARRAY_SIZE, so queries and merges that read parts still holding them (for example, old partitions of an AggregatingMergeTree rollup) would fail. A precision-18 state has the same medium-set layout as a default-precision String state written before #7222:

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 4 * medium_set_size_max accepts every earlier writer, including other precisions (String states written between 18.16 and #7222 hold up to 2^(K-4) elements; the limit is now 2^(K-5)). It still caps the allocation at 2 MiB (precision 20).

@alexey-milovidov
alexey-milovidov marked this pull request as ready for review November 16, 2026 16:41
alexey-milovidov and others added 2 commits November 19, 2026 12:28
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (resolved conflicts in IMergeTreeDataPart.h and Statistics.h) and pushed 0fea689.

Thanks @snelheidai for the table of historical medium-set sizes: the bound is now 4 * medium_set_size_max as you suggested, and the test reads your precision-18 String example as a default-precision state.

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.

@clickhouse-gh clickhouse-gh Bot added comp-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026
# Conflicts:
#	src/Storages/Statistics/tests/gtest_stats.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed cb8e120. The only conflict was in gtest_stats.cpp, where both sides added tests after DeserializeV3SkipsRevertedNullCount; both are kept. Verified locally on the merged tree: the Statistics unit tests pass (33 of 33), and so do 05227_statistics_cache_per_part, 05394_statistics_cache_weight, the three 05407_statistics_* tests and 05768_uniq_combined_medium_set_size_limit.

The only red check was Finish Workflow, blocked by the unresolved-review-threads gate (which also skips the full CI suite); no test failed. The one open thread is unchanged: rework into lazy per-column deserialization of cached packed bytes, or close in favor of #126625 / #126627. That is a human decision.

@stresshouse

stresshouse Bot commented Nov 22, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

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

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
  • StressHouse run: 51b51797-9c82-4894-ac6c-4cd35baacf85
  • MIRAI run: d9f95f73-4ca2-43c2-a2ac-1b95417d9602
  • PR check IDs:
    • clickbench_801411_1795356702
    • clickbench_801426_1795356702
    • tpch_adapted_1_official_801434_1795356702
    • tpch_adapted_1_official_801454_1795356702

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed 2e93832. The merge was clean (no conflicts) and the PR diff is unchanged. Verified locally on the merged tree: the server builds, and 05227_statistics_cache_per_part, 05394_statistics_cache_weight, 05407_statistics_load_all_columns_at_once, 05407_statistics_parallel_load and 05768_uniq_combined_medium_set_size_limit pass. Of the 167 stateless tests with statistics in the name, 125 pass; the other 42 fail only because of the minimal local server configuration (no test clusters, no ZooKeeper, no writable access storage, a different user_files path), with no difference in results. The unit tests were not rebuilt in this pass.

The only red check is Finish Workflow, blocked by the unresolved-review-threads gate, which also skips the full CI suite; no test failed. The one open thread is unchanged: rework this PR into lazy per-column deserialization of cached packed bytes, or close it in favor of #126625 and #126627. That is a human decision.

{
const auto & all_columns = getColumnsDescription();
CompressedReadBuffer compressed_buf(in);
if (auto stats = ColumnStatistics::deserialize(compressed_buf, column_desc->type))

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.

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

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.

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

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-statistics Column statistics: statistics kept per part on a column (tdigest, uniq, count-min sketch, minmax)... pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants