Repository navigation
fix(collection): distinct keeps first-occurrence order for every typed vector - #1478
Merged
Merged
Conversation
…d vector distinct over a numeric or temporal vector sorted the first-occurrence row ids by value before gathering them, so (distinct [3 1 3 2]) was [1 2 3] while SYM, STR, GUID and LIST kept first occurrence and the docs said "preserving order". The hash passes and the parallel radix kernel already collect the ids in row order, so the value sort is dropped; the sort-index fast path, which yields one first-occurrence row per value in value order, puts its rows back in row order through a bitmap. select, by:, lazy chains and parted columns take the same function.
…nts and docs no longer describe sorted distinct
….0 sorts before 0.0 within it
singaraiona
commented
Nov 23, 2026
singaraiona
left a comment
Collaborator
Author
There was a problem hiding this comment.
Verified at ff060b2.
- Order: typed
distinctkeeps first-occurrence order for every typed vector, per the owner's T-707 decision. A 960-config oracle at -c 1/4/28 passes, and all 230 sort-index cases equal the hash path, including -0.0/0.0. - Unchanged: LIST, SYM and STR are unchanged.
- Speed: 7–17× faster when many values are distinct.
- Tests: they fail on dev.
Approved.
singaraiona
added a commit
that referenced
this pull request
Nov 23, 2026
…als 0.0 in float vector cells (#1372) 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 - math.md, under `distinct`: built on #1478's text (every type keeps first-occurrence order, `(distinct [3 1 3 2 1])` is `[3 1 2]`). It adds that a list keeps each cell where it first occurs, whether its cells are atoms, vectors or nested lists, and the cell equality rule shared by distinct, except, sect, union, group, xkey and keyed `==`: in F64 and F32 vector cells -0.0 equals 0.0, and NaN equals only NaN. - all-functions.md: the distinct row adds list cells and -0.0 in float vector cells. functions.md keeps #1478's row. ## 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
pushed a commit
that referenced
this pull request
Nov 23, 2026
…o too (#1399) The owner decided (#1385, option A) that `union` is a set: `(union [1 1 2] [2 3])` is `[1 2 3]`. The result is the distinct elements of the left operand, then those of the right it lacks, each once, in order of first appearance; it equals `distinct` of the concatenation. `except` and `sect` keep the duplicates of the left operand, as documented; the docs now say so side by side. Both paths change: typed vectors (a hash set over the left operand, rows gathered only when it holds a duplicate) and boxed lists. On a span/point pair (TIMESTAMP or TIME against TIMESPAN) the left operand is deduplicated by its own cells, because the keys it is compared with can make two timestamps a day apart collide; the second hash set that needs is built only when two keys collide (equal cells have equal keys, so all-distinct keys mean no duplicate). Answers that change: any `union` whose left operand had a duplicate. Three older tests pinned that (`union_rhs_distinct`, `list_cell_sets`, `span_vec_cell_hash`); for list operands they now assert identity with `distinct` of the concatenation, next to a few literal expectations so a change to `distinct` does not carry `union` along. Performance, release build, best of 5, dev vs this branch (ms, laptop, -c 4): i64 5M distinct 585 vs 575, heavy duplicates 72 vs 70, moderate duplicates 467 vs 441, sym 38 vs 38, str 42 vs 38, f64 75 vs 75, empty left 315 vs 294, 30k-cell lists 0.62 vs 0.62; span/point (10M TIMESTAMP against a TIMESPAN) distinct left 596 vs 569, duplicate left 261 vs 259, 1000-row left 225 vs 226. The reviewer's example of an all-distinct left, which was 65% slower with an always-built second set, is now at parity. One run of the duplicate-left span/point case showed a 3.7 s outlier that did not repeat in four more runs (about 255-330 ms against dev's 255-262); I did not find a cause and put it down to system load, which I cannot prove. Land order: after #1478 and #1372 (the `distinct` order) merge, this is rebased on `dev`, `list_cell_rules.rfl` is repinned for the set rule, and the docs conflicts are resolved by keeping their first-occurrence wording. Closes #1385
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Bug
distinctover 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
distinct_radix_first_ids, which sweeps its first-row flags by row) already give the ids 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.distinct(unique characters, sorted) is not a typed vector and is unchanged. LIST order is fix(collection): LIST distinct reorders cells, and vector cells treat -0.0 and 0.0 as different #1361 (fix(collection): LIST distinct keeps first-occurrence order; -0.0 equals 0.0 in float vector cells #1372).Performance
10M rows, release, best of 3, two runs (ms). The machine was loaded by other test runs (load 23–44).
select {d: (distinct v) by: k}Dropping the value sort removes an O(u log u) qsort.
Tests
test/rfl/collection/distinct_first_order.rfl(new,@also-unfused) covers:group's first row of each value, in row order;select,by:, a lazy chain,countand a parted table.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.rflandagg/first_last_positional.rfl(the last one keeps its null-first input);test/test_idx_route.cdistinct_order_contractis now{5,1,9,3,7};test/test_group_extra.ccount_distinct_runs_partitionsnow checks that 1M all-distinct values come back equal to the input.Docs
docs/docs/reference/all-functions.mdanddocs/docs/language/functions.md: thedistinctrow states the rule, with(distinct [3 1 3 2])→[3 1 2].mkdocs build --strictpasses.Fixes #1477