Skip to content

fix(top): order floating NaNs deterministically - #26956

Merged
XuPeng-SH merged 20 commits into
matrixorigin:mainfrom
aunjgr:fix/26941-float-top-nan-order
Aug 14, 2026
Merged

XuPeng-SH merged 20 commits into
matrixorigin:mainfrom
aunjgr:fix/26941-float-top-nan-order

Conversation

@aunjgr

@aunjgr aunjgr commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #26941

What this PR does / why we need it:

Defines one explicit SQL ordering relation for scalar FLOAT and DOUBLE:

  • ASC: -Infinity < finite values < +Infinity < NaN
  • DESC: +Infinity > finite values > -Infinity, with NaN still last
  • all NaN payloads are ordering peers, so later ORDER BY keys break their ties
  • -0 and +0 are ordering peers
  • NULL placement remains controlled independently by the existing NULLS FIRST/LAST flags

NaN and infinities remain stored values. This change does not convert NaN to NULL,
change scalar predicate semantics, or migrate physical/storage ordering.

The SQL full-sort, Top, MergeTop, MergeOrder, and window peer-partition paths now
share this relation. Generic comparison and storage sorting retain their existing
contracts through separate entry points.

Regular secondary-index hidden keys are not proven to have the same ordering at
NaN boundaries. For a logical float sort key, the optimizer therefore keeps the
logical Sort and suppresses hidden-key ORDER BY substitution, cursor-range rewrite,
reader-side LIMIT, and TopValue messaging. The index can still be used as an access
path.

Validation

  • focused named regressions for both float widths, infinities, signed zero, multiple NaN payloads, NULL placement, secondary-key tie breaking, Top/MergeTop/MergeOrder, window rank peers, and planner typed state
  • public SQL regression: test/distributed/cases/optimizer/float_nan_order.sql
  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=240s ./pkg/container/types ./pkg/compare ./pkg/partition ./pkg/sort ./pkg/sql/colexec/order ./pkg/sql/colexec/top ./pkg/sql/colexec/mergetop ./pkg/sql/colexec/mergeorder ./pkg/sql/colexec/window
  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=300s ./pkg/sql/colexec/aggexec ./pkg/sql/plan

@aunjgr
aunjgr requested a review from XuPeng-SH as a code owner August 11, 2026 03:26
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking correctness gaps remain on exact head dc8e3b41a218b97d18dbb9007b31ddfcc778ad05:

  1. [P1] The new float total order is not used by ordinary full ORDER BY. pkg/sort.Sort still routes FLOAT32/FLOAT64 through raw </>, where NaN is unordered. A focused counterexample on this head leaves 1 before NaN in ASC while Float64AscCompare requires NaN first. Full Sort, Top, and merge can therefore still disagree. Please wire the same float order into pkg/sort and add full-sort-versus-Top prefix tests for both widths/directions, interspersed NaNs, infinities, signed zero, and distinct NaN payloads.

  2. [P1] The regular-index paths only suppress the reader-side LIMIT for floats, but still rewrite the SQL Sort/Top key to the serialized hidden index key. applyRegularIndexTopSort performs that rewrite even when regularIndexOrderedLimitSafe is false; handleMessageFromTopToScan has the same shape. Keeping all candidates cannot recover correctness when Top then compares varbinary keys instead of the logical float. The packer order is observably different at NaNs (for example positive NaNs serialize after finite values, while the new ASC comparator puts all NaNs first). Skip the hidden-key ordering rewrite for unsafe float keys, or retain a logical float Sort, and cover the actual indexed SQL plan/result.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review completed on exact head c3be86a86be9b5a3b16f6a0af097c6aea58c5ab4.

[P1] The bounded PARTITION Top-N path still uses the non-SQL float comparator — pkg/sql/colexec/partition/topn.go:156.

This path is publicly reachable when the MORPC v19 optimization is enabled: rule.PartitionTopN annotates the PARTITION child for ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) with a literal rn <= N bound, and compilePartition executes this heap before Window. Its orderSpecs still call compare.New, so NaN comparisons are not antisymmetric and the heap can discard rows from the true SQL-order prefix.

I reproduced it on this head through the real Partition operator with one integer partition, ORDER BY f ASC, id ASC, limit 2, and input [NaN, +Inf, 1, 0, -1, -Inf]. The expected retained ids are [10,20] (-Inf,-1); the operator retained [70,40] (NaN,1). Window’s later SortForSQLOrder cannot recover candidates already removed upstream.

The added TestWindowPartitionTopNUsesSQLOrderForFloatNaNPeers sends all candidates directly to Window, so it does not exercise this pre-reducer. Please use the SQL-order comparator for the partition Top-N order keys and add both an operator regression and a public SQL regression with a filtered row number (rn <= N), covering FLOAT/DOUBLE, ASC/DESC, secondary-key ties, and NaNs appearing before finite rows.

@iamlinjunhong iamlinjunhong left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review completed on exact head c3be86a86be9b5a3b16f6a0af097c6aea58c5ab4.

Two blocking correctness gaps remain:

  1. [P1] Use the SQL float comparator in bounded PARTITION Top-N — pkg/sql/colexec/partition/topn.go:156.

PartitionTopN appends the window ORDER BY expressions to the PARTITION child, and on MORPC v19 compilePartition executes this heap before Window. The heap still builds its ORDER BY comparators with compare.New, so NaN is unordered and it can discard rows that belong to the true SQL-order prefix. For example, with one integer partition, ORDER BY f ASC, id ASC, limit 2, and input beginning with NaNs before +Inf, 1, 0, -1, -Inf, the retained candidates can be NaN/finite rows instead of -Inf,-1; Window cannot recover discarded rows. TestWindowPartitionTopNUsesSQLOrderForFloatNaNPeers feeds all rows directly into Window and therefore bypasses the faulty pre-reducer. Please switch only the order-key comparators here to compare.NewOrder and add an operator/public SQL regression for ROW_NUMBER() ... WHERE rn <= N, covering both float widths and directions.

  1. [P1] RANGE offset frames still search float boundaries with native NaN comparisons — pkg/sql/colexec/window/window.go:1689-1712 (called from buildRangeInterval at line 1196).

For RANGE BETWEEN 1 PRECEDING AND CURRENT ROW, a NaN key produces a NaN target. The current genericEqual plus native </> predicates all return false for that target, so genericSearchLeft advances to the partition end. The subsequent CURRENT ROW peer lookup is then clamped to that already-empty interval. A minimal [1, NaN(payload1), NaN(payload2)] input therefore gives the NaN rows an empty frame (COUNT(*) = 0) even though the new SQL relation makes the two NaNs peers and the frame must include that current peer group (COUNT(*) = 2). The same omission affects FLOAT/DOUBLE and both directions. Please use the SQL float relation for RANGE boundary search and add offset-frame regressions with multiple NaN payloads.

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review completed on exact head c3be86a86be9b5a3b16f6a0af097c6aea58c5ab4, including all historical review comments and the full current diff. The full Sort/Top/merge/index rewrite and partitioned-window peer fixes are consistent, but two public correctness paths still bypass the new SQL float order:

  1. [P1] Bounded PARTITION Top-N can discard the true SQL-order prefix — pkg/sql/colexec/partition/topn.go:156. prepareTopN still creates every ORDER BY comparator with compare.New, whose FLOAT/DOUBLE branches deliberately retain native identity comparison. This operator runs before Window for the MORPC-v19 ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) ... rn <= N optimization, so Window cannot recover candidates the heap dropped. I reproduced this through the exact operator with one integer partition, ORDER BY f ASC, id ASC, limit 2, and [NaN,+Inf,1,0,-1,-Inf]: SQL order requires ids [10,20] (-Inf,-1), but this head returns [70,40] (NaN,1). The added Window PartitionTopN test feeds all rows directly to Window and bypasses this reducer. Use compare.NewOrder for orderSpecs (not the identity partition keys) and cover both widths/directions plus the public filtered-row-number plan.

  2. [P1] FLOAT/DOUBLE RANGE-offset frames can become empty for a NaN current row — pkg/sql/colexec/window/window.go:1689-1712,2050-2075 (the float branches of searchLeft and searchRight). Sorting/peer detection now makes all NaNs one SQL peer group, but RANGE boundary search still uses genericEqual and native </>. For RANGE BETWEEN 1 PRECEDING AND CURRENT ROW, a NaN current value produces a NaN target; all three native relations are false and the left search advances to the partition end. A focused exact-head control over sorted [1, NaN(payload1), NaN(payload2)] expected interval [1,3) for the first NaN and got start 3, yielding an empty frame instead of both current peers. Apply the same SQL float relation to both boundary searches and add FLOAT/DOUBLE, ASC/DESC offset-frame regressions.

Validation: both focused counterexamples fail exactly as described with the required CGO/thirdparties setup; the current required GitHub checks are green; and git diff --check is clean.

@aunjgr

aunjgr commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in aba2b97be7 (after merging upstream/main at 2909687dc7):

  • Bounded PARTITION Top-N now uses compare.NewOrder for SQL FLOAT/DOUBLE ordering, so NaNs cannot displace the true prefix. Added reducer→Window ROW_NUMBER ... rn <= 2 coverage with a secondary key and ASC/DESC behavior; the partition package covers both FLOAT and DOUBLE.
  • RANGE FLOAT/DOUBLE boundary searches now use the same SQL relation for equality and ASC/DESC bounds. Added offset-frame regressions with multiple NaN payloads in both widths and directions.

Validation after the merge: all owning packages (compare, container/types, partition, sort, merge/top/window operators, and sql/plan) pass with the CGo test wrapper; build, vet, and git diff --check pass.

@aunjgr

aunjgr commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

Added public distributed coverage in 5a8b7cd4b7: filtered partitioned ROW_NUMBER() (rn <= 2) over DOUBLE with ASC/DESC ordering and the secondary id key. The existing operator regressions cover FLOAT32/FLOAT64 and both directions; all changes remain on the same PR branch.

@aunjgr

aunjgr commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH @iamlinjunhong @aptend All P1 findings from the c3be86a review head are addressed on current head 5a8b7cd4b7: SQL-order comparators in bounded PARTITION Top-N, SQL-order FLOAT/DOUBLE RANGE searches, reducer→Window ROW_NUMBER coverage, multiple-NaN offset-frame coverage, and the public filtered rn <= 2 regression. The merged-main build/test/vet checks pass; please re-review this head once the remaining GitHub checks finish.

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep re-review completed on exact head 5a8b7cd, including the full review/comment history, the incremental fixes since c3be86a86a, and the full current diff. The two prior P1 correctness findings are resolved: bounded PARTITION Top-N now applies compare.NewOrder only to its order-key comparators, and FLOAT/DOUBLE RANGE searches use the same SQL relation in both directions. The focused affected-package tests all pass with the required CGO/thirdparties setup.

One blocking test issue remains:

[P1] Regenerate the multiline BVT result commands — test/distributed/cases/optimizer/float_nan_order.result:82

The two newly added filtered ROW_NUMBER commands retain two-space indentation on their inner SELECT/FROM lines in the result file, but mo-tester canonicalizes the SQL command by stripping that leading whitespace. On this exact head, the required PROXY BVT fails at ResultParser before executing the file: it reports the command at float_nan_order.sql:51 “does not exist in result file,” then marks all 19 statements ABNORMAL. The second new command has the same mismatch. Please regenerate or normalize both result entries so this public regression actually executes and the required check is green.

@aunjgr

aunjgr commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

@aptend Fixed in a98e58b (current head). The two filtered ROW_NUMBER result entries now match mo-tester’s canonical command text with no leading indentation on the inner SELECT/FROM lines. I validated the exact mo-tester ResultParser against the case: 19 commands, success=true. The latest upstream/main was merged before the push; the new Compose/coverage checks are running on a98e58b. Please re-review the current head.

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep re-review completed on exact head a98e58b, including the full review/comment history, the incremental changes since 5a8b7cd, and the full current diff. The prior bounded PARTITION Top-N and FLOAT/DOUBLE RANGE-frame P1s remain correctly closed, and the final BVT change now matches mo-tester canonical multiline command text; the current PROXY BVT is green. Focused NaN/order/index/window race tests (3x) and the complete ten affected Go packages pass with the required CGo environment; git diff --check is clean.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep re-review of head a98e58b: approved.

All previously reported blocking paths are now closed: full Sort uses the SQL float relation; Window peer/range and bounded partition Top-N use the same relation; later ORDER BY keys correctly break NaN peers; and regular-index order/limit/cursor/TopValue rewrites are conservatively disabled for logical float keys while retaining the index as an access path.

I re-enumerated the sort/comparator/partition call sites and found no remaining SQL ordering consumer using the legacy float identity relation. The relation keeps NaN last in both directions, treats all NaN payloads and signed zero as peers, and leaves NULL handling independent.

Independent validation passed: 19 focused regressions under -race, the complete 12-package affected test set, go list/build/vet, and diff whitespace checks. The exact remote head was rechecked before approval.

@mergify

mergify Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-14 11:38 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • 🚫 Left the queue — 2026-08-14 11:39 UTC · at a98e58bc7abd3df69090b96dcee68f458cde5ec0

This pull request spent 49 seconds in the queue, with no time running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)

Reason

The pull request #26956 has been manually updated

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/enhancement kind/refactor Code refactor kind/test-ci size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants