Skip to content

Use the top-K dynamic filter for ORDER BY of a single String column on MergeTree - #125122

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:topk-filter-single-string-sort-column
Oct 24, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:topk-filter-single-string-sort-column

Conversation

@groeneai

@groeneai groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125075
Related: #104216

Changelog category (leave one):

  • Performance Improvement

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

ORDER BY <column> LIMIT n on a MergeTree table now uses the top-K dynamic filter when the only sort column is a String (also inside Nullable), controlled by the new setting use_top_k_dynamic_filtering_for_single_string_sort_column (enabled by default). When most rows of a block are equal to the threshold, as in a column of mostly empty strings, the filter also skips those rows. For example, ClickBench WHERE SearchPhrase <> '' ORDER BY SearchPhrase LIMIT 10 repeated with the query condition cache is about 12 times faster.

Description

Since #104216 the filter is off for variable-length sort columns: with ORDER BY MobilePhoneModel LIMIT 300 (94% empty) the threshold becomes '' and MobilePhoneModel <= '' keeps every empty row. Such queries read and sort all rows on every run.

For a single String or Nullable(String) sort column the filter starts as before (<=/>=). Once most rows of a block are equal to the threshold, it drops them too for the rest of the read, unless the read is cloned (correlated_subqueries_use_in_memory_buffer = 0). With one sort column every published threshold is the n-th of n rows that stay in the sort, so the sort keys of the result do not change. GROUP BY key LIMIT n, Parquet, Memory, LowCardinality, more sort columns and fixed-length types keep today's behavior. A sparse argument is compared through its values instead of being converted on every call.

After that switch the read records nothing in the query condition cache. Such a granule may hold rows of the result, and the cache is a union over runs, so overlapping runs that keep different tied rows would mark every tied granule (with those granules recorded, 16 concurrent ORDER BY s LIMIT 1 returned 0 rows in 19/20 cycles; 0/20 here).

ClickBench hits (100M rows, Release, 8 paired rounds, geomean vs master), first run at 4 threads: MobilePhoneModel LIMIT 300 0.69x, HitColor LIMIT 10 0.71x; q26 repeat with the cache 318 -> 27 ms, q26 first run 1.06x [1.02, 1.10] (1.00x at 32 threads or without the cache). Two-column, q24, q27, GROUP BY and fixed-length controls are flat. Nullable(String) copies: Title DESC 0.45x, SearchPhrase 0.77x, MobilePhoneModel 0.84x. LowCardinality is excluded: the filter materializes it on every block (PageCharset LIMIT 10 1.97x).

I can fold this into use_top_k_dynamic_filtering without a new setting if you prefer.

Idea from #125075.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/125122]

Version info

  • Merged into: 26.11.1.706-master (included in 26.11 and later)

groeneai and others added 2 commits October 10, 2026 23:55
…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]>
Drop comments restating the new Mode enum, compare() and the optimizeTopK gate; shorten the isDeterministicAllowingTopKFilter note to one line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex) plus my own cold review, three rounds; the last round had no new findings from the model.

# Sev Finding Verdict Evidence / action
1 ❌ Dropping rows equal to the threshold is unsound with the query condition cache when two reads with the same TopK key overlap: each records the granules holding the other's tied rows, and the union loses them AGREE, fixed after the switch the read records nothing in the cache (16 concurrent clients: 19/20 wrong cycles before, 0/20 now)
2 ⚠️ The cache part of the new test fills the cache sequentially, so it cannot catch #1 AGREE, fixed the test asserts that a read which dropped ties records nothing (red on the old head)
3 ❌ Keys with nested Dynamic/Variant/JSON still get the filter on the fixed-length and opt-in paths DISAGREE present on master on paths this PR does not change; the new path is String only (04205 checks that JSON gets no filter)
4 ⚠️ The default-on gate also enabled Array, Map and variable-length Tuple keys, measured only for String AGREE, fixed narrowed to String keys
5 💡 The setting description implied it controls the strict comparison for every single-column read AGREE, fixed it now does only for its own case
6 ⚠️ The tie count runs on one block per threshold value, so a later block where ties dominate at the same threshold is not detected AGREE performance only; it cannot miss when the threshold is the smallest or largest value of the block; kept for q26, where every block keeps many rows better than the threshold; the setting description says so
7 ⚠️ LowCardinality and Nullable keys have no test that runs the filter and shows the rows equal to the threshold are dropped AGREE, fixed a rows-read check for Nullable(String) (red when it leaves the gate) and a "no filter" check for each excluded wrapper
8 ⚠️ The wrappers are on by default but only String was measured, and they run other code AGREE, fixed measured on hits: Nullable(String) kept (0.45x to 0.84x); LowCardinality(String) (PageCharset LIMIT 10 1.97x) and LowCardinality(Nullable(String)) (1.54x) excluded
9 💡 Two numeric checks in the new test cover only code this PR does not change AGREE, fixed removed
10 💡 A collated sort (ORDER BY s COLLATE ...) is on by default too, but only its correctness was checked, not its timing AGREE, not blocking with the filter on, the sort's own threshold pre-filter is off, and for LIMIT below 1500 the sort already does one collation compare per row, so the filter's compare replaces work rather than adding it

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261010-235800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 20k rows, s empty except every 20th row, index_granularity = 64: SELECT id, s FROM t ORDER BY s LIMIT 20 SETTINGS max_threads = 1, max_block_size = 64, query_plan_optimize_lazy_materialization = 0 reads id for 20000 rows on master (no filter) and 64 with this PR.
b Root cause explained? __topKFilter compares with <=/>=, so a threshold value that most rows hold keeps them all, and #104216 turned the filter off for variable-length columns. With one sort column every published threshold is the n-th of n rows that stay in the sort, so rows equal to it can be dropped once they dominate.
c Fix matches root cause? Yes. Tie-drop only for one String sort column and only once ties are most of a block; such a read stops feeding the query condition cache, because the cache is a union over runs.
d Test intent preserved / new tests added? New 05355_top_k_dynamic_filter_single_sort_column_ties, extended 04205. Eight mutations (flag for two columns, flag for GROUP BY, no switch, String gate removed, Nullable(String) dropped from the gate, sparse scatter off by one, cache fence removed, strict from the start) each fail a named check.
e Both directions demonstrated? Yes. The r1 head (strict, recorded) returns 0 rows in 19/20 concurrent cycles and fails the cache check; this PR 0/20 and passes; master lacks the filter (rows-read check fails). 50/50 randomized runs of each test.
f Fix is general across code paths? GROUP BY, Parquet, Memory, more sort columns and fixed-length types get no flag, i.e. today's filter (checked by a GROUP BY test whose boundary key is most rows). All three cache feeds of the read are gated.
g Fix generalizes across inputs (params/datatypes/wrappers)? String, LowCardinality, Nullable, LowCardinality(Nullable) x sparse/full x ASC/DESC x NULLS FIRST/LAST x collation x dominating ''/value/NULL x 1 and 4 threads: 352 cases, sort keys equal with and without the filter. LowCardinality is excluded from the gate after measuring it on hits (PageCharset LIMIT 10 1.97x), checked by 04205.
h Backward compatible? (maintainer-approved exception only) New setting with history 26.10: false -> true, so compatibility below 26.10 keeps today's plan. Only which tied rows a LIMIT without WITH TIES returns can differ.
i Invariants and contracts preserved? A strict call sets the flag before it returns, and the reader loads it after the block's PREWHERE in the same thread, so every recorded granule was filtered with <=/>= and is sound for any interleaving of runs.

Session id: cron:clickhouse-impl-slot-5:20261010-232300

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b760476]

Summary: ✅


AI Review

Summary

Enables top-K dynamic filtering by default for a single String or Nullable(String) sort column on MergeTree, skips dominating threshold ties, and avoids caching those tie-dependent exclusions. The previous cloned-plan correctness finding is fixed in b7604763dacc1338d2051e1aaebaf5fc871742e2. Both focused stateless tests (04205 and 05355) passed locally against the PR-head fast-test binary, including the unbuffered correlated-subquery regression. No unresolved findings remain.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Oct 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 30 queries analysed

This PR extends top-K dynamic filtering in PREWHERE to a single String ORDER BY column read from a MergeTree table, and drops rows equal to the threshold when they dominate a block. The only flagged query, clickbench Q33 (-5.9%), was correctly left as no change: its 988.5 ms median falls inside master's recent range of 960-1243 ms, its history is noisy, and CPU time barely moved. It also never runs the changed path, because it sorts by an aggregate and not by a String column. No ClickBench query that sorts by a single String column (for example ORDER BY SearchPhrase LIMIT 10) was flagged in either direction, so this run shows no measurable effect from the PR.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: defd07f9-a3d0-461f-9c93-e4355049f185
  • MIRAI run: 23b4401b-8467-469c-859b-98dbb9436227
  • PR check IDs:
    • clickbench_817156_1791685564
    • clickbench_817162_1791685564
    • clickbench_817168_1791685564
    • tpch_adapted_1_official_817175_1791685564
    • tpch_adapted_1_official_817191_1791685564
    • tpch_adapted_1_official_817226_1791685564

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b7604763d with master 0a3052562 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

413 translation units recompiled, 3765 s compile time in total, 413 of them have a recent master baseline.

Job report

alexey-milovidov and others added 2 commits October 17, 2026 03:26
…string-sort-column

Kept both sides of the conflicts: in `FunctionTopKFilter::executeCompare`, the per-`Mode` comparison function together with master's `threshold_type` conversion. In `ITopKThresholdTracker`, master's `data_type` member together with this branch's `version` member. In `tests/clickhouse-test`, master removed the dependency of the now-obsolete `use_statistics_cache` setting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ing_sort_column` to 26.11

`master` is now 26.11, so a new setting must be recorded in the 26.11 block;
otherwise `compatibility = '26.10'` would enable it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…loned

With `correlated_subqueries_use_in_memory_buffer = 0`, `materializeQueryPlanReferences`
clones the referenced subplan. `SortingStep::clone` and `ReadFromMergeTree::clone` share the
threshold tracker, so several sorts publish to one threshold. A threshold can then be backed
only by the rows of another copy, and dropping the rows equal to it can leave a copy without
rows: `SELECT s, (SELECT count() FROM numbers(3) WHERE toString(number) >= q.s) FROM
(SELECT s FROM t ORDER BY s LIMIT 10) AS q` returned NULL for the subquery over a column of
empty strings.

`ReadFromMergeTree::clone` now marks the tracker as shared, and `__topKFilter` keeps the
rows equal to the threshold for such a tracker, as it does for every other sort. Reads that
are not cloned (the default, buffered plan) are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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.

All good.

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 comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-issue PR origin: picked up an external GitHub issue manual approve Manual approve required to run CI pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants