Skip to content

Do not rescan the whole part's marks on every LowCardinality read - #116134

Merged
Avogar merged 6 commits into
ClickHouse:masterfrom
groeneai:lc-single-dict-marks-scan-115998
Aug 25, 2026
Merged

Avogar merged 6 commits into
ClickHouse:masterfrom
groeneai:lc-single-dict-marks-scan-115998

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #115998
Related: #105605

Changelog category (leave one):

  • Performance Improvement

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 MergeTree part when the table has LowCardinality columns. 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 small index_granularity were up to several times slower since 26.6.

Description

MergeTreeReaderStream::hasAtMostNDistinctMarks prefilters the single-dictionary decision added in #105605. It is documented as cheap, but it walked marks_count marks, which is the whole part's count rather than the range being read, once per LowCardinality column per read task. Each visit bit-unpacks a mark, so MarksInCompressedFile::get appears 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: DeserializationPrefixesCache is per read pool, so a UNION ALL of 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_bound away. The loop now walks runs rather than marks: at most max_transitions binary searches. MergeTreeReaderStreamSingleColumn::getRightOffset already 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 a findNextDifferentMark helper.

The boolean itself is unchanged, as is the final-mark asymmetry in MergeTreeReaderWide and the eof() validation in SerializationLowCardinality that #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-independent eof() check.

On the issue's reproducer (10M rows, index_granularity = 8, 9 parts of ~139k marks, 1500 UNION ALL branches, 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

  • Merged into: 26.9.1.73 (included in 26.9 and later)
  • Backported to: 26.8.1.2002, 26.7.7.51, 26.6.4.24

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).
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 0 blockers outstanding)

Reviewed cold against the code on disk before reading the implementation notes, then a second
independent model re-reviewed the full diff. Round 1 found one substantive gap and bounced it back;
round 2 is clean on both.

Round 1: one major, fixed in fbcb42c

❌ The fast path was unobserved. Deleting the memoized branch left every test green: the boolean
it returns is bit-identical to the scanned one, so the SQL tests could not tell the two apart, and
the new gtest exercises MarksInCompressedFile without going through the reader. The whole
user-visible effect of the change therefore rested on a branch nothing asserted, in a code path that
has been reverted twice.

Fixed by counting the fast path with a ProfileEvent and asserting a non-zero delta from a Wide
one-column LowCardinality read. The two mutations are complementary and both were run: forcing the
fast path to return false (optimization stops firing) reddens 04143 but not the new test; deleting
the fast path entirely (memoization stops firing, optimization still works via the scan) reddens the
new test while 04143, 04201, 04144, 04614, 04141, 04142 and the gtest all stay green.
A negative control confirms the counter discriminates rather than being always-on: a Compact part
reads 0, because the one-column guard rejects it and the scan runs.

⚠️ Two further round-1 items, both fixed: #103662 added two version-only-DictionaryKeys tests that
the acceptance gate had skipped (both pass unchanged, so the gate is now seven tests), and a dead
array copy in the gtest.

Round 1: two disagreements, with evidence

💡 A finding asserted a repository convention of backticking method names in comments. Measured across
src/Formats and src/Storages/MergeTree comments: 68 bare getFoo() against 66 backticked, so
there is no convention to violate.

💡 A concern that the new performance test could redden CI. report.py does set a failure status for
slow-average tests, but performance_tests.py discards that status and fails only on errors or on
more than ten slower queries, neither of which this matches.

Round 2: clean

Second model: 0 findings over the full diff. My own re-review: substitution exactness re-derived
independently for every bound the single caller can pass, both #105605 guards confirmed
byte-identical to master so neither revert class is reopened, and the invariant carriers enumerated
from scratch matched with no divergence.

One noted-not-blocking item: the new test reads a ProfileEvent from system.query_log, which holds
the initiator's counters only, so a fully-remote read would see zero. It cannot arise here:
parallel_replicas_local_plan defaults to true, the test pins no-random-settings, and the fixture
is a single 8192-row part. The closest precedent asserts an exact LoadedMarksFiles value the same
way and has no failures in the parallel-replicas job in 30 days.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9dc681d]

Summary: ✅


AI Review

Summary

This PR replaces the per-mark linear scan in MergeTreeReaderStream::hasAtMostNDistinctMarks with a run-skipping std::upper_bound walk and adds a focused performance benchmark. The code path itself looks consistent with the existing LowCardinality mark-ordering contract, but the PR metadata was not updated after the implementation switch, so the changelog and the quoted benchmark evidence currently describe a reverted approach rather than the code in this diff.

