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

topk-batch.test.ts

149 lines4.6 KB

1// Ordinary top-K batch tests: fixed replacements, collisions, and payload
2// access, plus exception propagation. Each compares production with literal
3// or input-derived expectations and reaches no declared part.
4// topk-batch-contract-oracle.test.ts owns the cancellation and replacement law.
5import { afterEach, expect, it, vi } from 'vitest'
6import { MultiSet } from '../../src/multiset.js'
7import * as hashing from '../../src/hashing/index.js'
8import { topKBatch } from '../../src/operators/topKState.js'
9import { D2 } from '../../src/d2.js'
10import { topKWithFractionalIndex } from '../../src/operators/topKWithFractionalIndex.js'
11import { output } from '../../src/operators/index.js'
12​
13afterEach(() => vi.restoreAllMocks())
14​
15it.each([
16 { name: `RegExp source`, before: /old/g, after: /new/g },
17 { name: `RegExp flags`, before: /same/g, after: /same/i },
18 {
19 name: `RegExp position`,
20 before: Object.assign(/same/g, { lastIndex: 0 }),
21 after: Object.assign(/same/g, { lastIndex: 1 }),
22 },
23 { name: `sparse-array length`, before: [], after: Array(2) },
24])(
25 `keeps a $name replacement through hash consolidation`,
26 ({ before, after }) => {
27 // Relation: a retraction and a distinct addition must remain observable to
28 // an ordered operator even when an earlier stage consolidates the batch.
29 const previous = { id: 1, value: before }
30 const next = { id: 1, value: after }
31 expect(
32 new MultiSet([
33 [previous, -1],
34 [next, 1],
35 ])
36 .consolidate()
37 .getInner(),
38 ).toEqual([
39 [previous, -1],
40 [next, 1],
41 ])
42 },
44​
45it(`keeps distinct row keys when structural hashes collide`, () => {
46 // A hash is an accelerator, never proof that two keyed rows are equal.
47 vi.spyOn(hashing, `hash`).mockReturnValue(7)
48 const batch = new MultiSet<[string | number, { id: number }]>([
49 [[1, { id: 1 }], 1],
50 [[`1`, { id: 2 }], 1],
51 ])
52 expect([...topKBatch([batch])]).toEqual(batch.getInner())
53})
54​
55it(`does not inspect payloads when each key occurs once`, () => {
56 let reads = 0
57 const rows = Array.from({ length: 100 }, (_, id) => ({
58 id,
59 get unused() {
60 reads++
61 return id
62 },
63 }))
64 const batch = new MultiSet<[number, (typeof rows)[number]]>(
65 rows.map((row) => [[row.id, row], 1]),
66 )
67 const actual = [...topKBatch([batch])]
68 expect(reads).toBe(0)
69 expect(actual).toHaveLength(rows.length)
70 for (const [index, [[key, row], weight]] of actual.entries()) {
71 expect(key).toBe(index)
72 expect(row).toBe(rows[index])
73 expect(weight).toBe(1)
74 }
75})
76​
77it.each([TypeError, RangeError])(
78 `does not swallow user %s exceptions while bucketing`,
79 (ErrorType) => {
80 const error = new ErrorType(`Cannot hash cyclic structural values`)
81 const row = {
82 get value(): number {
83 throw error
84 },
85 }
86 let observed: unknown
87 try {
88 Array.from(
89 topKBatch([
90 new MultiSet<[number, object]>([
91 [[1, row], 1],
92 [[1, row], -1],
93 [[1, { value: 2 }], 1],
94 ]),
95 ]),
96 )
97 } catch (caught) {
98 observed = caught
99 }
100 expect(observed).toBe(error)
101 },
103​
104it.each([`plain cycle`, `class cycle`, `large payload`] as const)(
105 `orders a unique key without imposing a structural hash domain: %s`,
106 (kind) => {
107 class Row {
108 id = 1
109 payload: unknown
110 }
111 const row =
112 kind === `class cycle`
113 ? new Row()
114 : { id: 1, payload: undefined as unknown }
115 row.payload = kind === `large payload` ? new Array(1_000_001).fill(0) : row
116 const entries = [
117 ...topKBatch([new MultiSet<[number, typeof row]>([[[1, row], 1]])]),
118 ]
119 expect(entries).toHaveLength(1)
120 expect(entries[0]![0][1]).toBe(row)
121 expect(entries[0]![1]).toBe(1)
122 const graph = new D2()
123 const input = graph.newInput<[number, typeof row]>()
124 const observed: Array<[[number, [typeof row, string]], number]> = []
125 input.pipe(
126 topKWithFractionalIndex((a, b) => a.id - b.id, { limit: 1 }),
127 output((message) => observed.push(...message.getInner())),
128 )
129 graph.finalize()
130 input.sendData(new MultiSet([[[1, row], 1]]))
131 graph.run()
132 expect(observed).toHaveLength(1)
133 expect(observed[0]![0][1][0]).toBe(row)
134 expect(observed[0]![1]).toBe(1)
135 },
137​
138it(`consolidates structurally equal fresh transient values before replacements`, () => {
139 const batch = new MultiSet<[number, { value: string }]>([
140 [[1, { value: `new` }], 1],
141 [[1, { value: `temporary` }], 1],
142 [[1, { value: `old` }], -1],
143 [[1, { value: `temporary` }], -1],
144 ])
145 expect([...topKBatch([batch])]).toEqual([
146 [[1, { value: `old` }], -1],
147 [[1, { value: `new` }], 1],
148 ])
149})