Repository navigation
Do not rescan the whole part's marks on every LowCardinality read - #116134
Conversation
MergeTreeReaderStream::hasAtMostNDistinctMarks decides whether a part has a single shared LowCardinality dictionary. It is described as a cheap prefilter, but it walks marks_count marks, which MergeTreeReaderWide::addStream fills from getMarksCount(), i.e. the whole part rather than the range being read. Its only caller is the has_uniform_marks_callback lambda, reached from deserializeBinaryBulkStatePrefix, so it runs once per read task per LowCardinality column. Each visit bit-unpacks a mark through MarksInCompressedFile::get, which is why that function shows up in profiles as a peer of the scan. Two details make the cost worse than it looks. The loop's early exit only fires on a multi-dictionary part, so a genuine single-dictionary part, the case the optimization exists to reward, always pays the full scan. And nothing dedupes the verdict across read tasks: DeserializationPrefixesCache does wrap prefix deserialization, but it is allocated per read pool, so a UNION ALL of N point lookups gets N empty caches. The number of groups of consecutive equal marks is a property of the marks file, so compute it once in MarksInCompressedFile::Builder::flushBlock, inside the loop that already visits every mark, and store it on the object MarkCache keys per mark file. Both construction paths funnel through flushBlock, and the last-seen mark is carried across calls so a group spanning a block or chunk boundary is counted once. The count saturates at a small cap, so the member stays one byte and the loop stays a compare plus a conditional increment. The reader answers from that value and keeps the original scan as a fallback for the cases the stored count cannot describe: a mark holding more than one column (the array interleaves them), a stored array that is not exactly the marks the scan would visit, and a requested bound that reaches the cap. The returned boolean, the final-mark asymmetry in MergeTreeReaderWide and the eof() validation in SerializationLowCardinality are all untouched; only how fast the same boolean is computed changes. The value lives in memory only, so the on-disk mark format is unaffected and no setting is added. On the reproducer from the issue (10M rows, index_granularity = 8, 1.25M marks per part, 1500 UNION ALL branches) the query drops from 25.5s to 7.9s and the share of CPU samples in the prefilter goes from 64% to under 1.5%, with identical results. The cost scales with marks per part as diagnosed: at index_granularity = 8192 the prefilter is already only ~0.5% before the change. The new gtest asserts the stored count equals a reference linear scan over both construction paths, including the streaming Builder::addMarks path which had no coverage, at chunk sizes straddling MARKS_PER_BLOCK. Closes: ClickHouse#115998
The precomputed distinct-mark count makes the single-dictionary check O(1), but nothing observed that the fast path was reached. Deleting it left every test green: the boolean is bit-identical, so the existing SQL tests cannot tell the memoized answer from the scanned one, and the gtest exercises MarksInCompressedFile without going through the reader. A later change to num_columns_in_mark or marks_count bookkeeping could therefore silently falsify the guard, restore the whole-part scan, and pass CI. This code path has already been reverted twice, so that is not a hypothetical cost. Count the fast path with a ProfileEvent and assert a non-zero delta from a Wide one-column LowCardinality read. Verified by deleting the fast-path block: the new test fails (1 vs 0) while 04143, 04201, 04144, 04614, 04141, 04142 and the gtest all stay green. That asymmetry is the point, since 04143 can only see the optimization stop firing, not the memoization. The event is named for the mechanism rather than for LowCardinality because SerializationObject consumes the same callback for JSON subcolumns. Also run the two version-only-DictionaryKeys tests ClickHouse#103662 added alongside 04143, and drop a dead array copy in the gtest (create takes a const ref).
Internal second-model review (2 rounds, 0 blockers outstanding)Reviewed cold against the code on disk before reading the implementation notes, then a second Round 1: one major, fixed in
|
|
Workflow [PR], commit [9dc681d] Summary: ✅
AI ReviewSummaryThis PR replaces the per-mark linear scan in PR Metadata
Tests
Final VerdictUpdate the PR description, changelog entry, and quoted performance evidence to match the current binary-search implementation before merge. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 15/15 (100.00%) · Uncovered code |
Pre-PR validation gate
Oracle liveness: four independent mutations were built and shown to fail the relevant test. Dropping the cross-block carry and ignoring Acceptance gate (7 tests): |
|
cc @bobrik @Avogar, could you review this? The single-dictionary prefilter you added in #103662 scans the whole part's marks once per read task, so a 1500-branch UNION ALL over a small index_granularity table spends most of its CPU there. This computes the distinct-mark-position count once in MarksInCompressedFile::Builder::flushBlock and stores it on the object MarkCache keys per mark file, leaving the returned boolean, the final-mark asymmetry and the eof() validation untouched. |
clang-tidy-22 rejects the index loop in `referenceDistinctMarksCapped` with modernize-loop-convert, which fails Build (arm_tidy) under -warnings-as-errors: the index is only ever used as `plain[i]`, so the check requires the range form. The other index loops in this file also use `i` in a diagnostic message or in a bound, so they do not qualify and are left alone. Behaviour is unchanged. Verified with clang-tidy-22 (1 error before, 0 after, and reintroducing the index form brings the error back) and by running the Marks gtests 60 times. Breaking the cross-element `last` carry in the converted loop reddens Marks.DistinctMarksCapped, so the loop is still load-bearing.
AGENTS.md asks for literal class, function and constant names to be written inside inline code blocks, and for a method to be spelled `f` rather than `f()` when referring to the function itself. The comments added by this pull request did neither. Comments only, no behaviour change.
CI fix pushed:
|
Reverts the previous approach, which counted groups of consecutive equal marks once per marks file in `MarksInCompressedFile::Builder::flushBlock` and stored the saturating result on the object `MarkCache` keys. It put a `LowCardinality`-specific question into a generic container: every marks file in the server paid a compare and a branch per mark at build time, and carried the byte of state, to answer something only `LowCardinality` dictionary streams ask. The stored value saturated at three, so it could never answer a different bound, and it counted runs rather than distinct positions, which is not what its name said. The reader needed a guard plus the original scan as a fallback for the cases the value could not describe, leaving two paths for one question. A `ProfileEvent` existed only so a test could observe which path ran. The next commit answers the same question by binary search, which needs no stored state at all. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=7 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
`MergeTreeReaderStream::hasAtMostNDistinctMarks` prefilters the single-dictionary decision for `LowCardinality` columns. It is documented as cheap, but it walks `marks_count` marks, which is the whole part's mark count rather than the range being read, once per `LowCardinality` column per read task. Its early exit only fires on a multi-dictionary part, so a genuine single-dictionary part, the case the optimization exists for, always paid the full scan. Marks are non-decreasing positions in the file, so equal marks form contiguous runs and the end of a run is one `std::upper_bound` away. Walk runs instead of marks: at most `max_transitions` binary searches, exact for any bound, with no precomputed state to store or invalidate. `getRightOffset` already did this search inline for the same `LowCardinality` dictionary stream, so both now share `findNextDifferentMark`. The check is only a necessary condition either way: `SerializationLowCardinality` still verifies it by reading the first dictionary and checking the stream reaches EOF, so the returned boolean and everything downstream are unchanged. Closes: ClickHouse#115998 Related: ClickHouse#105605 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
I've pushed a different implementation of this fix and reverted the previous one. Reasoning, for the record. What changed
This isn't a new assumption. Why this rather than the precomputed count
The semantics are unchanged, so no new correctness test is needed: Unrelated findings while measuring thisTwo further regressions show up on the same reproducer, neither in this code path:
These should be filed separately. Request@groeneai please measure this implementation on the reproducer and compare it against the precomputed-count version you had here, so we have numbers for both on the same setup. When measuring, please pin |
| /// Index of the first mark after `from` that points to a different position, or `marks_count` if | ||
| /// there is none. Marks are non-decreasing positions in the file, so equal marks form contiguous | ||
| /// runs and binary search is valid. | ||
| size_t findNextDifferentMark(const MergeTreeMarksGetter & marks, size_t from, size_t marks_count) |
There was a problem hiding this comment.
The PR body and changelog entry still describe the reverted MarksInCompressedFile::Builder::flushBlock precomputation path and quote its 25.5s -> 7.9s result. This diff now uses the std::upper_bound walk instead, so the current review contract and the published changelog text are both about code that is no longer in the PR. Please update the description and changelog entry to describe the binary-search implementation, and replace the quoted numbers with measurements for this version.
|
Measured both on the same setup. Equivalent on the reproducer; your version is ~1% better on mark-file load. Nothing here argues for restoring the precomputed count. Three binaries from one build dir: pre-fix master Fixture is the issue body verbatim: 9 Wide parts x 138,996 marks, with
Precomputed vs yours is -3.3% at The mark-file build cost you cited is where they genuinely differ.
Precomputed is +0.7% on the median and +1.3% on the minima vs base; yours is -0.4% and -0.1%. Consistent across median, p25 and min, and ~1% of 173ms over 5M marks is ~0.35 ns/mark, about right for one compare and branch, so the tax is real and attributable. One correction: a 12-run pilot gave +4.8% and I do not stand behind that number, it collapses to ~1% at 25 runs. So exactness and the single path carry the decision, not the reproducer numbers. Description and changelog entry rewritten to describe the binary search and quote this version's numbers, per the review bot. The two unrelated regressions I will file separately, |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units7 translation units recompiled, 11 s compile time in total, 7 of them have a recent master baseline. |
|
Filed the first of the two regressions you flagged: #116259. It is not the |
…ry LowCardinality read
Backport #116134 to 26.8: Do not rescan the whole part's marks on every LowCardinality read
|
Filed the second of the two regressions you flagged: #116348. The front end did not get slower. With |
Backport #116134 to 26.6: Do not rescan the whole part's marks on every LowCardinality read
…rks on every LowCardinality read
Backport #116134 to 26.7: Do not rescan the whole part's marks on every LowCardinality read
…rks on every LowCardinality read
… ran getSkipIndexProfiledConditionHash salts a condition hash with the effective skip-index profile so that skip-index-derived exclusions are only consulted by a query that ran the same index set (issue ClickHouse#108519). It had no early return for an empty effective set, and a SipHash of the bare hash is never the bare hash, so on a table with no secondary index the profiled key was still distinct from the bare row-level key. Index analysis (ReadFromMergeTree) and the row-level filter (FilterTransform) then recorded the same predicate under two keys: two zeroed O(marks per part) bitmaps per part, plus two lookups per part on the read side, each returning a full bitmap copy. Return the bare hash when the effective skip-index set is empty, and skip the lookup that is then a duplicate. This is not a weakening of issue ClickHouse#108519: with no effective index nothing profile-dependent can have been recorded, and the exclusions written under that key can only come from primary-key or partition pruning, for which the row-level key is already sound. The collapse is exact because write only ever clears bits into an all-true entry while reads AND-merge, so one key holds the same union of cleared bits as two. That is a dependency worth stating: if a future change ever sets a matching_marks bit back to true, the collapse stops being equivalent. distributed_index_analysis is excluded, because there each replica runs index analysis on its own metadata (StorageMergeTreeAnalyzeIndexes) while the coordinator keys the ranges it gets back with its own index set, so a locally empty set is no evidence that no skip index contributed. Its activation gate can fire on a table with no secondary index because get_indexes_size also counts the primary-key index. The single helper serves all three call sites (one write, two reads), so write and read keys move together and cannot diverge. UsefulSkipIndexes::empty() is used rather than useful_indices.empty() because a TopK-filtering index also makes the set non-empty. No use_skip_indexes conjunct is needed: buildIndexes returns before populating skip_indexes when that setting is off. Measured on the issue ClickHouse#115998 shape (10M rows, index_granularity = 8, five parts of 250k marks, 1500 independent point lookups), with the cache sized above the working set so the entry gauge is not eviction-pinned: 14370 entries / 452.7 MB before, 7500 / 236.3 MB after, i.e. one entry per part and predicate. Wall clock is unchanged at that fixture scale and is not claimed. Reported by Avogar on pull request ClickHouse#116134. Related: ClickHouse#115998
Closes: #115998
Related: #105605
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a CPU regression for queries that issue many independent small reads against the same
MergeTreepart when the table hasLowCardinalitycolumns. The check deciding whether a part has a single shared dictionary scanned every mark of the whole part on each read task; it now finds each run of equal marks by binary search instead. Queries of this shape on tables with a smallindex_granularitywere up to several times slower since 26.6.Description
MergeTreeReaderStream::hasAtMostNDistinctMarksprefilters the single-dictionary decision added in #105605. It is documented as cheap, but it walkedmarks_countmarks, which is the whole part's count rather than the range being read, once perLowCardinalitycolumn per read task. Each visit bit-unpacks a mark, soMarksInCompressedFile::getappears in profiles beside the scan.Two details make it worse than it looks. The loop's early exit only fires on a multi-dictionary part, so a genuine single-dictionary part, exactly the case the optimization exists for, always paid the full scan. And nothing dedupes the verdict:
DeserializationPrefixesCacheis per read pool, so aUNION ALLof N point lookups gets N empty caches.Mark positions within a stream are non-decreasing, so equal marks form contiguous runs and the end of a run is one
std::upper_boundaway. The loop now walks runs rather than marks: at mostmax_transitionsbinary searches.MergeTreeReaderStreamSingleColumn::getRightOffsetalready did this same search over the same stream a few lines below, so the ordering invariant was already load-bearing in this file; both now share afindNextDifferentMarkhelper.The boolean itself is unchanged, as is the final-mark asymmetry in
MergeTreeReaderWideand theeof()validation inSerializationLowCardinalitythat #105605 added: only how fast it is computed changes. Bounding the scan to the read range, the issue's other suggestion, was rejected because it changes the answer and invalidates the reasoning behind the range-independenteof()check.On the issue's reproducer (10M rows,
index_granularity = 8, 9 parts of ~139k marks, 1500UNION ALLbranches,use_query_condition_cache = 0) the query goes from 27.1s to 11.9s, and CPU samples in the prefilter drop from 60.8% to 0.4%. Full numbers, including a comparison against the precomputed-count implementation this replaces, are in the thread.Version info
26.9.1.73(included in26.9and later)26.8.1.2002,26.7.7.51,26.6.4.24