Repository navigation
Fix TopK filtering dropping NULL and NaN rows from the answer - #114812
Conversation
ORDER BY ... LIMIT n silently omitted rows that belong in the answer when the sort column contained a NaN or a nested NULL and TopK filtering was active. TopK filtering must order values the way the sorter does. It did not, in three shapes: - A composite type whose comparison resolves to plain UInt8 reaches GenericComparisonImpl, which hardcodes the nan/nulls-direction hint to 1 (NULLs and NaNs greatest). The order is total, so only the placement is wrong, which makes it incorrect exactly when nulls_direction is -1, i.e. ASC NULLS FIRST and DESC NULLS LAST. The latter loses every real value. - IEEE float comparison is partial: nan <= x, nan >= x, nan <= nan and nan >= nan are all false, while the sorter's FloatCompareHelper treats NaN as tying with itself. A NaN row is therefore equal under sort order yet fails both comparators, at every direction and nulls_direction. This shape is reachable at default settings, since Float64 is fixed-length and use_top_k_dynamic_filtering defaults to true. A root Tuple belongs here too: FunctionComparison dispatches executeTuple before the types_equal branch, so it composes partial per-element comparisons rather than reaching compareAt. - use_skip_indexes_for_top_k ranks granules through MinMaxGranuleItem::operator<, a bare Field comparison with no nulls_direction, and it runs before reads begin. No comparator change can reach it: the row is still lost with use_skip_indexes_on_data_read = 0, where no threshold tracker exists at all. For the first two, route the sort column to executeGeneral, which already passes nulls_direction into compareColumn and keeps equals. For the third, add floats to the two skip-index eligibility gates. Those gates already excluded Nullable and collators for the same reason and one carries a TODO naming this remedy; floats were missed because they are number-represented yet admit NaN. Losing granule pruning for floats is a performance cost; keeping it is a correctness bug. The float predicate is derived from WhichDataType::isFloat plus a recursive forEachChild walk rather than a list of wrapper types, so BFloat16, Tuple(Float64, ...), Array(Float64) and typed JSON are all covered. Object, Variant and Dynamic answer true unconditionally because the types they hold are only known at runtime; measured, that also fixes a LOGICAL_ERROR for a Tuple(Dynamic) or Tuple(Variant(...)) sort column, whose comparison resolves to Nullable(UInt8). TopKThresholdTracker::compareFields is left unchanged. testAndSet only ever stores a boundary value the sorter itself published from an already-sorted block, so the stored threshold is never tighter than the true boundary and cannot exclude a row that belongs in the answer. The one consumer that could turn a wrongly ordered threshold into a dropped row at read time is canSkipMark on floats, which the gate change removes. Cost on a NaN-free Float64 column, 10M rows, ORDER BY f ASC LIMIT 10: 6 ms to 14 ms, reading 10M rows instead of 81,920. An integer column is unchanged. Isolated to granule pruning: on a copy of the same data with no minmax index, before and after are 53 ms and 64 ms and both read everything. Making MinMaxGranuleItem order-aware would recover this and is left as the TODO already in the code. The new test runs each carrier with filtering on and off and requires the two to agree, since with it off the answer is ground truth. On the unmodified binary 20 arms disagree and the 11 control arms already agree. Controls cover the directions where nulls_direction is 1, the Array-wrapped floats that compare through a total order, a top-level Nullable(Float64) across all four direction and nulls-direction combinations, integer and Decimal domains that admit neither NULL nor NaN, and the same fixture shape with an ordinary value instead of NaN.
Review fix round 1. The test gained an assertion that the general comparison path still rejects rows: every existing arm only compares answers, so a filter returning an all-true mask would keep all of them correct while silently optimizing nothing. That matters here because excluding floats from skip-index granule ranking leaves the dynamic filter as the only remaining optimization on the float carriers. The new assertion compares RowsReadByMainReader against RowsReadByPrewhereReaders and was validated against a binary whose executeGeneral returns an all-true mask: the strict inequality originally considered survives that mutation, because a filter accepting every row still skips the last granule, so the assertion requires the main reader to read at most half. It selects a payload column rather than the sort column, since projecting only the sort column leaves the main reader no work and makes any such comparison trivially true. The test also gains no-parallel-replicas, matching all four in-tree tests that assert a TopK fact from EXPLAIN, and pins explain_query_plan_default because the assertions scan plan text. Two obsolete SETs are dropped. The ReadFromMergeTree TODO claimed NaN-aware comparison would suffice to lift the float restriction. It would not: getExtremes drops NaNs before the minmax index stores them, so a mixed granule records no NaN at all and no ordering change can recover it.
…ws-read probes The nested-Variant arm the test already carried uses Variant(Float64, String), whose declared alternatives make Float64 statically visible, so the unconditional float term alone routes it. Deleting the Variant term from hasTypeThatCanContainFloat therefore left the whole test green while reintroducing the LOGICAL_ERROR this change claims to fix. Add a Variant with no float member at all so that term is the only thing that can route the carrier. Verified against a binary with only that term removed: the new arm aborts with the carrier named in the message, while the test as it stood before this commit passes on the same binary. The two effectiveness probes assert a rows-read ratio but pinned none of the rows-read settings the test runner randomizes. Pin the two that 03533_skip_index_on_data_reading pins, on those probes only, since pinning them globally would change the plans the other arms assert on. Both probes still read 1 on the fix and 0 against an all-true-mask filter, so the pins do not weaken the assertion. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review (3 rounds, all findings adjudicated)An independent model reviewed this change three times without access to the author's notes. Every
Liveness. The answer-comparing arms stay green if the general path returns an all-true mask, so Attribution. Dropping all three runtime-typed disjuncts at once aborts at an earlier arm, which Not fixed here. A non-float Also disclosed: Reviewer never edited source; the source tree is byte-identical to the reviewed revision. |
|
Workflow [PR], commit [2418022] Summary: ✅
AI ReviewSummaryReviewed PR #114812 at Missing context / blind spots
Final VerdictStatus: ✅ Approve. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260813-214900 |
|
cc @rschu1ze @vdimir, could you review this? TopK dynamic filtering compared through lessOrEquals/greaterOrEquals, which place NULLs and NaNs last whatever nulls_direction says and leave NaN unordered against every value, so a row that belongs in the top n was dropped; the fix routes those sort columns to the existing general path and adds floats to the two skip-index eligibility gates that already excluded Nullable for the same reason. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units16 translation units recompiled, 132 s compile time in total, 16 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
CI finish ledger - ecc6c92Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this PR's diff: Session id: cron:our-pr-ci-monitor:20260814-180000 |
Resolved a single include-ordering conflict in ReadFromMergeTree.cpp: master added <DataTypes/IDataType.h> and <DataTypes/NestedUtils.h> at the same spot where this branch added <DataTypes/hasNullable.h>. All three are used, so all three are kept. Master's bytes-aware read-stream cap (18 commits) and its row-policy where_clause fix in optimizeTopK.cpp are preserved unchanged.
Merged master to resolve a conflictHead One conflict, in
|
The `jsub` pair only compared answers, so it stayed green whether or not a `__topKFilter` was installed for `ORDER BY v.f`: an uninstalled filter leaves the sorter to produce the correct answer on its own. A dotted sort column reaches the filter only through the alias-resolution branch in `tryOptimizeTopK`, which returns early when the name does not resolve, so that branch needs its own presence assertion alongside the four existing ones. Attributed with a mutation that rejects only carriers whose resolved sort-column name is still dotted: the test then fails on exactly the new `pres jsub` row and nothing else, while the pre-change test passes on the same binary.
|
One residual noticed while validating this round, disclosed rather than folded in. For a sort column of type
Fixing it means changing how the threshold is represented in |
…depth The threshold is published to TopKThresholdTracker as a bare Field (PartialSortingTransform / MergeSortingTransform call IColumn::get), and ColumnVariant::get keeps only the payload of the active alternative while discarding its discriminator. ColumnVariant::compareAt, which is what the sorter uses, ranks by discriminator before payload. TopKThresholdTracker::compareFields compares the Field with plain Field ordering and has no discriminator axis, so the published threshold is not ordered the way the sorter orders the column and the filter can reject rows that belong in the answer. The previous guard tested isDynamic/isVariant, which are root-only, so a Tuple(Dynamic) or a JSON reached the filter. Measured on a three-part fixture holding one constant Dynamic value per part, so the DESC extremum lives only in the last part: ORDER BY v DESC LIMIT 2 returned (0) where the correct answer is (1000). All values there share a single runtime type, so the mismatch does not require mixed alternatives. The same fixture with Tuple(UInt64) agrees, which attributes the divergence to the Dynamic member rather than to the layout. Test hardening: the failing DESC arm and its static twin, and presence rows for the nested Dynamic, root JSON and static-twin carriers. Sorting on a JSON subcolumn of static type keeps the filter, because the guard tests the sort column's own type. Reported by clickhouse-gh[bot] on the PR.
hasDynamicStructure asks whether an alternative is itself runtime-typed, so Variant(UInt64, UInt8) and Tuple(Variant(String, UInt64)) answered false and kept the filter. The discriminator is what makes them unsafe, not the alternatives, so test for Object/JSON, Variant or Dynamic appearing anywhere in the type instead. Measured on Tuple(Variant(UInt64, UInt8)), three parts, the UInt64 alternative only in the last one: alternatives are sorted by name so every UInt64 precedes every UInt8, and ORDER BY v ASC LIMIT 2 returned (3) where the correct answer is (900). Map(String, Nullable(UInt64)) and the other static carriers keep the filter. Also adds float arms for Map and LowCardinality, which reach their children through their own forEachChild implementations, so the recursion in hasTypeThatCanContainFloat was asserted only through Array and Tuple.
tryOptimizeTopK rejects a limit strictly above the cap, so a cap of 1 leaves LIMIT 1 eligible; it is the LIMIT 2 and LIMIT 3 arms that lose the filter.
The `pres jsub` arm sorts by the dotted name `v.f`. `tryOptimizeTopK` can only
reach a dotted sort column through the branch that resolves it to the storage
column name, and that resolution requires the node to be an ALIAS. Only the
analyzer produces an ALIAS there; the old interpreter leaves an INPUT node, so
`optimizeTopK` returns early ("Could not resolve column alias v.f INPUT") and no
filter is installed. The arm therefore asserted 1 unconditionally and failed on
the `old analyzer` job flavour.
Comparing the presence against `getSetting('enable_analyzer')` keeps the
assertion strict in both flavours instead of relaxing it to a wildcard: it still
reddens if the filter disappears under the analyzer, and it now also reddens if
one ever appears without it. The reference is unchanged, since the arm prints 1
either way, and no coverage is dropped from the other assertions in the file.
The early return is pre-existing master behaviour and is not what this PR
changes, so installing the filter for dotted names under the old interpreter
would be a new optimization rather than part of this fix.
CI finish ledger - bc30337Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this PR's diff: this branch narrows the dynamic-filtering and skip-index gates for Session id: cron:our-pr-ci-monitor:20260816-103000 |
Resolve the two TopK guard conflicts against master's empty-Tuple work: - FunctionTopKFilter: keep master's hasEmptyTuple() route to executeGeneral and add this branch's NULLS FIRST and float conditions to the same disjunction. - optimizeTopK: keep master's zero-sized-Tuple gate on dynamic filtering. Its isDynamic/isVariant checks are dropped because hasRuntimeTypedType subsumes them and also covers those types nested inside Array/Tuple/Map. The comment keeps the zero-sized-Tuple rationale next to the generalized Field one. Merged master at 0cba270.
A review comment reported `LowCardinality(Nullable(T))` slipping past the `isNullable` term of the skip-index eligibility guard in `tryOptimizeTopK` and its mirror in `ReadFromMergeTree::buildIndexes`. It does not: the guard's first term `isValueRepresentedByNumber` already rejects the whole family, because `DataTypeLowCardinality` forwards it to the dictionary type and `DataTypeNullable` does not override it, so it lands on the `IDataType` default `false`. Nothing outside `src/DataTypes` overrides that predicate. Measured, the carrier selects no top-K index and agrees with the answer computed with both TopK paths off, in all four nulls directions. Both rejections nevertheless rested on properties no arm asserted, so pin them. The two carriers added here are the only ones whose disqualifying property is out of reach of a root-only test: the NULL and the NaN sit in the dictionary, not at the root, so plain `Nullable(UInt64)` and plain `Float64` cannot stand in for them. Admitting a nullable dictionary in the first term turns the `NULLS FIRST` answer from `NULL` into `100`; narrowing the float term to a root-only test turns it from `nan` into `100`. Each mutation reddens only its own two arms, and the plain `LowCardinality(UInt64)` column in the same fixture stays eligible throughout, so neither rejection is attributable to the wrapper.
CI finish ledger - 8c1153aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Details on the node death. The 4 failing cases are one event, not four network flakes: the query This PR cannot reach it: the diff is 7 files confined to TopK filtering The shard did not overrun, so this is not the shard-budget family: One caveat recorded so the onset is not over-read: Session id: cron:our-pr-ci-monitor:20260829-193000 |
|
Following up on the The first PR out of that investigation is #117104. It does not fix the node death: it restores The node death itself stays open and is still being worked. It reproduces on plain |
…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.
|
Thanks. You are right that the The branch is 22 commits; I can squash it if you prefer, but that would move your inline anchors. |
CI finish ledger - bbadb47Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261020-213012 |
|
Fixing PR for the 03752_attach_as_replicated_transaction_metadata failure in the ledger above: #127074 |
|
@groeneai merge master and fix conflicts |
Conflict in src/Functions/FunctionTopKFilter.cpp: master moved the executeGeneral/executeVectorized dispatch from executeImpl into the new compareValues (rows equal to the threshold, sparse columns). Took master's executeImpl and applied this branch's change to compareValues: the float term uses the shared hasTypeThatCanContainFloat instead of the local hasFloatingPoint, with the NaN comment at the dispatch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged master in 3ad9624. The only conflict was in |
|
@groeneai I checked this PR against all seven cases of #116705 and against #124313. The code covers all of them: cases 1 to 4 and #124313 through the Since this PR closes #116705, please add regression arms (ON vs OFF) for the cases the tests do not reproduce yet:
While there, the header comment of The test additions don't block anything. CI is green; the PR now waits on a re-review from @Ergus. |
The new test `05453_topk_float_nan_nulls_first_wrong_results` compares the top-k answers for a float sort column containing `nan` against the answers with every top-k optimization disabled: case 2 (skip-index top-k under `DESC NULLS FIRST` with a `nan` in a mixed granule), cases 5 and 6 (dynamic filtering under `ASC/DESC NULLS FIRST` with `nan` rows read after a finite threshold was published, `Float64` and `Float32`), and case 7 (dynamic filtering under the default `NULLS LAST` when the first block's top-k ends in `nan`, plus its `DESC` twin). Also update the header comment of `05044_top_k_dynamic_filtering_float_special_values`, which still claimed that `__topKFilter` drops `nan` rows under `NULLS FIRST` against a finite threshold. ClickHouse#116705
|
Follow-up to my earlier comment, which this replaces: I added the missing tests myself in 46ee9cf, so groeneai has nothing to do here.
I could not build locally, so the reference file was derived by reasoning and then checked with
CI on the new head is the real check. |
upgrade_runner.sh calls configure() twice over one embedded Keeper and data directory, and with RANDOMIZE_KEEPER_FEATURE_FLAGS=1 each call draws check_not_exists, create_if_not_exists and remove_recursive again, independently. When create_if_not_exists goes from 1 to 0, a coordinated refreshable view created during the stress phase (04811's APPEND view in a database recreated as Replicated) is attached against a Keeper that lost the flag, and RefreshTask stops it by design, logging an <Error> that the upgrade log scan reports. This failed the check on 3 unrelated PRs in 30 days (ClickHouse#118372, ClickHouse#117784, ClickHouse#114812); all 3 job logs show the 1 -> 0 flip. A real in-place upgrade does not downgrade its Keeper, so carry the flags the previous-release configure() drew into the upgraded server's keeper_port.xml and fail the job if they still differ, the same shape as the codec carry-over of ClickHouse#121249. Every job still draws random flags. Validated locally: the real code extracted from both scripts, run 2000 times in the CI image, restores the first draw 2000/2000 with no FAIL row; with the restore removed the new check fails 1765/2000. On a master build, restarting with create_if_not_exists turned off logs exactly the CI line, and restarting with the flags unchanged logs nothing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@groeneai Refresh to latest master and fix the conflict |
Conflict in src/Processors/QueryPlan/Optimizations/optimizeTopK.cpp: master split the variable-length check of tryTopKForFormatSource into the statistics-only String path; kept that, with hasRuntimeTypedType in place of the Dynamic/Variant check and without the floating-point gate, as on this branch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged master in 2418022, on top of 46ee9cf (no rebase). One conflict, in On the merged debug build |
Ergus
left a comment
There was a problem hiding this comment.
All my comments were addressed, so I approve, (didn't make a full new review, just checked my previous comments)
…p-K gates ClickHouse#114812 added `hasRuntimeTypedType` (Object/JSON, Variant or Dynamic anywhere in the type tree) and already uses it in `tryTopKForFormatSource`, which is the gate this PR had changed for format sources. Drop this PR's identical `isTopKThresholdRepresentable` helper and use `hasRuntimeTypedType` in the two gates that still checked only the top level: the MergeTree dynamic-filtering path in `tryOptimizeTopK` and the GROUP BY path in `optimizeGroupByTopK`. The Parquet case of the test is removed: master already passes it through the format-source gate, and 05025_parquet_top_k_dynamic_filtering covers that gate for a nested Variant key. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #116705
Closes: #124313
Closes: #130823
Related: #124984
Related: #121145
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
ORDER BY ... LIMIT nover aFloat32/Float64/BFloat16column with aminmaxindex returning wrong rows when the column holdsNaN: underDESCorNULLS FIRST, top-K granule selection could skip the granules holding the answer.ASC NULLS LASTkeeps using the index.Description
On 26.8 and 26.9,
SELECT v FROM t ORDER BY v DESC LIMIT 3over aFloat64column with aminmaxindex whose first granules are allNaNreturnsnan, nan, naninstead of the three largest values, andORDER BY v ASC NULLS FIRST LIMIT 1returns a number instead ofnan.The top-K path ranks and skips granules by their stored bounds, compared as
Fields, which rankNaNgreatest. The bounds omitNaNunless a whole range isNaN, and merging bounds (accurateLess) can turn only the max intoNaN. SoASC NULLS LASTis handled correctly, whileNULLS FIRSTmisses theNaNrows the bounds omit andDESCranks aNaNmax first and skips it asNaN-last (#124313).tryOptimizeTopKnow refuses a float sort key outsideASC NULLS LAST, andbuildIndexesapplies the same rule (master refusedNULLS FIRSTthere only when a threshold tracker exists).hasTypeThatCanContainFloatreplaces the other two copies of the float predicate (FunctionTopKFilter, ParquetReader). The__topKFilterrouting for floats and nestedNULLs is already on master (#121145).The format-source path drops its float gate, which waited for
__topKFilterto becomeNaN-aware, so Parquet float sort keys get the per-row filter (still without the statistics shortcut). It now refusesDynamic/Variant/JSONanywhere in the key, which the float gate used to cover for aVariantholding a float. Runtime-typed keys elsewhere are #124984.On master the test fails in every
NULLS FIRSTandDESCarm except the two with a threshold tracker (anf ON dflt,idx anf), which master already refuses; theASC NULLS LASTarms assert the index is still used. Removing each guard term reddens only its own arms.Workflow [PR]
Sync PR [sync-upstream/pr/114812]
Version info
26.11.1.2177-master(included in26.11and later)