Repository navigation
Avoid TopK dynamic filter regression on variable-length sort columns - #104216
Conversation
PR #99537 turns on use_top_k_dynamic_filtering by default. For sort columns of fixed-length types (numbers, dates, etc.) this is a clear win: the per-row __topKFilter prewhere lets minmax/threshold-based mark skipping kick in early. For variable-length types (String, Array, Map, Tuple containing such), the per-row threshold comparison runs the generic less-or-equals over the column with no granule pruning, so when the lex-min value of the column dominates (mostly empty strings, e.g. MobilePhoneModel where 94/100M rows are "") the prewhere costs CPU without saving any I/O. Locally reproducing the regression flagged in the perf comparison for PR #99537, batch 3/6 amd_release: SELECT MobilePhoneModel FROM hits_100m_single ORDER BY MobilePhoneModel LIMIT 300 master default (both off): 0.013-0.015s PR #99537 default (both on): 0.022-0.026s 1.47-1.63x slower Profile events show identical SelectedRows (99,997,497) between the two — the dynamic filter skips zero granules but still pays a per-block lessOrEquals(String, String) cost, increasing UserTime by ~1.8x. The fix introduces use_top_k_dynamic_filtering_for_variable_length_types (off by default). When use_top_k_dynamic_filtering is enabled, the optimization is now restricted to columns whose values have a fixed maximum size in memory — i.e. haveMaximumSizeOfValue() returns true. That predicate forwards through Nullable and Tuple, so Nullable of a fixed-length type and Tuples of fixed-length types remain eligible, matching the user's request. Variable-length types only get the optimization when the user explicitly opts in. Test queries follow MobilePhoneModel's distribution and check the EXPLAIN output for the __topKFilter prewhere with each gate combination. End-to-end timing on the same data confirms the regression is gone with the new default settings: PR #99537 settings on, new gate off (default): 0.017s All on (old broken behavior): 0.026s master baseline (top-k off): 0.013s CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99537&sha=9d86b8cf27ca90c5223f949656f0141685ea3f6f&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%203%2F6%29 Original PR: #99537 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Workflow [PR], commit [69c620f] Summary: ✅ AI ReviewSummaryThis PR adds ClickHouse Rules
Final Verdict
|
…ngth gate The sanity-check at the end of the test asserts that `__topKFilter` is present in the plan when sorting by a non-key `String` column. With the new `use_top_k_dynamic_filtering_for_variable_length_types` gate (off by default), variable-length sort columns are skipped, so the assertion needs the gate set to `1` to preserve the original intent. Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104216&sha=5d54a05d7aa15fba383fc35f129640105c0793c8&name_0=PR&name_1=Fast%20test
The `SettingsChangesHistory` entry for
`use_top_k_dynamic_filtering_for_variable_length_types` previously
recorded `{false, false}`, which means `compatibility` for older
versions would still leave variable-length types out of the dynamic
filter. In older versions, when a user opted into
`use_top_k_dynamic_filtering = 1` (or once PR #99537 turns it on by
default), variable-length sort columns received the dynamic filter
unconditionally — i.e. the effective value of the new gate was `true`.
Change the entry to `{true, false}` so `compatibility` correctly
restores the previous behavior.
Flagged by AI Review on PR #104216.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The flaky check randomizes `query_plan_max_limit_for_top_k_optimization` (via `tests/clickhouse-test`) over `[0, 1, 10, 100, 1000, 100000]`. When the value lands at `1`, the planner skips the top-k optimization for the test's `LIMIT 5` queries (since `n > max_limit_for_top_k_optimization` in `tryOptimizeTopK`), and the `__topKFilter` prewhere never appears, making queries 2/4/4b/5 return `0` instead of `1`. Pin `query_plan_max_limit_for_top_k_optimization = 100` in every `SETTINGS` clause so the test exercises the planner-level gate deterministically — same approach as `04051_top_k_dynamic_filter_read_in_order`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104216&sha=a476cb9eaa9ad09f2edbcf0110be1302a07b11e6&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
|
|
||
| For such types, the per-row threshold comparison performed by the dynamic filter can outweigh its savings when the column's lexicographic minimum dominates (e.g. mostly empty strings) and few granules can be skipped. In that case the dynamic filter degrades query latency rather than improving it. | ||
|
|
||
| When this setting is `0`, dynamic filtering is restricted to columns whose values have a fixed maximum size in memory (numbers, `Date`, `DateTime`, `FixedString`, `Enum`, `Nullable` of such types, `Tuple` of such types). When set to `1`, dynamic filtering applies to variable-length types as well, matching the previous behavior. |
There was a problem hiding this comment.
The reader is confused what "previous behavior" means in this context (use_top_k_dynamic_filtering has never been default enabled). Let's remove that four words.
`use_top_k_dynamic_filtering` has never been default-enabled, so "previous behavior" is misleading in the description of `use_top_k_dynamic_filtering_for_variable_length_types`. Per #104216 (comment) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The test was hitting the 180s "Test runs too long" timeout in the flaky check on `amd_asan_ubsan, flaky check, s3 storage, meta in keeper`. Per-run time varied from 10s to >180s under heavy parallel load, dominated by the 1 M row INSERT. Reducing the row count from 1 000 000 to 200 000 brings the test comfortably under the timeout while still detecting the regression: the buggy "full scan" path would read 200 000 rows, which is still greater than the `read_rows < 100000` threshold; the correct "read-in-order" path reads ~one granule (64 rows). Failing CI: https://github.com/clickhouse-private/actions/runs/25454026603/job/74679232002 PR: #104216 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Will this be backported to 26.3 LTS or 26.4 to recover the TopK optimization without regression? |
|
The optimization was opt-in in previous versions, exactly for this reason - it does not always improve. There is no reason to backport. |
|
Ah, my bad. I assumed the referenced PR was already merged, and it isn't. Agreed there's nothing to backport :) |
LLVM Coverage Report
Changed lines: 100.00% (46/46) · Uncovered code |
Drop two randomization adds from this PR that need additional groundwork to ship safely, and revert the seven test files that needed `-- Tags: no-random-settings` because of them: * `max_streams_for_union_step` and `max_streams_for_union_step_to_max_threads_ratio` (ClickHouse#100176) — reshape the `UNION ALL` pipeline, which surfaced pre-existing weak-ordering invariants in 8 tests (constant ORDER BY keys, NaN sort keys from `sin(0/0)`, `ORDER BY tuple()`, duplicate values without secondary sort). The dedicated `04051_max_streams_for_union_step` test also failed in a way suggesting randomized session-level values bypass per-query `SETTINGS` for these settings — a separate interaction worth investigating first. * Pairing `max_bytes_ratio_before_external_join` with `max_bytes_before_external_join` in `randomize_external_sort_group_by` using the same `threshold_generator(0.3, 0.5, 0, 10 GiB)` as sort/group_by — caused `03279_join_choose_build_table` to fail at `--max_bytes_before_external_join 7693351` (grace hash join returned 500/125 rows instead of 1000). That smells like a real correctness issue in grace hash join under spilling. Restore upstream's standalone `max_bytes_before_external_join: random.choice([0, 1000000000])` (binary off / 1 GiB, never spills) and drop the ratio randomization for now. What stays in this PR: * `optimize_dictget_tuple_element` (ClickHouse#100186) * `use_top_k_dynamic_filtering_for_variable_length_types` (ClickHouse#104216) with conditional_settings parent * `page_cache_max_coalesced_bytes` (ClickHouse#104230) * re-enable `grace_hash_join_initial_buckets` randomization with the narrow, previously-working `[1, 2, 4, 8]` range CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105630&sha=6f3e784ddf7&name_0=PR Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
QA notes on recent PRs flagged that the following settings were introduced but not added to the randomization list in `tests/clickhouse-test`: * `max_bytes_ratio_before_external_join` (ClickHouse#103862) — mirrors the existing `max_bytes_ratio_before_external_group_by` and `max_bytes_ratio_before_external_sort`, so wire it through the Bytes-vs-Ratio choice in `randomize_external_sort_group_by` alongside its absolute counterpart `max_bytes_before_external_join`. * `max_streams_for_union_step` and `max_streams_for_union_step_to_max_threads_ratio` (ClickHouse#100176) — occasionally clamp to a small number of simultaneously active streams to exercise the `UNION ALL` narrowing path. * `optimize_dictget_tuple_element` (ClickHouse#100186) — default-true; disable with a small probability so both planner paths stay covered. * `use_top_k_dynamic_filtering_for_variable_length_types` (ClickHouse#104216) — cover both the fixed-length-only default and the opt-in path. * `page_cache_max_coalesced_bytes` (ClickHouse#104230) — randomize across small/large values so the coalescing path and the cap that splits long miss runs into multiple reads both get exercised. Also re-enable randomization of `grace_hash_join_initial_buckets`, which had been disabled in `tests/clickhouse-test` after wrong results on some tests. Restore the original conservative range `[1, 2, 4, 8]`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…n MergeTree Since ClickHouse#104216 `use_top_k_dynamic_filtering` is off for variable-length sort columns: a dominating value that is the threshold (e.g. mostly empty strings) keeps most rows, so the filter only adds cost. The new setting `use_top_k_dynamic_filtering_for_single_string_sort_column` (default on) enables it for a single `String` sort column of a `MergeTree` read (also inside `Nullable`). Once most rows of a block are equal to the threshold, `__topKFilter` also drops those rows, which keeps the result for a single sort column. A tracker version limits the tie count to once per threshold value. From then on the read records nothing in the query condition cache: a granule emptied that way may hold rows of the result, and the cache is a union over runs, so overlapping runs that keep different tied rows together mark every tied granule (measured with strict reads recorded: `ORDER BY s LIMIT 1` returned 0 rows in 19/20 cycles of 16 concurrent clients). `MergeTreeSelectProcessor::readCurrentTask` loads the per-read flag after the PREWHERE of the block ran. A sparse argument is compared through its values instead of being converted to a full column. ClickBench `hits` (100M rows), release, x86, first run vs master at 4 threads: `MobilePhoneModel LIMIT 300` 0.69x, `HitColor LIMIT 10` 0.71x, `PageCharset LIMIT 10` 0.65x, `Title DESC` 0.84x; q26 1.06x with the query condition cache (1.00x at 32 threads or without it), its repeat 318 -> 27 ms. Two-column, q24, q27, GROUP BY and fixed-length controls are unchanged. `Nullable(String)` copies of the columns: `Title DESC` 0.45x, `SearchPhrase <> ''` 0.77x, `MobilePhoneModel LIMIT 300` 0.84x. `LowCardinality` columns are not included: `__topKFilter` is not deterministic in the scope of a query, so the default implementation converts such an argument to a full column on every block, and the filter cost more than it saved (`PageCharset LIMIT 10` 1.97x, `MobilePhoneModel LIMIT 300` 1.08x). Closes ClickHouse#125075 Co-Authored-By: Claude Opus 5.5 <[email protected]>
PR #99537 enables
use_top_k_dynamic_filteringby default. For sort columns of fixed-length types this is a clear win, but for variable-length types (String,Array,Map,Tuplecontaining such) the per-row__topKFilterprewhere can outweigh its savings — most notably when the column's lex-min value dominates and few granules can be skipped. In that case the dynamic filter degrades query latency rather than improving it.This PR adds a new setting
use_top_k_dynamic_filtering_for_variable_length_types(off by default) that gates dynamic filtering for variable-length types. Whenuse_top_k_dynamic_filtering = 1, dynamic filtering is now restricted to columns whose values have a fixed maximum size in memory —IDataType::haveMaximumSizeOfValuereturns true. That predicate forwards throughNullableandTuple, soNullableof a fixed-length type andTuples of fixed-length types remain eligible. Settinguse_top_k_dynamic_filtering_for_variable_length_types = 1restores the previous behavior.This addresses the perf regressions observed in PR #99537's CI:
CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99537&sha=9d86b8cf27ca90c5223f949656f0141685ea3f6f&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%203%2F6%29
The largest regression in batch 3/6 amd_release was
string_sort #10:Reproduced locally on
hits_100m_single(94/100MMobilePhoneModelvalues are empty):SelectedRowsis identical (99,997,497) with and without the dynamic filter — it skips zero granules but still pays a per-blocklessOrEquals(String, String)cost (UserTime~1.8x).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Restrict
use_top_k_dynamic_filteringto fixed-length sort columns by default, avoiding regressions onORDER BY <var-length-column> LIMIT Nqueries where the per-row threshold comparison cost exceeds the I/O savings. The previous behavior is available via the newuse_top_k_dynamic_filtering_for_variable_length_typessetting.Documentation entry for user-facing changes
The new setting is documented in
src/Core/Settings.cpp; no separate docs page is required for a session-level setting.Version info
26.5.1.397