Skip to content

Do not invalidate dictionary if there is only one of them - #99285

Merged
Avogar merged 3 commits into
ClickHouse:masterfrom
bobrik:ivan/single-dict-no-reload
Apr 2, 2026
Merged

Avogar merged 3 commits into
ClickHouse:masterfrom
bobrik:ivan/single-dict-no-reload

Conversation

@bobrik

@bobrik bobrik commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

There are cases where having one big dictionary helps quite a bit:

  • low_cardinality_use_single_dictionary_for_part=1
  • low_cardinality_max_dictionary_size=1048576

Prior to this patch discontinuous reads caused repeated invalidation of the dictionary, which gets expensive when a dictionary is large. With this change the dictionary is only invalidated if there's more than one dictionary associated with the part.

Closes #99236.

Changelog category (leave one):

  • Performance Improvement

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

Faster discontinuous queries for LowCardinality columns with a single dictionary.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Medium Risk
Touches LowCardinality bulk deserialization state and dictionary refresh logic; an incorrect single-dictionary detection could lead to stale dictionaries or read errors in edge cases.

Overview
Improves performance of discontinuous reads for LowCardinality columns by not invalidating/re-reading the cached per-part dictionary when the part is detected to contain exactly one dictionary (tracked via a new single_dictionary_for_part flag set after the first dictionary read reaches EOF).

Adds a stateless regression test that exercises a selective PREWHERE query and asserts bounded ReadCompressedBytes to catch dictionary re-decompression/read amplification, plus a correctness check for multi-dictionary cases.

Written by Cursor Bugbot for commit 0c4cefe72e655253880633d8af2bdf8b2c0d316a. This will update automatically on new commits. Configure here.

@bobrik

bobrik commented Mar 11, 2026

Copy link
Copy Markdown
Contributor Author

I would like to write a test for this, but I'm struggling to understand how to do this. The behavior depends on low_cardinality_use_single_dictionary_for_part, which can only be set in the profile: #98968 (comment).

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bae33b1]

Summary: ❌

job_name test_name status info comment
Stress test (arm_msan) failure
Server died FAIL cidb IGNORED
MemorySanitizer: use-of-uninitialized-value (STID: 2410-47e0) FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR optimizes LowCardinality deserialization for wide parts by avoiding dictionary invalidation/reload on discontinuous reads when a part is detected to use a single dictionary, and adds focused stateless regressions for version-only-key streams and read-amplification behavior. I reviewed all touched files and did not find new correctness, safety, or performance issues beyond already-posted bot comments; no additional inline findings were posted.

Missing context
  • ⚠️ Several CI checks are still pending, so full CI signal is not yet available.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 12, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good!

Also, I'd like to have input from @KochetovNicolai - maybe there is a more generic way to solve it? By not re-reading dictionary if it appears to be the same.

@bobrik
bobrik force-pushed the ivan/single-dict-no-reload branch from 03a6dab to 74a2bcb Compare March 12, 2026 04:50
@bobrik

bobrik commented Mar 12, 2026

Copy link
Copy Markdown
Contributor Author

Some sort of cache for deserialized dictionaries would be great as a generic solution. I don't think I'm in a position to make that happen though.

@bobrik
bobrik force-pushed the ivan/single-dict-no-reload branch 2 times, most recently from 9909840 to 0c4cefe Compare March 13, 2026 00:40

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests have failed, and CI found memory safety issues.

@bobrik

bobrik commented Mar 13, 2026

Copy link
Copy Markdown
Contributor Author

I think the eof check bumps into some corner cases. I'm checking what can be done to make it sound.

Two observations from writing a test for this:

  1. Having 64k rows doesn't trigger it, 128k does (with the same dictionary size).
  2. Having a smaller stack frames doesn't trigger it either.

There's an visible order of magnitude visible effect. Maybe there is a cache somewhere that gets disabled.

@bobrik
bobrik force-pushed the ivan/single-dict-no-reload branch 3 times, most recently from 6fc93b8 to 400d950 Compare March 13, 2026 17:15
@bobrik
bobrik force-pushed the ivan/single-dict-no-reload branch from 400d950 to 9f03306 Compare March 13, 2026 17:59
@bobrik
bobrik requested a review from alexey-milovidov March 14, 2026 01:22
@bobrik

bobrik commented Mar 14, 2026

Copy link
Copy Markdown
Contributor Author

Having 64k rows doesn't trigger it, 128k does (with the same dictionary size).

I couldn't let this go, so I tried bothering Claude about it. I think it nailed it:

Root cause: When preferred_block_size_bytes causes the effective block size to land at a value where ceil(rows/granularity) does not evenly divide the total mark count, the part gets split into 3+ read blocks. If a split-point lands mid-way through the alternating PREWHERE filter pattern (starting on a failing granule), optimize()'s shrink fires asymmetrically — it collapses failing granule entries in rows_per_granule to 0. In continueReadingChain, those 0-row entries call toNextMark() which advances Stream::current_mark without advancing DelayedStream::current_mark. The next actual read then sees position() != expected → continue_reading=false → seeks back to dict start → re-reads the dictionary ~1000 times.

Settings that eliminate the amplification:

  • preferred_block_size_bytes=0 (or any large value like 10000000) with max_block_size ≥ total rows in part — ensures at most 1 read block per part, no shrink-induced discontinuities.
  • max_block_size=65536 with preferred_block_size_bytes=0 also works because 65536/32=2048 evenly divides 4096.

Both setting sets indeed help with the synthetic table in the test.

Having a really large max_block_size and preferred_block_size_bytes=0 in also helps my repro in #99236:

  • Baseline: 26.3s
SELECT sum(length(stack))
FROM
(
    SELECT
        id,
        stack
    FROM stack_map_v2_single_dict
    WHERE seen > '2026-03-11 04:00:00'
)
   ┌─sum(length(stack))─┐
1. │             657712 │
   └────────────────────┘

1 row in set. Elapsed: 26.288 sec. Processed 2.51 million rows, 690.36 MB (95.56 thousand rows/s., 26.26 MB/s.)
Peak memory usage: 296.67 MiB.
  • With settings: 4.7s
SELECT sum(length(stack))
FROM
(
    SELECT
        id,
        stack
    FROM stack_map_v2_single_dict
    WHERE seen > '2026-03-11 04:00:00'
)
SETTINGS preferred_block_size_bytes = 0, max_block_size = 10000000
   ┌─sum(length(stack))─┐
1. │             657712 │
   └────────────────────┘

1 row in set. Elapsed: 4.691 sec. Processed 2.35 million rows, 549.67 MB (500.65 thousand rows/s., 117.17 MB/s.)
Peak memory usage: 363.66 MiB.

This is of course strictly worse than the patch in this PR, which zips through the same query in 0.5s:

   ┌─sum(length(stack))─┐
1. │             657712 │
   └────────────────────┘

1 row in set. Elapsed: 0.490 sec. Processed 2.18 million rows, 423.77 MB (4.44 million rows/s., 863.97 MB/s.)
Peak memory usage: 156.41 MiB.

Using these settings to counter the behavior doesn't sound like the right thing to do.

The settings also do not help much when I try to select 6k ids out of 117 million, this is still slow:

select count(), sum(length(stack)) from (SELECT id, stack FROM open.stack_map_v2 WHERE id in ['6k ids here']) SETTINGS preferred_block_size_bytes = 0, max_block_size = 131072000000
  • Baseline:
   ┌─count()─┬─sum(length(stack))─┐
1. │    5057 │             636900 │
   └─────────┴────────────────────┘

1 row in set. Elapsed: 40.327 sec. Processed 9.61 million rows, 242.95 MB (238.22 thousand rows/s., 6.02 MB/s.)
Peak memory usage: 2.47 GiB.
  • With settings:
   ┌─count()─┬─sum(length(stack))─┐
1. │    5049 │             635945 │
   └─────────┴────────────────────┘

1 row in set. Elapsed: 39.433 sec. Processed 11.28 million rows, 323.56 MB (286.17 thousand rows/s., 8.21 MB/s.)
Peak memory usage: 2.68 GiB.

My hope is that this "no invalidation for a single dict" change will make it right, but I can't really test it without jumping through the deployment process hoops, which takes some time.

@bobrik

bobrik commented Mar 14, 2026

Copy link
Copy Markdown
Contributor Author

Two s3 related tests failed as they still saw amplification:

  • Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel)
  • Stateless tests (amd_tsan, s3 storage, parallel, 2/2)

I just pushed an update which I think should help.

@bobrik
bobrik force-pushed the ivan/single-dict-no-reload branch 2 times, most recently from b4bdb24 to d7ef68d Compare March 14, 2026 16:42
@bobrik
bobrik force-pushed the ivan/single-dict-no-reload branch from d7ef68d to 4226171 Compare March 14, 2026 18:12
@bobrik

