Skip to content

Filter rows and skip granules by the top-K heap boundary in GROUP BY LIMIT queries - #121145

Merged
alexey-milovidov merged 43 commits into
masterfrom
group-by-limit-dynamic-filter
Oct 9, 2026
Merged

alexey-milovidov merged 43 commits into
masterfrom
group-by-limit-dynamic-filter

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Queries of the shape GROUP BY keys LIMIT n without ORDER BY (ClickBench Q16, Q17, Q18) and GROUP BY keys ORDER BY keys LIMIT n already 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 MergeTree reading step the same way ORDER BY column LIMIT n is linked today. Once a heap holds LIMIT keys, it publishes the value of its first ranked key column at the boundary into a TopKThresholdTracker shared with ReadFromMergeTree. The reading step then:

  • drops rows whose key lies beyond the boundary in a PREWHERE (__topKFilter), before the other columns of the granule are read;
  • skips whole granules that lie entirely beyond the boundary, either through a minmax skip 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 LIMIT distinct 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 existing ORDER BY ... LIMIT path does. The up-front narrowing to the granules of the LIMIT smallest rows (getTopKMarks) is deliberately not used here: LIMIT rows may hold fewer than LIMIT distinct keys, and a group needs all of its rows.

The primary-index granule skipping also applies to the existing ORDER BY column LIMIT n dynamic 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). Nullable and floating-point keys get the row filter but not the primary-index skipping, as NULLs and NaNs are placed by NULLS FIRST/LAST rather 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:

query before after bytes read before bytes read after granules skipped by the primary key
Q16 GROUP BY UserID LIMIT 10 34 ms 9 ms 763 MiB 119 MiB 10555
Q17 GROUP BY UserID, SearchPhrase LIMIT 10 187 ms 12 ms 1.71 GiB 134 MiB 10485
Q18 GROUP BY UserID, minute, SearchPhrase LIMIT 10 266 ms 12 ms 2.45 GiB 131 MiB 10524
GROUP BY UserID ORDER BY UserID LIMIT 10 34 ms 9 ms 763 MiB 119 MiB 10461
GROUP BY CounterID ORDER BY CounterID DESC LIMIT 10 23 ms 7 ms 381 MiB 13 MiB 12042

The optimization is gated by the new setting enable_group_by_top_k_dynamic_filtering (enabled by default). A new profile event TopKGranulesSkippedByPrimaryKey counts the granules skipped through the primary index.

Changelog category (leave one):

  • Performance Improvement

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

Queries GROUP BY key LIMIT n and GROUP BY key ORDER BY key LIMIT n over MergeTree tables 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 a minmax skip index (ClickBench Q18 went from 266 ms to 12 ms). Controlled by the new setting enable_group_by_top_k_dynamic_filtering. The same primary-key granule skipping now also applies to ORDER BY column LIMIT n when the column is in the primary key.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1902-master (included in 26.10 and later)

alexey-milovidov and others added 4 commits September 20, 2026 04:13
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]>
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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6806fdf]

Summary: ✅


AI Review

Summary

This PR wires the GROUP BY ... LIMIT top-K heap into ReadFromMergeTree so reads can filter rows and skip granules by the running boundary, and it extends the existing ORDER BY ... LIMIT path with primary-key granule skipping. The overall design is strong, but I still see two unresolved issues in the current code: one can still return wrong results for floating-point NULLS FIRST queries, and the other re-enables read-time pruning in a mode that supportsSkipIndexesOnDataRead explicitly fences off.

