Open History to see the last commit
1/**
2 * Progressive Mode Test Suite
3 *
4 * Tests progressive sync mode behavior including:
5 * - Snapshot loading during initial sync
6 * - Atomic swap on first up-to-date
7 * - Incremental updates after swap
8 * - Txid tracking behavior
9 */
10
11import { describe, expect, it } from 'vitest'
12import { createLiveQueryCollection, eq, gt } from '@tanstack/db'
13import { waitFor, waitForQueryData } from '../utils/helpers'
14import type { E2ETestConfig, User } from '../types'
15import type { Collection } from '@tanstack/db'
16import type { ElectricCollectionUtils } from '@tanstack/electric-db-collection'
17
18export function createProgressiveTestSuite(
19 getConfig: () => Promise<E2ETestConfig>,
20) {
21 describe(`Progressive Mode Suite`, () => {
22 describe(`Basic Progressive Mode`, () => {
23 it(`should explicitly validate snapshot phase and atomic swap transition`, async () => {
24 const config = await getConfig()
25 if (!config.collections.progressive || !config.progressiveTestControl) {
26 return // Skip if progressive collections or test control not available
27 }
28 const progressiveUsers = config.collections.progressive.users
29
30 // Start sync for this test
31 progressiveUsers.startSyncImmediate()
32
33 // === PHASE 1: SNAPSHOT PHASE ===
34 // Collection might already be ready from a previous test
35 // (progressive collections are shared and not cleaned up between tests)
36 await new Promise((resolve) => setTimeout(resolve, 50))
37
38 const initialStatus = progressiveUsers.status
39
40 // If already ready, we can't test the explicit transition
41 if (initialStatus === `ready`) {
42 console.log(
43 `Progressive collection already ready, skipping explicit transition test`,
44 )
45 return
46 }
47
48 // Should be loading or idle (hook prevents marking ready)
49 expect([`idle`, `loading`]).toContain(initialStatus)
50
51 // Create a query - this triggers fetchSnapshot
52 const query = createLiveQueryCollection((q) =>
53 q
54 .from({ user: progressiveUsers })
55 .where(({ user }) => eq(user.age, 25)),
56 )
57
58 await query.preload()
59 await waitForQueryData(query, { minSize: 1, timeout: 10000 })
60
61 // Validate snapshot data
62 const snapshotQuerySize = query.size
63 const snapshotItems = Array.from(query.values())
64
65 expect(snapshotQuerySize).toBeGreaterThan(0)
66 snapshotItems.forEach((user) => {
67 expect(user.age).toBe(25)
68 expect(user.id).toBeDefined()
69 expect(user.name).toBeDefined()
70 })
71
72 // Collection should STILL be loading (paused before atomic swap)
73 expect(progressiveUsers.status).toBe(`loading`)
74
75 // Collection has snapshot data
76 const snapshotCollectionSize = progressiveUsers.size
77 expect(snapshotCollectionSize).toBeGreaterThan(0)
78
79 // === PHASE 2: TRIGGER ATOMIC SWAP ===
80 config.progressiveTestControl.releaseInitialSync()
81
82 // === PHASE 3: POST-SWAP (FULLY SYNCED) ===
83 // Wait for ready (atomic swap complete)
84 await waitFor(() => progressiveUsers.status === `ready`, {
85 timeout: 30000,
86 message: `Progressive collection did not complete sync`,
87 })
88
89 // Collection now has full dataset (more than just snapshot)
90 const finalCollectionSize = progressiveUsers.size
91 expect(finalCollectionSize).toBeGreaterThan(snapshotQuerySize)
92
93 // Query still works with consistent data
94 const finalQueryItems = Array.from(query.values())
95 finalQueryItems.forEach((user) => {
96 expect(user.age).toBe(25) // Still matches predicate
97 expect(user.id).toBeDefined()
98 })
99
100 // Verify original snapshot items are still present after swap
101 snapshotItems.forEach((originalUser) => {
102 const foundInCollection = progressiveUsers.get(originalUser.id)
103 expect(foundInCollection).toBeDefined()
104 expect(foundInCollection?.age).toBe(25)
105 })
106
107 await query.cleanup()
108 })
109
110 it(`should load snapshots during initial sync and perform atomic swap`, async () => {
111 const config = await getConfig()
112 if (!config.collections.progressive) {
113 return // Skip if progressive collections not available
114 }
115 const progressiveUsers = config.collections.progressive.users
116
117 // Start sync for this test
118 progressiveUsers.startSyncImmediate()
119
120 // Query a subset (triggers snapshot fetch)
121 const query = createLiveQueryCollection((q) =>
122 q
123 .from({ user: progressiveUsers })
124 .where(({ user }) => eq(user.age, 25)),
125 )
126
127 await query.preload()
128
129 // Wait for query to have snapshot data
130 await waitForQueryData(query, { minSize: 1, timeout: 10000 })
131
132 // Collection should still be loading if test control is active
133 const wasStillLoading = progressiveUsers.status === `loading`
134
135 // Release the initial sync to allow atomic swap
136 if (config.progressiveTestControl) {
137 config.progressiveTestControl.releaseInitialSync()
138 }
139
140 const beforeSwapSize = query.size
141 const beforeSwapItems = Array.from(query.values())
142
143 // Verify all items match the predicate
144 beforeSwapItems.forEach((user) => {
145 expect(user.age).toBe(25)
146 expect(user.id).toBeDefined()
147 expect(user.name).toBeDefined()
148 })
149
150 if (wasStillLoading) {
151 // If we caught it during snapshot phase, wait for atomic swap
152 await waitFor(() => progressiveUsers.status === `ready`, {
153 timeout: 30000,
154 message: `Progressive collection did not complete sync`,
155 })
156
157 // After atomic swap, verify data is consistent
158 // The query should have the same data (from full sync)
159 const afterSwapItems = Array.from(query.values())
160 expect(afterSwapItems.length).toBeGreaterThanOrEqual(beforeSwapSize)
161
162 // All original items should still be present
163 beforeSwapItems.forEach((originalUser) => {
164 const stillPresent = afterSwapItems.some(
165 (u) => u.id === originalUser.id,
166 )
167 expect(stillPresent).toBe(true)
168 })
169 } else {
170 // Already ready - verify final state is correct
171 expect(progressiveUsers.status).toBe(`ready`)
172 }
173
174 // Final validation: all items still match predicate
175 Array.from(query.values()).forEach((user) => {
176 expect(user.age).toBe(25)
177 })
178
179 await query.cleanup()
180 })
181
182 it(`should handle multiple snapshots with different predicates`, async () => {
183 const config = await getConfig()
184 if (!config.collections.progressive) {
185 return // Skip if progressive collections not available
186 }
187 const progressiveUsers = config.collections.progressive.users
188
189 // Start sync for this test
190 progressiveUsers.startSyncImmediate()
191
192 // Create multiple queries with different predicates
193 const query1 = createLiveQueryCollection((q) =>
194 q
195 .from({ user: progressiveUsers })
196 .where(({ user }) => eq(user.age, 25)),
197 )
198
199 const query2 = createLiveQueryCollection((q) =>
200 q
201 .from({ user: progressiveUsers })
202 .where(({ user }) => gt(user.age, 30)),
203 )
204
205 await Promise.all([query1.preload(), query2.preload()])
206
207 // Wait for both to load snapshots
208 await Promise.all([
209 waitForQueryData(query1, { minSize: 1, timeout: 10000 }),
210 waitForQueryData(query2, { minSize: 1, timeout: 10000 }),
211 ])
212
213 // Release initial sync to allow atomic swap
214 if (config.progressiveTestControl) {
215 config.progressiveTestControl.releaseInitialSync()
216 }
217
218 expect(query1.size).toBeGreaterThan(0)
219 expect(query2.size).toBeGreaterThan(0)
220
221 // Verify data correctness
222 const query1Snapshot = Array.from(query1.values())
223 const query2Snapshot = Array.from(query2.values())
224
225 query1Snapshot.forEach((user) => {
226 expect(user.age).toBe(25)
227 })
228 query2Snapshot.forEach((user) => {
229 expect(user.age).toBeGreaterThan(30)
230 })
231
232 // Wait for full sync
233 await waitFor(() => progressiveUsers.status === `ready`, {
234 timeout: 30000,
235 message: `Progressive collection did not complete sync`,
236 })
237
238 // Both queries should still have data after swap with same predicates
239 expect(query1.size).toBeGreaterThan(0)
240 expect(query2.size).toBeGreaterThan(0)
241
242 // Verify predicates still match after swap
243 Array.from(query1.values()).forEach((user) => {
244 expect(user.age).toBe(25)
245 })
246 Array.from(query2.values()).forEach((user) => {
247 expect(user.age).toBeGreaterThan(30)
248 })
249
250 await Promise.all([query1.cleanup(), query2.cleanup()])
251 })
252 })
253
254 describe(`Incremental Updates After Swap`, () => {
255 it(`should receive incremental updates after atomic swap`, async () => {
256 const config = await getConfig()
257 if (!config.collections.progressive || !config.mutations?.insertUser) {
258 return // Skip if progressive collections or mutations not available
259 }
260 const progressiveUsers = config.collections.progressive.users
261
262 // Release initial sync immediately (we don't care about snapshot phase for this test)
263 if (config.progressiveTestControl) {
264 config.progressiveTestControl.releaseInitialSync()
265 }
266
267 // Wait for full sync
268 await waitFor(() => progressiveUsers.status === `ready`, {
269 timeout: 30000,
270 message: `Progressive collection did not complete sync`,
271 })
272
273 const initialSize = progressiveUsers.size
274
275 // Insert new data
276 const newUser = {
277 id: crypto.randomUUID(),
278 name: `Progressive Test User`,
279 email: `progressive@test.com`,
280 age: 35,
281 isActive: true,
282 createdAt: new Date(),
283 metadata: null,
284 deletedAt: null,
285 }
286
287 await config.mutations.insertUser(newUser)
288
289 // Wait for incremental update
290 if (config.hasReplicationLag) {
291 await waitFor(() => progressiveUsers.size > initialSize, {
292 timeout: 10000,
293 message: `New user not synced via incremental update`,
294 })
295 }
296
297 expect(progressiveUsers.size).toBeGreaterThan(initialSize)
298
299 // Verify the new user is in the collection with correct data
300 const foundUser = progressiveUsers.get(newUser.id)
301 expect(foundUser).toBeDefined()
302 expect(foundUser?.id).toBe(newUser.id)
303 expect(foundUser?.name).toBe(newUser.name)
304 expect(foundUser?.email).toBe(newUser.email)
305 expect(foundUser?.age).toBe(newUser.age)
306 })
307 })
308
309 describe(`Predicate Handling`, () => {
310 it(`should correctly handle predicates during and after snapshot phase`, async () => {
311 const config = await getConfig()
312 if (!config.collections.progressive) {
313 return // Skip if progressive collections not available
314 }
315 const progressiveUsers = config.collections.progressive.users
316
317 // Create query with predicate during snapshot phase
318 const query = createLiveQueryCollection((q) =>
319 q
320 .from({ user: progressiveUsers })
321 .where(({ user }) => gt(user.age, 25))
322 .orderBy(({ user }) => [user.age, `asc`])
323 .limit(5),
324 )
325
326 await query.preload()
327 await waitForQueryData(query, { minSize: 1, timeout: 10000 })
328
329 const snapshotPhaseSize = query.size
330
331 // Release initial sync to allow atomic swap
332 if (config.progressiveTestControl) {
333 config.progressiveTestControl.releaseInitialSync()
334 }
335
336 // Wait for atomic swap
337 await waitFor(() => progressiveUsers.status === `ready`, {
338 timeout: 30000,
339 message: `Progressive collection did not complete sync`,
340 })
341
342 // Verify predicate still works after swap
343 const afterSwapSize = query.size
344 const afterSwapItems = Array.from(query.values())
345
346 // Size should be reasonable (at least what we had in snapshot phase)
347 expect(afterSwapSize).toBeGreaterThanOrEqual(snapshotPhaseSize)
348
349 // All items should match the predicate
350 afterSwapItems.forEach((user) => {
351 expect(user.age).toBeGreaterThan(25)
352 })
353
354 // Should respect limit
355 expect(afterSwapSize).toBeLessThanOrEqual(5)
356
357 await query.cleanup()
358 })
359
360 it(`should deduplicate snapshot requests during snapshot phase`, async () => {
361 const config = await getConfig()
362 if (!config.collections.progressive) {
363 return // Skip if progressive collections not available
364 }
365 const progressiveUsers = config.collections.progressive.users
366
367 // Create multiple identical queries (should be deduplicated)
368 const queries = Array.from({ length: 3 }, () =>
369 createLiveQueryCollection((q) =>
370 q
371 .from({ user: progressiveUsers })
372 .where(({ user }) => eq(user.age, 30)),
373 ),
374 )
375
376 // Execute concurrently
377 await Promise.all(queries.map((q) => q.preload()))
378
379 // Wait for data
380 await Promise.all(
381 queries.map((q) =>
382 waitForQueryData(q, { minSize: 1, timeout: 10000 }),
383 ),
384 )
385
386 // Release initial sync to allow completion
387 if (config.progressiveTestControl) {
388 config.progressiveTestControl.releaseInitialSync()
389 }
390
391 // All should have the same size and same data
392 const sizes = queries.map((q) => q.size)
393 expect(new Set(sizes).size).toBe(1) // All sizes are identical
394
395 // Verify all queries have identical data (deduplication working)
396 const firstQueryData = Array.from(queries[0]!.values())
397 const firstQueryIds = new Set(firstQueryData.map((u) => u.id))
398
399 queries.forEach((query) => {
400 const queryData = Array.from(query.values())
401 queryData.forEach((user) => {
402 expect(user.age).toBe(30) // All match predicate
403 expect(firstQueryIds.has(user.id)).toBe(true) // Same items
404 })
405 })
406
407 await Promise.all(queries.map((q) => q.cleanup()))
408 })
409 })
410
411 describe(`Txid Tracking Behavior (Electric only)`, () => {
412 it(`should not track txids during snapshot phase but track them after atomic swap`, async () => {
413 const config = await getConfig()
414 if (
415 !config.collections.progressive ||
416 !config.mutations?.insertUser ||
417 !config.getTxid
418 ) {
419 return // Skip if progressive collections, mutations, or getTxid not available
420 }
421 const progressiveUsers = config.collections.progressive
422 .users as Collection<User, string, ElectricCollectionUtils>
423
424 // awaitTxId is guaranteed to exist on ElectricCollectionUtils
425 // This test is Electric-only via the describe block name
426
427 // Start sync but don't release yet (stay in snapshot phase)
428 progressiveUsers.startSyncImmediate()
429 await new Promise((resolve) => setTimeout(resolve, 100))
430
431 // Should be in loading state (snapshot phase)
432 if (progressiveUsers.status !== `loading`) {
433 console.log(
434 `Collection already ready, cannot test snapshot phase txid behavior`,
435 )
436 return
437 }
438
439 // === PHASE 1: INSERT DURING SNAPSHOT PHASE ===
440 const snapshotPhaseUser = {
441 id: crypto.randomUUID(),
442 name: `Snapshot Phase User`,
443 email: `snapshot@test.com`,
444 age: 28,
445 isActive: true,
446 createdAt: new Date(),
447 metadata: null,
448 deletedAt: null,
449 }
450
451 // Insert user and track when awaitTxId completes
452 let txidResolved = false
453
454 // Start the insert
455 await config.mutations.insertUser(snapshotPhaseUser)
456
457 // Get the txid from postgres
458 const txid = await config.getTxid()
459
460 if (!txid) {
461 console.log(`Could not get txid, skipping txid tracking validation`)
462 config.progressiveTestControl?.releaseInitialSync()
463 return
464 }
465
466 // Start awaiting the txid (should NOT resolve during snapshot phase)
467 progressiveUsers.utils.awaitTxId(txid, 60000).then(() => {
468 txidResolved = true
469 })
470
471 // Wait a moment for sync to process
472 await new Promise((resolve) => setTimeout(resolve, 500))
473
474 // Txid should NOT have resolved yet (snapshot phase, txids not tracked)
475 expect(txidResolved).toBe(false)
476
477 // Query for the user (triggers fetchSnapshot with this user)
478 const query = createLiveQueryCollection((q) =>
479 q
480 .from({ user: progressiveUsers })
481 .where(({ user }) => eq(user.id, snapshotPhaseUser.id)),
482 )
483
484 await query.preload()
485 await waitForQueryData(query, { minSize: 1, timeout: 10000 })
486
487 // User should be in snapshot data
488 expect(query.size).toBe(1)
489 expect(query.get(snapshotPhaseUser.id)).toBeDefined()
490
491 // But collection is still in snapshot phase
492 expect(progressiveUsers.status).toBe(`loading`)
493
494 // Txid should STILL not have resolved (snapshot doesn't track txids)
495 expect(txidResolved).toBe(false)
496
497 // === PHASE 2: TRIGGER ATOMIC SWAP ===
498 if (config.progressiveTestControl) {
499 config.progressiveTestControl.releaseInitialSync()
500 }
501
502 // Wait for atomic swap to complete
503 await waitFor(() => progressiveUsers.status === `ready`, {
504 timeout: 30000,
505 message: `Progressive collection did not complete sync`,
506 })
507
508 // NOW txid should resolve (buffered messages include txids)
509 await waitFor(() => txidResolved, {
510 timeout: 5000,
511 message: `Txid did not resolve after atomic swap`,
512 })
513
514 expect(txidResolved).toBe(true)
515
516 // === PHASE 3: VERIFY TXID TRACKING POST-SWAP ===
517 // User should still be present after atomic swap
518 expect(progressiveUsers.get(snapshotPhaseUser.id)).toBeDefined()
519
520 // Now insert another user and verify txid tracking works
521 const postSwapUser = {
522 id: crypto.randomUUID(),
523 name: `Post Swap User`,
524 email: `postswap@test.com`,
525 age: 29,
526 isActive: true,
527 createdAt: new Date(),
528 metadata: null,
529 deletedAt: null,
530 }
531
532 await config.mutations.insertUser(postSwapUser)
533
534 // Wait for incremental update (txid tracking should work now)
535 if (config.hasReplicationLag) {
536 await waitFor(() => progressiveUsers.has(postSwapUser.id), {
537 timeout: 10000,
538 message: `Post-swap user not synced via incremental update`,
539 })
540 }
541
542 // Both users should be present
543 expect(progressiveUsers.get(snapshotPhaseUser.id)).toBeDefined()
544 expect(progressiveUsers.get(postSwapUser.id)).toBeDefined()
545
546 await query.cleanup()
547 })
548 })
549
550 describe(`Progressive Mode Resilience`, () => {
551 it(`should handle cleanup and restart during snapshot phase`, async () => {
552 const config = await getConfig()
553 if (!config.collections.progressive) {
554 return // Skip if progressive collections not available
555 }
556 const progressiveUsers = config.collections.progressive.users
557
558 // This test verifies the collection can be cleaned up even during snapshot phase
559 const query = createLiveQueryCollection((q) =>
560 q
561 .from({ user: progressiveUsers })
562 .where(({ user }) => eq(user.age, 25)),
563 )
564
565 await query.preload()
566
567 // Release initial sync
568 if (config.progressiveTestControl) {
569 config.progressiveTestControl.releaseInitialSync()
570 }
571
572 // Don't wait for data, just cleanup immediately
573 await query.cleanup()
574
575 // Should not throw
576 expect(true).toBe(true)
577 })
578 })
579 })
580}