Skip to content

Add lock free topk threshold tracker for numeric types. - #116512

Merged
CurtizJ merged 12 commits into
ClickHouse:masterfrom
CurtizJ:lock-free-topk-tracker
Oct 6, 2026
Merged

CurtizJ merged 12 commits into
ClickHouse:masterfrom
CurtizJ:lock-free-topk-tracker

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Improved performance of queries with ORDER BY ... LIMIT that use top-k pruning by minmax indexes (setting use_skip_indexes_for_top_k) for large tables with many granules.


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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aeb1475]

Summary: ✅


AI Review

Summary

This PR replaces the shared-mutex TopKThresholdTracker with a lock-free numeric tracker and adds targeted perf/stateless coverage. The lock-free tracker itself looks reasonable, but the PR still enables float sort keys on two MergeTree top-k pruning paths that are not NaN-aware, so ORDER BY ... LIMIT can still return wrong rows around NaN. I do not think this is safe to merge until floats are gated off those paths or the comparisons are made consistent with ORDER BY semantics.

Missing context / blind spots
  • ⚠️ I do not see any benchmark results from tests/performance/top_k_threshold_tracker.xml, so I could not validate the size of the claimed speedup on the workload named in the changelog. Running that perf case, or attaching before/after numbers for a many-granule ORDER BY ... LIMIT query, would close this gap.
