Skip to content

Parquet ORDER BY <String> LIMIT with s != '' skips no row groups because every minimum is ''; bounding them by their dictionary makes ClickBench Q26 12-16% faster #128233

Closed

Description

@snelheidai

Describe the situation

Parquet ORDER BY s LIMIT n with WHERE s != '' skips no row groups: each row group's min statistic is the empty string. For chunks whose pages are all dictionary-encoded, bounding the row group by its dictionary values that pass the filter skips most: ClickBench Q26 12-16% faster.

Fresh clickhouse local per run, ClickBench Parquet, 4-core Graviton3; median seconds; paired ratio with 95% CI.

Query Data Base Patched Ratio [95% CI]
Q26 WHERE SearchPhrase <> '' ORDER BY SearchPhrase LIMIT 10 100 files 0.462 s 0.386 s 0.839 [0.830, 0.848], n=10
Q26 hits.parquet 0.940 s 0.825 s 0.873 [0.867, 0.878], n=8
Q26 100 S3 objects, 20 ms to first byte 2.574 s 2.321 s 0.899 [0.888, 0.911], n=6
WHERE MobilePhoneModel <> '' ORDER BY MobilePhoneModel LIMIT 10 100 files 0.198 s 0.067 s 0.329 [0.310, 0.348], n=10
same hits.parquet 0.376 s 0.209 s 0.542 [0.514, 0.572], n=8
Q26, page cache dropped before each run 100 files 3.449 s 3.406 s 0.989 [0.983, 0.996], n=4
Q26, 4 processes at once (wall time) 100 files 1.978 s 1.699 s 0.879 [0.811, 0.952], n=4
Control: ORDER BY Title DESC LIMIT 10 100 files 0.259 s 0.263 s 0.998 [0.961, 1.037], n=10
Control: Q25 ... ORDER BY EventTime LIMIT 10 100 files 0.117 s 0.117 s 0.998 [0.949, 1.050], n=10

Base is master 8d5702d8 with #124827 applied (required, still open), not a released version: #124827 passes the String threshold to the reader.

Peak memory of the query (clickhouse local --memory-usage), median of 3 runs (4 for the last row):

Query Data Base Patched
Q26 100 files 164 MB 159 MB
Q26 hits.parquet 68 MB 78 MB
MobilePhoneModel query above 100 files 51 MB 30 MB
WHERE URL <> '' ORDER BY URL LIMIT 10 100 files 560 MB 461 MB
WHERE SearchPhrase <> '' ORDER BY SearchPhrase LIMIT 1000 hits.parquet 72 MB 107 MB
1,024 row groups, each '' and the same 1 MiB value (all bounds tie) 1 file 270 MB 690 MB
Why it happens and what the patch changes

With #124827, ORDER BY <String> LIMIT n passes the top-K threshold to the Parquet reader, which skips a row group when its min/max statistics are beyond the threshold. The statistics include the rows that the filter removes. In ClickBench every row group of SearchPhrase contains empty strings, so its minimum is '' and no row group can be skipped, although rows with '' never reach the sort.

The dictionary of a column chunk whose data pages are all dictionary-encoded holds every value of the chunk. The patch uses it when the statistics cannot bound the row group:

  • Eligibility: the sort column is read as String without conversion; its chunk has no nulls and passes the dictionary filter's check (encoding_stats show only dictionary-encoded data pages, dictionary page within input_format_parquet_dictionary_filter_push_down); the minimum statistic (or maximum for DESC) is '' and a conjunct of the filter rejects '' (s != '', notEmpty(s), s > '', or a LIKE/position/startsWith/endsWith/= condition extracted as a string value filter), or the chunk has no statistics. The filter is PREWHERE or the filter pushed down to the source (filter_actions_dag, already used to prune row groups); Q26 needs the latter, because a condition on the only column read stays a Filter step.
  • When such a row group starts and the threshold is already set, its dictionary page is decoded in the Dictionary stage, before the data pages. The row group's range becomes the minimum and maximum of the dictionary values that can pass: non-empty values, and the values matching the string value filter mask when one is built. The existing check before the data pages then skips the row group. A dictionary decoded this way is reused for the data pages.
  • The range stays with the row group until the file is read, while the dictionary is released with the row group, so the range keeps at most 256 bytes of each bound: a longer minimum is replaced by its prefix, a longer maximum by its prefix with the last byte incremented (if those 256 bytes are all 0xFF, the maximum statistic is kept; without statistics the row group is not bounded). The range only gets wider, so the results don't change, and it takes at most about 0.5 KB per row group whatever the length of the values.
  • If any row group of a file can be bounded this way, row groups are started gradually, as already done when statistics differ (ReadManager::admitTopKRowGroups), so that in a single file most row groups start after the threshold is set.

In the 100 ClickBench files, 182 of 325 row groups have a dictionary-only SearchPhrase chunk (the others fall back to PLAIN pages); Q26 skips 166 of them (event ParquetTopKSkippedRowGroups, new event ParquetTopKRowGroupsBoundedByDictionary). A skipped row group still reads and decompresses its dictionary page, so the decompressed bytes drop only by ~2%; the saving is decoding and filtering 40M of 100M rows. In the single file 75 of 226 row groups are skipped.

Memory: the decoded dictionaries are charged to the Dictionary-stage share of input_format_parquet_memory_high_watermark, the budget the dictionary filter already uses; a dictionary that does not fit is decoded with the data pages as before. Bounded row groups that cannot be skipped keep their dictionary from that stage until their data is read, so with large dictionaries and few skips the peak memory grows up to that budget, as in the last row of the memory table (1,024 row groups, each with '' and the same 1 MiB value, compact statistics ''/'y', so every bound ties with the threshold): about 270 MB in the base and 690 MB patched; 870 MB with 2,048 row groups; 340 MB with input_format_parquet_memory_high_watermark = 1 GiB and 250 MB with 256 MiB. Without the 256-byte limit the same file used 2.4 GB and failed with max_memory_usage = 1 GB, because each bounded row group kept two copies of the 1 MiB value.

