Skip to content

Compressed data is decompressed repeatedly for a single query #99236

Closed

Description

@bobrik

Company or project name

No response

Describe the unexpected behaviour

I have a table (the full database copy in the repro section):

CREATE TABLE stack_map_v2
(
    `id` UInt128 CODEC(NONE),
    `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
    `seen` datetime CODEC(ZSTD(1))
)
ENGINE = ReplacingMergeTree(seen)
PRIMARY KEY (id, stack)
SETTINGS index_granularity = 256

I have a copy of this table that was populated with the following settings (see #98968):

  • low_cardinality_use_single_dictionary_for_part=1
  • low_cardinality_max_dictionary_size=1048576
CREATE TABLE stack_map_v2_single_dict
(
    `id` UInt128 CODEC(NONE),
    `stack` Array(LowCardinality(String)) CODEC(ZSTD(1)),
    `seen` datetime CODEC(ZSTD(1))
)
ENGINE = ReplacingMergeTree(seen)
PRIMARY KEY (id, stack)
SETTINGS index_granularity = 256

The second table is much smaller even with toy data (354MiB -> 155MiB), but unfortunately it is much slower to query due to repeated decompressions.

Bad query (single dict): the amount of data read from disk is 50x (!) the table size!

Image

Good query (baseline table): everything seems in order in terms of read data.

Image

Here's the flamegraph at the time of slow read:

Image

Which ClickHouse versions are affected?

26.1 and 25.10 reproduce with the provided data.

How to reproduce

Download and extract the database:

curl -s https://r2.ivan.computer/clickhouse-extra-read-repro.tar | tar -C /tmp -xvf-

Run clickhouse-local pointed to the database above:

docker run --rm -it -v /tmp/repro:/tmp/repro clickhouse/clickhouse-server:25.10.3.100 clickhouse-local --path /tmp/repro

Select a lot of data (fast on either table, faster with a single dict, but using more memory):

:) select sum(length(stack)) from (SELECT id, stack FROM stack_map_v2 WHERE seen > '2026-03-08 04:00:00')

   ┌─sum(length(stack))─┐
1. │          102617735 │ -- 102.62 million
   └────────────────────┘

1 row in set. Elapsed: 2.895 sec. Processed 2.51 million rows, 1.50 GB (865.27 thousand rows/s., 516.53 MB/s.)
Peak memory usage: 31.00 MiB.
:) select sum(length(stack)) from (SELECT id, stack FROM stack_map_v2_single_dict WHERE seen > '2026-03-08 04:00:00')

   ┌─sum(length(stack))─┐
1. │          102257695 │ -- 102.26 million
   └────────────────────┘

1 row in set. Elapsed: 1.625 sec. Processed 2.37 million rows, 534.10 MB (1.46 million rows/s., 328.68 MB/s.)
Peak memory usage: 265.92 MiB.

Select a little bit of data (much slower with a single dict despite querying for less data):

:) select sum(length(stack)) from (SELECT id, stack FROM stack_map_v2 WHERE seen > '2026-03-11 04:00:00')

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

1 row in set. Elapsed: 1.801 sec. Processed 2.48 million rows, 481.58 MB (1.38 million rows/s., 267.46 MB/s.)
Peak memory usage: 23.83 MiB.
:) 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: 27.805 sec. Processed 2.51 million rows, 692.90 MB (90.40 thousand rows/s., 24.92 MB/s.)
Peak memory usage: 339.64 MiB.

Expected behavior

Smaller amounts of data selected mean faster queries, or at least not slower.

Error message and/or stacktrace

No response

Additional context

No response

Activity

  1. added
    unexpected behaviour
    on Mar 11, 2026
  2. PedroTadim commented on Mar 11, 2026

    @PedroTadim
    Member

    Hello! The dictionary is going to be applied to the whole part. If a query has to read a few granules from it, it still has to decompress it entirely. I see it only gets an advantage in full scans.

  3. bobrik commented on Mar 11, 2026

    @bobrik
    ContributorAuthor

    @PedroTadim, I think you skipped over some key parts in the report.

    My whole table is 155MiB, there's 8.10GiB read from disk to fulfill the query. That's 50x more than reading it entirely.

    The dict is less than 5MiB:

    ivan@cube:~$ ls -lh /tmp/repro/data/default/stack_map_v2_single_dict/*/stack.dict.bin
    -rw-r--r-- 1 ivan ivan 2.9M Mar 11 06:13 /tmp/repro/data/default/stack_map_v2_single_dict/all_1_6_2/stack.dict.bin
    -rw-r--r-- 1 ivan ivan 1.3M Mar 11 06:13 /tmp/repro/data/default/stack_map_v2_single_dict/all_7_7_1/stack.dict.bin
    
  4. bobrik commented on Mar 11, 2026

    @bobrik
    ContributorAuthor

    I made this change:

    diff --git a/src/DataTypes/Serializations/SerializationLowCardinality.cpp b/src/DataTypes/Serializations/SerializationLowCardinality.cpp
    index c7325aab43a..5e20aadaa82 100644
    --- a/src/DataTypes/Serializations/SerializationLowCardinality.cpp
    +++ b/src/DataTypes/Serializations/SerializationLowCardinality.cpp
    @@ -675,6 +675,12 @@ void SerializationLowCardinality::deserializeBinaryBulkWithMultipleStreams(
                     !global_dictionary || index_type.need_update_dictionary || low_cardinality_state->need_update_dictionary;
                 if (index_type.need_global_dictionary && need_update_dictionary)
                 {
    +                const char * reason =
    +                    !global_dictionary                                    ? "no dictionary loaded yet" :
    +                    index_type.need_update_dictionary                     ? "NeedUpdateDictionary flag set in index stream" :
    +                    low_cardinality_state->need_update_dictionary         ? "non-continuous read (mark range skipped)" :
    +                                                                            "unknown";
    +                fprintf(stderr, "Opening and decompressing dictionary because: %s\n", reason);
                     read_dictionary();
                     low_cardinality_state->need_update_dictionary = false;
                 }
    

    I'm seeing a lot of these log lines with it:

    Opening and decompressing dictionary because: non-continuous read (mark range skipped)
    Opening and decompressing dictionary because: non-continuous read (mark range skipped)
    Opening and decompressing dictionary because: non-continuous read (mark range skipped)
    Opening and decompressing dictionary because: non-continuous read (mark range skipped)
    Opening and decompressing dictionary because: non-continuous read (mark range skipped)
    Opening and decompressing dictionary because: non-continuous read (mark range skipped)
    Opening and decompressing dictionary because: non-continuous read (mark range skipped)
    Opening and decompressing dictionary because: non-continuous read (mark range skipped)
    Opening and decompressing dictionary because: non-continuous read (mark range skipped)
    

    This makes no sense as there's only one dictionary for the part.

    Commenting out this need_update_dictionary = true helps:

        if (!settings.continuous_reading)
        {
            low_cardinality_state->num_pending_rows = 0;
    
            /// Remember in state that some granules were skipped and we need to update dictionary.
            low_cardinality_state->need_update_dictionary = true;
        }

    It makes the single dict table query succeed in 0.32s with one dictionary open per thread (arguably it should be opened once, but who's counting). The multiple dict table (the default behavior) runs in 0.93s, which slower.

    I think there are two ways to go about this.

    1. The simple and straightforward optimization is to stop reload the dictionary if there's only one of them.
    2. The more involved fix is to do some sort of caching for multiple dictionaries for discontinuous reads. It's clear that even with multiple dictionaries it is much cheaper to cache and reuse them. There might be some weird cases where it doesn't hold.
  5. bobrik commented on Mar 11, 2026

    @bobrik
    ContributorAuthor

    I might be able to figure out the patch for the first approach here.

  6. PedroTadim commented on Mar 13, 2026

    @PedroTadim
    Member

    Hello again! You are right, there is something missing for sure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    unexpected behaviour

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions