Correlated toArray over a distinct derived query drops children from earlier parents #2273
A correlated toArray() loses rows from an earlier parent when its source is a derived query with .distinct(). The same query without .distinct() returns all expected rows, even though the input contains no duplicates.
Reproduced with @tanstack/react-db@0.5.12 / @tanstack/db@0.15.2, Bun 1.4.4, macOS. No React rendering or external sync service is needed.
Run this as bun repro.mjs in a project with @tanstack/react-db@0.5.12 installed:
import { createCollection, Query, eq, toArray, queryOnce } from '@tanstack/react-db';
function coll(id, rows) {
return createCollection({
id, getKey: r => r.id, startSync: true,
sync: { sync: ({ begin, write, commit, markReady }) => {
begin();
for (const value of rows) write({ type: 'insert', value });
commit();
markReady();
} },
});
}
const groups = coll('groups', [{ id: 'a' }, { id: 'b' }]);
const items = coll('items', [
{ id: 'a1', group: 'a', value: '1' },
{ id: 'a2', group: 'a', value: '2' },
{ id: 'b1', group: 'b', value: '1' },
{ id: 'b2', group: 'b', value: '2' },
]);
for (const dedup of [false, true]) {
let derived = new Query().from({ row: items })
.select(({ row }) => ({ group: row.group, value: row.value }));
if (dedup) derived = derived.distinct();
const query = new Query().from({ g: groups }).select(({ g }) => ({
id: g.id,
items: toArray(new Query().from({ item: derived })
.where(({ item }) => eq(item.group, g.id))
.select(({ item }) => ({ value: item.value }))),
}));
console.log(dedup, JSON.stringify((await queryOnce({ query }))
.map(({ id, items }) => ({ id, items }))));
}
Expected for both iterations:
[{"id":"a","items":[{"value":"1"},{"value":"2"}]},{"id":"b","items":[{"value":"1"},{"value":"2"}]}]
Actual with dedup=true:
[{"id":"a","items":[]},{"id":"b","items":[{"value":"1"},{"value":"2"}]}]
The derived rows differ by group, so they should remain distinct. This silently omits children when multiple parents have equal projected child values. Materializing the distinct derived query into a live-query collection before using it as the nested source avoids the omission in testing, but requires a separate collection lifecycle.
I checked #1709 (join scan cost) and #1975 (reused aliases). This reproduction has no join and uses different aliases, so it appears to be a separate correctness issue.
TkDodo closed this
Sign in to join this conversation.