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 { 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 weighted deltas 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 weighted deltas
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.deltaCount).toBeLessThanOrEqual(8)
215 expect(updateResult.deltaCount).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 weighted deltas only affect the null key (verify incremental processing)
221 assertOnlyKeysAffected(`topK remove row`, updateResult.weightedDeltas, [
222 null,
223 ])
224 tracker.relation.expectRows(
225 [
226 [null, 1, `a`],
227 [null, 3, `c`],
228 [null, 4, `d`],
229 ],
230 0,
231 )
232 })
233
234 test(`incremental update - adding rows that push existing rows out of limit window`, () => {
235 const graph = new D2()
236 const input = graph.newInput<
237 [
238 null,
239 {
240 id: number
241 value: string
242 },
243 ]
244 >()
245 let latestMessage: any = null
246
247 input.pipe(
248 topKWithIndex((a, b) => a.value.localeCompare(b.value), { limit: 3 }),
249 output((message) => {
250 latestMessage = message
251 }),
252 )
253
254 graph.finalize()
255
256 // Initial data
257 input.sendData(
258 new MultiSet([
259 [[null, { id: 1, value: `c` }], 1],
260 [[null, { id: 2, value: `d` }], 1],
261 [[null, { id: 3, value: `e` }], 1],
262 ]),
263 )
264 graph.run()
265
266 // Initial result should be all three items with indices
267 let result = latestMessage.getInner()
268 let sortedResult = sortByIndexAndId(result)
269 expect(sortedResult).toEqual([
270 [[null, [{ id: 1, value: `c` }, 0]], 1],
271 [[null, [{ id: 2, value: `d` }, 1]], 1],
272 [[null, [{ id: 3, value: `e` }, 2]], 1],
273 ])
274
275 // Add two new rows that should appear before existing rows
276 input.sendData(
277 new MultiSet([
278 [[null, { id: 4, value: `a` }], 1],
279 [[null, { id: 5, value: `b` }], 1],
280 ]),
281 )
282 graph.run()
283
284 // Result should show:
285 // - 'a' and 'b' being added at indices 0 and 1
286 // - 'c' moving from index 0 to 2
287 // - 'd' and 'e' being removed as they're pushed out of the limit window
288 result = latestMessage.getInner()
289 sortedResult = sortByMultiplicityIndexAndId(result)
290
291 expect(sortedResult).toEqual([
292 [[null, [{ id: 1, value: `c` }, 0]], -1], // 'c' removed from old index 0
293 [[null, [{ id: 2, value: `d` }, 1]], -1], // 'd' removed from index 1
294 [[null, [{ id: 3, value: `e` }, 2]], -1], // 'e' removed from index 2
295 [[null, [{ id: 4, value: `a` }, 0]], 1], // New row at index 0
296 [[null, [{ id: 5, value: `b` }, 1]], 1], // New row at index 1
297 [[null, [{ id: 1, value: `c` }, 2]], 1], // 'c' added at new index 2
298 ])
299 })
300
301 test(`incremental update - changing a value that affects ordering`, () => {
302 const graph = new D2()
303 const input = graph.newInput<
304 [
305 null,
306 {
307 id: number
308 value: string
309 },
310 ]
311 >()
312 let latestMessage: any = null
313
314 input.pipe(
315 topKWithIndex((a, b) => a.value.localeCompare(b.value), { limit: 3 }),
316 output((message) => {
317 latestMessage = message
318 }),
319 )
320
321 graph.finalize()
322
323 // Initial data
324 input.sendData(
325 new MultiSet([
326 [[null, { id: 1, value: `a` }], 1],
327 [[null, { id: 2, value: `b` }], 1],
328 [[null, { id: 3, value: `c` }], 1],
329 ]),
330 )
331 graph.run()
332
333 // Initial result should be all three items with indices
334 let result = latestMessage.getInner()
335 let sortedResult = sortByIndexAndId(result)
336 expect(sortedResult).toEqual([
337 [[null, [{ id: 1, value: `a` }, 0]], 1],
338 [[null, [{ id: 2, value: `b` }, 1]], 1],
339 [[null, [{ id: 3, value: `c` }, 2]], 1],
340 ])
341
342 // Change 'a' to 'z' which should move it to the end, outside the limit
343 input.sendData(
344 new MultiSet([
345 [[null, { id: 1, value: `a` }], -1],
346 [[null, { id: 1, value: `z` }], 1],
347 ]),
348 )
349 graph.run()
350
351 // Result should show:
352 // - 'a' being removed from index 0
353 // - 'b' moving from index 1 to 0
354 // - 'c' moving from index 2 to 1
355 // - 'z' being added at index 2
356 result = latestMessage.getInner()
357 sortedResult = sortByMultiplicityIndexAndId(result)
358
359 expect(sortedResult).toEqual([
360 [[null, [{ id: 1, value: `a` }, 0]], -1], // 'a' removed from index 0
361 [[null, [{ id: 2, value: `b` }, 1]], -1], // 'b' removed from old index 1
362 [[null, [{ id: 3, value: `c` }, 2]], -1], // 'c' removed from old index 2
363 [[null, [{ id: 2, value: `b` }, 0]], 1], // 'b' added at new index 0
364 [[null, [{ id: 3, value: `c` }, 1]], 1], // 'c' added at new index 1
365 [[null, [{ id: 1, value: `z` }, 2]], 1], // 'z' added at index 2
366 ])
367 })
368
369 test(`incremental update with offset - items moving in and out of window`, () => {
370 const graph = new D2()
371 const input = graph.newInput<
372 [
373 null,
374 {
375 id: number
376 value: string
377 },
378 ]
379 >()
380 let latestMessage: any = null
381
382 input.pipe(
383 topKWithIndex((a, b) => a.value.localeCompare(b.value), {
384 limit: 2,
385 offset: 1,
386 }),
387 output((message) => {
388 latestMessage = message
389 }),
390 )
391
392 graph.finalize()
393
394 // Initial data - a, b, c, d, e
395 input.sendData(
396 new MultiSet([
397 [[null, { id: 1, value: `a` }], 1],
398 [[null, { id: 2, value: `b` }], 1],
399 [[null, { id: 3, value: `c` }], 1],
400 [[null, { id: 4, value: `d` }], 1],
401 [[null, { id: 5, value: `e` }], 1],
402 ]),
403 )
404 graph.run()
405
406 // Initial result should be b, c (offset 1, limit 2)
407 let result = latestMessage.getInner()
408 let sortedResult = sortByIndexAndId(result)
409 expect(sortedResult).toEqual([
410 [[null, [{ id: 2, value: `b` }, 1]], 1],
411 [[null, [{ id: 3, value: `c` }, 2]], 1],
412 ])
413
414 // Add a new item 'aa' that should be between 'a' and 'b'
415 input.sendData(new MultiSet([[[null, { id: 6, value: `aa` }], 1]]))
416 graph.run()
417
418 // Result should show:
419 // - 'aa' being added at index 1
420 // - 'b' moving from index 1 to 2
421 // - 'c' being removed as it's pushed out of the window
422 result = latestMessage.getInner()
423 sortedResult = sortByMultiplicityIndexAndId(result)
424
425 expect(sortedResult).toEqual([
426 [[null, [{ id: 2, value: `b` }, 1]], -1], // 'b' removed from old index 1
427 [[null, [{ id: 3, value: `c` }, 2]], -1], // 'c' removed from index 2
428 [[null, [{ id: 6, value: `aa` }, 1]], 1], // 'aa' added at index 1
429 [[null, [{ id: 2, value: `b` }, 2]], 1], // 'b' added at new index 2
430 ])
431 })
432 })
433})
434
435/**
436 * Helper function to sort results by index and then id
437 */
438function sortByIndexAndId(results: Array<any>) {
439 return [...results].sort(
440 (
441 [[_aKey, [aValue, aIndex]], _aMultiplicity],
442 [[_bKey, [bValue, bIndex]], _bMultiplicity],
443 ) => {
444 // First sort by index
445 if (aIndex !== bIndex) {
446 return aIndex - bIndex
447 }
448 // Then by id if indices are the same
449 return aValue.id - bValue.id
450 },
451 )
452}
453
454/**
455 * Helper function to sort results by key, then index, then id
456 */
457function sortByKeyIndexAndId(results: Array<any>) {
458 return [...results].sort(
459 (
460 [[aKey, [aValue, aIndex]], _aMultiplicity],
461 [[bKey, [bValue, bIndex]], _bMultiplicity],
462 ) => {
463 // First sort by key
464 if (aKey !== bKey) {
465 return aKey < bKey ? -1 : 1
466 }
467 // Then by index
468 if (aIndex !== bIndex) {
469 return aIndex - bIndex
470 }
471 // Then by id if indices are the same
472 return aValue.id - bValue.id
473 },
474 )
475}
476
477/**
478 * Helper function to sort results by multiplicity, then index, then id
479 */
480function sortByMultiplicityIndexAndId(results: Array<any>) {
481 return [...results].sort(
482 (
483 [[_aKey, [aValue, aIndex]], aMultiplicity],
484 [[_bKey, [bValue, bIndex]], bMultiplicity],
485 ) => {
486 // First sort by multiplicity
487 if (aMultiplicity !== bMultiplicity) {
488 return aMultiplicity - bMultiplicity
489 }
490 // Then by index
491 if (aIndex !== bIndex) {
492 return aIndex - bIndex
493 }
494 // Then by id if indices are the same
495 return aValue.id - bValue.id
496 },
497 )
498}