PR Metadata
  • Changelog category: Performance Improvement is correct for the actual change.
  • Changelog entry: required, but the current text is stale because it says the number of distinct mark positions is precomputed once per marks file and reused. That implementation was reverted; the diff now performs binary searches over the marks instead.
  • Suggested replacement text: 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 no longer rescans every mark of the whole part on each read task, so these queries on tables with a smallindex_granularity are no longer several times slower since 26.6.
  • The Description section also still documents the reverted MarksInCompressedFile::Builder::flushBlock memoization path and its tradeoffs, so it should be rewritten to match the std::upper_bound implementation in this diff.
Tests
  • ⚠️ The quoted 25.5s -> 7.9s improvement in the PR body belongs to the reverted precomputed-count approach. Please replace it with the same before/after measurement for the current binary-search implementation, or link that measurement explicitly.
Final Verdict

Update the PR description, changelog entry, and quoted performance evidence to match the current binary-search implementation before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 15/15 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Answer
a Deterministic repro? Yes. Issue's fixture verbatim (10M rows, index_granularity = 8 -> 1.25M marks across 4 Wide parts) plus the N=1500 UNION ALL. Primary oracle is the system.trace_log CPU sample share in hasAtMostNDistinctMarks, not wall clock: 63-65% of samples on master, stable across 3 runs.
b Root cause explained? Yes. The prefilter's loop bound is the whole part's mark count (MergeTreeReaderWide.cpp:311 -> the stream's marks_count), and it runs once per read task per LowCardinality column (single caller, MergeTreeReaderWide.cpp:499). Its early exit only fires on a multi-dictionary part, so the single-dictionary case always pays the full scan, and DeserializationPrefixesCache is per read pool so nothing dedupes the verdict.
c Fix matches root cause? Yes. The redundant recomputation is removed by computing the count once in MarksInCompressedFile::Builder::flushBlock and storing it on the object MarkCache keys per mark file. No widened bound, no disable setting, no change to what the check means.
d Test intent preserved / new tests? Yes. No existing test modified or weakened. New TEST(Marks, DistinctMarksCapped), new 05042_low_cardinality_uniform_marks_precomputed (asserts the fast path is actually taken, via a new ProfileEvent), plus tests/performance/low_cardinality_many_marks_point_lookups.xml.
e Demonstrated in BOTH directions? Yes. ig=8: 25.5s -> 7.9s, prefilter CPU share 64% -> under 1.5%. Full-query result checksum identical on both binaries (4500 6624071222971776645). The discriminating arm holds: at index_granularity = 8192 (~1000x fewer marks) the master-side cost is already only ~0.5%, so the cost scales with marks per part as diagnosed.
f General across CODE paths? Yes. Both construction paths funnel through flushBlock (create/addAllMarks and the streaming addMarks), and both consumers of the callback benefit: SerializationLowCardinality and SerializationObject's safe_has_uniform_marks_callback for JSON dynamic subcolumns. The original scan is kept as a fallback for the cases the memo cannot answer.
g Generalizes across INPUTS? Yes. Verified live: single-dictionary, multi-dictionary (200k distinct), Compact parts, non-adaptive marks (index_granularity_bytes = 0), JSON subcolumns, index_granularity 8 and 8192 - all byte-identical to master. The gtest covers 0/1/2/3/many groups, empty, single mark, a repeat after a gap, and a transition landing exactly on a MARKS_PER_BLOCK boundary, over both paths at chunk sizes 1/7/255/256/257/300/511/513.
h Backward compatible? Yes, nothing engaged. In-memory only: the on-disk .mrk/.mrk2 format is read into plain marks and compressed afterwards, so nothing is persisted or sent over the wire. No new setting, hence no SettingsChangesHistory.cpp entry.
i Invariants and contracts preserved? Yes. The boolean is bit-identical: the fast path is guarded to answer only when it provably equals the scan (one column per mark, stored array equal to the scanned count, requested bound below the cap), otherwise the original loop runs. The accumulator is a compare and a conditional increment inside the loop that already visits every mark, with no second pass. MarksInCompressedFile remains immutable and thread-safe, which is what keeps the thread-pool SerializationObject consumer correct.

Oracle liveness: four independent mutations were built and shown to fail the relevant test. Dropping the cross-block carry and ignoring offset_in_decompressed_block each redden Marks.DistinctMarksCapped in different cases. Forcing the fast path to return false (the optimization stops firing) reddens 04143_low_cardinality_single_dict_read_amplification (1 vs 0). Deleting the fast path entirely (the optimization still fires, but via the scan) reddens only the new 05042 test (1 vs 0) while all five other tests and the gtest stay green - so the memoization itself is observed, and a later silent revert of it cannot pass CI.

Acceptance gate (7 tests): 05042_low_cardinality_uniform_marks_precomputed, 04143_low_cardinality_single_dict_read_amplification, 04201_low_cardinality_multiple_dicts_single_mark, 04144_low_cardinality_map_wrong_value_nonadaptive, 04614_ownership_validator_prefix_cache_shared_dictionary, 04141_variant_low_cardinality_version_only_keys and 04142_array_low_cardinality_version_only_keys all pass, and pass 50x each (350/350) under the randomized runner. unit_tests_dbms --gtest_filter='*Mark*:*Format*': 111/111.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fix pushed: 038c4344cb26c72

Build (arm_tidy) was PR-caused: clang-tidy-22 rejected the index loop I added in referenceDistinctMarksCapped (gtest_marks.cpp:82) with modernize-loop-convert, since the index is only ever used as plain[i]. Converted to the range form. Reproduced and verified locally with clang-tidy-22: 1 error before, 0 after, and reintroducing the index form brings it back. Marks.* gtests pass 60/60; breaking the cross-element last carry in the converted loop reddens Marks.DistinctMarksCapped, so the loop is still load-bearing. The file's other index loops use the index in a bound or a diagnostic message, so they do not qualify and are untouched.

Also wrapped the method and constant names in my new comments in inline code, per AGENTS.md.

Fast test / 04506_cascades_join_commutativity_using_types is not reachable from this change, measured rather than assumed:

  • 04506 declares only UInt32, Int64 and String columns. The callback this PR touches has exactly two consumers, SerializationLowCardinality and SerializationObject, so nothing in that test enters the modified path.
  • It failed at 60030ms against the 60s cap. Its own healthy runs already reach 52940ms (p95 26.9s, 74 of 3474 runs over 30s, 9 over 45s), so it sits close to the cap on its own.
  • The run at my head was not slow: its p50 was 150ms and p99 3766ms, faster than all 14 other Fast test runs in the surrounding 8 hours. My own new test cost 750ms.
  • 210 distinct tests hit that same 60s cap in the last 30 days.

I have not changed 04506 or its budget: it is not my test, and the one-line timing margin belongs to its owner. The fresh run on this head will show whether it recurs.

Session id: cron:clickhouse-maint-slot-14:20260824-164800

@Avogar Avogar self-assigned this Aug 24, 2026
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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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
  • StressHouse run: a632d83d-7dbd-4820-98ec-e2d678f442bf
  • MIRAI run: a8ce7dd9-7281-43df-97f9-17fe69cc46bf
  • PR check IDs:
    • clickbench_246677_1787611567
    • clickbench_246683_1787611567
    • clickbench_246694_1787611567
    • tpch_adapted_1_official_246706_1787611567
    • tpch_adapted_1_official_246720_1787611567
    • tpch_adapted_1_official_246748_1787611568

`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]>
@Avogar

Avogar commented Aug 24, 2026

Copy link
Copy Markdown
Member

I've pushed a different implementation of this fix and reverted the previous one. Reasoning, for the record.

What changed

hasAtMostNDistinctMarks answers the same question by binary search instead of from a precomputed count. Mark positions within a stream are non-decreasing, so equal marks form contiguous runs and the end of each run is one std::upper_bound away. The loop walks runs instead of marks: at most max_transitions binary searches, roughly 36 mark decodes instead of 1.25M on the reproducer's part.

This isn't a new assumption. MergeTreeReaderStreamSingleColumn::getRightOffset already did exactly this upper_bound over the same DictionaryKeys stream a few lines below, so the ordering invariant is already load-bearing in this file. Both now share a findNextDifferentMark helper.

Why this rather than the precomputed count

  • It keeps a LowCardinality-specific question out of a generic container. MarksInCompressedFile backs every marks file in the server; the previous version made all of them pay a compare and a branch per mark at build time, and carry a byte of state, to answer something only LowCardinality dictionary streams ask.
  • It is exact for any bound. The stored count saturated at 3, so it could only answer max_transitions < 3; any other caller silently fell back to the whole-part scan.
  • It removes the fallback path. The previous version needed a getNumColumns() == 1 && getNumRows() == marks_count && max_transitions < DISTINCT_MARKS_CAP guard plus the original scan for the cases the stored value could not describe, leaving two paths for one question.
  • No new ProfileEvent. UniformMarksCheckFromPrecomputedCount existed only so a test could observe which path ran; with one path there is nothing to observe.
  • The net change is +33/-14 in one function plus a shared helper, against ~295 lines across 9 files.

The semantics are unchanged, so no new correctness test is needed: 04143, 04144, 04201 and 04614 from #105605 already cover them, and 04143 in particular fails if the optimization stops firing. The perf test is kept, with the query formatted one branch per line.

Unrelated findings while measuring this

Two further regressions show up on the same reproducer, neither in this code path:

  • use_query_condition_cache costs about 4.4s on 26.8 and nothing on 26.5. QueryConditionCache::write allocates and zeroes a per-part bitmap sized by the part's mark count, once per read task and again from ReadFromMergeTree::selectRangesToRead, which is the same O(marks per part) per-independent-read shape as the bug this PR fixes. It accounted for 35% of CPU samples in a profile of the reproducer.
  • The query front-end (parse, analysis, plan, pipeline build) on the 1500-branch UNION ALL went from 2.54s to 3.36s, measured against an empty table so nothing is read.

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 use_query_condition_cache explicitly and keep the part layout identical across binaries, since both of those confound the comparison badly.

/// 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)

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.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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 eed16ec35a84e76a (base), the reverted precomputed-count version fbcb42cd91a151e, and your 9dc681d4ce1513f. Build IDs asserted against the live server per arm. Both confounders controlled: use_query_condition_cache pinned in SETTINGS on every query and measured at 0 and 1; the fixture inserted once, SYSTEM STOP MERGES, then all three servers pointed at that same data directory, each run asserting the layout against a canonical system.parts snapshot and aborting on drift.

Fixture is the issue body verbatim: 9 Wide parts x 138,996 marks, with exchange.dict and currency.dict at exactly 2 distinct mark positions in all 9, so this is the single-dictionary case where the old early exit never fires.

N=1500, max_threads = 1, 3 runs per cell after a discarded warm-up. Oracle is the share of trace_type='CPU' samples whose stack contains hasAtMostNDistinctMarks, joined by query_id:

arm use_query_condition_cache query_duration_ms (median) samples in prefilter
base 0 26872 60.80%
base 1 27437 59.79%
precomputed 0 11341 0.31%
precomputed 1 11594 0.27%
yours 0 11724 0.43%
yours 1 11090 0.42%

Precomputed vs yours is -3.3% at qcc=0 and +4.5% at qcc=1. The sign flips between settings, so that residual is noise, not a difference between the designs. use_query_condition_cache moved the total by under 3% at this scale, so your ~4.4s figure needs the production-scale shape.

The mark-file build cost you cited is where they genuinely differ. SYSTEM DROP MARK CACHE, then a query touching every mark of every part; each run confirms LoadedMarksCount = 5,000,064, LoadedMarksFiles = 36, MarkCacheMisses = 36. 25 runs per arm, WaitMarksLoadMicroseconds:

arm median p25 min
base 173624 170888 168471
precomputed 174854 172813 170605
yours 172885 169635 168294

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, QueryConditionCache::write first, and will not touch either here.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9dc681d4c with master 977ba7e1a (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
Binary Master PR Δ
programs/clickhouse-stripped 709.23 MiB 706.19 MiB -3.04 MiB (-0.43%)

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 units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Filed the first of the two regressions you flagged: #116259. It is not the write-side allocation itself but its cause on this reproducer, an unindexed table storing each predicate under two cache keys instead of one, so two O(marks per part) bitmaps are allocated where one suffices. Entries drop 14370 to 7500 and bytes 452.7 MB to 236.3 MB on your shape; wall clock is unchanged at that scale and I do not claim your 4.4s as mine. The front-end regression is still to come.

@Avogar
Avogar added this pull request to the merge queue Aug 25, 2026
Merged via the queue into ClickHouse:master with commit e0ba603 Aug 25, 2026
184 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 25, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo labels Aug 25, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 25, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 25, 2026
Backport #116134 to 26.8: Do not rescan the whole part's marks on every LowCardinality read
@groeneai

Copy link
Copy Markdown
Collaborator Author

Filed the second of the two regressions you flagged: #116348.

The front end did not get slower. With use_statistics = 0 on official 26.5 / 26.6 / 26.7 / 26.8 binaries the ladder is 1705 / 1796 / 1825 / 1748 ms, so the whole delta you measured is statistics loading during planning. MergeTreeData::getConditionSelectivityEstimator memoizes only in cached_estimator, which only the background refreshStatistics task writes, so until it publishes each of the 1500 branches re-reads and re-merges every part's statistics. Reusing the merged payload within the query takes statistics reads on the reproducer from 85573500 bytes to 57049, flat in the branch count instead of linear, with estimates byte-identical.

fm4v added a commit that referenced this pull request Aug 25, 2026
Backport #116134 to 26.6: Do not rescan the whole part's marks on every LowCardinality read
@fm4v fm4v removed the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 26, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 26, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
Avogar added a commit that referenced this pull request Sep 8, 2026
Backport #116134 to 26.7: Do not rescan the whole part's marks on every LowCardinality read
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
serhiy-bzhezytskyy pushed a commit to serhiy-bzhezytskyy/ClickHouse that referenced this pull request Oct 2, 2026
… 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport v26.7-must-backport v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MergeTree: LowCardinality single-dictionary detection scans the whole part's marks on every read, causing severe CPU regression

6 participants