skip to content

Since Rust 1.81, why can sorting floats with sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)) panic, and how do you write a comparator that cannot?

level: seniorimportance: should knowfreq 30%

answer

  1. new sort algorithms
  2. NaN equal to everything
  3. transitivity breaks
  4. a real total order

basics

~20 s

Rust 1.81's new sort implementations may panic when the comparator is not a total order. Treating NaN as Equal makes 1 == NaN == 5 while 1 < 5, breaking transitivity. Use f64::total_cmp, or keep Ord and its supertraits consistent.

solid answer

~40 s

Rust 1.81 replaced the slice sorts with driftsort (stable) and ipnsort (unstable), and the release notes warn that they may panic if `Ord`, or the comparison function, is not a total order. `unwrap_or(Ordering::Equal)` declares NaN equal to every number, so `1.0 == NaN` and `NaN == 5.0` but `1.0 < 5.0`: equality is not transitive. Older sorts silently returned unsorted data; the new ones have a good chance of noticing and panicking with "user-provided comparison function does not correctly implement a total order". Either way the docs say the order is unspecified, though no element is lost and there is no undefined behaviour. Use `sort_by(f64::total_cmp)`, reject NaN before sorting, or implement `Ord` once and define `PartialOrd` as `Some(self.cmp(other))` so the traits cannot disagree.

code

rust · 13 lines
rust
use std::cmp::Ordering;

fn main() {
    // Elevations in metres; every fourth reading failed and is NaN.
    let mut elevations: Vec<f64> = (0..32)
        .map(|i| if i % 4 == 0 { f64::NAN } else { ((i * 17) % 50) as f64 })
        .collect();

    // Looks harmless: treat "incomparable" as "equal".
    elevations.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));

    println!("{:?}", &elevations[..6]);
}

go deeper

for a junior

Recall that a comparator must be a consistent total order and that f64::total_cmp is the safe way to sort floats.

for a middle

Explain why NaN-as-Equal breaks transitivity and what sort_by's docs promise: may panic, unspecified order, no lost elements.

for a senior

Diagnose the total-order panic after an upgrade to Rust 1.81 or later, trace it to the comparator or a mismatched Ord, and fix the order rather than catching the panic.

for a principal

Ask for comparators and Ord impls to be reviewed as contracts, with total_cmp and canonical PartialOrd as the house style, before the next toolchain upgrade.

## What changed in Rust 1.81 Rust 1.81 replaced the implementations behind `slice::sort*`: the stable sorts now use **driftsort** and the unstable sorts **ipnsort**. The 1.81 compatibility notes carry the consequence that matters here: the new sort implementations **may panic** if a type's `Ord`, or the comparison function passed to `sort_by`, does not implement a total order, and `Ord`'s supertraits `PartialOrd`, `Eq` and `PartialEq` must be consistent too. The previous implementations would not notice; the new ones "have a good chance of detecting inconsistencies, throwing a panic rather than returning knowingly unsorted data". The panic message a program built with rustc 1.99.1 prints is: ```plaintext user-provided comparison function does not correctly implement a total order ``` Code that "worked" for years can start panicking after a toolchain upgrade without a single source change, which is why this shows up as a production incident rather than a compile error. A green test suite is weak evidence here: tests often sort a handful of tidy values, while whether the check fires depends on the particular data and slice length. ## Why unwrap_or(Ordering::Equal) is not a total order `f64::partial_cmp` returns `None` when either side is NaN. Mapping that to `Equal` looks like a harmless way to "keep NaNs somewhere in the middle", but a total order needs these laws for every `a`, `b`, `c`: - exactly one of `a < b`, `a == b`, `a > b` holds; - `<` is transitive, and so is `==`. With the NaN-is-Equal comparator, `1.0` compares `Equal` to NaN and NaN compares `Equal` to `5.0`, yet `1.0` compares `Less` than `5.0`. Equality is not transitive, so no consistent sorted arrangement exists for the algorithm to find. Whether a given run panics depends on the data and the length of the slice: in testing, some inputs sorted to a wrong order without panicking, and the 32-element example below panics on every run. `partial_cmp(b).unwrap()` is different: it is a valid total order on NaN-free data and panics with the `Option::unwrap()` message as soon as it meets a NaN, so it fails loudly instead of inconsistently. ## What the documentation promises The `slice::sort_by` docs give the contract for a comparator that is not a total order: - the function **may panic**; - even if it returns normally, **the resulting order is unspecified**; - all safe slice functions keep every original element in the slice even when they panic, so a `Vec` still drops everything correctly; - none of this is undefined behaviour. In the `cmp` docs' words, violating these requirements is a logic error and `unsafe` code must not rely on the impls being correct. The same holds for `sort`, `sort_by_key`, `sort_by_cached_key` and the `sort_unstable*` family, each worded for its own trait or closure. ## Comparators that cannot trip the check 1. **`sort_by(f64::total_cmp)`** implements IEEE 754 totalOrder: every `f64`, including each NaN and both zeros, gets one position. Positive NaNs sort after positive infinity and negative NaNs before negative infinity. 2. **Reject NaN first**, then sort with `partial_cmp(b).unwrap()`. For sensor or price data, a NaN is usually a bug worth surfacing rather than a value worth placing. 3. **Implement `Ord` once and derive the rest from it.** The `Ord` docs say to choose `Ord` first; if you hand-write it, write `PartialOrd` as `Some(self.cmp(other))` and make `PartialEq` agree with `cmp`. Clippy's `non_canonical_partial_ord_impl` warns when a `PartialOrd` on an `Ord` type does its own comparison instead. 4. **Keep every trait on the same fields.** A hand-written `Ord` that compares only `major` beside a derived `PartialEq` that compares `major` and `minor` claims `cmp == Equal` for values that are not `==`, which is exactly the supertrait inconsistency the 1.81 note names. ## Where else a broken order bites Sorting is where the panic appears, but the same broken comparator corrupts anything that assumes a total order: | Consumer | Typical symptom of an inconsistent order | |---|---| | `binary_search` on the slice | finds nothing, or the wrong element | | `iter().max()` / `min()` | answer depends on input order | | ordered collections keyed by the type | lookups miss entries that were inserted | | `dedup` after sorting | duplicates survive | Those behaviours belong to the material on collections; the fix is always here, in the comparator or the `Ord` impl.

  • The same code sorted fine before upgrading the toolchain. Was the old behaviour correct?
    No. Before Rust 1.81 the sort accepted the inconsistent comparator and returned some arrangement that was not reliably sorted, so the bug was already there; the new driftsort and ipnsort implementations simply have a good chance of detecting the inconsistency and panic instead of returning knowingly unsorted data.
  • Can you catch the panic and keep going?
    You could wrap the sort in `std::panic::catch_unwind`, and the slice keeps all its elements, but their order is unspecified, so the result is still wrong. The panic is a symptom of a broken comparator; fix the order with `total_cmp`, NaN filtering or a consistent `Ord` instead of suppressing it.

  • The sort panic is undefined behaviour caused by the new algorithm.
  • Treating NaN as Ordering::Equal is a valid total order for floats.
  • If the sort returns without panicking, the slice is correctly sorted.
  • Only sort_unstable can panic on an inconsistent comparator; sort cannot.
  • A panicking sort can drop or duplicate elements of the slice.

Assumes Rust 1.99; the may-panic behaviour of slice sorts on an inconsistent order arrived with the new sort implementations in Rust 1.81.