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