Results are identical to the base for 19 variants over the 100 files: ASC/DESC, LIMIT 10 to 3,000,000, OFFSET, !=, notEmpty, >, '' <, LIKE, an extra conjunct, OR (not used for the bound), 1 and 16 threads; for 40 queries over values whose common prefixes are 248 to 263 bytes long, followed by 0x00, a or 0xFF (ASC/DESC, LIMIT 1 to 1000, 1 and 4 threads); and for the memory files. Over S3 both versions make the same number of GET requests (425) and read the same bytes. The new test 05461_parquet_top_k_string_dictionary_bound checks results with the optimization off and on (1 and 4 threads, NULLs, OR, LIKE, DESC, OFFSET, values longer than 256 bytes, 0xFF maxima, equal bounds) and that fewer rows are read.

Which ClickHouse versions are affected?

Tested versions and source commits

Master 8d5702d8ee60 (2026-10-26) with #124827 applied (net diff of its head d33a3f99), local Release builds with clang 21, without ThinLTO. Up to master a7f30854cfbd (2026-10-29), no change in the code paths of the patch applies to these queries with default settings.

How to reproduce

Data, queries and measurement procedure

Data: ClickBench hits_0.parquet ... hits_99.parquet and hits.parquet, with the table from ClickBench's clickhouse-parquet-partitioned/create.sql (ENGINE = File(Parquet, 'hits_*.parquet'), explicit schema); for the single file the path is hits.parquet. For S3, the same table with ENGINE = S3('http://.../hits_*.parquet', ..., 'Parquet') over a local S3 server with 20 ms added before the first byte of each response.

Each run is a new process, as in ClickBench:

clickhouse local --time --format=Null --query="$(cat create.sql); SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY SearchPhrase LIMIT 10"

Per query: one warm-up run of each binary, then pairs of runs in alternating order (10 pairs for 100 files, 8 for the single file, 6 for S3, 4 for the cold and concurrent rows). The table shows medians and the geometric mean of the paired ratios with a Student-t 95% interval. Cold: sync; echo 3 > /proc/sys/vm/drop_caches and the binary read back before each run. Concurrent: 4 processes started together, wall time of the batch. Peak memory: clickhouse local --memory-usage.

SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY SearchPhrase LIMIT 10;
SELECT MobilePhoneModel FROM hits WHERE MobilePhoneModel <> '' ORDER BY MobilePhoneModel LIMIT 10;
SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime LIMIT 10;
SELECT Title FROM hits ORDER BY Title DESC LIMIT 10;

Skipped row groups: SELECT event, value FROM system.events WHERE event LIKE 'ParquetTopK%' after the query in the same clickhouse local call.

Memory file with equal bounds (1,024 row groups of 2 rows; the compact statistics ''/'y' were written into the footer afterwards, which Parquet allows because they bound the values):

INSERT INTO FUNCTION file('eq.parquet', Parquet)
SELECT if(number % 2 = 0, '', concat('x', repeat('ab', 524287), 'a')) AS s FROM numbers(2 * 1024)
SETTINGS output_format_parquet_row_group_size = 2, max_block_size = 64, output_format_parquet_max_dictionary_size = 4194304;

SELECT s FROM file('eq.parquet') WHERE s != '' ORDER BY s LIMIT 10;

Measurement IDs of the table rows: Q26 100 files clickbench-q26-parquet-100files-oneshot, Q26 hits.parquet clickbench-q26-parquet-single-file-oneshot, MobilePhoneModel parquet-100files-mobilephonemodel-nonempty-orderby-limit10-oneshot and parquet-single-file-mobilephonemodel-nonempty-orderby-limit10-oneshot, Title control parquet-100files-title-desc-limit10-oneshot-control.

Expected performance

Expected behavior

A filter that removes the empty string should not stop ORDER BY <String> LIMIT n from skipping row groups whose remaining values are all beyond the threshold. Q26 then decodes mostly the row groups that can hold one of the smallest values, plus the dictionaries of the others.

Related issues and pull requests

Related work

Additional context

Full patch

On top of #124827 (d33a3f99):

diff --git a/src/Common/ProfileEvents.cpp b/src/Common/ProfileEvents.cpp
index 52479e059f6..16aecaecdf0 100644
--- a/src/Common/ProfileEvents.cpp
+++ b/src/Common/ProfileEvents.cpp
@@ -1785,6 +1785,7 @@ The server successfully detected this situation and will download merged part fr
     M(ParquetPrefetcherUsedBytes, "Total bytes of the ranges read by DB::Parquet::Prefetcher that were actually used by the parquet reader.", ValueType::Bytes) \
     M(ParquetDecompressedBytes, "Total uncompressed size of parquet pages (data and dictionary pages) decompressed by the parquet reader.", ValueType::Bytes) \
     M(ParquetPagesDecompressedToSkipRows, "Number of parquet data pages whose decompression was triggered by skipping rows filtered out by PREWHERE (the page may also serve rows read later).", ValueType::Number) \
+    M(ParquetTopKRowGroupsBoundedByDictionary, "The number of parquet row groups whose `ORDER BY ... LIMIT` sort column range was taken from the values of its dictionary that can pass PREWHERE, because its min/max statistics could not bound it", ValueType::Number) \
     M(ParquetTopKSkippedRowGroups, "The number of parquet row groups skipped while reading because their min/max statistics showed that they can't contain rows of the `ORDER BY ... LIMIT` result (see `use_top_k_dynamic_filtering`)", ValueType::Number) \
     M(ParquetFilesSkippedByCachedStatistics, "The number of Parquet files that a read skipped without opening them, because the min/max statistics of the filter columns, kept with the cached file metadata by an earlier read of the same file version, exclude every row group", ValueType::Number) \
     M(ParquetReadMinMaxFromStatistics, "The number of parquet files whose `min` / `max` were computed from column chunk statistics instead of reading the data (see `optimize_min_max_from_files`)", ValueType::Number) \
diff --git a/src/Interpreters/extractStringValueFilters.cpp b/src/Interpreters/extractStringValueFilters.cpp
index 4e05b522ca2..200d792d0d8 100644
--- a/src/Interpreters/extractStringValueFilters.cpp
+++ b/src/Interpreters/extractStringValueFilters.cpp
@@ -326,6 +326,71 @@ void tryExtractConditionsFromAtom(const ActionsDAG::Node * atom, ConditionsByCol
 
 }
 
+static bool filterNodeRejectsEmptyString(const ActionsDAG::Node * filter_node, const String & column_name);
+
+bool filterRejectsEmptyString(const ActionsDAG & filter_dag, const String & filter_column_name, const String & column_name)
+{
+    const auto * root = filter_dag.tryFindInOutputs(filter_column_name);
+    return root && filterNodeRejectsEmptyString(root, column_name);
+}
+
+bool filterRejectsEmptyString(const ActionsDAG & filter_dag, const String & column_name)
+{
+    const auto & outputs = filter_dag.getOutputs();
+    return outputs.size() == 1 && filterNodeRejectsEmptyString(outputs.front(), column_name);
+}
+
+static bool filterNodeRejectsEmptyString(const ActionsDAG::Node * filter_node, const String & column_name)
+{
+    /// Only conjuncts: every row that one of them rejects is filtered out.
+    std::vector<const ActionsDAG::Node *> stack;
+    stack.push_back(skipAliases(filter_node));
+    while (!stack.empty())
+    {
+        const auto * node = stack.back();
+        stack.pop_back();
+        if (node->type != ActionsDAG::ActionType::FUNCTION)
+            continue;
+
+        const String & name = node->function_base->getName();
+        if (name == "and")
+        {
+            for (const auto * child : node->children)
+                stack.push_back(skipAliases(child));
+            continue;
+        }
+
+        if (name == "notEmpty" && node->children.size() == 1)
+        {
+            if (tryGetStringInputName(node->children[0]) == column_name)
+                return true;
+            continue;
+        }
+
+        /// `s != ''`, `s > ''`, and the same with the arguments swapped.
+        if ((name == "notEquals" || name == "greater" || name == "less") && node->children.size() == 2)
+        {
+            for (size_t column_pos : {0, 1})
+            {
+                if ((name == "greater" && column_pos != 0) || (name == "less" && column_pos != 1))
+                    continue;
+                auto constant = tryGetConstString(node->children[1 - column_pos]);
+                if (constant && constant->empty() && tryGetStringInputName(node->children[column_pos]) == column_name)
+                    return true;
+            }
+            continue;
+        }
+
+        /// The conditions of string value filters never match the empty string.
+        ConditionsByColumn conditions_by_column;
+        tryExtractConditionsFromAtom(node, conditions_by_column);
+        auto it = conditions_by_column.find(column_name);
+        if (it != conditions_by_column.end() && !it->second.conditions.empty())
+            return true;
+    }
+    return false;
+}
+
 bool likePatternHasStringValueFilterConditions(const String & pattern)
 {
     return !parseLikePattern(pattern).empty();
diff --git a/src/Interpreters/extractStringValueFilters.h b/src/Interpreters/extractStringValueFilters.h
index 7557b5e99ab..c3cf8e30045 100644
--- a/src/Interpreters/extractStringValueFilters.h
+++ b/src/Interpreters/extractStringValueFilters.h
@@ -27,6 +27,12 @@ class Field;
 StringValueFiltersPtr extractStringValueFilters(
     const ActionsDAG & filter_dag, const String & filter_column_name, const ActionsDAG * row_level_filter = nullptr);
 
+/// Whether the filter expression rejects every row in which the `String` column `column_name` is empty,
+/// i.e. one of its conjuncts is `s != ''`, `notEmpty(s)`, `s > ''` or a condition that `extractStringValueFilters` extracts.
+bool filterRejectsEmptyString(const ActionsDAG & filter_dag, const String & filter_column_name, const String & column_name);
+/// Same for a filter DAG whose only output is the filter.
+bool filterRejectsEmptyString(const ActionsDAG & filter_dag, const String & column_name);
+
 /// Whether a LIKE pattern contains fixed substrings that can be used as a string value filter.
 bool likePatternHasStringValueFilterConditions(const String & pattern);
 
diff --git a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp
index 7930e4bcb1e..753441b034f 100644
--- a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp
+++ b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp
@@ -301,6 +301,11 @@ void ReadManager::finishRowGroupStage(size_t row_group_idx, ReadStage stage, Mem
             ProfileEvents::increment(ProfileEvents::ParquetDictionaryFilterPrunedRowGroups);
             stage = ReadStage::Deliver; // skip the row group
         }
+        else
+        {
+            /// Checked against the threshold in the `OffsetIndex` stage.
+            reader.refineTopKRangeFromDictionary(row_group);
+        }
         release_bloom_filters();
     }
 
@@ -336,10 +341,16 @@ void ReadManager::finishRowGroupStage(size_t row_group_idx, ReadStage stage, Mem
                 break;
             case ReadStage::Dictionary:
                 for (size_t i = 0; i < row_group.columns.size(); ++i)
-                    if (row_group.columns[i].use_dictionary_filter || row_group.columns[i].decode_dictionary_early)
+                {
+                    auto & column = row_group.columns[i];
+                    /// Before the TopN threshold is set, the dictionary could not skip the row group, so it is not
+                    /// decoded separately from the data pages.
+                    column.decode_dictionary_for_top_k = column.top_k_bound_from_dictionary && reader.topKThresholdIsSet();
+                    if (column.use_dictionary_filter || column.decode_dictionary_early || column.decode_dictionary_for_top_k)
                         add_tasks.push_back(Task {
                             .stage = ReadStage::Dictionary,
                             .row_group_idx = row_group_idx, .column_idx = i});
+                }
                 break;
             case ReadStage::ColumnIndexAndOffsetIndex:
                 for (size_t i = 0; i < row_group.columns.size(); ++i)
@@ -1296,7 +1307,7 @@ void ReadManager::runTask(Task task, bool last_in_batch, MemoryUsageDiff & diff)
                 /// The dictionary is decoded here for the dictionary filter, or to estimate the size of the decoded
                 /// strings, see `ColumnChunk::decode_dictionary_early`. The same budget is used for both: if the
                 /// dictionary does not fit, the size of the strings stays unknown.
-                if (column.use_dictionary_filter || column.decode_dictionary_early)
+                if (column.use_dictionary_filter || column.decode_dictionary_early || column.decode_dictionary_for_top_k)
                 {
                     /// Reserve the decoded dictionary's footprint live against the shared pruning-stage
                     /// budget so it is visible to every row group pruning in parallel the moment it is
diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp
index ddfaec04bc6..c22290b7d3d 100644
--- a/src/Processors/Formats/Impl/Parquet/Reader.cpp
+++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp
@@ -83,6 +83,7 @@ namespace ProfileEvents
     extern const Event ParquetPagesDecompressedToSkipRows;
     extern const Event ColumnsCacheHits;
     extern const Event ColumnsCacheMisses;
+    extern const Event ParquetTopKRowGroupsBoundedByDictionary;
 }
 
 namespace DB::Parquet
@@ -612,7 +613,12 @@ std::optional<Range> Reader::getTopKSortColumnRange(size_t row_group_idx) const
 bool Reader::topKShouldSkipRowGroup(const RowGroup & row_group) const
 {
     const auto & top_k = format_filter_info->top_k_filter;
-    if (!top_k || !row_group.top_k_sort_column_range.has_value())
+    if (!top_k)
+        return false;
+    /// See `refineTopKRangeFromDictionary`.
+    if (row_group.top_k_no_value_passes)
+        return true;
+    if (!row_group.top_k_sort_column_range.has_value())
         return false;
     const auto & tracker = *top_k->threshold_tracker;
     if (!tracker.isSet())
@@ -635,6 +641,121 @@ bool Reader::topKShouldSkipRowGroup(const RowGroup & row_group) const
     return !tracker.isValueInsideThreshold(boundary);
 }
 
+bool Reader::topKRowGroupMayBeBoundedByDictionary(size_t row_group_idx, const std::optional<Range> & statistics_range) const
+{
+    return topKDictionaryCanTightenRange(row_group_idx, statistics_range)
+        && columnChunkCanUseDictionaryFilter(getColumnChunk(row_group_idx, primitive_columns[*top_k_primitive_idx].column_idx));
+}
+
+bool Reader::topKThresholdIsSet() const
+{
+    return format_filter_info->top_k_filter && format_filter_info->top_k_filter->threshold_tracker->isSet();
+}
+
+bool Reader::topKDictionaryCanTightenRange(size_t row_group_idx, const std::optional<Range> & statistics_range) const
+{
+    if (!top_k_dictionary_bound)
+        return false;
+    const PrimitiveColumnInfo & column_info = primitive_columns[*top_k_primitive_idx];
+    const auto & column_meta = getColumnChunk(row_group_idx, column_info.column_idx).meta_data;
+    /// The dictionary does not describe the null rows, which may belong to the top-K (see `getTopKSortColumnRange`).
+    bool nullable = column_info.levels.back().def > 0;
+    bool no_nulls = column_meta.__isset.statistics && column_meta.statistics.__isset.null_count && column_meta.statistics.null_count == 0;
+    if (nullable && !no_nulls)
+        return false;
+    if (!statistics_range.has_value())
+        return true;
+    if (!top_k_column_rejects_empty)
+        return false;
+    const bool ascending = format_filter_info->top_k_filter->threshold_tracker->getDirection() == 1;
+    const Field & bound = ascending ? statistics_range->left : statistics_range->right;
+    return bound.getType() == Field::Types::String && bound.safeGet<String>().empty();
+}
+
+/// TopN dynamic filtering: the maximum length of the values of a `RowGroup::top_k_sort_column_range` taken from a
+/// dictionary, see `Reader::refineTopKRangeFromDictionary`.
+static constexpr size_t max_top_k_dictionary_bound_size = 256;
+
+/// A string of at most `max_size` bytes that is not less than `value` in bytewise order, if there is one.
+static std::optional<String> shortenedUpperBound(std::string_view value, size_t max_size)
+{
+    if (value.size() <= max_size)
+        return String(value);
+    String bound(value.substr(0, max_size));
+    while (!bound.empty() && static_cast<UInt8>(bound.back()) == 0xFF)
+        bound.pop_back();
+    if (bound.empty())
+        return std::nullopt;
+    bound.back() = static_cast<char>(static_cast<UInt8>(bound.back()) + 1);
+    return bound;
+}
+
+void Reader::refineTopKRangeFromDictionary(RowGroup & row_group) const
+{
+    if (!top_k_dictionary_bound)
+        return;
+    const ColumnChunk & column = row_group.columns.at(*top_k_primitive_idx);
+    if (!column.decode_dictionary_for_top_k)
+        return;
+    /// Before the threshold is set there is nothing to compare the bound with.
+    if (!format_filter_info->top_k_filter->threshold_tracker->isSet())
+        return;
+    const Dictionary & dictionary = column.dictionary;
+    /// Not decoded within the pruning memory budget (see `decodeDictionaryPage`).
+    if (!dictionary.isInitialized() || dictionary.mode != Dictionary::Mode::StringPlain)
+        return;
+
+    /// Values that no row references only widen the range. A string filter mask is built from conditions
+    /// that are necessary for a value to pass PREWHERE (see `StringValueFilter`), so its rejected entries are excluded.
+    const bool use_mask = !dictionary.string_value_filter_mask.empty();
+    std::string_view min_value;
+    std::string_view max_value;
+    bool found = false;
+    for (size_t i = 0; i < dictionary.count; ++i)
+    {
+        if (use_mask && !dictionary.string_value_filter_mask[i])
+            continue;
+        size_t start = (i == 0 ? 0 : size_t(dictionary.offsets[i - 1])) + 4;
+        size_t end = dictionary.offsets[i];
+        if (start == end && top_k_column_rejects_empty)
+            continue;
+        std::string_view value(dictionary.data.data() + start, end - start);
+        if (!found)
+        {
+            min_value = value;
+            max_value = value;
+            found = true;
+        }
+        else if (value < min_value)
+            min_value = value;
+        else if (value > max_value)
+            max_value = value;
+    }
+
+    if (!found)
+    {
+        ProfileEvents::increment(ProfileEvents::ParquetTopKRowGroupsBoundedByDictionary);
+        row_group.top_k_no_value_passes = true;
+        return;
+    }
+
+    /// Unlike the dictionary, the range is kept until the reader is destroyed, so it must not hold long values: they
+    /// are shortened to `max_top_k_dictionary_bound_size` bytes. The prefix of the minimum is not greater than it,
+    /// and the prefix of the maximum with its last byte incremented is greater than it, so the range only gets wider.
+    /// A row group whose values differ from the threshold within these bytes is still skipped.
+    Field max_bound;
+    if (auto shortened = shortenedUpperBound(max_value, max_top_k_dictionary_bound_size))
+        max_bound = std::move(*shortened);
+    else if (row_group.top_k_sort_column_range.has_value())
+        /// Every byte of the prefix of the maximum is 0xFF: the maximum statistic is still an upper bound.
+        max_bound = std::move(row_group.top_k_sort_column_range->right);
+    else
+        return;
+    ProfileEvents::increment(ProfileEvents::ParquetTopKRowGroupsBoundedByDictionary);
+    row_group.top_k_sort_column_range = Range(
+        Field(String(min_value.substr(0, max_top_k_dictionary_bound_size))), true, std::move(max_bound), true);
+}
+
 std::optional<Chunk> Reader::readMinMaxFromStatistics(const std::optional<std::unordered_set<UInt64>> & row_groups_to_read) const
 {
     /// Statistics cannot describe a subset of rows inside a row group.
@@ -1224,6 +1345,30 @@ void Reader::prefilterAndInitRowGroups(const std::optional<std::unordered_set<UI
 
                 if (top_k_column_is_read && format_filter_info->top_k_filter->track_row_group_best_values)
                     top_k_best_value_column_pos = sample_block->findPositionByName(format_filter_info->top_k_filter->column_name);
+
+                /// The statistics of a `String` sort column often cannot bound a row group: e.g. with
+                /// `WHERE s != '' ORDER BY s LIMIT n`, the minimum of nearly every row group is the empty string,
+                /// which no row reaching the sort has. A dictionary that encodes all data pages of the chunk holds
+                /// every value, so the values that can pass PREWHERE bound it exactly (see `refineTopKRangeFromDictionary`).
+                /// The values are compared bytewise, so the column must be read as `String` without conversion.
+                if (top_k_primitive_idx.has_value())
+                {
+                    const PrimitiveColumnInfo & pc = primitive_columns[*top_k_primitive_idx];
+                    top_k_dictionary_bound = isString(pc.decoded_type)
+                        && isString(removeNullable(removeLowCardinality(output_info.output_type)))
+                        && pc.max_array_def == 0 && pc.decoder.string_converter && pc.decoder.string_converter->isTrivial();
+                    const String & column_name = format_filter_info->top_k_filter->column_name;
+                    const auto & prewhere = format_filter_info->prewhere_info;
+                    if (top_k_dictionary_bound && prewhere && prewhere->need_filter)
+                        top_k_column_rejects_empty = filterRejectsEmptyString(
+                            prewhere->prewhere_actions, prewhere->prewhere_column_name, column_name);
+                    /// The filter pushed down to the source is applied to every row it returns, which is why
+                    /// the row groups can be pruned by it (see `key_condition`); e.g. a `WHERE` on the only column
+                    /// read is not moved to PREWHERE.
+                    const auto & filter_dag = format_filter_info->filter_actions_dag;
+                    if (top_k_dictionary_bound && !top_k_column_rejects_empty && filter_dag)
+                        top_k_column_rejects_empty = filterRejectsEmptyString(*filter_dag, column_name);
+                }
             }
         }
     }
@@ -1377,6 +1522,11 @@ void Reader::prefilterAndInitRowGroups(const std::optional<std::unordered_set<UI
             can_skip = accurateLess(a, b) || accurateLess(b, a);
         }
 
+        /// A row group bounded by its dictionary can be skipped only if the threshold is set when the row group
+        /// starts, so the row groups are started gradually (see `ReadManager::admitTopKRowGroups`).
+        for (size_t i = 0; !can_skip && i < candidates.size(); ++i)
+            can_skip = topKRowGroupMayBeBoundedByDictionary(candidates[i].row_group_idx, candidates[i].top_k_sort_column_range);
+
         if (can_skip)
         {
             std::stable_sort(candidates.begin(), candidates.end(), [ascending](const RowGroupCandidate & a, const RowGroupCandidate & b)
@@ -1653,6 +1803,13 @@ void Reader::initializePrefetches()
                 if (primitive_columns[column_idx].use_bloom_filter)
                     column.use_dictionary_filter = columnChunkCanUseDictionaryFilter(*column.meta);
 
+                /// TopN dynamic filtering: the dictionary of the sort column may bound the row group, see
+                /// `refineTopKRangeFromDictionary`. It is decoded before the data pages only if the threshold is set
+                /// when the row group starts, see `ReadManager::finishRowGroupStage`.
+                if (top_k_dictionary_bound && column_idx == *top_k_primitive_idx && !column.served_from_cache
+                    && topKRowGroupMayBeBoundedByDictionary(row_group.row_group_idx, row_group.top_k_sort_column_range))
+                    column.top_k_bound_from_dictionary = true;
+
                 /// For a column with the dictionary filter, the bloom filter is checked first and may
                 /// rule the row group out (or make the dictionary filter of this column unnecessary)
                 /// before the dictionary page is requested. So don't let the prefetcher piggy-back the
diff --git a/src/Processors/Formats/Impl/Parquet/Reader.h b/src/Processors/Formats/Impl/Parquet/Reader.h
index 650cdf11e33..db1a37a4752 100644
--- a/src/Processors/Formats/Impl/Parquet/Reader.h
+++ b/src/Processors/Formats/Impl/Parquet/Reader.h
@@ -354,6 +354,12 @@ struct Reader
         /// So its dictionary is decoded in the `Dictionary` stage, before the row group is split into
         /// row subgroups, to estimate the size of a chunk, see `intersectColumnIndexResultsAndInitSubgroups`.
         bool decode_dictionary_early = false;
+        /// The chunk of the TopN sort column, whose data pages are all dictionary-encoded: if the threshold is set
+        /// when the row group starts, its dictionary is decoded in the `Dictionary` stage to bound the row group by
+        /// the values that can pass the filter (see `refineTopKRangeFromDictionary`).
+        bool top_k_bound_from_dictionary = false;
+        /// Set when the `Dictionary` stage decodes the dictionary for `top_k_bound_from_dictionary`.
+        bool decode_dictionary_for_top_k = false;
 
         /// Prefetches.
         /// TODO [parquet]: Check that all handles and tokens are reset after correct stages.
@@ -510,6 +516,8 @@ struct Reader
         ColumnPtr top_k_best_value;
         /// `top_k_best_value` equals the bound of `top_k_sort_column_range` on its side, so no later row can improve it.
         bool top_k_best_value_is_final = false;
+        /// No value of the sort column's dictionary can pass PREWHERE, so no row of the row group can reach the top-K.
+        bool top_k_no_value_passes = false;
 
         std::deque<RowSubgroup> subgroups;
 
@@ -627,6 +635,11 @@ struct Reader
     /// TopN dynamic filtering: index in `primitive_columns` of the sort column, when eligible for
     /// row-group skipping by min/max statistics (see FormatFilterInfo::top_k_filter).
     std::optional<size_t> top_k_primitive_idx;
+    /// TopN dynamic filtering: the sort column is a `String` read without conversion, so the dictionary of
+    /// its dictionary-encoded chunks can bound a row group (see `refineTopKRangeFromDictionary`).
+    bool top_k_dictionary_bound = false;
+    /// PREWHERE rejects every row whose sort column value is the empty string (e.g. `s != ''`).
+    bool top_k_column_rejects_empty = false;
     /// TopN dynamic filtering: whether this file physically stores the sort column. If it doesn't,
     /// the reader only produces type defaults for it while the threshold comes from the values the
     /// pipeline puts in their place, so the filter must not be applied at all.
@@ -750,6 +763,14 @@ struct Reader
     /// top-K heap, so the row group can be skipped without reading its column data. The threshold
     /// only ever tightens, so a `false` result is safely revisited by the row filter later.
     bool topKShouldSkipRowGroup(const RowGroup & row_group) const;
+    /// Whether the dictionary of the sort column chunk can bound the row group more tightly than its statistics:
+    /// they hold the empty string that PREWHERE rejects, or they are missing.
+    bool topKDictionaryCanTightenRange(size_t row_group_idx, const std::optional<Range> & statistics_range) const;
+    /// Called after the `Dictionary` stage: bounds the row group by the dictionary values that can pass PREWHERE.
+    void refineTopKRangeFromDictionary(RowGroup & row_group) const;
+    bool topKThresholdIsSet() const;
+    /// `topKDictionaryCanTightenRange` and the sort column chunk is dictionary-encoded (`columnChunkCanUseDictionaryFilter`).
+    bool topKRowGroupMayBeBoundedByDictionary(size_t row_group_idx, const std::optional<Range> & statistics_range) const;
     /// Folds the sort column of a chunk delivered from the row group into RowGroup::top_k_best_value.
     void updateTopKBestValue(RowGroup & row_group, const IColumn & column) const;
 
diff --git a/tests/queries/0_stateless/05461_parquet_top_k_string_dictionary_bound.reference b/tests/queries/0_stateless/05461_parquet_top_k_string_dictionary_bound.reference
new file mode 100644
index 00000000000..c05de200069
--- /dev/null
+++ b/tests/queries/0_stateless/05461_parquet_top_k_string_dictionary_bound.reference
@@ -0,0 +1,48 @@
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+000003
+000013
+000023
+000033
+000043
+skipped
+skipped
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+same
+1
+1
+0
+skipped
+skipped
diff --git a/tests/queries/0_stateless/05461_parquet_top_k_string_dictionary_bound.sh b/tests/queries/0_stateless/05461_parquet_top_k_string_dictionary_bound.sh
new file mode 100755
index 00000000000..338f4713c1b
--- /dev/null
+++ b/tests/queries/0_stateless/05461_parquet_top_k_string_dictionary_bound.sh
@@ -0,0 +1,104 @@
+#!/usr/bin/env bash
+# Tags: no-fasttest
+# - no-fasttest: writes and reads Parquet files
+
+# ORDER BY <String column> LIMIT over Parquet with a filter that rejects the empty string: the minimum statistic of
+# every row group is '', so it cannot skip them, but the dictionary of a fully dictionary-encoded chunk bounds the
+# values that can pass the filter.
+
+CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
+# shellcheck source=../shell_config.sh
+. "$CUR_DIR"/../shell_config.sh
+
+DIR=$(mktemp -d "${CLICKHOUSE_TMP}/05461_parquet_topk_dict_XXXXXX")
+trap 'rm -rf "${DIR}"' EXIT
+
+LOCAL=(${CLICKHOUSE_LOCAL} --input_format_parquet_filter_push_down=1 --input_format_parquet_preserve_order=0)
+ST="max_threads = 1, max_parsing_threads = 1"
+ON="use_top_k_dynamic_filtering = 1, use_top_k_dynamic_filtering_for_variable_length_types = 0"
+OFF="use_top_k_dynamic_filtering = 0"
+
+# 20 row groups of 1000 rows. `e` is '' in nine of ten rows, otherwise a value of a range of k that is disjoint
+# between row groups (the smallest in row group 11): every row group has the minimum ''. `n` is `e` with a NULL in
+# row groups 0 and 10, whose dictionary then does not bound them.
+"${LOCAL[@]}" --query "
+    INSERT INTO FUNCTION file('${DIR}/t.parquet', Parquet)
+    SELECT if(number % 10 = 3, leftPad(toString(k), 6, '0'), '') AS e, number AS v,
+        if(number % 10000 = 5, NULL, e) AS n
+    FROM (SELECT (number % 1000) + 1000 * ((intDiv(number, 1000) * 7 + 3) % 20) AS k, number FROM numbers(20000))
+    SETTINGS output_format_parquet_row_group_size = 1000, engine_file_truncate_on_insert = 1"
+
+QUERIES=(
+    "SELECT e FROM file('${DIR}/t.parquet') WHERE e != '' ORDER BY e LIMIT 5"
+    "SELECT e FROM file('${DIR}/t.parquet') WHERE notEmpty(e) ORDER BY e LIMIT 5 OFFSET 3"
+    "SELECT e FROM file('${DIR}/t.parquet') WHERE e > '' ORDER BY e LIMIT 5"
+    "SELECT e, v FROM file('${DIR}/t.parquet') WHERE e != '' ORDER BY e LIMIT 5"
+    "SELECT e, v FROM file('${DIR}/t.parquet') WHERE e != '' AND v % 2 = 1 ORDER BY e LIMIT 5"
+    "SELECT e, v FROM file('${DIR}/t.parquet') WHERE e LIKE '%11%' ORDER BY e LIMIT 5"
+    "SELECT e, v FROM file('${DIR}/t.parquet') WHERE e != '' OR v = 7 ORDER BY e, v LIMIT 5"
+    "SELECT e FROM file('${DIR}/t.parquet') WHERE e != '' ORDER BY e DESC LIMIT 5"
+    "SELECT n, v FROM file('${DIR}/t.parquet') WHERE n != '' ORDER BY n LIMIT 5"
+    "SELECT n, v FROM file('${DIR}/t.parquet') WHERE n != '' ORDER BY n NULLS FIRST LIMIT 5"
+)
+
+for q in "${QUERIES[@]}"; do
+    on=$("${LOCAL[@]}" --query "${q} SETTINGS ${ST}, ${ON}")
+    off=$("${LOCAL[@]}" --query "${q} SETTINGS ${ST}, ${OFF}")
+    [ "${on}" == "${off}" ] && echo "same" || echo "DIFFERENT: ${q}"
+    multi=$("${LOCAL[@]}" --query "${q} SETTINGS max_threads = 4, max_parsing_threads = 4, ${ON}")
+    [ "${multi}" == "${off}" ] && echo "same" || echo "DIFFERENT (4 threads): ${q}"
+done
+
+"${LOCAL[@]}" --query "SELECT e FROM file('${DIR}/t.parquet') WHERE e != '' ORDER BY e LIMIT 5 SETTINGS ${ST}, ${ON}"
+
+# Row groups bounded by their dictionary are not read (one thread: the threshold is set by the first row group).
+rows_read() { "${LOCAL[@]}" --query "$1 SETTINGS ${ST}, $2 FORMAT JSON" | python3 -c "import sys, json; print(json.load(sys.stdin)['statistics']['rows_read'])"; }
+for q in "SELECT e FROM file('${DIR}/t.parquet') WHERE e != '' ORDER BY e LIMIT 5" \
+         "SELECT e, v FROM file('${DIR}/t.parquet') WHERE e != '' ORDER BY e LIMIT 5"; do
+    [ "$(rows_read "${q}" "${ON}")" -lt "$(rows_read "${q}" "${OFF}")" ] && echo "skipped" || echo "read all"
+done
+
+# A range taken from a dictionary keeps at most 256 bytes of a value: the prefix of the minimum, and the prefix of
+# the maximum with its last byte incremented. `p` has the same 300-byte prefix in every row group, so its range
+# cannot skip; `q` differs within the prefix, so its range still skips; the maximum of `r` (300 0xFF bytes) cannot be
+# shortened, so its maximum statistic is used and the range still skips; `u` is the same but longer than the writer
+# puts into statistics, except in the first row group, so the other row groups are not bounded by their dictionary;
+# `w` is the same value of 1000 bytes in every row group, so the range has equal bounds and the ties are kept.
+"${LOCAL[@]}" --query "
+    INSERT INTO FUNCTION file('${DIR}/long.parquet', Parquet)
+    SELECT if(number % 10 = 3, concat(repeat('x', 300), leftPad(toString(k), 6, '0')), '') AS p,
+        if(number % 10 = 3, concat(leftPad(toString(k), 6, '0'), repeat('y', 300)), '') AS q,
+        multiIf(number % 10 = 3, leftPad(toString(k), 6, '0'), number % 10 = 7, repeat(unhex('FF'), 300), '') AS r,
+        multiIf(number % 10 = 3, leftPad(toString(k), 6, '0'), number % 10 = 7 AND number >= 1000, repeat(unhex('FF'), 5000), '') AS u,
+        if(number % 10 = 3, repeat('z', 1000), '') AS w, number AS v
+    FROM (SELECT (number % 1000) + 1000 * ((intDiv(number, 1000) * 7 + 3) % 20) AS k, number FROM numbers(20000))
+    SETTINGS output_format_parquet_row_group_size = 1000, engine_file_truncate_on_insert = 1"
+
+LONG_QUERIES=(
+    "SELECT p, v FROM file('${DIR}/long.parquet') WHERE p != '' ORDER BY p LIMIT 5"
+    "SELECT p FROM file('${DIR}/long.parquet') WHERE p != '' ORDER BY p DESC LIMIT 5"
+    "SELECT q, v FROM file('${DIR}/long.parquet') WHERE q != '' ORDER BY q LIMIT 5"
+    "SELECT q FROM file('${DIR}/long.parquet') WHERE q != '' ORDER BY q DESC LIMIT 5"
+    "SELECT hex(r), v FROM file('${DIR}/long.parquet') WHERE r != '' ORDER BY r LIMIT 5"
+    "SELECT hex(r) FROM file('${DIR}/long.parquet') WHERE r != '' ORDER BY r DESC LIMIT 5"
+    "SELECT hex(u), v FROM file('${DIR}/long.parquet') WHERE u != '' ORDER BY u LIMIT 5"
+    "SELECT w, v FROM file('${DIR}/long.parquet') WHERE w != '' ORDER BY w, v LIMIT 5"
+)
+
+for q in "${LONG_QUERIES[@]}"; do
+    on=$("${LOCAL[@]}" --query "${q} SETTINGS ${ST}, ${ON}")
+    off=$("${LOCAL[@]}" --query "${q} SETTINGS ${ST}, ${OFF}")
+    [ "${on}" == "${off}" ] && echo "same" || echo "DIFFERENT: ${q}"
+    multi=$("${LOCAL[@]}" --query "${q} SETTINGS max_threads = 4, max_parsing_threads = 4, ${ON}")
+    [ "${multi}" == "${off}" ] && echo "same" || echo "DIFFERENT (4 threads): ${q}"
+done
+
+# The range is taken from the dictionary for `p` and `w`, not for `u`; the shortened ranges of `q` and `r` still skip row groups.
+bounded() { "${LOCAL[@]}" --query "$1 SETTINGS ${ST}, ${ON} FORMAT Null; SELECT sum(value) > 0 FROM system.events WHERE event = 'ParquetTopKRowGroupsBoundedByDictionary'"; }
+bounded "SELECT p FROM file('${DIR}/long.parquet') WHERE p != '' ORDER BY p LIMIT 5"
+bounded "SELECT w FROM file('${DIR}/long.parquet') WHERE w != '' ORDER BY w LIMIT 5"
+bounded "SELECT u FROM file('${DIR}/long.parquet') WHERE u != '' ORDER BY u LIMIT 5"
+for c in q r; do
+    q="SELECT ${c} FROM file('${DIR}/long.parquet') WHERE ${c} != '' ORDER BY ${c} LIMIT 5"
+    [ "$(rows_read "${q}" "${ON}")" -lt "$(rows_read "${q}" "${OFF}")" ] && echo "skipped" || echo "read all"
+done

@groeneai could you take a look? If the analysis and patch hold up, feel free to open a PR if it fits.

Version info

Activity

  1. added
    comp-parquet-reader-v3
    on Oct 30, 2026
  2. groeneai commented on Oct 30, 2026

    @groeneai
    Collaborator

    The analysis holds. I opened #128290: your patch on top of #124827, plus changes from my review. The dictionary is freed right after bounding and its page is read on its own; LowCardinality(String) columns and position comparisons are recognized. Remote reads keep the old code path unless the file is read into memory, because there bounding held up to 3.4x the memory (1 thread, 206 MiB file on MinIO, 59 -> 199 MB), so the S3 speed-up from the report is not included. Locally, Q26 over the 100 files runs at 0.886 [0.853, 0.920] of the time with 4 threads; the full table, including the 16-thread memory cost, is in the PR description.

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

    comp-parquet-reader-v3performance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions