AK/Wri/Sorting Your Way Into A Bug

Sorting your way into a bug

1 min read

you thinkwhat the runtime does
"sort puts equal items in input order"only if the sort is stable
"sort compares whole objects"it compares return values of your comparator
"sorted means deterministic"ties + unstable sort = shuffle season

javascript: numeric sort trap

JAVASCRIPT
[10, 2, 1].sort(); // [1, 10, 2] — lexicographic by default

fix is boring and correct:

JAVASCRIPT
[10, 2, 1].sort((a, b) => a - b);

python: timsort is stable (mostly you)

PYTHON
users = [("ada", 2), ("lin", 1), ("ada", 1)]
sorted(users, key=lambda u: u[0])
# ada stays in original relative order for equal keys

good when you sort by name and want predictable tie behavior.

the production bug

we sorted dashboard rows by priority descending, then rendered. looked fine in dev. in prod, rows with the same priority jumped between refreshes.

TYPESCRIPT
items.sort((a, b) => b.priority - a.priority);

v8's sort is stable now, but the comparator lied. when priorities tied, it returned 0 and the engine kept order — until a different engine version, a wasm path, or a secondary sort key was missing.

the fix we should have written on day one

TYPESCRIPT
items.sort((a, b) => {
  if (b.priority !== a.priority) return b.priority - a.priority;
  return a.id.localeCompare(b.id); // explicit tie-break
});

rust reminder (for contrast)

rust's sort_by is not stable. if you need stability, sort_by_key on indices or sort_by with explicit secondary keys.

pocket rules

  1. never trust default sort for numbers in js
  2. always define tie-breakers for business-visible ordering
  3. if order matters legally or financially, write it in the comparator, not in hope