Skip to content

fix(collection): LIST distinct keeps first-occurrence order; -0.0 equals 0.0 in float vector cells - #1372

Merged
singaraiona merged 4 commits into
devfrom
fix/list-cell-order-signed-zero
Nov 23, 2026
Merged

singaraiona merged 4 commits into
devfrom
fix/list-cell-order-signed-zero

Conversation

@singaraiona

@singaraiona singaraiona commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #1361

Two fixes, one commit each.

1. distinct over a LIST keeps first-occurrence order

Cause. ray_distinct_fn (src/ops/collection.c:2497-2508 on dev e3dbd9c) dedups LIST cells in first-occurrence order and then runs a swap loop that moves atoms ahead of vectors. That breaks the documented "Remove duplicates, preserving order" and also scrambles the vectors: (distinct (list [1] [2] 3 [4] 5)) gave [3 5 [1] [4] [2]].

Fix. The swap loop is gone. The scan path (under 64 cell pairs) and the hashed path (list_set_t) both already keep cells in order.

Answers that change. Any LIST distinct holding both atoms and vectors now comes back in input order: (distinct (list [1] [2] 3 [4] 5)) is [[1] [2] 3 [4] 5], and (distinct (list [3i 3i] 2i [3i 3i] 2i)) is (list [3i 3i] 2i). Four existing pins expected the old order and are updated with a comment pointing here: distinct.rfl:32, collection_branch_cov.rfl:699, list_cell_sets.rfl:356-358 (the 3000-cell MK set), and distinct_exact_int.rfl:10 (added by #1453, which pinned atoms ahead of vector cells).

2. -0.0 equals 0.0 in F64 and F32 vector cells

Cause. atom_eq compared two vector cells of one type with memcmp (src/ops/collection.c:1866), and key_hash hashed their bytes (collection.c:2061). Between atoms, and under identical, -0.0 equals 0.0. Inside vector cells it did not, so [0.0] and (enlist (neg 0.0)) stayed two cells in distinct, except, sect, union, group, select ... by:, count distinct, xkey and keyed-table ==. Both of those functions are shared by every one of these consumers: the list sets, group's LIST path, the grouped and parallel LIST key paths in agg_engine.c, xkey and keyed == in tblop.c and cmp.c, and the table and dict column compares through atom_eq_cell_col. Nested lists recurse through the same two functions, so fixing them fixes every consumer at any depth. The other hashes a vector cell can reach agree already: ray_atom_hash (dict cells) and hs_hash_row's LIST arm hash a vector by type and length only, and span_vec_hash (a TIMESPAN in the set) rounds each element through ray_hash_f64, which already clears -0.0.

Fix.

  • Compare: an F64 or F32 cell pair is first compared with memcmp. Equal bytes are equal cells, which is the common case on a hash hit. Only when the bytes differ is each element compared on its bits, with -0.0 cleared by b & ((b == SIGN) - 1). That mask is integer arithmetic, so the release build's -fno-signed-zeros cannot fold it away the way it can fold v + 0.0. NaN bits are left alone, so the F64 null still equals only the same null bits, as before.
  • Hash: a cell of up to 64 bytes (8 F64 or 16 F32) is hashed directly from the normalised words, 16 bytes per mixing step. This costs no more than the byte hash it replaces, and less for short cells. A longer cell is checked for -0.0 one compare per element in 4096-byte chunks. A chunk with no -0.0 is hashed in place with ray_hash_bytes. A chunk that holds one goes through a cold normalising copy and is hashed as the +0.0 chunk would be.
  • Other vector types still use memcmp and the byte hash.

Answers that change.

(count (distinct (list [0.0] (enlist (neg 0.0)))))     ; 2 -> 1
(count (distinct (list [0.0e] (enlist (neg 0.0e)))))   ; 2 -> 1
(except (list (enlist (neg 0.0)) 1) (list [0.0]))      ; [[-0.0] 1] -> [1]
(xkey (table [k v] (list (list [0.0] (enlist (neg 0.0))) [1 2])) [k])   ; 2 keys -> domain error (duplicate key)
(diverse (list [0.0] (enlist (neg 0.0))))              ; true -> false
(count (distinct (table [k] (list (list [7 7] [0.0] (enlist (neg 0.0)))))))   ; 3 -> 2

group, select ... by: and count distinct over such cells merge them, at any core count. The parallel directory path was checked at -c 8 with 200k rows. Keyed == with a -0.0 key now finds the 0.0 key. Existing pins updated, each with a comment pointing here: xkey_vector_keys.rfl:15, container_equality_vector_keys.rfl:20, list_cell_sets.rfl:197-211 (rule 8) and span_vec_cell_hash.rfl:341, 342, 368.

Not changed: in. The issue's (in (list (enlist (neg 0.0))) (list [0.0])) is still [[false]]. in with a list on the left tests each leaf atom, and an atom never equals a vector cell, so (in (list [0.0]) (list [0.0])) is [[false]] on dev too. The leaf -0.0 already matches a 0.0 atom ((in (list N) (list 0.0)) is [[true]]). Getting [[true]] for the issue's example would mean changing in's leaf rule, which is outside this fix.

Docs

Tests

New test/rfl/collection/list_cell_rules.rfl, with @also-unfused. It fails on dev at its first line in both parts: the order cases, and with the order section removed, at (count (distinct (list P N))). It covers:

  • distinct order: mixed atoms, vectors and nested lists, duplicates of both kinds, on both the scan path and the hashed path (past 64 pairs).
  • signed zero for F64 and F32 cells in distinct, except, sect, union, group, select ... by:, count distinct (grouped and whole), xkey and keyed ==. Cells are nested in lists, dicts and tables.
  • every cell length the hash treats differently: up to 64 bytes, longer, past one 4096-byte chunk, and a -0.0 in the first chunk, the last chunk or both.
  • [1.0] against [-1.0] (only -0.0 is cleared, not every sign bit).
  • NaN and null cells unchanged, and empty vectors per type.
  • a hash/equality differential. A pool of 17 cells (signed zeros, NaN, nested lists, tables, empties) is deduplicated two cells at a time, which takes the scan path and never hashes, and the result must be identical to the hashed distinct over 51 copies. group, except, sect and union over the same copies must agree with it.

The file also runs in the release-flavour binary (make test-release). The issue's examples give the new answers from both a clang and a gcc release binary, and group, select ... by:, count distinct, except, sect and union over 200k cells agree at -c 1 and -c 8 in the clang release binary. Together these confirm the normalisation survives -fno-signed-zeros.

Mutations

Each mutant was built into the test binary and run against list_cell_rules.rfl. These fail:

  • compare is memcmp only
  • hash is bytes only
  • F64 mask removed
  • F32 mask removed
  • the mask clears every sign bit
  • the short-path F64 words loaded raw
  • the F32 low half not cleared
  • the F32 high half not cleared
  • the F32 odd tail loaded raw
  • the long-path -0.0 scan blind, for F64 and for F32
  • the normalising copy not normalising, for F64 and for F32
  • the chunk loop stopping after the first chunk with a -0.0
  • the F64 path only hashing F64, so F32 cells get the byte hash
  • the part 1 swap loop restored

The hash-only mutant is also caught by the differential alone.

Three mutants survive, and none is a wrong answer through equality:

  • packing the F32 high lanes with the wrong shift
  • dropping the last 16-byte step from the short path

Both still give equal cells equal hashes, so they only weaken the hash.

  • raising the short-path limit to 72 bytes

That one writes past the 8-word buffer, which the non-sanitised test binary does not detect.

Timings

Release build (clang), min of 7 to 15 runs, taskset -c 4 ./rayforce -c 1, in ms. The baseline is dev's collection.c built in the same tree. A separately built dev tree measured up to 12% apart from it on atom-only paths with identical source, so cross-tree numbers are not comparable at that level. The cells are 1M (F, I: two elements, 97k distinct) unless noted.

case dev branch
distinct F64 cells 28.1 25.8
distinct I64 cells 27.9 28.0
in (50k cells) F64 20.5 16.8
in I64 20.4 19.6
except F64 19.7 18.7
except I64 19.7 20.2
group F64 32.6 31.9
group I64 33.4 33.4
select by: F64 21.4 20.3
select by: I64 21.5 21.9
distinct mixed atoms and I64 cells (part 1) 14.4 14.2
distinct 4-element F64 14.5 14.3
distinct 4-element F32 14.8 15.3
distinct 8-element F64 18.3 18.3
distinct 8-element I64 18.4 18.4
distinct 16-element F64 (500k) 11.0 12.4
distinct 16-element F32 (500k) 8.8 8.9
distinct 64-element F64 (200k) 11.2 12.3
distinct 16-element I64 (500k) 11.0 11.2

All cores (28): distinct, in and except are serial and match the table. group over F64 and I64 cells is about 5.0 ms on both, and select by: is 4.3-4.5 ms on both.

Cells of up to 64 bytes are as fast as before or faster. Longer float cells pay the one compare per element that finds a -0.0, about 2.7 ns per 16-element cell. I64 cells are within run-to-run noise.

Independent review

  • Hash and equality. The new compare and hash functions ran in a standalone harness under clang and gcc, with the release flags and with ASan+UBSan. They were fuzzed on 300k random F64/F32 cell pairs, including 0.0/-0.0, NaN, -NaN, unaligned buffers, and lengths around 0-20 cells and around every 4096-byte chunk boundary. A targeted sweep then covered every length from 0 to 2100 cells, with -0.0 at the edges, at either side of a chunk boundary, and at every element. Result: 0 cases where equal cells hashed differently. The in-place path and the normalising-copy path agree.
  • Rfl differential. 312 random pools compared a two-cell scan oracle with hashed distinct, group, except, union and sect. All were consistent, in release and ASan builds.
  • Unchanged answers. Without -0.0, dev and this branch give byte-identical answers, so NaN, null and mixed-type behaviour is unchanged.
  • Release flags. The normalisation survives make release, because it is integer masking that -fno-signed-zeros can't remove.

The cost of the rule, measured. Hashing a float cell longer than 64 bytes now includes one compare per element to find a -0.0, which is the per-element cost the rule was accepted with. That makes such cells hash about 1.4-1.6x slower than on dev. For example, an F64 cell of 200 values goes from 40 to 58 ns, and distinct over 2000 cells of 2000 F64 values from about 2.2 to 3.4 ms. Unrelated to that scan, an unequal float-cell compare costs about 0.7 ns more. Cells of 64 bytes or less are as fast or faster than on dev, and so are non-float cells.

Suites

On dev 676ff3c (rebased over #1478; only its three docs files conflicted):

  • make test (clang): 5590 of 5594 passed, 4 skipped, 0 failed.
  • make clean && make CC=gcc test: 5590 of 5594 passed, 4 skipped, 0 failed.
  • make CC=gcc release: clean.
  • make release && make test-release (ASan+UBSan): 7062 of 7066 passed, 4 skipped, 0 failed.

@singaraiona singaraiona left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review of 4087250. No correctness bug in the change.

  • Order: first-occurrence order holds on every LIST route at -c 1 and -c 8, against a 200k-row oracle: distinct, group keys, by: keys, union/except/sect both ways, per-group distinct and count distinct.
  • -0.0: a constant-hash oracle build over 470 seeds (mixed F64/F32 cells with ±0.0, NaN and null, long cells at the 4096-byte edges, nested, dict and table cells, TIMESPAN mixes, 70k-row parallel paths) is byte-identical to this build, so no equal pair hashes differently.
  • Tests: reverting each commit fails its tests.

Two items:

  1. The docs overstate the order. Typed numeric and temporal distinct returns ascending order, on dev and here: (distinct [3 1 3 2]) is [1 2 3], (distinct [2024.01.02 2024.01.01]) is ascending, and only SYM, STR and LIST keep first occurrence. The new math.md line and the functions.md row say vectors keep first occurrence; say it for lists, and leave typed order as it is documented today. I've raised the typed-order question separately, since all-functions.md already says "preserving order".
  2. Two more answer changes to list (both right under the new rule):
    • (diverse (list [0.0] (enlist (neg 0.0)))) goes true → false;
    • table distinct with -0.0 and 0.0 cells, (count (distinct (table [k] (list (list [7 7] [0.0] (enlist (neg 0.0))))))), goes 3 → 2.

Not blocking: F64x200 cells are about 15% slower (the disclosed long-cell scan), and group over F32x16 cells at -c 8 is about 9% slower (64-byte cells, short path).

Found on the way, already on dev, filed separately: joins on LIST key columns compare cell pointers (wrong matches); find with a LIST needle of vector cells; pivot over a LIST column.

@singaraiona

Copy link
Copy Markdown
Collaborator Author

Thanks. Both items are done in 1b42dd0 and in the body. The branch is rebased onto dev da47b28.

  1. Order in the docs. math.md and functions.md now say that a list, SYM or STR vector keeps first-occurrence order, while a numeric or temporal vector comes back ascending, as on dev. The example is (distinct [3 1 3 2]) → [1 2 3]. I checked it on the branch: ['c 'a 'c 'b] gives [c a b], and a STR vector keeps its order too. Typed order itself is unchanged here, pending your separate question.
  2. Two more answer changes are listed in the body, both checked on the branch:
    • (diverse (list [0.0] (enlist (neg 0.0)))) goes true → false;
    • the table distinct over [7 7] [0.0] [-0.0] cells goes 3 → 2.

The rebase crosses #1413 and #1376, which also change LIST key hashing. On the new base, make test and a clean make CC=gcc test both pass 5551/5555, gcc release is clean, and make test-release passes 7004/7008.

@singaraiona

Copy link
Copy Markdown
Collaborator Author

Rebased onto dev 8c18b24.

  • Docs: distinct now keeps first-occurrence order for every type, as decided, and math.md and functions.md say so.
  • This PR's scope: it still changes only LIST order. Numeric and temporal vectors still come back ascending on dev; moving them to first-occurrence order is a separate change. Until that lands, the docs' typed-vector example ((distinct [3 1 3 2]) is [3 1 2]) describes the coming behaviour.
  • New pin: perf(distinct): hash eligible LIST integers by exact value #1453 added distinct_exact_int.rfl, which pinned atoms ahead of vector cells in a mixed list. It's repinned to first-occurrence order.
  • Suites: make test passes 5587/5591. The gcc and test-release runs before the repin failed only on that pin.

singaraiona added a commit that referenced this pull request Nov 23, 2026
…d vector (#1478)

## Bug

`distinct` over a numeric or temporal vector returned its values sorted, not in first-occurrence order (#1477):
- `(distinct [3 1 3 2])` gave `[1 2 3]`;
- `(distinct [true false true])` gave `[false true]`;
- `select … by:` distinct came back sorted per group.

SYM, STR, GUID and LIST keep first occurrence, and the docs say "Remove duplicates, preserving order". anton decided A on the board (T-707): every typed vector keeps first-occurrence order.

## Cause

`distinct_vec_eager` (`src/ops/collection.c`) collected one first-occurrence row id per value. For non-SYM, non-STR, non-GUID types it then sorted those ids by value (`distinct_sort_indices`, a qsort with a per-type comparator) before gathering them. The sort-index fast path (`ray_index_distinct_ids`) returns one first-occurrence row per value, in value order.

## Fix

- The value sort and its comparator are gone. The hash passes (hashset, GUID set, SYM and dict-STR presence arrays) and the parallel radix kernel (`distinct_radix_first_ids`, which sweeps its first-row flags by row) already give the ids in row order.
- The sort-index fast path puts its rows back in row order: `distinct_ids_in_row_order`, a bitmap over the rows, or a qsort for at most 64 ids.
- `select`, `by:`, lazy chains (`OP_DISTINCT`) and parted columns all go through the same function.
- A string atom's `distinct` (unique characters, sorted) is not a typed vector and is unchanged. LIST order is #1361 (#1372).

## Performance

10M rows, release, best of 3, two runs (ms). The machine was loaded by other test runs (load 23–44).

| | 1 core dev | 1 core PR | multi-core dev | multi-core PR |
|---|---|---|---|---|
| I64, 1k distinct values | 22.9 | 15.9 | 10.2 | 9.9 |
| I64, 1M distinct values | 91.5 | 34.9 | 69.6 | 19.1 |
| I64, all distinct | 399.4 | 68.1 | 353.3 | 46.7 |
| F64, 100k distinct values | 97.1 | 102.5 | 97.5 | 94.4 |
| I64, 1M distinct, sort index | 85.8 | 83.9 | 81.6 | 92.9 |
| `select {d: (distinct v) by: k}` | 56.0 | 55.8 | 30.4 | 30.4 |

Dropping the value sort removes an O(u log u) qsort.

## Tests

- `test/rfl/collection/distinct_first_order.rfl` (new, `@also-unfused`) covers:
  - every typed vector, with nulls;
  - 200k–300k rows through the radix kernel, against an oracle: `group`'s first row of each value, in row order;
  - a null between duplicates;
  - a sort index, against the same oracle (it fails with the reordering removed);
  - `select`, `by:`, a lazy chain, `count` and a parted table.
- Tests that pinned the sorted order now expect first-occurrence order:
  - `test/rfl/collection/distinct.rfl`, `collection_branch_cov.rfl`, `null/distinct.rfl`, `lazy/chains.rfl`, `ops/idiom.rfl`, `ops/idiom_branch_cov.rfl`, `ops/idx_route.rfl`, `agg/count_distinct.rfl`, `group/strlen_grow.rfl` and `agg/first_last_positional.rfl` (the last one keeps its null-first input);
  - `test/test_idx_route.c` `distinct_order_contract` is now `{5,1,9,3,7}`;
  - `test/test_group_extra.c` `count_distinct_runs_partitions` now checks that 1M all-distinct values come back equal to the input.
- Full suite: 5588 of 5592 passed (4 skipped, 0 failed).

## Docs

- `docs/docs/reference/all-functions.md` and `docs/docs/language/functions.md`: the `distinct` row states the rule, with `(distinct [3 1 3 2])` → `[3 1 2]`. `mkdocs build --strict` passes.

Fixes #1477
distinct over a LIST deduplicated in first-occurrence order and then
moved the atoms ahead of the vectors, which also scrambled the vectors:
(distinct (list [1] [2] 3 [4] 5)) gave [3 5 [1] [4] [2]].  Drop the
reorder so a list keeps the order the docs describe and typed vectors
already give.  Refs #1361.
atom_eq compared two F64 or F32 vector cells by memcmp and ray_key_hash
hashed their bytes, so [0.0] and (enlist (neg 0.0)) were two cells in
distinct, except, sect, union, group, select by:, count distinct, xkey
and keyed-table ==, while the atoms and identical call them equal.

Compare float cells by memcmp and, only when the bytes differ, on their
bits with -0.0 cleared to +0.0: an integer mask the release build's
-fno-signed-zeros cannot fold.  Hash a cell of up to 64 bytes by mixing
those bits directly, 16 bytes a step; a longer one is hashed in place a
4096-byte chunk at a time, through a normalising copy only for a chunk
that holds a -0.0.  NaN bits are kept, so the F64 null still equals only
itself.  Other vector cells keep memcmp and byte hashing.  Refs #1361.
@singaraiona
singaraiona force-pushed the fix/list-cell-order-signed-zero branch from d20fee9 to 9015fea Compare November 23, 2026 12:37
@singaraiona

Copy link
Copy Markdown
Collaborator Author

Rebased onto dev 676ff3c, after #1478. Only the three docs files conflicted, and I resolved them by keeping #1478's text and its (distinct [3 1 3 2 1]) → [3 1 2] example. Added on top:

  • math.md: list cells keep first occurrence, and the cell equality rule (-0.0 equals 0.0 in float vector cells; NaN equals only NaN), with list examples;
  • all-functions.md: the distinct row now covers list cells and -0.0.

Suites: make test and clean gcc make test pass 5590/5594, gcc release is clean, and make test-release passes 7062/7066.

@singaraiona singaraiona left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Verified at 9015fea, rebased onto dev after #1478; the src changes are identical to the reviewed d20fee9.

  • LIST order: LIST distinct keeps first-occurrence order (1242 configs against the first-occurrence oracle).
  • Signed zero: -0.0 equals 0.0 in F64/F32 vector cells and nothing else merges (600-seed model oracle).
  • Speed and tests: no slowdown, and the test fails on dev.

Approved.

@singaraiona
singaraiona merged commit 0f819e3 into dev Nov 23, 2026
11 checks passed
@singaraiona
singaraiona deleted the fix/list-cell-order-signed-zero branch November 23, 2026 12:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(collection): LIST distinct reorders cells, and vector cells treat -0.0 and 0.0 as different

1 participant