bobrik commented Mar 16, 2026

Copy link
Copy Markdown
Contributor Author

I deployed it internally. Here's the query:

select count(), sum(length(stack)) from (SELECT id, stack FROM r0.stack_map_v2_replica WHERE id in [<6k ids>])

I ran it from my puny account with a 4 thread limit. Before and after did run on different shards, but they are not very different in size (less than 2x).

Before:

1 row in set. Elapsed: 407.225 sec. Processed 8.09 million rows, 588.11 MB (19.87 thousand rows/s., 1.44 MB/s.)
Peak memory usage: 2.61 GiB.

After:

1 row in set. Elapsed: 0.823 sec. Processed 4.71 million rows, 540.71 MB (5.72 million rows/s., 657.05 MB/s.)
Peak memory usage: 1.28 GiB.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is very interesting! But I'd also like to ask @KochetovNicolai for review.

/// Keyed by column name. True if the DictionaryKeys stream for that LowCardinality column
/// has at most 2 distinct consecutive compressed offsets across all marks, meaning the part
/// has a single dictionary. Populated in addStream(), consumed in deserializePrefix().
std::unordered_map<String, bool> low_cardinality_single_dictionary_for_column;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a DeserializationPrefixesCache mechanism; probably we'd better reuse it.

It is also possible that one part is read from multiple threads. I think in this case we will also have multiple reads (but it will be parallel, so maybe not important).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't we need to pass marks loader here, also in a map, to be able to make the determination of whether there's only one dictionary in MergeTreeReaderWide::deserializePrefix? Is that what you expect to see?

Maybe I'm missing something.

@Avogar Avogar self-assigned this Mar 20, 2026

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea is really good — detecting single-dictionary parts via marks and skipping redundant re-reads is the right approach. However, I think the current implementation has two main disadvantages:

1) In multi-threaded reads from the same part, the dictionary is still read multiple times

Right now the dictionary is read independently by every thread during the first granule's processing (!global_dictionary is true in deserializeBinaryBulkWithMultipleStreams). If 8 threads read the same part, each one reads the dictionary from disk once and keeps its own copy in memory.

We can fix this by reading the dictionary in deserializeBinaryBulkStatePrefix instead. For Wide parts, use_specialized_prefixes_and_suffixes_substreams is false, so the prefix and data share the same DictionaryKeys stream. After reading the version (8 bytes), the stream is positioned exactly at the start of the dictionary data — we can read it right there.

MergeTreeReaderWide already has a DeserializationPrefixesCache that is shared across all readers of the same part. The first reader calls deserializeBinaryBulkStatePrefix (which would now read the dictionary), and all subsequent readers get cloned states via DeserializationPrefixesCache::clonePrefixes. The clone copies global_dictionary as a shared_ptr<const IColumnUnique>, so all threads share the same const dictionary object — no memory duplication and no per-thread disk reads.

The existing condition in deserializeBinaryBulkWithMultipleStreams already handles the rest: single_dictionary_for_part=true and global_dictionary != null means read_dictionary() is never called, and the DictionaryKeys stream is effectively unused during per-granule processing.

2) The low_cardinality_single_dictionary_for_column map is too specific

The current approach with a per-column map in MergeTreeReaderWide and special detection logic in addStream is tightly coupled to LowCardinality. It only works for top-level LowCardinality columns and adds LowCardinality-specific code to MergeTreeReaderWide, which shouldn't need to know about serialization internals.

Instead, we can add a generic callback to DeserializeBinaryBulkSettings that checks whether a given substream has uniform marks. SerializationLowCardinality::deserializeBinaryBulkStatePrefix calls it to decide whether to read the dictionary upfront. MergeTreeReaderWide only needs to set this callback — no pre-computed map, no LowCardinality-specific logic in the reader.

In ISerialization::DeserializeBinaryBulkSettings:

/// Returns true if all marks for the given substream have at most
/// `max_transitions` distinct consecutive positions.
std::function<bool(const SubstreamPath &, size_t max_transitions)> has_uniform_marks_callback;

In SerializationLowCardinality::deserializeBinaryBulkStatePrefix:

// ... existing code: read version ...

auto new_state = std::make_shared<DeserializeStateLowCardinality>(keys_version);

bool is_single_dict = settings.has_uniform_marks_callback
    && settings.data_part_type == MergeTreeDataPartType::Wide
    && settings.has_uniform_marks_callback(settings.path, 2);

new_state->single_dictionary_for_part = is_single_dict;

if (is_single_dict)
{
    UInt64 num_keys;
    readBinaryLittleEndian(num_keys, *stream);

    auto keys_type = removeNullable(dictionary_type);
    auto global_dict_keys = keys_type->createColumn();
    dict_inner_serialization->deserializeBinaryBulk(*global_dict_keys, *stream, 0, num_keys, 0);

    new_state->global_dictionary = DataTypeLowCardinality::createColumnUnique(
        *dictionary_type, std::move(global_dict_keys));
}

state = std::move(new_state);

In MergeTreeReaderWide::deserializePrefix, set the callback:

deserialize_settings.has_uniform_marks_callback =
    [&](const ISerialization::SubstreamPath & substream_path,
        size_t max_transitions) -> bool
{
    auto stream_name = IMergeTreeDataPart::getStreamNameForColumn(
        name_and_type, substream_path, ".bin",
        data_part_info_for_read->getChecksums(), storage_settings);
    if (!stream_name)
        return false;

    auto it = streams.find(*stream_name);
    if (it == streams.end())
        return false;

    return it->second->hasAtMostNDistinctMarks(max_transitions);
};

Where hasAtMostNDistinctMarks is a new method on MergeTreeReaderStream — it loads marks (they should already be in the mark cache from addStream) and runs the same transitions-counting loop. This removes low_cardinality_single_dictionary_for_column from MergeTreeReaderWide, moves the detection out of addStream, and makes it work for LowCardinality columns at any nesting level (e.g. inside Array, Tuple, Map). The callback is also generic enough that other serializations could reuse it.

@bobrik
bobrik force-pushed the ivan/single-dict-no-reload branch from 2c8f50a to bd3bb45 Compare March 27, 2026 17:52
@bobrik

bobrik commented Mar 27, 2026

Copy link
Copy Markdown
Contributor Author

@Avogar, I updated the code with your suggestions and rebased on top of the latest master.

Let me know if I got it right.

@Avogar

Avogar commented Mar 27, 2026

Copy link
Copy Markdown
Member

Great! I will take a look early next week

There are cases where having one big dictionary helps quite a bit:

* `low_cardinality_use_single_dictionary_for_part=1`
* `low_cardinality_max_dictionary_size=1048576`

Prior to this patch discontinuous reads caused repeated invalidation of the dictionary,
which gets expensive when a dictionary is large. With this change the dictionary is only
invalidated if there's more than one dictionary associated with the part.

Signed-off-by: Ivan Babrou <[email protected]>
@bobrik
bobrik force-pushed the ivan/single-dict-no-reload branch from bd3bb45 to c5e41a5 Compare March 27, 2026 23:32

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great, thanks!

@clickhouse-gh

clickhouse-gh Bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 97.33% (73/75) · Uncovered code

Full report · Diff report

@Avogar
Avogar added this pull request to the merge queue Apr 2, 2026
Merged via the queue into ClickHouse:master with commit e3e3a90 Apr 2, 2026
158 of 159 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@bobrik, we suspect (just a suspicion, not validated) that this PR introduced one of the most severe problems in master we have had in years - sometimes reading the value of Map for a certain key gives a different value. A lot of tests in CI have failed. I will revert just in case.

@bobrik

bobrik commented Apr 9, 2026

Copy link
Copy Markdown
Contributor Author

A lot of tests in CI have failed

Do you have a link to those tests? Observable CI for this branch was clean.

@Avogar

Avogar commented Apr 9, 2026 •

Copy link
Copy Markdown
Member

This one - https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101051&sha=97ada9aeaa003462ea35690a3fb182c7d7f26a4a&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29

Map(LowCardinality(String), LowCardinality(String)) in table system.query_log. I found that we might have a problem when parts have disabled adaptive granularity (in this case we will have 2 different marks even for 2 dictionaries written in the dictionary stream as we don't write final marks after we write suffix). But for enabled adaptive granularity (which is by default), there is no such problem. So we can't confirm if this change is the problem, but we cannot also find the root cause or other suspicious PRs. So we can try to revert it, wait for some time and check if the failure will reproduce or not

@bobrik

bobrik commented Apr 10, 2026

Copy link
Copy Markdown
Contributor Author

I'm taking a couple of weeks off, but I'll have a look at this when I'm back if it's not sorted by then.

@bobrik

bobrik commented Apr 28, 2026

Copy link
Copy Markdown
Contributor Author

#103662 should address the problem and it comes with a test.

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 pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Compressed data is decompressed repeatedly for a single query

5 participants