Findings
  • ❌ [src/Processors/QueryPlan/Optimizations/optimizeTopK.cpp:294, src/Functions/FunctionTopKFilter.cpp:113, src/Core/AccurateComparison.h:96] MergeTree top-k dynamic filtering still accepts non-nullable float sort keys, but __topKFilter sends them through executeVectorized, which builds plain lessOrEquals / greaterOrEquals. Those comparisons return false on any NaN, so once a finite threshold is published a later NaN under ORDER BY ... NULLS FIRST is filtered out before it reaches the sorter and the query returns the wrong row. The PR now adds float coverage while leaving this wrong-result path enabled.
    Suggested fix: either keep float-containing types off use_top_k_dynamic_filtering for MergeTree (mirroring the format-source guard), or route float inputs through the compareColumn(..., nulls_direction) path and add a regression where the first NaN appears only after the first threshold publication.
  • ❌ [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/116512#discussion_r3864731390] [src/Processors/QueryPlan/Optimizations/optimizeTopK.cpp:277, src/Storages/MergeTree/MergeTreeIndexMinMax.cpp:360, src/Columns/ColumnVector.cpp:1276] MergeTree skip-index top-k preselection is still unsound for float sort keys. getExtremes hides NaN inside mixed granules and returns raw NaN for all-NaN granules, while getTopKMarks ranks granules by plain Field min/max order. That means a NULLS FIRST query can still drop the only granule containing NaN before any row-level filtering, and the no-WHERE preselection path is therefore still capable of returning the wrong top row for float data. I still consider this real because the current code path at these lines has not become NaN/NULLS-aware; the new test simply avoids the failing shape.
    Suggested fix: keep float-containing types off the skip-index preselection path until minmax ranking uses the same ordering as ORDER BY, or make getTopKMarks / minmax extrema computation explicitly NaN-aware and add a no-WHERE regression where the NaN lives in a different granule than the best finite extreme.
Tests
  • ⚠️ tests/queries/0_stateless/05044_top_k_dynamic_filtering_float_special_values.sql:6 explicitly avoids the mixed-data NULLS FIRST case because it is still broken, so the new stateless coverage does not protect either wrong-result surface above.
Final Verdict

❌ Changes requested — the PR still routes float sort keys into MergeTree top-k pruning paths that can return wrong results around NaN. Either gate floats off those paths for now, or make both the dynamic-filter and skip-index comparisons honor full ORDER BY semantics before merging.

LLVM Coverage Report

Measured on commit aeb1475.

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

Changed lines: Changed C/C++ lines covered: 73/76 (96.05%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 26, 2026
Comment thread src/Processors/TopKThresholdTracker.cpp Resolved
`createTopKThresholdTracker` routes floating point sort keys to the
lock-free `TopKThresholdTrackerNumeric`, whose boundary logic is specific
to floats: a `NaN` boundary is never published as the threshold, and the
initial threshold is `+-inf` rather than the maximum finite value.

Compare the optimized and the unoptimized result for `Float64` /
`Float32` data containing `nan`, `inf` and `-inf`, for the default
`NULLS LAST` ordering and for `NULLS FIRST`, which flips where `NaN`
sorts. A second table covers the case where the whole top-k consists of
infinities, so the published threshold equals the initial sentinel and
must not exclude the values it was reached by.

Both the `__topKFilter` prewhere path and the `isValueInsideThreshold`
granule-skipping path are exercised.

Requested in ClickHouse#116512 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
@EmeraldShift

Copy link
Copy Markdown
Contributor

This is great, thank you! Ive seen some worst-case manycore TopK queries spinning 50% of CPU time on RWLock cache line ping-ponging. I suppose this cuts the number of atomic operations in at least half, and significantly less when a good threshold is already established :)

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR splits the top-K threshold tracker into a lock-free version for numeric sort keys and a mutex-based version for everything else. Only ORDER BY <table column> LIMIT n queries that use skip-index top-K or dynamic filtering run that code. The four flagged ClickBench queries (Q16 +15.7%, Q18 +12.5%, Q32 +15.1%, Q33 +7.2%) are all heavy GROUP BY queries whose ORDER BY, where present, is on an aggregate, so none of them touches the changed code. Every PR-side median falls inside master's normal range for its query, and all PR-side runs ran on the same node, so the not_sure verdicts stand and nothing here points to a regression from this change.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 544 630 +15.7% <0.0001 aggregation: This is a heavy GROUP BY query, and any ORDER BY is on an aggregate result. The top-K tracker only covers sorts on columns read straight from the table, so this query never uses the changed code. The +15.7% sits inside master's normal range.
⚠️ 18 not_sure 883 993 +12.5% <0.0001 aggregation: This high-cardinality GROUP BY query doesn't build a top-K tracker, because there is no sort on a table column. The +12.5% falls inside master's normal range.
⚠️ 32 not_sure 722 830 +15.1% <0.0001 aggregation: This query groups by WatchID and ClientIP, and its ORDER BY is on an aggregate, so it never reaches the top-K tracker. The +15.1% comes from noisy measurements and is within master's normal range.
⚠️ 33 not_sure 1161 1245 +7.2% <0.0001 aggregation: This query groups by URL and its ORDER BY is on the count, so the changed threshold tracker is not used. The +7.2% is within master's normal range.

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: 1c02ad0b-d9bf-4be1-aba2-f06c46798615
  • MIRAI run: 3eea5621-4d13-47ac-9a5f-5d7a16d442ec
  • PR check IDs:
    • clickbench_3433755_1791238318
    • clickbench_3433768_1791238318
    • clickbench_3433774_1791238318
    • tpch_adapted_1_official_3433780_1791238318
    • tpch_adapted_1_official_3433812_1791238318
    • tpch_adapted_1_official_3433826_1791238318

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing aeb147525 with master e5aa26e90 (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

33 object files changed (+3.50 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/TopKThresholdTracker.cpp.o 6.54 KiB 71.59 KiB +65.06 KiB (+995.52%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeTopK.cpp.o 266.09 KiB 246.42 KiB -19.68 KiB (-7.39%)
src/CMakeFiles/dbms.dir/Processors/Transforms/MergeSortingTransform.cpp.o 575.92 KiB 556.40 KiB -19.52 KiB (-3.39%)

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

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

Job report

CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Aug 26, 2026
The minmax index skips nan unless the whole granule is nan, and the
top-k mark preselection ranks granules via raw Field comparison which
orders nan above +inf. This produced wrong results in three ways:

- a granule holding nan next to finite values is indistinguishable from
  one without nan, so nan-first orderings (NULLS FIRST) could drop the
  granule that must supply the leading nan rows;
- an all-nan granule (min = max = nan) ranked as the best candidate for
  DESC with the default NULLS LAST, crowding out the granules with the
  actual finite extremes.

Fix: disable the skip-index top-k path for float sort columns with
nulls_direction != direction (plumbed through TopKFilterInfo), and rank
an all-nan granule as the worst - still selectable - candidate by
substituting its ranking value with +-inf.

Review: ClickHouse#116512 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
CurtizJ added a commit to CurtizJ/ClickHouse that referenced this pull request Aug 27, 2026
…S FIRST

Once a finite threshold is published, __topKFilter sent non-nullable
floats through the vectorized path, where plain lessOrEquals /
greaterOrEquals return 0 whenever either side is nan, so nan rows
arriving in later blocks were filtered out even though NULLS FIRST
sorts them before every finite value. Route such floats through the
nan-aware compareColumn path that respects nulls_direction.

ClickHouse#116512 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
@CurtizJ

CurtizJ commented Aug 27, 2026 •

Copy link
Copy Markdown
Member Author

It went too far with fixes for nans which are unrelated to changes in this PR. Let's fix them separately: #116705.

@CurtizJ
CurtizJ requested a review from shankar-iyer August 27, 2026 15:37
Comment thread src/Processors/TopKThresholdTracker.cpp Resolved
@shankar-iyer shankar-iyer self-assigned this Aug 31, 2026
CurtizJ and others added 2 commits August 31, 2026 09:22
Derive the "not set" state from `threshold` itself: `testAndSet` can
never store the sentinel initial value (a candidate equal to it fails
the strict comparison and NaN returns early), so `threshold != sentinel`
means a real value was published. With a single atomic there is no
separate publication to order, which fixes the race where a reader
could observe `isSet` as true while still loading the sentinel from
`threshold`.

Addresses review comment: ClickHouse#116512 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
Pin `use_top_k_dynamic_filtering` explicitly to both 0 and 1 in
`top_k_threshold_tracker.xml` so each query deterministically measures a
single path, per review comment
ClickHouse#116512 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Dear @shankar-iyer, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

CurtizJ and others added 3 commits October 1, 2026 02:01
…rmat top-K path

The Parquet top-K dynamic filtering path merged from master still forward-declared
the concrete `TopKThresholdTracker` in `FormatFilterInfo.h` and created it with
`std::make_shared<TopKThresholdTracker>` in `optimizeTopK.cpp`. Point the alias to
`ITopKThresholdTracker` and create the tracker with `createTopKThresholdTracker`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116512&sha=d7973245fdf74b761aed20ae7a12eecb3d7ba512&name_0=PR
PR: ClickHouse#116512

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With a finite threshold, `__topKFilter` drops `nan` rows under `NULLS FIRST`
(preexisting bug, ClickHouse#116705).
The test hit it in the ParallelReplicas + s3 storage job: the coordinator
handed out the preselected granules in two requests, the first of which
published a finite threshold before the granules with `nan` were read.
Keep `NULLS FIRST` only on `tab_sentinel`, where every block's top-k is
`nan`, which the numeric tracker never publishes.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116512&sha=8a66b58c628844ce9ed5b167dd080478cfc30b16&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
PR: ClickHouse#116512

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@CurtizJ

CurtizJ commented Oct 6, 2026

Copy link
Copy Markdown
Member Author

Perf tests:

Screenshot 2026-10-06 at 14 16 01

@CurtizJ
CurtizJ enabled auto-merge October 6, 2026 12:16
@CurtizJ CurtizJ self-assigned this Oct 6, 2026
@CurtizJ
CurtizJ added this pull request to the merge queue Oct 6, 2026
Merged via the queue into ClickHouse:master with commit f5d7510 Oct 6, 2026
149 checks passed
@CurtizJ
CurtizJ deleted the lock-free-topk-tracker branch October 6, 2026 13:14
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 6, 2026
alexey-milovidov pushed a commit that referenced this pull request Oct 16, 2026
Resolve the conflicts of the 26.9 cherry-pick of #125221 ("Fix `ORDER BY ... LIMIT`
over an `Interval` column with top-K dynamic filtering").

The conflicts come from #116512, which on master split `TopKThresholdTracker` into
`ITopKThresholdTracker` with the lock-free `TopKThresholdTrackerNumeric` and
`TopKThresholdTrackerGeneric`, created by `createTopKThresholdTracker`. 26.9 has the
single `TopKThresholdTracker` struct, and #116512 is not marked for backport, so the
resolution keeps the 26.9 tracker and applies only what #125221 changes:

- `TopKThresholdTracker` takes and keeps the type of the sort column (`getDataType`),
  as `ITopKThresholdTracker` does on master.
- `optimizeTopK.cpp` passes `sort_column.type` where it creates the tracker. On master
  this is done inside `createTopKThresholdTracker`, which 26.9 does not have.
- `FunctionTopKFilter.cpp` merged without conflicts (the hunks of #125221 verbatim).
- `TopKThresholdTracker.cpp` keeps the 26.9 version: its conflicting hunks are #116512's.
- The test drops its `GROUP BY` query and that query's three reference lines, because
  it uses `enable_group_by_top_k_dynamic_filtering`, which 26.9 does not have.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 16, 2026
Resolve the conflicts of the 26.8 cherry-pick of #125221 ("Fix `ORDER BY ... LIMIT`
over an `Interval` column with top-K dynamic filtering").

The conflicts come from #116512, which on master split `TopKThresholdTracker` into
`ITopKThresholdTracker` with the lock-free `TopKThresholdTrackerNumeric` and
`TopKThresholdTrackerGeneric`, created by `createTopKThresholdTracker`. 26.8 has the
single `TopKThresholdTracker` struct, and #116512 is not marked for backport, so the
resolution keeps the 26.8 tracker and applies only what #125221 changes:

- `TopKThresholdTracker` takes and keeps the type of the sort column (`getDataType`),
  as `ITopKThresholdTracker` does on master.
- `optimizeTopK.cpp` passes `sort_column.type` where it creates the tracker. On master
  this is done inside `createTopKThresholdTracker`, which 26.8 does not have.
- `FunctionTopKFilter.cpp` merged without conflicts (the hunks of #125221 verbatim).
- `TopKThresholdTracker.cpp` keeps the 26.8 version: its conflicting hunks are #116512's.
- The test drops its `GROUP BY` query and that query's three reference lines, because
  it uses `enable_group_by_top_k_dynamic_filtering`, which 26.8 does not have.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 16, 2026
Resolve the conflicts of the 26.7 cherry-pick of #125221 ("Fix `ORDER BY ... LIMIT`
over an `Interval` column with top-K dynamic filtering").

The conflicts come from #116512, which on master split `TopKThresholdTracker` into
`ITopKThresholdTracker` with the lock-free `TopKThresholdTrackerNumeric` and
`TopKThresholdTrackerGeneric`, created by `createTopKThresholdTracker`. 26.7 has the
single `TopKThresholdTracker` struct, and #116512 is not marked for backport, so the
resolution keeps the 26.7 tracker and applies only what #125221 changes:

- `TopKThresholdTracker` takes and keeps the type of the sort column (`getDataType`),
  as `ITopKThresholdTracker` does on master.
- `optimizeTopK.cpp` passes `sort_column.type` where it creates the tracker. On master
  this is done inside `createTopKThresholdTracker`, which 26.7 does not have.
- `FunctionTopKFilter.cpp` merged without conflicts (the hunks of #125221 verbatim).
- `TopKThresholdTracker.cpp` keeps the 26.7 version: its conflicting hunks are #116512's.
- The test drops its `GROUP BY` query and that query's three reference lines, because
  it uses `enable_group_by_top_k_optimization` and `enable_group_by_top_k_dynamic_filtering`,
  which 26.7 does not have.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 16, 2026
Resolve the conflicts of the 26.3 cherry-pick of #125221 ("Fix `ORDER BY ... LIMIT`
over an `Interval` column with top-K dynamic filtering").

The conflicts come from master-only changes to the top-K filter: #116512 split
`TopKThresholdTracker` into `ITopKThresholdTracker` with lock-free implementations in a
new `TopKThresholdTracker.cpp`, and later PRs rewrote `FunctionTopKFilter`. 26.3 has the
original header-only `TopKThresholdTracker` constructed from the sort direction, and a
`FunctionTopKFilter` with a single comparison path. The resolution keeps both and applies
only what #125221 changes:

- `TopKThresholdTracker` takes and keeps the type of the sort column (`getDataType`).
- `optimizeTopK.cpp` passes `sort_column.type` where it creates the tracker. On master
  this is done inside `createTopKThresholdTracker`, which 26.3 does not have.
- `FunctionTopKFilter` gets the threshold type from the tracker, without `LowCardinality`,
  and passes it as the source type of the threshold conversion, as on master.
- `TopKThresholdTracker.cpp` stays absent, as it is on 26.3.
- The test enables `use_top_k_dynamic_filtering`, which is off by default on 26.3 and not
  randomized by its test runner, and drops two queries with their reference lines: the
  `Array` one uses `use_top_k_dynamic_filtering_for_variable_length_types` and the
  `GROUP BY` one uses `enable_group_by_top_k_*`, none of which 26.3 has.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

5 participants