Repository navigation
Sparsity-aware part/granule pruning and trivial-count optimization - #105890
Merged
Algunenano merged 147 commits intoJul 8, 2026
Merged
Conversation
Adds optimize_trivial_count_with_sparsity_filter (default true) which serves SELECT count() FROM t WHERE col <op> const from per-column num_rows / num_defaults in serialization.json instead of scanning data, when <op> const exactly partitions the column into defaults and non-defaults. Recognised predicates (operands may be in either order for symmetric operators): - any T: col = default(col), col != default(col) - Nullable(T): IS NULL, IS NOT NULL - String: empty(col), notEmpty(col) - Bool: col = true, col != true - unsigned int: col > 0, col >= 1, col < 1, col <= 0 The on-disk num_defaults written by SerializationInfo::Data::add was previously sampled (10% via getRatioOfDefaultRows) so it could not be used as an exact count. Switch the writer to compute it via IColumn::getNumberOfDefaultRows on every block, and persist exact_num_defaults: true alongside in serialization.json. Old parts that don't have the flag are treated as non-trustworthy and the optimisation skips them storage-wide. Storage-level reliability checks (active transaction, presence of patch parts) are kept as in optimize_trivial_count_query. The optimisation never produces wrong answers; it just stops firing when those conditions don't hold. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`SerializationInfo::Data::add(IColumn)` now records the exact `num_defaults` for every sparse-eligible column on insert/merge, not just those that end up sparse-encoded. The `exact_num_defaults` flag in `serialization.json` is the single safety invariant; the extra Sparse-kind check was a leftover from when the count was sampled and only correlated loosely with exactness. Removing the check extends the optimisation to dense-encoded sparse-eligible columns. On `hits`, queries like `count() WHERE Age = 0` (Int16 column with ~30% defaults, kind Default) drop from 13ms / 100M rows scanned to 1ms / 0 marks -- roughly 13x faster vs the ~4x speedup previously seen on sparse-encoded columns. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Covers every predicate shape the classifier recognises -- equality to type default, IS NULL / IS NOT NULL on Nullable, empty / notEmpty on String, Bool against true, asymmetric integer comparisons on unsigned columns -- and confirms the rewrite returns the same answer as the unoptimised path. Also covers shapes that must NOT be recognised (signed-integer asymmetric comparisons, AND of two predicates, comparison against a non-default constant) so the test fails if a future change loosens the classifier incorrectly. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds `use_serialization_info_for_part_pruning` (default true). At part
scan time, drop parts whose WHERE predicate is provably false on every
row, based on the per-column `num_defaults` / `num_rows` recorded in
`serialization.json` and the `optimize_trivial_count_with_sparsity_filter`
predicate classifier:
- `col != default(col)` and `num_defaults == num_rows` (every row is
the default) -> drop the part.
- `col = default(col)` and `num_defaults == 0` (no row is the
default) -> drop the part.
Predicate shapes recognised match those of the trivial-count rewrite
(equality to type default, IS NULL / IS NOT NULL on Nullable, empty /
notEmpty on String, Bool against true, unsigned-int asymmetric
comparisons).
Reliability rules mirror `MergeTreeData::getColumnDefaultnessStats`:
the optimisation is skipped on FINAL, on parts written by older servers
(no `exact_num_defaults` flag), inside an active transaction, and when
patch parts / pending data mutations are present.
Wired into `MergeTreeDataSelectExecutor` as a new
`filterPartsBySparsityInfo` step that runs after `filterPartsByStatistics`;
an `IndexType::Sparsity` row appears in EXPLAIN indexes output.
Unlike the trivial-count rewrite, this fires on non-`count()` queries
too -- e.g. `SELECT col1 FROM t WHERE HTTPError != 0` skips every part
on `hits` since `HTTPError` is uniformly default. It complements the
existing `filterPartsByStatistics` step rather than replacing it.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds `use_sparsity_info_for_pruning` (`off` / `planning` / `data_read`)
as a tri-state enum replacing the previous boolean
`use_serialization_info_for_part_pruning`. Default is `data_read`
(scales to TB-size columns); `planning` is the eager variant useful
for predictable mark counts and EXPLAIN visibility on smaller workloads.
This commit implements the `planning` mode end-to-end. The `data_read`
variant is wired to the same setting but the granule-level analysis
currently runs at plan time identically to `planning`; the lazy
scan-time hook is a follow-up.
Mechanism (Phase A still applies for part-level drops):
- For sparse-encoded columns hit by a sparsity predicate that the
Layer A classifier recognises (equality to type default, IS NULL /
IS NOT NULL on Nullable, empty / notEmpty on String, Bool against
true, unsigned-int asymmetric comparisons), read the column's
offsets stream and mark each granule as `all-default`,
`all-non-default`, or `mixed`.
- In `Planning` mode, `filterMarkRangesBySparsityInfo` trims each
part's `MarkRanges` to drop granules that can't contribute to the
answer for the classified predicate class.
- Unlike Phase A, this works on any sparse-encoded part regardless
of the `exact_num_defaults` flag in `serialization.json`, so it
applies to parts written by older servers.
The analyzer reads granule-by-granule via `createMergeTreeReader`, so
Compact, Wide, and Packed part formats are all handled by the existing
factory dispatch. `continue_reading` is reset between mark ranges so
the reader seeks correctly when the input ranges are non-contiguous
(e.g. when the query condition cache or PK index already trimmed some
granules in the middle).
Tests:
- 04216: extended to the new enum setting; part-level pruning.
- 04217: new test for granule-level pruning, EXPLAIN check, and the
unprunable predicate direction.
- 04218: regression for the multi-range bug -- a first query
populates the query condition cache, the second arrives at
`filterMarkRangesBySparsityInfo` with non-contiguous `MarkRanges`,
and the analyzer must still classify correctly. Without the
`continue_reading` reset this returned `sum(x) = 3` instead of 5.
Both 04217 and 04218 are parallel-safe (per-test database UUID makes
the server-wide query condition cache effectively private).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds the lazy variant of Phase B and extends Phase A / Phase B to walk
top-level `AND` conjuncts so multi-condition WHEREs (e.g.
`WHERE a != 0 AND b != 0`) benefit from sparsity pruning the way skip
indexes do.
Lazy mode (`use_sparsity_info_for_pruning = 'data_read'`):
- `MergeTreeSparsityReader` reuses `analyzeSparseColumnGranules` but
runs it lazily per part inside `MergeTreeIndexReadResultPool`.
- Result is a `granules_selected: vector<bool>` bitmap consumed by
`MergeTreeReaderIndex::canSkipMark`, the same path as
`use_skip_indexes_on_data_read`.
- Subject to the existing `supportsSkipIndexesOnDataRead` invariants
(no FINAL exact mode, no plan-time row-count dependency in JOINs,
no throw on `max_rows_to_read`, no pending data mutations or
patch parts).
Multi-conjunct AND walking (`collectSparsityConjuncts`):
- `WHERE classified_a AND classified_b AND unclassifiable_c` -> we
prune by the union of `a` and `b`'s verdicts; the unclassifiable
conjunct is just evaluated normally on the surviving rows.
- A part / granule is dropped iff ANY classified conjunct proves no
rows in it can match (AND semantics).
- Layer C-1 trivial-count rewrite intentionally stays single-predicate
-- it returns an exact constant from metadata and can't soundly
compose verdicts across columns. Phase A and Phase B cover the
multi-conjunct case.
Tests (one focused file per behaviour):
- 04219: `data_read` mode correctness against baseline and `planning`.
- 04220: multi-conjunct WHERE across all three modes, plus mixed
classified+unclassifiable conjuncts.
CI integration:
- `tests/clickhouse-test` randomizes `use_sparsity_info_for_pruning`
across `{off, planning, data_read}` so existing tests exercise all
three modes.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Phase B's per-(part, column) classification (which granules are
all-default / all-non-default) is independent of the specific
predicate -- it's a function of the column data. Stash it under
synthetic condition hashes keyed on `(column_name, predicate_class)`
in the existing `QueryConditionCache` so repeated queries don't
re-run the analyzer for the same (part, column) pair.
Two cache entries per (part, column):
- `__phaseB_offsets_defaults__`: "granule G has only defaults"
-- usable for any `MatchesNonDefault` predicate on the column.
- `__phaseB_offsets_non_defaults__`: symmetric, for `MatchesDefault`.
Writes happen unconditionally (even when the bitmap is empty) so the
cache records a "no prunable granules" verdict and the next query
short-circuits to the cache rather than re-running the analyzer's
per-part reader setup -- which was the bulk of the regression on
`SELECT count() FROM hits WHERE AdvEngineID != 0` after warmup.
Subtle correctness fix bundled in: `QueryConditionCache::write`
assumes `marks_count` *includes* the final-mark sentinel and flips
`matching_marks[marks_count - 1]` to false when `has_final_mark` is
true. Earlier we were passing `getMarksCountWithoutFinal()` for
`marks_count`, so the cache silently marked our last real granule
as "no matches", causing wrong results on `WHERE x = 0`. Now we
pass `getMarksCount()` and read/write only positions in
`[0, total_marks)`.
Benchmark on `hits` (warm cache):
off / planning / data_read ~ 240 QPS each
(cold-query overhead now amortizes after the first query; previously
planning was ~110 QPS and data_read ~135 QPS, repeatedly).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous implementation scanned every row of the column in a per-row loop. For columns that are 99% default (the common case for sparse serialization), most iterations only did `res_offset += filt[i] != 0;` while paying the cost of an iterator check on every row. Walk the offsets array instead and use `countBytesInFilter` over the runs of default rows between offsets. That reduces work from O(_size) to O(non_defaults + _size/64), since `countBytesInFilter` uses 64-bit popcount under the hood. Both the const and in-place overloads share the algorithm.
The cache lookup in `analyzeSparseColumnGranules` was using `storage.getContext()`, which is the daemon startup context. As a result `SETTINGS use_query_condition_cache = 0` on the query had no effect on the synthetic-key entries this code writes -- the cache was always consulted regardless of the per-query setting. Plumb the query context in through `analyzeSparseColumnGranules` and `MergeTreeSparsityReader`, and use it to gate the cache. Also register the two new settings in `SettingsChangesHistory.cpp` under the 26.6 block: - `optimize_trivial_count_with_sparsity_filter` - `use_sparsity_info_for_pruning`
The added sparsity pruning code carried heavy "Phase A / Phase B / Layer
C-1" narrative inherited from the design notes. That terminology doesn't
exist in the rest of the codebase and adds nothing once a reader can
just read the function it's annotating.
This commit:
- removes every "Phase A / Phase B / Layer C-1" reference from code
comments, log messages, test comments and cache key labels (the
`__phaseB_*` cache domain strings become `__sparse_*`);
- collapses verbose what-the-code-does comments into short why-it-does-it
notes wherever the WHY isn't obvious from the code;
- drops a few comments that just restated the next line.
No behavior change.
`use_sparsity_info_for_pruning` is already randomized; do the same for the trivial-count rewrite gate so both code paths (rewritten constant count vs full scan) get exercised by stateless tests.
When the trivial-count rewrite based on per-column sparsity stats silently skips, the rewrite simply doesn't fire and the user has no hint about why. Most often the cause is a part on disk written by a binary that didn't set the `exact_num_defaults` flag (e.g. legacy parts from before the flag existed, or parts produced by an older binary still in the table). Add a `LOG_DEBUG` for each bail-out branch (active transaction, patch parts, column missing from serialization info, exact flag missing).
`data_read` and `planning` modes re-read the predicate column's sparse
offsets twice per query: once during granule classification, then again
during the actual scan. With the query-condition cache off, the per-query
cost roughly doubles compared to `off` mode.
Introduce a query-scoped store of decompressed sparse offsets:
- `SparseOffsetsShare` holds the per-(part, column) offsets read by the
analyzer, indexed by absolute row range. Its `slice()` builds a
`SubstreamsCacheSparseOffsetsElement` for an arbitrary sub-range, with
positions shifted into the consumer's frame and `skipped_values_rows`
pre-computed so the values stream still gets positioned correctly.
- `MergeTreeIndexReadResultPool` owns the share, so its lifetime matches
the query.
- `analyzeSparseColumnGranules` writes into the share when one is provided.
The planning-mode call (which doesn't need the data-scan handshake)
passes nullptr.
- `IMergeTreeReader` gains `setSparseOffsetsShare()` and a protected
`seedSparseOffsetsCacheForColumn()` helper.
- `MergeTreeReaderWide::readRows` calls the seed helper before `readData`,
pre-populating the per-readRows `SubstreamsCache` so
`readOrGetCachedSparseOffsets` serves from memory.
- `MergeTreeReadTask::initializeIndexReader` hands the share from the
pool to every reader (main + prewhere chain) after the analyzer ran.
Limitations carried into a follow-up:
- Compact parts: the main-column path passes `nullptr` as `substreams_cache`,
so the seed has no effect there. Sparse subcolumn reads in Compact would
benefit, but the common heavy-column case is Wide.
- Wrapped Sparse serializations (Sparse inside another serialization layer)
use a different `SubstreamPath` and the seed silently misses, falling
back to a normal disk read.
The previous slicer set the cached `skipped_values_rows` to the count of non-defaults *in the analyzer's stored range* preceding the scan's row window. That field is consumed by `readOrGetCachedSparseOffsets` and passed verbatim to the values reader as `rows_offset`, but the values stream was already seeked to the scan's `from_mark`, so the extra skip walked past EOF and the read failed with `ATTEMPT_TO_READ_AFTER_EOF`. `deserializeOffsets` defines `skipped_values_rows` as call-local: the number of non-defaults seen while consuming the *first `rows_offset` rows* of the current call, before any rows are produced. Update the slicer to match: take both `rows_offset` and `limit`, split the request into a skip zone `[abs_row_start, +rows_offset)` and a produce zone `[+rows_offset, +limit)`, count skipped-values inside the skip zone only, and emit produce-zone positions into the consumer's frame. Pass `rows_offset` through `seedSparseOffsetsCacheForColumn` from `MergeTreeReaderWide::readRows`. There is a known perf regression with this fix: every scan call does an `O(N)` linear walk over the entire analyzer's offsets array and allocates a column reserving the full source size. Both go away once the slicer uses `std::lower_bound` and reserves only the produce window.
The previous slicer did a full linear scan over the stored range's offsets and reserved a column the size of the entire source array. With ~12K scan calls per query and ~630K offsets per range the cost was quadratic; combined with a non-shared mutex that serialized all scan threads, planning/data_read modes ended up 5x+ slower than off. Rewrite the slicer to use `std::lower_bound` for the skip/produce-zone boundaries and copy only the produce-window into a column sized exactly to fit. Switch the share's mutex to SharedMutex so concurrent scan threads don't block each other on the read path.
Three counters to verify the share is doing what we expect: - SparseOffsetsShareSeedHits: scan readRows calls where the share found a covering range and produced a sliced cache element. - SparseOffsetsShareSeedMisses: scan readRows calls where no covering range was found, falling back to a normal disk read. - SparseOffsetsShareConsumed: times the offsets deserializer served from a pre-seeded cache element. If much smaller than SeedHits, the consumer's SubstreamPath doesn't match the seed's. With these three numbers we can tell hit/miss math from path-key mismatch from coverage gaps without running perf.
`SparseOffsetsShare` was only created and populated in `data_read` mode
(by `MergeTreeIndexReadResultPool` when it has a `MergeTreeSparsityReader`).
Planning mode ran the analyzer directly in `filterMarkRangesBySparsityInfo`
with `offsets_share = nullptr`, so the scan that followed had to re-decode
the same offsets stream from disk.
Lift share ownership to `ReadFromMergeTree::AnalysisResult`:
- `selectRangesToReadImpl` lazily creates the share when the planning
pass is going to run.
- `filterMarkRangesBySparsityInfo` (and `analyzeSparseColumnGranules`)
accept a non-null share and persist their per-MarkRange offsets there.
- `initializePipeline` extends the pool-construction condition to also
fire when the share is populated, and passes the share into the new
`MergeTreeIndexReadResultPool` constructor parameter. The pool stops
creating its own share when one is handed in.
The scan-side plumbing (`MergeTreeReadTask::initializeIndexReader` →
`IMergeTreeReader::setSparseOffsetsShare`) is unchanged; it just finds a
populated share now in both modes.
Two changes that go together because the second exposes a bug introduced by the first. 1) Split each analyzed `MarkRange` into ~1024-mark chunks and run them on the global IO thread pool. The serial analyzer pass was adding wall-time on the planning thread that the parallel scan couldn't amortize; chunking divides the offsets decode across cores. Each chunk's reader produces a local classification; results are concatenated back into one offsets entry per original `MarkRange` for the share (so `slice()` only needs to find one covering entry). 2) `IMergeTreeReader::seedSparseOffsetsCacheForColumn` was computing `abs_row_start` as `getMarkStartingRow(from_mark)`, which is wrong for `continue_reading=true` calls: the reader has advanced past `from_mark` from previous calls in the same task, but the seed kept producing slices for the original `from_mark` row window. The resulting cache hit returned offsets from rows the scan already consumed, so the returned count drifted by row windows that overlapped chunk boundaries. Track the next row position on `IMergeTreeReader::current_scan_row` and use it as the scan-row anchor when `continue_reading=true`. The reader's `readRows` initializes it from `from_mark` on the seek path (`continue_reading=false`) and advances it by `rows_offset + read_rows` at the end of each call.
For uniformly-distributed sparse columns no granule is ever all-default or all-non-default, so the analyzer's full pass produces a trivial bitmap that prunes nothing. The wall-time cost (~30% on top of an equivalent `off`-mode scan, even with parallelism) was pure overhead. Add a sample step in front of the full pass: classify the first 32 marks of the first MarkRange synchronously, and only continue with the parallelized full pass if at least one sampled granule is all-default or all-non-default. If none is, return nullopt -- the share stays empty, the scan-side seed is silently a no-op, and the query runs as if `use_sparsity_info_for_pruning='off'`. For `AdvEngineID`-style uniformly-distributed columns, `data_read` and `planning` are now within 4% of `off` QPS on the hits benchmark (225/226 vs 235), down from the previous 162/157.
`SparseOffsetsShare::slice` was acquiring the share's `SharedMutex` on
every scan-side `readRows` call (~1500 per query in the benchmark).
Perf showed ~1.3% of total CPU sitting in `lock_shared` and the kernel
spinlock backend, which is wasted work because the bucket for a given
`(part, column)` is immutable once a scan-side reader can see it.
Split the API into a lookup step that takes the lock once and a slicing
step that doesn't:
- `SparseOffsetsShare::findBucket(part, column)` resolves and returns a
stable `const Bucket *` under `shared_lock`. `unordered_map`
guarantees pointer stability across rehashes; entries are never
erased.
- `SparseOffsetsShare::sliceFromBucket(bucket, ...)` is a free function
that does the binary searches and copy on the already-resolved
bucket. No locking.
`IMergeTreeReader` caches the resolved `(column, bucket)` pair on a
single-entry slot. The reader is scoped to one part and typically reads
one sparse predicate column thousands of times in a row, so we hit the
share's mutex once per (reader, column) instead of once per scan call.
No measurable QPS change in `data_read` mode -- the wall-time
bottleneck is the analyzer's serial pass, not the slicer -- but it
removes a real CPU hotspot and is a cleaner abstraction for the next
optimisations on the slicer itself.
Two small things found in the slicer/seed hot path: 1) `rows_offset == 0` is the common case for scan reads -- the call only passes a non-zero offset on rows-offset reads which are rare in practice. When it's zero, `skip_end_rel == skip_start_rel`, so the middle `lower_bound` returns its starting iterator and `skipped` is trivially 0. Skip the redundant binary search. 2) The per-reader bucket cache was comparing the column name as a `String &` (i.e. a full string compare) on every slice call. The `String &` returned by `NameAndTypePair::getNameInStorage()` is a reference to a string that lives inside the reader's `columns_to_read` and whose address is stable for the reader's lifetime; pointer-equality is enough as a cache-key and saves the string compare on the ~1500 calls per query in the benchmark. The `create()`-then-`resize` pattern for the sliced column is kept deliberately: switching to `create(n)` looked tidier but the compiler lost the SIMD vectorisation of the shifted copy loop because the constructor takes the size by `const size_t &` (the address ends up on the stack and the optimiser can't prove the loop bound is invariant). The current pattern produces a tight SSE2 paddq loop (4 UInt64 per iteration), which beats the smaller code size. Modest ~3% QPS bump in the worst case (sample-bail disabled) on the hits-style benchmark.
Chunk the post-sample marks into roughly `max_threads` pieces (clamped to [256, 8192] marks) so the parallel pass finishes in one round instead of stair-stepping. Pre-size the per-range merge buffer and write by index so the no-shift case becomes a `memcpy` and the shifted case auto-vectorises to SSE2 `paddq` (4 UInt64 per iter), matching the slicer's copy loop.
Two changes that together cut the analyzer's wall time roughly in half on single-part queries: - Drop the serial merge that concatenated per-chunk offsets into one column per `MarkRange`. The analyzer now inserts each chunk directly into the share, and the slicer's existing covering-range search picks the right chunk on the hot path. When a scan window straddles a chunk boundary the slicer stitches the affected chunks into a fresh column itself; the disk fallback is not safe there because the scan never seeked the SparseOffsets stream (prior calls were cache hits) and the `DeserializeStateSparse` would be stale. - Teach `sliceFromBucket` to return a deferred-slice descriptor (source pointer + shift) instead of a freshly materialised column. The consumer in `readOrGetCachedSparseOffsets` appends `src[i] + shift` straight into its persistent offsets column, skipping the temporary alloc and the `insertRangeFrom` copy.
The analyzer only inspects the offsets column for non-default counts per granule; reading the values substream is pure overhead. Add an opt-in `skip_sparse_values_substream` flag on `DeserializeBinaryBulkSettings`: when set, `SerializationSparse::deserializeBinaryBulkWithMultipleStreams` skips the nested values read and pads the values column with defaults to keep the `offsets.size() + 1 == values.size()` invariant. The analyzer's chunk reader sets the matching `setOnlyReadSparseOffsets` flag and is discarded immediately after one `readRows`, so the un-advanced nested state is harmless. Cuts the analyzer wall-time gap by another ~30-45% on single-part queries by avoiding the values LZ4 decompress and the corresponding column construction.
A 32-mark sample is too narrow to predict whether the rest of the column contains extreme granules. Benchmarks on real columns from a 100M-row hits table showed the bailout false-positives on the columns where pruning is actually most useful: AdvEngineID (0.6% density) loses 52% of its pruning, HasGCLID (0.35%) loses 76% - their first 32 marks happen to be mixed but later marks have extremes. The savings on truly uniform columns are 1-3 ms (worst observed: NetMajor +3 ms wall), much smaller than the pruning benefits on real-world workloads. Now that the merge-step alloc and the values substream read are both gone, the analyzer's wall-time on uniform columns is small enough that the heuristic doesn't carry its weight. Removing it also collapses the two-phase chunking back to a single uniform partition.
`WHERE col != 0 AND col != 0` and similar patterns (often produced by ORMs, view rewrites, or accidental copy-paste) used to call `analyzeSparseColumnGranules` once per duplicate. Without `QueryConditionCache`, that's pure waste; with it, the duplicates race the cache slot rather than waiting on the first call. Sort and unique by `(column_name, predicate_class)` before returning, so each distinct (column, sparsity-class) pair is analysed at most once per part for a given query.
The pruning optimization is shipping as an experimental feature, so the two user-visible settings default to off (`false` / `Off`) and carry the `EXPERIMENTAL` tier. Adjust the 26.6 entries in `SettingsChangesHistory.cpp` to reflect the new "off-by-default" state so `compatibility = '26.5'` is a no-op for either setting.
The existing 04215 coverage only exercised the `= true` / `!= true` Bool branch. Add plan-firing and result checks for the bare-truthy shapes so that path can't regress silently. Narrow the classifier header doc: SQL rejects Int/UInt columns wider than UInt8 as filter columns before the predicate reaches `classifySparsityPredicate`, so `Bool` / `UInt8` are the only reachable bare-truthy types. Reported at ClickHouse#105890 (comment) Co-Authored-By: Claude Opus 4.7 <[email protected]>
filterPartsByStatistics prunes parts from per-column min/max estimates of the on-disk (pre-mask) values, so `WHERE masked_col = x` could prune parts that masking would turn into matches. Disable it when a masking policy applies, the same way it is already disabled for on-the-fly mutations and patch parts.
Contributor
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 571/713 (80.08%) · Uncovered code |
Algunenano
enabled auto-merge
July 8, 2026 17:08
Merged
via the queue into
ClickHouse:master
with commit Jul 8, 2026
5d24ddd
342 of 345 checks passed
1 task done
zeekay
pushed a commit
to hanzoai/datastore
that referenced
this pull request
Sep 11, 2026
`filterPartsBySparsityInfo` and the planning-mode `filterMarkRangesBySparsityInfo` classify predicates from the full query `WHERE` and apply them per-table, but a `WHERE` over a JOIN result is not safe to push below the join. With `LEFT JOIN ... WHERE r.v = 0` and `join_use_nulls = 0`, dropping a right part whose `v` column has no zero rows turns formerly-matched left rows into unmatched ones; those then receive the type-default `r.v = 0` and pass the post-join `WHERE`, contradicting the pruning step's assumption. Mirror the `data_read` path's existing JOIN opt-out into both planning paths via a shared `queryHasJoinedTable` helper in `Analyzer/Utils.h`. Refactors the `data_read` inline check to use the same helper so the three paths stay in sync. Reported in ClickHouse#105890 (comment).
zeekay
pushed a commit
to hanzoai/datastore
that referenced
this pull request
Sep 11, 2026
`queryHasJoinedTable` only inspected the root node of the join tree, so an `ARRAY JOIN` wrapping a JOIN made it return false. The sparsity pruners then still pushed the post-JOIN `WHERE` below the outer join: with `LEFT JOIN ... ARRAY JOIN [1] AS a WHERE r.v = 0` and `join_use_nulls = 0`, the right part was dropped because `num_defaults(r.v) = 0` and the unmatched left rows received the default `r.v = 0`, returning rows the scan would reject. Reuse `buildTableExpressionsStack` so the check sees every node in the join tree, including JOINs reached through `ARRAY_JOIN`, `CROSS_JOIN`, or nested `JOIN`s. Extend `04332` with the ARRAY JOIN case. Reported in ClickHouse#105890 (comment).
zeekay
pushed a commit
to hanzoai/datastore
that referenced
this pull request
Sep 11, 2026
…columns docs The setting was described as required by sparsity-based pruning in general. It is actually only required by part-level pruning under `use_sparsity_info_for_pruning` and by `optimize_trivial_count_with_sparsity_filter`, which read the persisted `num_defaults` counter. Granule-level pruning (`planning` / `data_read`) reads the `SparseOffsets` stream directly and works on sparse-serialized columns without the exact counter (Nullable columns additionally need `nullable_serialization_version = 'allow_sparse'`). Reported in ClickHouse#105890 (comment).
zeekay
pushed a commit
to hanzoai/datastore
that referenced
this pull request
Sep 11, 2026
…e_offsets` `MergeTreePrefetchedReadPool::createPrefetchedReadersForTask` ran `prefetchBeginOfRange` before `MergeTreeReadTask::initializeIndexReader` attached the share, so the prefetcher still issued reads for `SparseOffsets` streams that the planning-mode analyzer had already cached in `SparseOffsetsShare` — wasteful on remote storage. Separately, `only_read_sparse_offsets` was honored only at deserialize time, after `readRows` had already called `prefetchForAllColumns`; the analyzer's offsets-only reads were still prefetching the `SparseElements` stream. Thread the share into the pool and attach it to readers before prefetch starts, then teach `MergeTreeReaderWide::prefetchForColumn` to: * skip a `SparseOffsets` substream when the share already has a bucket for the `(part, column-in-storage)` pair, and * skip every substream under `SparseElements` when `only_read_sparse_offsets` is set on the reader. `initializeIndexReader` still re-attaches the share for the `data_read`-mode path; that runs after prefetch and overwrites with the same value. Reported in ClickHouse#105890 (comment) and ClickHouse#105890 (comment).
zeekay
pushed a commit
to hanzoai/datastore
that referenced
this pull request
Sep 11, 2026
Two follow-ups to the planning-mode share wiring: * The share was allocated eagerly before the analyzer ran, so queries with no recognised conjuncts (or no sparse columns) ended up with an empty but non-null share attached to every scan reader, paying for a per-block `seedSparseOffsetsCacheForColumn` miss for no benefit. Reset the share to null when `filterMarkRangesBySparsityInfo` returns without inserting any bucket. * The analyzer inserts decompressed offsets for every analyzed `(part, column)` before the pruning verdict is applied. For parts that the same call then drops, the buckets sat in the share until query end with no consumer. Walk the surviving parts after pruning and drop the rest via `SparseOffsetsShare::retainOnlyParts`. Adds `SparseOffsetsShare::empty()` and `retainOnlyParts(...)` for the cleanup. Reported in ClickHouse#105890 (comment) and ClickHouse#105890 (comment).
zeekay
pushed a commit
to hanzoai/datastore
that referenced
this pull request
Sep 11, 2026
`createEmptyPart` (e.g. from a full-`DELETE` mutation on plain `MergeTree`) produces an active zero-row part whose `SerializationInfoByName` is empty. The aggregation then hits `infos.find(column_name) == end()` and disables `optimize_trivial_count_with_sparsity_filter` table-wide until cleanup removes the empty part. Reported at ClickHouse#105890 (comment) Co-Authored-By: Claude Opus 4.7 <[email protected]>
zeekay
pushed a commit
to hanzoai/datastore
that referenced
this pull request
Sep 11, 2026
`optimize_empty_string_comparisons = 1` (default) rewrites `s = ''` / `!= ''` into `empty(s)` / `notEmpty(s)` before the sparsity classifier runs, so the common empty-string spellings hit `isStringLike`. That helper only accepted `String`, which meant the PR's advertised `FixedString` equality-to-default support did not actually fire. `typeMatchesDefaultnessStat` already accepts `FixedString`, and the bitwise "row is default" semantics of `IColumn::isDefaultAt` are the same for `String` (empty) and `FixedString` (all zeros), so accepting it here is safe. Reported at ClickHouse#105890 (comment) Co-Authored-By: Claude Opus 4.7 <[email protected]>
zeekay
pushed a commit
to hanzoai/datastore
that referenced
this pull request
Sep 11, 2026
`applyTrivialCountWithSparsityFilterIfPossible` accepted any `AggregateFunctionCount`, including `count(expr)`. But the rewrite seeds the aggregate state with a row count derived from the per-column `num_defaults`, which is only right for `count()` / `count(*)` (row count). `count(expr)` counts non-`NULL` argument values, and on `Nullable(T)` the two disagree: e.g. `SELECT count(n) FROM t WHERE n IS NULL` must return 0, but the rewrite would have returned `num_defaults` (the NULL count). Reject non-empty aggregate arguments so `count(expr)` falls through to the normal path. Reported at ClickHouse#105890 (comment) Co-Authored-By: Claude Opus 4.7 <[email protected]>
zeekay
pushed a commit
to hanzoai/datastore
that referenced
this pull request
Sep 11, 2026
The existing 04215 coverage only exercised the `= true` / `!= true` Bool branch. Add plan-firing and result checks for the bare-truthy shapes so that path can't regress silently. Narrow the classifier header doc: SQL rejects Int/UInt columns wider than UInt8 as filter columns before the predicate reaches `classifySparsityPredicate`, so `Bool` / `UInt8` are the only reachable bare-truthy types. Reported at ClickHouse#105890 (comment) Co-Authored-By: Claude Opus 4.7 <[email protected]>
zeekay
pushed a commit
to hanzoai/datastore
that referenced
this pull request
Sep 11, 2026
…trivial-count Sparsity-aware part/granule pruning and trivial-count optimization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Experimental: serve
SELECT count(*) FROM t WHERE col <op> default(col)from per-column sparsity statistics inserialization.jsonwithout any data scan when the predicate exactly partitions the column into defaults and non-defaults.Recognised predicate shapes:
col = const/col != constforInt*/UInt*,String/FixedString,Date/DateTime/DateTime64,Decimal*,UUID,IPv4/IPv6. Excluded forFloat*(treats+0.0and-0.0separately),Enum*(named default is not bitwise zero),Nullable,LowCardinality, and composite types (Tuple,Array,Map) where SQL equality and the persisted counter diverge.IS NULL/IS NOT NULLonNullablecolumns.empty(col)/notEmpty(col)onStringcolumns.col = true/col != trueonBoolcolumns.col > 0,col >= 1,col < 1,col <= 0on unsigned integer columns.col/NOT colonInt*,UInt*,Boolcolumns (truthy test).The constant side is compared against the column default via the least common supertype (so e.g.
dt_col = toDateTime64('…', 3)is classified correctly); lossy conversions (Decimaltruncation, out-of-rangeBool, etc.) opt out rather than misclassify.Two new settings, both experimental:
optimize_trivial_count_with_sparsity_filter(default off) — extendsoptimize_trivial_count_queryto the predicates above, served from the per-columnnum_defaults/num_rowscounters with no scan. Honorsselect_sequential_consistency(the rewrite consults the same ZK-filtered active-parts list asReplicatedMergeTree::totalRows).compute_exact_num_defaults_for_sparse_columnsMergeTree setting (default off) — gates the O(rows) exact counting at part-write time. Without it the producer keeps the pre-existing sampled estimate and the part is silently opted out of the new optimization.Also included as part of the sparsity work:
FilterWithCachedCountpreserves the sparse filter shape end-to-end soMergeTreeRangeReader::optimizeshrinks reads on sparse conjuncts as aggressively as PREWHERE does on dense ones.tryOptimizeTopKruns in the second optimization pass, after PREWHERE has claimed sparse conjuncts, so__topKFilterno longer steals PREWHERE from a classifiable sparse predicate.ColumnSparse::filterwalks the offsets array with 64-bit popcount, dropping O(rows) to O(non_defaults + rows/64).IColumnHelper::getNumberOfDefaultRowsgets container-column overrides (ColumnArray,ColumnMap,ColumnObject,ColumnTuple) instead of the O(rows × subcolumns) virtual-call default.Part-statistics change
MergeTree already records
num_defaultsandnum_rowsper column inserialization.json, but the oldnum_defaultswas a sampled estimate (sufficient for the sparse/dense kind decision, not for serving counts). This PR adds anexact_num_defaults: trueflag toSerializationInfothat's set when the producer counted every default, and the trivial-count rewrite only fires when the flag is present.Backward compatibility:
false; the trivial-count code guards on the flag so the part is opted out of the optimization. The pre-existing sampled counters are still used for the kind decision, exactly as before.serialization.jsonfor legacy parts is byte-identical because the new writer only emits the key whentrue; for parts written by the new server the JSON gains one extra key (exact_num_defaults: true). OldSerializationInfo::fromJSONparsing usesPoco::JSON::Object, which silently ignores unknown keys, so the older server reads the part normally.Tests under
tests/queries/0_stateless/04215_*,04278_*,04279_*,04281_*,04283_*,04285_*,04325_*,04326_*,04328_*cover correctness across Nullable columns, persisted exact counters round-tripped through restart, decimal precision-loss guards, supertype-based classification, and sequential consistency on Replicated tables.Version info
26.7.1.682(included in26.7and later)