Repository navigation
Filter rows and skip granules by the top-K heap boundary in GROUP BY LIMIT queries - #121145
Conversation
The top-K heap of the aggregation () now publishes its boundary into a `TopKThresholdTracker` shared with the `ReadFromMergeTree` step, the same way `ORDER BY column LIMIT n` does: a `__topKFilter` PREWHERE drops rows whose first ranked key is beyond the boundary before the other columns are read, and granules that lie entirely beyond it are skipped through a `minmax` skip index or, new, through the primary index (`SkipIndexReadResult::isGranuleBeyondTopKThreshold`). Applies to `GROUP BY key ORDER BY key LIMIT n` and to `GROUP BY key LIMIT n` without `ORDER BY` (ClickBench Q16-Q18), gated by the new setting `enable_group_by_top_k_dynamic_filtering`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The planner puts the top-K heap on the partial aggregation of a distributed query itself, without a `LimitStep` above it; the optimization now attaches the boundary filter to such aggregations too. Adds the stateless test `05233_group_by_limit_dynamic_filter` and the performance test `group_by_limit_dynamic_filter` over `hits_100m_single`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
The analyzer aliases `a` to `__table1.a` between the reading step and the aggregation, so a same-name pass-through check never reached the read. Trace logs now name the reason when the filter is not attached. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Workflow [PR], commit [6806fdf] Summary: ✅
AI ReviewSummaryThis PR wires the Findings
Final Verdict
LLVM Coverage ReportMeasured on commit 6806fdf.
Changed lines: Changed C/C++ lines covered: 363/409 (88.75%) · Uncovered code |
|
📊 Cloud Performance Report
No query shows a reliable change from this PR. ClickBench Q33 (-9.5%) and Q34 (-8.6%) are faster with lower CPU, but both stay not_sure because master's own timings for them shifted on 2026-10-08, so the baseline cannot back up the comparison. Both queries sort by an aggregate count, not by a GROUP BY key, so they never run the new enable_group_by_top_k_dynamic_filtering path, where the aggregation passes its top-K boundary down to the MergeTree read. Neither benchmark appears to include a GROUP BY key ORDER BY key LIMIT n query that would exercise the new path, and TPC-H showed no flagged changes. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…e heap-mechanics test `04538_explain_query_tree_access_check` and `04540_insert_schema_mismatch_diagnostic` were untracked files of other work in the checkout, added by mistake. `04657_group_by_top_k_no_order_by_never_freezes` counts the rows the heap rejects; the reading step now drops them earlier, so the test turns the dynamic filter off. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…r off in the plateau-eviction heap test The conjunction with an existing PREWHERE is now checked on an explicit `PREWHERE`, since whether a `WHERE` moves depends on the part format and on randomized settings. `04655_group_by_top_k_boundary_plateau_eviction` counts the rows the heap rejects, which the reading step now drops earlier. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… drop a stray file `enable_group_by_top_k_dynamic_filtering` is a new default-on setting, so its `SettingsChangesHistory` row must record `false -> true`: with `true -> true` a `compatibility` below 26.10 left the optimization enabled and there was no way to get the pre-26.10 behavior back. This matches the `enable_group_by_top_k_optimization` row of 26.8 and the rule stated at the top of the file. `src/CMakeLists.txt.backup.2952220` was an accidental snapshot of `src/CMakeLists.txt` taken by tooling; it is not referenced by the build. Remove it.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes106 object files changed (+173.01 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units259 translation units recompiled, 2642 s compile time in total, 259 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
Slowest changed entities of
|
The primary key is in byte order, but `TopKThresholdTracker` compares with the
query's collator. For `ORDER BY s COLLATE 'en' LIMIT n` on a table ordered by
`s`, a granule ('c', 'c', 'c', 'ä') starts beyond the threshold 'b', yet its last
row 'ä' collates before 'b' and is the answer; `isGranuleBeyondTopKThreshold`
skipped it and the query returned 'b'. Apply the same `getCollator` fence the
`minmax` top-K path already has.
The new test returns 'b' instead of 'ä' on the previous head of the branch.
Addresses the AI review: #121145
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…allel replicas The dynamic filter is deliberately not attached to a `FINAL` read or a read from parallel replicas (the heap boundary is not carried to the remote reads), the same as the join runtime filters. State it in the setting's description, and add a correctness test of `GROUP BY key [ORDER BY key] LIMIT n` with parallel replicas, both with `serialize_query_plan` on and off. Addresses the AI review: #121145 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…mic-filter # Conflicts: # src/Core/SettingsChangesHistory.cpp
The table uses `index_granularity_bytes = 0` (non-adaptive granularity) to get exact 4-row granules. Such a table can store only Wide parts, so a non-zero `min_bytes_for_wide_part` (the server default or a randomized value) makes `MergeTreeData` log a warning, and the test fails with "having stderror". Set `min_bytes_for_wide_part` and `min_rows_for_wide_part` to 0 explicitly. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=121145&sha=86e82de7679f4fbd66a7f777ec593835863b9c8d&name_0=PR PR: #121145 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The vectorized path of `__topKFilter` compares with `lessOrEquals` or `greaterOrEquals`, which are false for NaN. The sort places NaN first or last by `nulls_direction`, so under `NULLS FIRST` a NaN row ranks before any threshold, yet the filter dropped it. With the `GROUP BY` top-K heap publishing its boundary to the read, `GROUP BY f ORDER BY f ASC NULLS FIRST LIMIT n` returned the NaN group with only the rows read before the boundary was set, e.g. 58 of 100 in `04498_group_by_limit_pushdown_key_types` under `max_block_size = 23742`. Route the types that may hold NaN (floating-point, also inside `Nullable`, `LowCardinality` and `Tuple`) to the column comparison path, which places NaN the way the sort does. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=121145&sha=86e82de7679f4fbd66a7f777ec593835863b9c8d&name_0=PR PR: #121145 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The `minmax` index leaves NaN out of the granule bounds. Under `NULLS FIRST` NaN ranks before the top-K threshold, so a granule whose finite values are all beyond the threshold must not be skipped: it may hold NaN rows. Disable the skip-index top-K filtering for floating-point keys when NaN is ranked first. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`SkipIndexReadResult::isGranuleBeyondTopKThreshold` reads granule bounds from the primary index assuming the key column ascends within a part. With a reverse sorting key (`allow_experimental_reverse_key`) the bounds are flipped, and `ORDER BY A DESC LIMIT 10` skipped granules holding the top rows. Found by the private sync CI: `03459-reverse-sorting-key-stable-result` returned a wrong result. ClickHouse/clickhouse-private#76155 https://github.com/ClickHouse/clickhouse-private/actions/runs/35934175373/job/107433471186 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…eezes` The flaky check failed with "Test runs too long (> 180s)" in the run where `index_granularity` was randomized to 14: the 700000 rows became 50000 granules, and every query touching the table took 15 s or more (the `INSERT`, the unoptimized `GROUP BY`), with `GROUP BY k LIMIT 5` taking 109 s. The other ~50 repetitions of the same flaky check, with larger granularities, finish these queries in about a second. Master and PR binaries behave the same on this shape with the exact CI settings, so this is not a regression; the granularity is simply irrelevant to the heap mechanics the test checks, so pin it. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121145&sha=9cf5529c8f6f70965be63c4a441d6c3761980028&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29 #121145 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
The fix is in #124696 (test-only). The fixture's crashed writer used a deferred |
|
🕵 Thanks, @groeneai, for the fix of The only red job on 6806fdf, |
…top-K dynamic filtering settings - `max_bytes_before_external_set` / `max_bytes_ratio_before_external_set` join the external sort/group by/distinct family. The bytes threshold is drawn low (1 byte to 64 MiB) so that sets actually spill. - `enable_join_seal_gated_reading` (experimental) is enabled with 30% probability. - `enable_group_by_top_k_dynamic_filtering` is disabled with 5% probability. The last two are forced off when their parent settings are off. Related: #123860 Related: #113512 Related: #121145 Co-Authored-By: Claude Opus 5.5 <[email protected]>
SQLite treats a rollback journal as hot only if it is non-empty and its first byte is non-zero (hasHotJournal). The journal header magic is first written as zeros and is synced by syncJournal only after the writer has obtained the EXCLUSIVE lock. The crashed writer used a deferred BEGIN with PRAGMA cache_size = 2, so each cache spill had to take the EXCLUSIVE lock at spill time. When another connection held a SHARED lock on the file during the writer's ~1 ms INSERT, every spill got SQLITE_BUSY, which sqlite3PcacheFetchStress ignores, and was skipped. kill -9 then left a non-empty journal whose first byte is 0: `[ -s journal ]` printed "hot journal created", but SQLite saw a cold journal, so the four read-only reads succeeded instead of returning "attempt to write a readonly database". This is the failure seen in Stateless tests (arm_binary, parallel) on PR ClickHouse#121145. The writer now sets `.timeout 10000` and starts with BEGIN EXCLUSIVE, so it waits out a concurrent reader and every spill syncs the journal header. The "hot journal created" check also requires a non-zero first byte, the same predicate SQLite uses, so a broken fixture fails on that line instead of as four missing refusals. With a reader holding a SHARED lock on the file for 3 s, the old test fails 5/5 with the CI diff and the new one passes 5/5. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hat master already does Review feedback on ClickHouse#114812: - The `__topKFilter` routing for floats and nested NULLs is on master (ClickHouse#121145, ClickHouse#113406), so the PR's `(nulls_direction == -1 && hasTypeThatCanContainNulls(...))` term is dead and is removed. The `hasRuntimeTypedType` term there is removed too: where a nested Variant reaches the function (the GROUP BY installer admits one), `executeGeneral` returns the same wrong row, since the Field threshold has already lost the discriminator. Refusing such keys in all three installers is ClickHouse#124984, so the MergeTree installer is left as on master. The format-source installer keeps the recursive check, because dropping its float gate would otherwise arm `Tuple(Variant(Float64, UInt64, UInt8))`, which that gate refused. - The float refusal of the skip-index path was too broad. Field ranks NaN greatest, the min of a granule ignores NaN unless the whole range is NaN, and merging bounds with `accurateLess` can only turn the max into NaN, so ASC NULLS LAST is ranked and skipped correctly. Every other order is not: NULLS FIRST misses NaN rows absent from the bounds, and DESC ranks a NaN max first and skips it as NaN-last (ClickHouse#116705 case 3, ClickHouse#124313). `tryOptimizeTopK` now refuses a float key only outside ASC NULLS LAST, and `buildIndexes` generalizes master's NULLS FIRST check to the same rule (it sees NULLS FIRST only through a threshold tracker, which exists whenever the planner did not decide the index itself). - One float predicate: `hasTypeThatCanContainFloat` replaces `hasFloatingPoint` in `FunctionTopKFilter.cpp` and the inline lambda in Parquet `Reader.cpp`. The test is rewritten to what master gets wrong: ASC NULLS FIRST without a threshold tracker, a leading all-NaN granule under DESC (also behind LowCardinality), the ClickHouse#124313 merged NaN max, plus the ASC NULLS LAST shapes that must keep the index (including ClickHouse#124313 mirrored for the min) and the plan-based parallel replicas observable for the planner's direction term. Each guard term was removed in turn and reddens only its own arms; a root-only float check reddens only the LowCardinality arms.

Queries of the shape
GROUP BY keys LIMIT nwithoutORDER BY(ClickBench Q16, Q17, Q18) andGROUP BY keys ORDER BY keys LIMIT nalready combine the aggregation with the limit: the aggregation keeps a bounded top-K heap of keys (enable_group_by_top_k_optimization) and drops rows whose key can no longer reach the result. But every row was still read from the table, and every column of the query with it.This change links that heap to the
MergeTreereading step the same wayORDER BY column LIMIT nis linked today. Once a heap holdsLIMITkeys, it publishes the value of its first ranked key column at the boundary into aTopKThresholdTrackershared withReadFromMergeTree. The reading step then:__topKFilter), before the other columns of the granule are read;minmaxskip index on the column (the existing top-K path) or, new in this change, through the primary index when the key is a primary key column. The primary index check is per granule and works for any position of the column in the primary key: a granule is skipped when the key columns before it do not change inside the granule and the granule's bound is beyond the threshold.Each aggregation stream publishes its own boundary, and the tracker keeps the tightest one. Any published value is a valid bound: the stream has already seen
LIMITdistinct keys not worse than it, so no group that the query returns can contain a row beyond it. Results are the same with the optimization on and off.The link is made at the end of plan optimization, after PREWHERE was moved and the query condition cache keys were assigned, so the new filter is conjoined with the existing PREWHERE and the query-condition-cache key of the WHERE filter is re-salted with the top-K parameters (or dropped when
use_query_condition_cache_for_top_k = 0), as the existingORDER BY ... LIMITpath does. The up-front narrowing to the granules of theLIMITsmallest rows (getTopKMarks) is deliberately not used here:LIMITrows may hold fewer thanLIMITdistinct keys, and a group needs all of its rows.The primary-index granule skipping also applies to the existing
ORDER BY column LIMIT ndynamic filtering when the column is in the primary key.The first ranked key must be a physical column that reaches the aggregation without being computed on (aliases are fine).
Nullableand floating-point keys get the row filter but not the primary-index skipping, as NULLs and NaNs are placed byNULLS FIRST/LASTrather than by the key order.Measurements
100M-row
hits(ClickBench schema,ORDER BY (CounterID, EventDate, UserID, EventTime, WatchID)), 16 threads, hot cache, best of 3, on a loaded shared machine:GROUP BY UserID LIMIT 10GROUP BY UserID, SearchPhrase LIMIT 10GROUP BY UserID, minute, SearchPhrase LIMIT 10GROUP BY UserID ORDER BY UserID LIMIT 10GROUP BY CounterID ORDER BY CounterID DESC LIMIT 10The optimization is gated by the new setting
enable_group_by_top_k_dynamic_filtering(enabled by default). A new profile eventTopKGranulesSkippedByPrimaryKeycounts the granules skipped through the primary index.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Queries
GROUP BY key LIMIT nandGROUP BY key ORDER BY key LIMIT noverMergeTreetables now read much less data: the aggregation publishes the boundary of its top-K heap to the reading step, which drops rows beyond it before reading the other columns and skips whole granules through the primary key or aminmaxskip index (ClickBench Q18 went from 266 ms to 12 ms). Controlled by the new settingenable_group_by_top_k_dynamic_filtering. The same primary-key granule skipping now also applies toORDER BY column LIMIT nwhen the column is in the primary key.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/121145]
Version info
26.10.1.1902-master(included in26.10and later)