Repository navigation
Do not invalidate dictionary if there is only one of them - #99285
Conversation
|
I would like to write a test for this, but I'm struggling to understand how to do this. The behavior depends on |
|
Workflow [PR], commit [bae33b1] Summary: ❌
AI ReviewSummaryThis PR optimizes Missing context
ClickHouse Rules
Final Verdict
|
alexey-milovidov
left a comment
There was a problem hiding this comment.
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.
03a6dab to
74a2bcb
Compare
|
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. |
9909840 to
0c4cefe
Compare
alexey-milovidov
left a comment
There was a problem hiding this comment.
Tests have failed, and CI found memory safety issues.
|
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:
There's an visible order of magnitude visible effect. Maybe there is a cache somewhere that gets disabled. |
6fc93b8 to
400d950
Compare
400d950 to
9f03306
Compare
I couldn't let this go, so I tried bothering Claude about it. I think it nailed it:
Both setting sets indeed help with the synthetic table in the test. Having a really large
SELECT sum(length(stack))
FROM
(
SELECT
id,
stack
FROM stack_map_v2_single_dict
WHERE seen > '2026-03-11 04:00:00'
)
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 = 10000000This is of course strictly worse than the patch in this PR, which zips through the same query in 0.5s: 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
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. |
|
Two s3 related tests failed as they still saw amplification:
I just pushed an update which I think should help. |
b4bdb24 to
d7ef68d
Compare
d7ef68d to
4226171
Compare
|
I deployed it internally. Here's the query: 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: After: |
alexey-milovidov
left a comment
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
2c8f50a to
bd3bb45
Compare
|
@Avogar, I updated the code with your suggestions and rebased on top of the latest Let me know if I got it right. |
|
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]>
bd3bb45 to
c5e41a5
Compare
…ingle-dict-no-reload
LLVM Coverage Report
Changed lines: 97.33% (73/75) · Uncovered code |
e3e3a90
|
@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. |
Do you have a link to those tests? Observable CI for this branch was clean. |
|
|
|
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. |
|
So there is a high chance that this PR was the problem. Unfortunately it's hard to reproduce. I will also try to investigate. It seems like sometimes we can use wrong dictionary, but it's unclear how. |
|
#103662 should address the problem and it comes with a test. |

There are cases where having one big dictionary helps quite a bit:
low_cardinality_use_single_dictionary_for_part=1low_cardinality_max_dictionary_size=1048576Prior 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Faster discontinuous queries for
LowCardinalitycolumns with a single dictionary.Documentation entry for user-facing changes
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
LowCardinalitycolumns by not invalidating/re-reading the cached per-part dictionary when the part is detected to contain exactly one dictionary (tracked via a newsingle_dictionary_for_partflag set after the first dictionary read reaches EOF).Adds a stateless regression test that exercises a selective
PREWHEREquery and asserts boundedReadCompressedBytesto 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.