Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

topKWithIndex.test.ts

496 lines14.3 KB

1import { describe, expect, test } from 'vitest'
2import { D2 } from '../../src/d2.js'
3import { MultiSet } from '../../src/multiset.js'
4import { output } from '../../src/operators/index.js'
5import { topKWithIndex } from '../../src/operators/topK.js'
6import { assertOnlyKeysAffected, assertResults } from '../test-utils.js'
7import { TopKMessageTracker } from './topk-relation-oracle.js'
8​
9describe(`Operators`, () => {
10 describe(`TopKWithIndex operation`, () => {
11 test(`initial results with limit - no key`, () => {
12 const graph = new D2()
13 const input = graph.newInput<
14 [
15 null,
16 {
17 id: number
18 value: string
19 },
20 ]
21 >()
22 let latestMessage: any = null
23​
24 input.pipe(
25 topKWithIndex((a, b) => a.value.localeCompare(b.value), { limit: 3 }),
26 output((message) => {
27 latestMessage = message
28 }),
29 )
30​
31 graph.finalize()
32​
33 input.sendData(
34 new MultiSet([
35 [[null, { id: 1, value: `a` }], 1],
36 [[null, { id: 2, value: `z` }], 1],
37 [[null, { id: 3, value: `b` }], 1],
38 [[null, { id: 4, value: `y` }], 1],
39 [[null, { id: 5, value: `c` }], 1],
40 ]),
41 )
42 graph.run()
43​
44 expect(latestMessage).not.toBeNull()
45​
46 const result = latestMessage.getInner()
47 const sortedResult = sortByIndexAndId(result)
48​
49 expect(sortedResult).toEqual([
50 [[null, [{ id: 1, value: `a` }, 0]], 1],
51 [[null, [{ id: 3, value: `b` }, 1]], 1],
52 [[null, [{ id: 5, value: `c` }, 2]], 1],
53 ])
54 })
55​
56 test(`initial results with limit and offset - no key`, () => {
57 const graph = new D2()
58 const input = graph.newInput<
59 [
60 null,
61 {
62 id: number
63 value: string
64 },
65 ]
66 >()
67 let latestMessage: any = null
68 input.pipe(
69 topKWithIndex((a, b) => a.value.localeCompare(b.value), {
70 limit: 3,
71 offset: 2,
72 }),
73 output((message) => {
74 latestMessage = message
75 }),
76 )
77​
78 graph.finalize()
79​
80 input.sendData(
81 new MultiSet([
82 [[null, { id: 1, value: `a` }], 1],
83 [[null, { id: 2, value: `z` }], 1],
84 [[null, { id: 3, value: `b` }], 1],
85 [[null, { id: 4, value: `y` }], 1],
86 [[null, { id: 5, value: `c` }], 1],
87 ]),
88 )
89 graph.run()
90​
91 expect(latestMessage).not.toBeNull()
92​
93 const result = latestMessage.getInner()
94 const sortedResult = sortByIndexAndId(result)
95​
96 expect(sortedResult).toEqual([
97 [[null, [{ id: 5, value: `c` }, 2]], 1],
98 [[null, [{ id: 4, value: `y` }, 3]], 1],
99 [[null, [{ id: 2, value: `z` }, 4]], 1],
100 ])
101 })
102​
103 test(`initial results with limit - with key`, () => {
104 const graph = new D2()
105 const input = graph.newInput<
106 [
107 string,
108 {
109 id: number
110 value: string
111 },
112 ]
113 >()
114 let latestMessage: any = null
115​
116 input.pipe(
117 topKWithIndex((a, b) => a.value.localeCompare(b.value), { limit: 3 }),
118 output((message) => {
119 latestMessage = message
120 }),
121 )
122​
123 graph.finalize()
124​
125 input.sendData(
126 new MultiSet([
127 [[`one`, { id: 1, value: `9` }], 1],
128 [[`one`, { id: 2, value: `8` }], 1],
129 [[`one`, { id: 3, value: `7` }], 1],
130 [[`one`, { id: 4, value: `6` }], 1],
131 [[`one`, { id: 5, value: `5` }], 1],
132 [[`two`, { id: 6, value: `4` }], 1],
133 [[`two`, { id: 7, value: `3` }], 1],
134 [[`two`, { id: 8, value: `2` }], 1],
135 [[`two`, { id: 9, value: `1` }], 1],
136 [[`two`, { id: 10, value: `0` }], 1],
137 ]),
138 )
139 graph.run()
140​
141 expect(latestMessage).not.toBeNull()
142​
143 const result = latestMessage.getInner()
144 const sortedResult = sortByKeyIndexAndId(result)
145​
146 expect(sortedResult).toEqual([
147 [[`one`, [{ id: 5, value: `5` }, 0]], 1],
148 [[`one`, [{ id: 4, value: `6` }, 1]], 1],
149 [[`one`, [{ id: 3, value: `7` }, 2]], 1],
150 [[`two`, [{ id: 10, value: `0` }, 0]], 1],
151 [[`two`, [{ id: 9, value: `1` }, 1]], 1],
152 [[`two`, [{ id: 8, value: `2` }, 2]], 1],
153 ])
154 })
155​
156 test(`incremental update - removing a row`, () => {
157 const graph = new D2()
158 const input = graph.newInput<
159 [
160 null,
161 {
162 id: number
163 value: string
164 },
165 ]
166 >()
167 const tracker = new TopKMessageTracker<null, number>()
168​
169 input.pipe(
170 topKWithIndex((a, b) => a.value.localeCompare(b.value), { limit: 3 }),
171 output((message) => {
172 tracker.addMessage(message)
173 }),
174 )
175​
176 graph.finalize()
177​
178 // Initial data
179 input.sendData(
180 new MultiSet([
181 [[null, { id: 1, value: `a` }], 1],
182 [[null, { id: 2, value: `b` }], 1],
183 [[null, { id: 3, value: `c` }], 1],
184 [[null, { id: 4, value: `d` }], 1],
185 ]),
186 )
187 graph.run()
188​
189 // Check initial state - should have top 3 items with indices
190 const initialResult = tracker.getResult()
191 assertResults(
192 `topK initial - remove row test`,
193 initialResult,
194 [
195 [null, [{ id: 1, value: `a` }, 0]],
196 [null, [{ id: 2, value: `b` }, 1]],
197 [null, [{ id: 3, value: `c` }, 2]],
198 ],
199 4, // Max expected messages for initial data
200 )
201​
202 tracker.reset()
203​
204 // Remove 'b' from the result set
205 input.sendData(new MultiSet([[[null, { id: 2, value: `b` }], -1]]))
206 graph.run()
207​
208 // After removing 'b', we should get incremental changes
209 // The important thing is that we get a reasonable number of messages
210 // and that only the affected key (null) produces output
211 const updateResult = tracker.getResult()
212​
213 // This is an output-transfer cap, not a measurement of internal recomputation.
214 expect(updateResult.messageCount).toBeLessThanOrEqual(8)
215 expect(updateResult.messageCount).toBeGreaterThan(0) // Should have some changes
216​
217 // The materialized result should have some entries (items with positive multiplicity)
218 expect(updateResult.sortedResults.length).toBeGreaterThan(0)
219​
220 // Check that the messages only affect the null key (verify incremental processing)
221 assertOnlyKeysAffected(`topK remove row`, updateResult.messages, [null])
222 tracker.relation.expectRows(
223 [
224 [null, 1, `a`],
225 [null, 3, `c`],
226 [null, 4, `d`],
227 ],
228 0,
229 )
230 })
231​
232 test(`incremental update - adding rows that push existing rows out of limit window`, () => {
233 const graph = new D2()
234 const input = graph.newInput<
235 [
236 null,
237 {
238 id: number
239 value: string
240 },
241 ]
242 >()
243 let latestMessage: any = null
244​
245 input.pipe(
246 topKWithIndex((a, b) => a.value.localeCompare(b.value), { limit: 3 }),
247 output((message) => {
248 latestMessage = message
249 }),
250 )
251​
252 graph.finalize()
253​
254 // Initial data
255 input.sendData(
256 new MultiSet([
257 [[null, { id: 1, value: `c` }], 1],
258 [[null, { id: 2, value: `d` }], 1],
259 [[null, { id: 3, value: `e` }], 1],
260 ]),
261 )
262 graph.run()
263​
264 // Initial result should be all three items with indices
265 let result = latestMessage.getInner()
266 let sortedResult = sortByIndexAndId(result)
267 expect(sortedResult).toEqual([
268 [[null, [{ id: 1, value: `c` }, 0]], 1],
269 [[null, [{ id: 2, value: `d` }, 1]], 1],
270 [[null, [{ id: 3, value: `e` }, 2]], 1],
271 ])
272​
273 // Add two new rows that should appear before existing rows
274 input.sendData(
275 new MultiSet([
276 [[null, { id: 4, value: `a` }], 1],
277 [[null, { id: 5, value: `b` }], 1],
278 ]),
279 )
280 graph.run()
281​
282 // Result should show:
283 // - 'a' and 'b' being added at indices 0 and 1
284 // - 'c' moving from index 0 to 2
285 // - 'd' and 'e' being removed as they're pushed out of the limit window
286 result = latestMessage.getInner()
287 sortedResult = sortByMultiplicityIndexAndId(result)
288​
289 expect(sortedResult).toEqual([
290 [[null, [{ id: 1, value: `c` }, 0]], -1], // 'c' removed from old index 0
291 [[null, [{ id: 2, value: `d` }, 1]], -1], // 'd' removed from index 1
292 [[null, [{ id: 3, value: `e` }, 2]], -1], // 'e' removed from index 2
293 [[null, [{ id: 4, value: `a` }, 0]], 1], // New row at index 0
294 [[null, [{ id: 5, value: `b` }, 1]], 1], // New row at index 1
295 [[null, [{ id: 1, value: `c` }, 2]], 1], // 'c' added at new index 2
296 ])
297 })
298​
299 test(`incremental update - changing a value that affects ordering`, () => {
300 const graph = new D2()
301 const input = graph.newInput<
302 [
303 null,
304 {
305 id: number
306 value: string
307 },
308 ]
309 >()
310 let latestMessage: any = null
311​
312 input.pipe(
313 topKWithIndex((a, b) => a.value.localeCompare(b.value), { limit: 3 }),
314 output((message) => {
315 latestMessage = message
316 }),
317 )
318​
319 graph.finalize()
320​
321 // Initial data
322 input.sendData(
323 new MultiSet([
324 [[null, { id: 1, value: `a` }], 1],
325 [[null, { id: 2, value: `b` }], 1],
326 [[null, { id: 3, value: `c` }], 1],
327 ]),
328 )
329 graph.run()
330​
331 // Initial result should be all three items with indices
332 let result = latestMessage.getInner()
333 let sortedResult = sortByIndexAndId(result)
334 expect(sortedResult).toEqual([
335 [[null, [{ id: 1, value: `a` }, 0]], 1],
336 [[null, [{ id: 2, value: `b` }, 1]], 1],
337 [[null, [{ id: 3, value: `c` }, 2]], 1],
338 ])
339​
340 // Change 'a' to 'z' which should move it to the end, outside the limit
341 input.sendData(
342 new MultiSet([
343 [[null, { id: 1, value: `a` }], -1],
344 [[null, { id: 1, value: `z` }], 1],
345 ]),
346 )
347 graph.run()
348​
349 // Result should show:
350 // - 'a' being removed from index 0
351 // - 'b' moving from index 1 to 0
352 // - 'c' moving from index 2 to 1
353 // - 'z' being added at index 2
354 result = latestMessage.getInner()
355 sortedResult = sortByMultiplicityIndexAndId(result)
356​
357 expect(sortedResult).toEqual([
358 [[null, [{ id: 1, value: `a` }, 0]], -1], // 'a' removed from index 0
359 [[null, [{ id: 2, value: `b` }, 1]], -1], // 'b' removed from old index 1
360 [[null, [{ id: 3, value: `c` }, 2]], -1], // 'c' removed from old index 2
361 [[null, [{ id: 2, value: `b` }, 0]], 1], // 'b' added at new index 0
362 [[null, [{ id: 3, value: `c` }, 1]], 1], // 'c' added at new index 1
363 [[null, [{ id: 1, value: `z` }, 2]], 1], // 'z' added at index 2
364 ])
365 })
366​
367 test(`incremental update with offset - items moving in and out of window`, () => {
368 const graph = new D2()
369 const input = graph.newInput<
370 [
371 null,
372 {
373 id: number
374 value: string
375 },
376 ]
377 >()
378 let latestMessage: any = null
379​
380 input.pipe(
381 topKWithIndex((a, b) => a.value.localeCompare(b.value), {
382 limit: 2,
383 offset: 1,
384 }),
385 output((message) => {
386 latestMessage = message
387 }),
388 )
389​
390 graph.finalize()
391​
392 // Initial data - a, b, c, d, e
393 input.sendData(
394 new MultiSet([
395 [[null, { id: 1, value: `a` }], 1],
396 [[null, { id: 2, value: `b` }], 1],
397 [[null, { id: 3, value: `c` }], 1],
398 [[null, { id: 4, value: `d` }], 1],
399 [[null, { id: 5, value: `e` }], 1],
400 ]),
401 )
402 graph.run()
403​
404 // Initial result should be b, c (offset 1, limit 2)
405 let result = latestMessage.getInner()
406 let sortedResult = sortByIndexAndId(result)
407 expect(sortedResult).toEqual([
408 [[null, [{ id: 2, value: `b` }, 1]], 1],
409 [[null, [{ id: 3, value: `c` }, 2]], 1],
410 ])
411​
412 // Add a new item 'aa' that should be between 'a' and 'b'
413 input.sendData(new MultiSet([[[null, { id: 6, value: `aa` }], 1]]))
414 graph.run()
415​
416 // Result should show:
417 // - 'aa' being added at index 1
418 // - 'b' moving from index 1 to 2
419 // - 'c' being removed as it's pushed out of the window
420 result = latestMessage.getInner()
421 sortedResult = sortByMultiplicityIndexAndId(result)
422​
423 expect(sortedResult).toEqual([
424 [[null, [{ id: 2, value: `b` }, 1]], -1], // 'b' removed from old index 1
425 [[null, [{ id: 3, value: `c` }, 2]], -1], // 'c' removed from index 2
426 [[null, [{ id: 6, value: `aa` }, 1]], 1], // 'aa' added at index 1
427 [[null, [{ id: 2, value: `b` }, 2]], 1], // 'b' added at new index 2
428 ])
429 })
430 })
431})
432​
433/**
434 * Helper function to sort results by index and then id
435 */
436function sortByIndexAndId(results: Array<any>) {
437 return [...results].sort(
438 (
439 [[_aKey, [aValue, aIndex]], _aMultiplicity],
440 [[_bKey, [bValue, bIndex]], _bMultiplicity],
441 ) => {
442 // First sort by index
443 if (aIndex !== bIndex) {
444 return aIndex - bIndex
445 }
446 // Then by id if indices are the same
447 return aValue.id - bValue.id
448 },
449 )
451​
452/**
453 * Helper function to sort results by key, then index, then id
454 */
455function sortByKeyIndexAndId(results: Array<any>) {
456 return [...results].sort(
457 (
458 [[aKey, [aValue, aIndex]], _aMultiplicity],
459 [[bKey, [bValue, bIndex]], _bMultiplicity],
460 ) => {
461 // First sort by key
462 if (aKey !== bKey) {
463 return aKey < bKey ? -1 : 1
464 }
465 // Then by index
466 if (aIndex !== bIndex) {
467 return aIndex - bIndex
468 }
469 // Then by id if indices are the same
470 return aValue.id - bValue.id
471 },
472 )
474​
475/**
476 * Helper function to sort results by multiplicity, then index, then id
477 */
478function sortByMultiplicityIndexAndId(results: Array<any>) {
479 return [...results].sort(
480 (
481 [[_aKey, [aValue, aIndex]], aMultiplicity],
482 [[_bKey, [bValue, bIndex]], bMultiplicity],
483 ) => {
484 // First sort by multiplicity
485 if (aMultiplicity !== bMultiplicity) {
486 return aMultiplicity - bMultiplicity
487 }
488 // Then by index
489 if (aIndex !== bIndex) {
490 return aIndex - bIndex
491 }
492 // Then by id if indices are the same
493 return aValue.id - bValue.id
494 },
495 )