Findings
  • ❌ Blockers
    • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:3194] [dismissed by author -- https://github.com/Filter rows and skip granules by the top-K heap boundary in GROUP BY LIMIT queries #121145#discussion_r4088470466] The minmax TopK path still accepts floating-point keys when there is no runtime threshold_tracker, so ORDER BY f ASC NULLS FIRST LIMIT n can preselect marks from a granule whose minmax metadata ignored a NaN that should sort first. A minimal two-granule shape like [1, 2, 3, 4] and [nan, 100, 101, 102] can still return 1 instead of nan when __topKFilter / read-time tracker pruning are off.
    • Suggested fix: reject the minmax TopK path for floating-point keys whenever nulls_direction != direction, not only when a runtime tracker exists; add a focused stateless regression that disables the runtime tracker and exercises ASC NULLS FIRST.
  • ⚠️ Majors
    • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:5541] [dismissed by author -- https://github.com/Filter rows and skip granules by the top-K heap boundary in GROUP BY LIMIT queries #121145#discussion_r4087941977] The new primary-key TopK pruning still bypasses supportsSkipIndexesOnDataRead(). That re-enables read-time mark skipping in modes the engine currently fences off, notably read_overflow_mode = 'throw' with max_rows_to_read / max_rows_to_read_leaf. In a simple two-granule ORDER BY key LIMIT 1 query, initialization can still throw from the full-data estimate even though execution would skip the later granule once the threshold tightens.
    • Suggested fix: factor the shared safety predicate out of supportsSkipIndexesOnDataRead() and reuse it before setting top_k_primary_key_column_position; add a focused regression with read_overflow_mode = 'throw'.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    • close the floating-point NULLS FIRST hole in the minmax TopK path when no runtime threshold_tracker is present;
    • put the new primary-key TopK pruning behind the same read-time-skip safety fence as supportsSkipIndexesOnDataRead(), or prove with a focused regression that the read_overflow_mode contract is still preserved.

LLVM Coverage Report

Measured on commit 6806fdf.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 363/409 (88.75%) · Uncovered code

Full report · Diff report

@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 Sep 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 31 queries analysed

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1143 1034 -9.5% <0.0001 aggregation: This query sorts by COUNT(*) DESC, not by a GROUP BY key, so the new top-K boundary pushdown cannot apply to it. Master's baseline for this query shifted on 2026-10-08, so the -9.5% cannot be credited to this PR.
⚠️ 34 not_sure 1141 1043 -8.6% <0.0001 aggregation: This query sorts by COUNT(*) DESC, so the GROUP BY key top-K heap and the new read-side filter are never set up. The -8.6% matches the master baseline shift for this query, not this diff.

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
  • StressHouse run: a989fda1-2e9b-4857-86ee-30e3e8d68dc2
  • MIRAI run: d133a488-e377-4e7d-ac49-e936c8b50b4b
  • PR check IDs:
    • clickbench_401601_1791480682
    • clickbench_401614_1791480682
    • clickbench_401620_1791480682
    • tpch_adapted_1_official_401632_1791480682
    • tpch_adapted_1_official_401658_1791480682
    • tpch_adapted_1_official_401672_1791480682

…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]>
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread src/CMakeLists.txt.backup.2952220 Resolved
alexey-milovidov and others added 3 commits September 20, 2026 21:26
…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.
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6806fdfa7 with master dcd03bb83 (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.

Object file sizes

106 object files changed (+173.01 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeGroupByTopK.cpp.o 87.20 KiB 184.82 KiB +97.62 KiB (+111.95%)
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 22.23 MiB 22.25 MiB +22.85 KiB (+0.10%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

259 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.
The matched translation units cost +187.2 s (+8%) in total before that adjustment.

Translation unit Master PR Δ vs median
src/Processors/QueryPlan/Optimizations/optimizeGroupByTopK.cpp 6.0 s 12.1 s +5.6 s (+86%)

Slowest changed entities of src/Processors/QueryPlan/Optimizations/optimizeGroupByTopK.cpp:

  • ParseClass DB::ReadFromMergeTree: +0.7 s

Job report

@shankar-iyer shankar-iyer self-assigned this Sep 22, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author
Screenshot_20260923_013140

alexey-milovidov and others added 5 commits September 22, 2026 23:48
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]>
alexey-milovidov and others added 3 commits September 24, 2026 03:11
`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]>
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

The fix is in #124696 (test-only). The fixture's crashed writer used a deferred BEGIN, so while another connection held a shared lock on the file, every cache spill got SQLITE_BUSY and was skipped: the journal was left non-empty but with a zero first byte, which SQLite treats as cold, so the reads succeeded instead of returning attempt to write a readonly database. The writer now uses BEGIN EXCLUSIVE with .timeout 10000, and hot journal created also requires a non-zero first byte. With a reader holding a shared lock, the old test fails 5/5 with the same diff as CI and the new one passes 5/5.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, @groeneai, for the fix of 05261_sqlite_read_does_not_recover_hot_journal in #124696.

The only red job on 6806fdf, Integration tests (amd_asan_ubsan, db disk, targeted), finished with ERROR and reported no test results, so it was an infrastructure failure and not a test failure. It is running again now. All review threads are resolved, and the branch was merged with master today (2026-10-08), so I am not pushing anything new.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
Merged via the queue into master with commit 7d6c931 Oct 9, 2026
301 of 302 checks passed
@alexey-milovidov
alexey-milovidov deleted the group-by-limit-dynamic-filter branch October 9, 2026 03:51
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
PedroTadim added a commit that referenced this pull request Oct 9, 2026
…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]>
alexey-milovidov pushed a commit to fastio/ClickHouse that referenced this pull request Oct 10, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 20, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants