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

persisted-subset.test.ts

1,150 lines36.6 KB

1/**
2 * Ordinary tests for persistedCollectionOptions single-process and remote subset wiring, transported subset validation, and coordinator configuration, as fixed scenarios. The subset demand and coordinator laws they touch are owned by persisted-oracle.test.ts, which keeps the generated retained-demand and follower cases.
3 */
4import { describe, expect, it, vi } from 'vitest'
5import { IR, createCollection } from '@tanstack/db'
6import {
7 InvalidPersistedCollectionCoordinatorError,
8 InvalidSyncConfigError,
9 SingleProcessCoordinator,
10 persistedCollectionOptions,
11 toTransportedLoadSubsetOptions,
12 validateRemoteSubsetOptions,
13} from '../src'
14import {
15 atPersistedOracleCheckpoint,
16 createNoopAdapter,
17 createRecordingAdapter,
18 flushAsyncWork,
19 stripVirtualProps,
20} from './persisted-support'
21import type {
22 Collection,
23 LoadSubsetOptions,
24 Subscription,
25 SyncConfig,
26} from '@tanstack/db'
27import type {
28 PersistedCollectionCoordinator,
29 PersistedCollectionPersistence,
30 PersistedSyncWrappedOptions,
31 RemoteSubsetOwner,
32} from '../src'
33import type { Todo } from './persisted-support'
34​
35describe(`persistedCollectionOptions`, () => {
36 it(`throws InvalidSyncConfigError when sync key is present but invalid`, () => {
37 const invalidOptions = {
38 id: `invalid-sync-shape`,
39 getKey: (item: Todo) => item.id,
40 sync: {} as unknown as SyncConfig<Todo, string>,
41 persistence: {
42 adapter: createNoopAdapter(),
43 },
44 } as PersistedSyncWrappedOptions<Todo, string>
45​
46 expect(() => persistedCollectionOptions(invalidOptions)).toThrow(
47 InvalidSyncConfigError,
48 )
49 })
50​
51 it(`uses SingleProcessCoordinator when coordinator is omitted`, () => {
52 const options = persistedCollectionOptions<Todo, string>({
53 id: `default-coordinator`,
54 getKey: (item) => item.id,
55 persistence: {
56 adapter: createNoopAdapter(),
57 },
58 })
59​
60 expect(options.persistence.coordinator).toBeInstanceOf(
61 SingleProcessCoordinator,
62 )
63 })
64​
65 it(`coalesces duplicate single-process subset acknowledgements until owner work finishes`, async () => {
66 const coordinator = new SingleProcessCoordinator(`single-coalesced`)
67 let releaseLoad = (): void => {}
68 const loadGate = new Promise<void>((resolve) => {
69 releaseLoad = resolve
70 })
71 const owner = Object.assign(
72 vi.fn(() => loadGate),
73 { unloadSubset: vi.fn(), onError: vi.fn() },
74 )
75 const unregisterOwner = coordinator.registerRemoteSubsetOwner(
76 `todos`,
77 owner,
78 )
79 const options: LoadSubsetOptions = { limit: 1 }
80​
81 try {
82 let firstSettled = false
83 let duplicateSettled = false
84 const first = coordinator
85 .requestEnsureRemoteSubset(`todos`, options)
86 .then(() => {
87 firstSettled = true
88 })
89 await Promise.resolve()
90 const duplicate = coordinator
91 .requestEnsureRemoteSubset(`todos`, options)
92 .then(() => {
93 duplicateSettled = true
94 })
95 await Promise.resolve()
96​
97 expect({
98 ownerCalls: owner.mock.calls.length,
99 firstSettled,
100 duplicateSettled,
101 }).toEqual({
102 ownerCalls: 1,
103 firstSettled: false,
104 duplicateSettled: false,
105 })
106​
107 releaseLoad()
108 await Promise.all([first, duplicate])
109 } finally {
110 releaseLoad()
111 unregisterOwner()
112 }
113 })
114​
115 it(`preserves process-local subset lifecycle fields for owner load and unload`, async () => {
116 const coordinator = new SingleProcessCoordinator(`single-live-fields`)
117 const owner = Object.assign(vi.fn(), {
118 unloadSubset: vi.fn(),
119 onError: vi.fn(),
120 })
121 const unregisterOwner = coordinator.registerRemoteSubsetOwner(
122 `todos`,
123 owner,
124 )
125 const signal = new AbortController().signal
126 const subscription = {
127 on: () => () => {},
128 } as unknown as Subscription
129 const options: LoadSubsetOptions = { limit: 1, signal, subscription }
130​
131 try {
132 await coordinator.requestEnsureRemoteSubset(`todos`, options)
133 expect(owner).toHaveBeenCalledTimes(1)
134 const delivered = owner.mock.calls[0]![0] as LoadSubsetOptions
135 expect(delivered).toMatchObject({ limit: 1 })
136 expect(delivered.signal).toBe(signal)
137 expect(delivered.subscription).toBe(subscription)
138​
139 await coordinator.requestReleaseRemoteSubset(`todos`, options)
140 expect(owner.unloadSubset).toHaveBeenCalledTimes(1)
141 expect(owner.unloadSubset).toHaveBeenCalledWith(delivered)
142 } finally {
143 unregisterOwner()
144 }
145 })
146​
147 it(`coalesces same-stack single-process subset reentry until owner work finishes`, async () => {
148 const coordinator = new SingleProcessCoordinator(`single-reentrant`)
149 let releaseLoad = (): void => {}
150 const loadGate = new Promise<void>((resolve) => {
151 releaseLoad = resolve
152 })
153 const options: LoadSubsetOptions = { limit: 1 }
154 let duplicate: Promise<void> | undefined
155 let didReenter = false
156 const owner = Object.assign(
157 vi.fn(() => {
158 if (!didReenter) {
159 didReenter = true
160 duplicate = coordinator.requestEnsureRemoteSubset(`todos`, options)
161 }
162 return loadGate
163 }),
164 { unloadSubset: vi.fn(), onError: vi.fn() },
165 )
166 const unregisterOwner = coordinator.registerRemoteSubsetOwner(
167 `todos`,
168 owner,
169 )
170​
171 try {
172 let firstSettled = false
173 let duplicateSettled = false
174 const first = coordinator
175 .requestEnsureRemoteSubset(`todos`, options)
176 .then(() => {
177 firstSettled = true
178 })
179 await Promise.resolve()
180 const duplicateResult = duplicate!.then(() => {
181 duplicateSettled = true
182 })
183 await Promise.resolve()
184​
185 expect({
186 ownerCalls: owner.mock.calls.length,
187 firstSettled,
188 duplicateSettled,
189 }).toEqual({
190 ownerCalls: 1,
191 firstSettled: false,
192 duplicateSettled: false,
193 })
194​
195 releaseLoad()
196 await Promise.all([first, duplicateResult])
197 } finally {
198 releaseLoad()
199 unregisterOwner()
200 }
201 })
202​
203 // Acquisition release gives the owner its cancellation opportunity before
204 // the source load settles. A load that needs unload to settle is legal;
205 // waiting for that load before calling unload deadlocks scoped recovery.
206 it(`unloads a pending single-process subset before waiting for its source load`, async () => {
207 const coordinator = new SingleProcessCoordinator(`single-release-order`)
208 let releaseLoad = (): void => {}
209 const loadGate = new Promise<void>((resolve) => {
210 releaseLoad = resolve
211 })
212 const events: Array<string> = []
213 const owner = Object.assign(
214 vi.fn(async () => {
215 events.push(`load-start`)
216 await loadGate
217 events.push(`load-finish`)
218 }),
219 {
220 unloadSubset: vi.fn(() => {
221 events.push(`unload`)
222 }),
223 onError: vi.fn(),
224 },
225 )
226 const unregisterOwner = coordinator.registerRemoteSubsetOwner(
227 `todos`,
228 owner,
229 )
230 const options: LoadSubsetOptions = { limit: 1 }
231​
232 try {
233 const load = coordinator.requestEnsureRemoteSubset(`todos`, options)
234 await Promise.resolve()
235 let releaseSettled = false
236 const release = coordinator
237 .requestReleaseRemoteSubset(`todos`, options)
238 .then(() => {
239 releaseSettled = true
240 })
241 await atPersistedOracleCheckpoint(
242 release,
243 `release before source settlement`,
244 )
245​
246 const beforeLoadRelease = { events: [...events], releaseSettled }
247 expect(beforeLoadRelease).toEqual({
248 events: [`load-start`, `unload`],
249 releaseSettled: true,
250 })
251​
252 releaseLoad()
253 await Promise.all([load, release])
254 expect(events).toEqual([`load-start`, `unload`, `load-finish`])
255 } finally {
256 releaseLoad()
257 unregisterOwner()
258 }
259 })
260​
261 it(`rejects unsupported single-process subset values before owner work`, async () => {
262 const coordinator = new SingleProcessCoordinator(`single-wire-domain`)
263 const owner = Object.assign(vi.fn(), {
264 unloadSubset: vi.fn(),
265 onError: vi.fn(),
266 })
267 const unregisterOwner = coordinator.registerRemoteSubsetOwner(
268 `todos`,
269 owner,
270 )
271​
272 try {
273 await expect(
274 coordinator.requestEnsureRemoteSubset(`todos`, {
275 where: new IR.Func(`in`, [
276 new IR.PropRef([`todos`, `status`]),
277 new IR.Value([`kept`, () => {}]),
278 ]),
279 }),
280 ).rejects.toMatchObject({
281 name: `RemoteSubsetWireValueError`,
282 path: `options.where.args[1].value[1]`,
283 })
284 expect(owner).not.toHaveBeenCalled()
285 } finally {
286 unregisterOwner()
287 }
288 })
289​
290 it(`rejects a sparse function argument at its exact expression path`, async () => {
291 const coordinator = new SingleProcessCoordinator(`single-wire-hole`)
292 const owner = Object.assign(vi.fn(), {
293 unloadSubset: vi.fn(),
294 onError: vi.fn(),
295 })
296 const unregisterOwner = coordinator.registerRemoteSubsetOwner(
297 `todos`,
298 owner,
299 )
300 const args = [new IR.PropRef([`todos`, `status`])]
301 args.length = 2
302​
303 try {
304 await expect(
305 coordinator.requestEnsureRemoteSubset(`todos`, {
306 where: new IR.Func(`eq`, args),
307 }),
308 ).rejects.toMatchObject({
309 name: `RemoteSubsetWireValueError`,
310 path: `options.where.args[1]`,
311 })
312 expect(owner).not.toHaveBeenCalled()
313 } finally {
314 unregisterOwner()
315 }
316 })
317​
318 it(`preserves an explicit source alias through remote subset projection`, async () => {
319 const coordinator = new SingleProcessCoordinator(`single-wire-alias`)
320 const owner = Object.assign(vi.fn(), {
321 unloadSubset: vi.fn(),
322 onError: vi.fn(),
323 })
324 const unregisterOwner = coordinator.registerRemoteSubsetOwner(
325 `todos`,
326 owner,
327 )
328 const options: LoadSubsetOptions = {
329 where: new IR.Func(`eq`, [
330 new IR.PropRef([`todos`, `status`], `todos`),
331 new IR.Value(`kept`),
332 ]),
333 }
334​
335 try {
336 await coordinator.requestEnsureRemoteSubset(`todos`, options)
337 expect(owner).toHaveBeenCalledWith({
338 where: {
339 type: `func`,
340 name: `eq`,
341 args: [
342 { type: `ref`, path: [`todos`, `status`], sourceAlias: `todos` },
343 { type: `val`, value: `kept` },
344 ],
345 },
346 })
347 } finally {
348 await coordinator.requestReleaseRemoteSubset(`todos`, options)
349 unregisterOwner()
350 }
351 })
352​
353 it(`rejects a remote subset source alias that disagrees with its path`, () => {
354 expect(() =>
355 toTransportedLoadSubsetOptions({
356 where: new IR.Func(`eq`, [
357 new IR.PropRef([`todos`, `status`], `other`),
358 new IR.Value(`kept`),
359 ]),
360 }),
361 ).toThrowError(/options\.where\.args\[0\]\.sourceAlias/)
362 })
363​
364 // A projection is a detached snapshot at one call boundary. A later call on
365 // reused input must observe its current data, without changing the first
366 // snapshot. This distinguishes safe per-call reuse from a global identity cache.
367 it(`takes a fresh detached wire snapshot on each projection`, () => {
368 const literal = new IR.Value({ label: `before` })
369 const options = {
370 where: new IR.Func(`eq`, [new IR.PropRef([`value`]), literal]),
371 }
372 const first = toTransportedLoadSubsetOptions(options)
373 literal.value.label = `after`
374 const second = toTransportedLoadSubsetOptions(options)
375 expect(first.where).toMatchObject({
376 args: [{}, { value: { label: `before` } }],
377 })
378 expect(second.where).toMatchObject({
379 args: [{}, { value: { label: `after` } }],
380 })
381 expect(first).not.toBe(second)
382 })
383​
384 // Read-only admission is a law about caller state, including builtin internal
385 // slots that Object.freeze cannot protect. Capture expectations before either
386 // traversal, and retain them when a later invalid field rejects the request.
387 // Fresh snapshots must preserve internal aliases but share no mutable payload
388 // with the caller or a later projection. These are two call-boundary histories,
389 // not a reference implementation of the encoder.
390 it.each([false, true])(
391 `preserves caller state and detached snapshots / rejected suffix %s`,
392 (rejectedSuffix) => {
393 const date = new Date(`2026-09-16T12:34:56.123Z`)
394 const buffer = new Uint8Array([7, 8]).buffer
395 const shared = { label: `before` }
396 const payload = {
397 date,
398 buffer,
399 view: new Uint8Array(buffer),
400 map: new Map([[shared, date]]),
401 set: new Set([shared]),
402 first: shared,
403 second: shared,
404 }
405 // Compare values and aliases explicitly. In jsdom, structuredClone can
406 // return a buffer from another realm, which Vitest's object comparison
407 // does not equate with this realm's otherwise identical ArrayBuffer.
408 // These observations preserve contents, order, multiplicity and identity
409 // relationships without requiring cross-realm object equality.
410 const observe = (value: typeof payload) => ({
411 keys: Reflect.ownKeys(value),
412 recordKeys: [
413 Reflect.ownKeys(value.first),
414 Reflect.ownKeys(value.second),
415 ],
416 date: value.date.getTime(),
417 bytes: Array.from(new Uint8Array(value.buffer)),
418 view: Array.from(value.view),
419 map: [...value.map].map(([key, entry]) => ({
420 label: key.label,
421 date: entry.getTime(),
422 keyIsFirst: key === value.first,
423 valueIsDate: entry === value.date,
424 })),
425 set: [...value.set].map((entry) => ({
426 label: entry.label,
427 isFirst: entry === value.first,
428 })),
429 first: value.first.label,
430 second: value.second.label,
431 sharedRecord: value.first === value.second,
432 sharedBuffer: value.view.buffer === value.buffer,
433 })
434 const before = {
435 keys: [`date`, `buffer`, `view`, `map`, `set`, `first`, `second`],
436 recordKeys: [[`label`], [`label`]],
437 date: Date.UTC(2026, 8, 16, 12, 34, 56, 123),
438 bytes: [7, 8],
439 view: [7, 8],
440 map: [
441 {
442 label: `before`,
443 date: Date.UTC(2026, 8, 16, 12, 34, 56, 123),
444 keyIsFirst: true,
445 valueIsDate: true,
446 },
447 ],
448 set: [{ label: `before`, isFirst: true }],
449 first: `before`,
450 second: `before`,
451 sharedRecord: true,
452 sharedBuffer: true,
453 }
454 // Calibrate the fixture before entering either production traversal.
455 expect(observe(payload)).toEqual(before)
456 const options = {
457 where: new IR.Func(`eq`, [
458 new IR.PropRef([`payload`]),
459 new IR.Value(payload),
460 ]),
461 ...(rejectedSuffix ? { limit: -1 } : {}),
462 }
463 if (rejectedSuffix) {
464 for (const visit of [
465 validateRemoteSubsetOptions,
466 toTransportedLoadSubsetOptions,
467 ]) {
468 expect(() => visit(options)).toThrowError(
469 expect.objectContaining({
470 name: `RemoteSubsetWireValueError`,
471 path: `options.limit`,
472 }),
473 )
474 expect(observe(payload)).toEqual(before)
475 }
476 return
477 }
478 expect(validateRemoteSubsetOptions(options)).toBeUndefined()
479 expect(observe(payload)).toEqual(before)
480 const first = toTransportedLoadSubsetOptions(options)
481 expect(observe(payload)).toEqual(before)
482 date.setTime(1)
483 new Uint8Array(buffer)[0] = 9
484 shared.label = `after`
485 payload.map.clear()
486 payload.set.clear()
487 const after = {
488 ...before,
489 date: 1,
490 bytes: [9, 8],
491 view: [9, 8],
492 map: [],
493 set: [],
494 first: `after`,
495 second: `after`,
496 }
497 expect(observe(payload)).toEqual(after)
498 expect(validateRemoteSubsetOptions(options)).toBeUndefined()
499 expect(observe(payload)).toEqual(after)
500 const second = toTransportedLoadSubsetOptions(options)
501 expect(observe(payload)).toEqual(after)
502 for (const [snapshot, expected] of [
503 [first, before],
504 [second, after],
505 ] as const) {
506 if (snapshot.where?.type !== `func`)
507 throw new Error(`missing predicate`)
508 const literal = snapshot.where.args[1]
509 if (literal?.type !== `val`) throw new Error(`missing literal`)
510 const value = literal.value as typeof payload
511 expect(observe(value)).toEqual(expected)
512 expect(value.first).toBe(value.second)
513 expect(value.view.buffer).toBe(value.buffer)
514 for (const key of Object.keys(payload) as Array<keyof typeof payload>)
515 expect(value[key]).not.toBe(payload[key])
516 }
517 },
518 )
519​
520 // Both modes enforce the complete request schema. Validation must only read
521 // the caller's frozen graph; projection still returns detached request data.
522 it.each([`lexical`, `locale`] as const)(
523 `validates frozen request fields without projecting or rewriting them / %s`,
524 (stringSort) => {
525 const reference = new IR.PropRef([`todos`, `title`], `todos`)
526 const literal = new IR.Value({ label: `unchanged` })
527 const where = new IR.Func(`eq`, [reference, literal])
528 const compareOptions = {
529 direction: `asc` as const,
530 nulls: `last` as const,
531 stringSort,
532 locale: `en`,
533 localeOptions: { sensitivity: `base` as const },
534 }
535 const clause = { expression: reference, compareOptions }
536 const options = {
537 where,
538 orderBy: [clause, clause],
539 cursor: { whereFrom: where, whereCurrent: where, lastKey: `last` },
540 limit: 0,
541 offset: Number.MAX_SAFE_INTEGER,
542 signal: new AbortController().signal,
543 }
544 for (const value of [
545 options,
546 where,
547 where.args,
548 reference,
549 reference.path,
550 literal,
551 literal.value,
552 options.orderBy,
553 clause,
554 compareOptions,
555 compareOptions.localeOptions,
556 options.cursor,
557 ])
558 Object.freeze(value)
559 expect(validateRemoteSubsetOptions(options)).toBeUndefined()
560 const result = toTransportedLoadSubsetOptions(options)
561 expect(result).toMatchObject({
562 limit: 0,
563 offset: Number.MAX_SAFE_INTEGER,
564 })
565 expect(result.where).not.toBe(where)
566 expect(result.cursor?.whereFrom).toBe(result.where)
567 expect(result.cursor?.whereCurrent).toBe(result.where)
568 expect(result.orderBy?.[0]).toBe(result.orderBy?.[1])
569 expect(result.orderBy?.[0]?.compareOptions).toEqual(
570 stringSort === `lexical`
571 ? { direction: `asc`, nulls: `last`, stringSort }
572 : compareOptions,
573 )
574 expect(options.cursor.whereFrom).toBe(where)
575 expect(options.orderBy[0]).toBe(clause)
576 },
577 )
578​
579 it(`projects lexical comparison options without locale-only wire fields`, () => {
580 const projected = toTransportedLoadSubsetOptions({
581 orderBy: [
582 {
583 expression: new IR.PropRef([`todos`, `title`]),
584 compareOptions: {
585 direction: `asc`,
586 nulls: `last`,
587 stringSort: `lexical`,
588 locale: `en`,
589 localeOptions: { sensitivity: `base` },
590 },
591 },
592 ],
593 } as unknown as LoadSubsetOptions)
594​
595 expect(projected.orderBy?.[0]?.compareOptions).toEqual({
596 direction: `asc`,
597 nulls: `last`,
598 stringSort: `lexical`,
599 })
600 })
601​
602 it(`preserves locale comparison fields when the optional sort mode is omitted`, () => {
603 const projected = toTransportedLoadSubsetOptions({
604 orderBy: [
605 {
606 expression: new IR.PropRef([`todos`, `title`]),
607 compareOptions: {
608 direction: `asc`,
609 nulls: `last`,
610 locale: `en`,
611 localeOptions: { sensitivity: `base` },
612 },
613 },
614 ],
615 } as LoadSubsetOptions)
616​
617 expect(projected.orderBy?.[0]?.compareOptions).toEqual({
618 direction: `asc`,
619 nulls: `last`,
620 locale: `en`,
621 localeOptions: { sensitivity: `base` },
622 })
623 })
624​
625 it.each([
626 [`limit`, { limit: Number.NaN }, `options.limit`],
627 [`limit`, { limit: Number.POSITIVE_INFINITY }, `options.limit`],
628 [`limit`, { limit: -1 }, `options.limit`],
629 [`limit`, { limit: 0.5 }, `options.limit`],
630 [`limit`, { limit: Number.MAX_SAFE_INTEGER + 1 }, `options.limit`],
631 [`offset`, { offset: Number.NaN }, `options.offset`],
632 [`offset`, { offset: Number.NEGATIVE_INFINITY }, `options.offset`],
633 [`offset`, { offset: -1 }, `options.offset`],
634 [`offset`, { offset: 0.5 }, `options.offset`],
635 [`offset`, { offset: Number.MAX_SAFE_INTEGER + 1 }, `options.offset`],
636 ] as const)(
637 `rejects an invalid transported subset %s before owner work`,
638 (_field, options, path) => {
639 let error: unknown
640 try {
641 toTransportedLoadSubsetOptions(options)
642 } catch (caught) {
643 error = caught
644 }
645 expect(error).toMatchObject({
646 name: `RemoteSubsetWireValueError`,
647 path,
648 })
649 },
650 )
651​
652 it(`preserves valid transported subset window boundaries`, () => {
653 expect(
654 toTransportedLoadSubsetOptions({
655 limit: 0,
656 offset: Number.MAX_SAFE_INTEGER,
657 }),
658 ).toEqual({ limit: 0, offset: Number.MAX_SAFE_INTEGER })
659 })
660​
661 it(`transports an explicit source refetch without changing subset data`, () => {
662 expect(toTransportedLoadSubsetOptions({ limit: 1, refetch: true })).toEqual(
663 {
664 limit: 1,
665 refetch: true,
666 },
667 )
668 expect(() =>
669 toTransportedLoadSubsetOptions({ refetch: `true` } as never),
670 ).toThrow(`options.refetch`)
671 })
672​
673 it(`reports and rethrows a single-process owner unload rejection`, async () => {
674 const coordinator = new SingleProcessCoordinator(`single-unload-error`)
675 const unloadError = new Error(`single-process owner unload failed`)
676 const ownerErrors: Array<unknown> = []
677 const owner = Object.assign(vi.fn(), {
678 unloadSubset: vi.fn(() =>
679 Promise.reject(unloadError),
680 ) as unknown as RemoteSubsetOwner[`unloadSubset`],
681 onError: (error: unknown) => ownerErrors.push(error),
682 })
683 const unregisterOwner = coordinator.registerRemoteSubsetOwner(
684 `todos`,
685 owner,
686 )
687 const options: LoadSubsetOptions = { limit: 1 }
688​
689 try {
690 await coordinator.requestEnsureRemoteSubset(`todos`, options)
691 await expect(
692 coordinator.requestReleaseRemoteSubset(`todos`, options),
693 ).rejects.toBe(unloadError)
694 expect(ownerErrors).toEqual([unloadError])
695 } finally {
696 unregisterOwner()
697 }
698 })
699​
700 // An adapter's unloadSubset that rejects broke its contract. Core reports a
701 // throwing unloadSubset uncaught and fails no load, replay, or caller
702 // (subscription.ts, releaseAcquisition); the wrapper forwards the call as
703 // core makes it, so a rejection surfaces uncaught once and changes neither
704 // the status nor the node, whether or not the sync adapter gave up first.
705 // The supplemental witness for the persisted sync-run oracle's
706 // `unload-reject` site.
707 it.each([false, true])(
708 `reports a single-process async unload rejection uncaught without changing the Collection (sync adapter gave up first: %s)`,
709 async (gaveUpFirst) => {
710 const unloadError = new Error(`remote owner unload failed`)
711 const gaveUp = new Error(`sync adapter gave up`)
712 let giveUp: ((error: unknown) => void) | undefined
713 let unloadThenCalls = 0
714 const rejectingThenable = {
715 then: (
716 _resolve: (value?: void) => void,
717 reject: (error: unknown) => void,
718 ) => {
719 unloadThenCalls++
720 queueMicrotask(() => reject(unloadError))
721 },
722 }
723 const sourceUnloadMock = vi.fn((options: LoadSubsetOptions) =>
724 options.limit === 1 ? rejectingThenable : undefined,
725 )
726 const sourceUnload = sourceUnloadMock as unknown as (
727 options: LoadSubsetOptions,
728 ) => void
729 const collection = createCollection(
730 persistedCollectionOptions<Todo, string>({
731 id: `owner-unload-error`,
732 getKey: (todo) => todo.id,
733 syncMode: `on-demand`,
734 sync: {
735 sync: ({ markReady, fail }) => {
736 markReady()
737 giveUp = fail
738 return {
739 loadSubset: () => true,
740 unloadSubset: sourceUnload,
741 }
742 },
743 },
744 persistence: {
745 adapter: createRecordingAdapter(),
746 },
747 }),
748 )
749 const failing: LoadSubsetOptions = { limit: 1 }
750 const sibling: LoadSubsetOptions = { limit: 2 }
751 const crash = vi.spyOn(collection._lifecycle, `crash`)
752 const unhandled: Array<unknown> = []
753 const captureUnhandled = (error: unknown) => unhandled.push(error)
754 process.on(`unhandledRejection`, captureUnhandled)
755 const uncaught: Array<unknown> = []
756 const queue = globalThis.queueMicrotask.bind(globalThis)
757 const microtasks = vi
758 .spyOn(globalThis, `queueMicrotask`)
759 .mockImplementation((task) =>
760 queue(() => {
761 try {
762 task()
763 } catch (error) {
764 uncaught.push(error)
765 }
766 }),
767 )
768​
769 try {
770 collection.startSyncImmediate()
771 await collection._sync.loadSubset(failing)
772 await collection._sync.loadSubset(sibling)
773 if (gaveUpFirst) {
774 giveUp!(gaveUp)
775 await flushAsyncWork()
776 expect(collection.status).toBe(`ready`)
777 expect(collection.health.error?.cause).toBe(gaveUp)
778 }
779 collection._sync.unloadSubset(failing)
780 collection._sync.unloadSubset(sibling)
781 await flushAsyncWork()
782 await flushAsyncWork()
783​
784 expect({
785 status: collection.status,
786 error: collection.health.error?.cause,
787 failureReason: collection.health.failureReason,
788 unloadThenCalls,
789 unloadOptions: sourceUnloadMock.mock.calls.map(
790 ([options]) => options,
791 ),
792 lifecycleErrors: crash.mock.calls.map(([error]) => error),
793 uncaught,
794 unhandled,
795 }).toEqual({
796 status: `ready`,
797 error: gaveUpFirst ? gaveUp : undefined,
798 failureReason: null,
799 unloadThenCalls: 1,
800 unloadOptions: [failing, sibling],
801 lifecycleErrors: [],
802 uncaught: [unloadError],
803 unhandled: [],
804 })
805​
806 await flushAsyncWork()
807 expect(sourceUnloadMock).toHaveBeenCalledTimes(2)
808 expect(crash).not.toHaveBeenCalled()
809 } finally {
810 microtasks.mockRestore()
811 process.off(`unhandledRejection`, captureUnhandled)
812 await collection.cleanup()
813 }
814 },
815 )
816​
817 it(`surfaces duplicate remote-subset owner registration through the collection lifecycle`, async () => {
818 const coordinator = new SingleProcessCoordinator()
819 const unhandled: Array<unknown> = []
820 const sourceLoads: Array<string> = []
821 const onUnhandled = (error: unknown) => unhandled.push(error)
822 process.on(`unhandledRejection`, onUnhandled)
823 const create = (label: string) =>
824 createCollection(
825 persistedCollectionOptions<Todo, string>({
826 id: `duplicate-owner-lifecycle`,
827 getKey: (row) => row.id,
828 sync: {
829 sync: ({ markReady }) => {
830 markReady()
831 return {
832 loadSubset: () => {
833 sourceLoads.push(label)
834 return true
835 },
836 unloadSubset: () => {},
837 }
838 },
839 },
840 persistence: { adapter: createRecordingAdapter(), coordinator },
841 }),
842 )
843 const first = create(`first`)
844 let duplicate: ReturnType<typeof create> | undefined
845​
846 try {
847 first.startSyncImmediate()
848 await first.stateWhenReady()
849 await vi.waitFor(() =>
850 expect(
851 (
852 coordinator as unknown as {
853 remoteSubsetOwners: Map<string, RemoteSubsetOwner>
854 }
855 ).remoteSubsetOwners.size,
856 ).toBe(1),
857 )
858 duplicate = create(`duplicate`)
859 duplicate.startSyncImmediate()
860 const readinessError = await duplicate.stateWhenReady().then(
861 () => undefined,
862 (error: unknown) => error,
863 )
864 await flushAsyncWork()
865​
866 expect(readinessError).toMatchObject({
867 name: `DuplicateRemoteSubsetOwnerError`,
868 collectionId: `duplicate-owner-lifecycle`,
869 })
870 expect(duplicate.status).toBe(`error`)
871 expect(sourceLoads).toEqual([])
872 expect(unhandled).toEqual([])
873 } finally {
874 process.off(`unhandledRejection`, onUnhandled)
875 await duplicate?.cleanup()
876 await first.cleanup()
877 }
878 })
879​
880 it(`resolves persistence per collection and forwards schemaVersion`, () => {
881 const baseAdapter = createNoopAdapter()
882 const syncAdapter = createNoopAdapter()
883 const localAdapter = createNoopAdapter()
884 const resolverCalls: Array<{
885 collectionId: string
886 mode: `sync-present` | `sync-absent`
887 schemaVersion?: number
888 }> = []
889​
890 const persistence: PersistedCollectionPersistence = {
891 adapter: baseAdapter,
892 resolvePersistenceForCollection: (options) => {
893 resolverCalls.push(options)
894 return {
895 adapter: options.mode === `sync-present` ? syncAdapter : localAdapter,
896 }
897 },
898 }
899​
900 const syncOptions = persistedCollectionOptions<Todo, string>({
901 id: `sync-collection`,
902 getKey: (item) => item.id,
903 sync: {
904 sync: ({ markReady }) => {
905 markReady()
906 },
907 },
908 schemaVersion: 7,
909 persistence,
910 })
911 expect(syncOptions.persistence.adapter).toBe(syncAdapter)
912​
913 const localOptions = persistedCollectionOptions<Todo, string>({
914 id: `local-collection`,
915 getKey: (item) => item.id,
916 schemaVersion: 3,
917 persistence,
918 })
919 expect(localOptions.persistence.adapter).toBe(localAdapter)
920​
921 expect(resolverCalls).toEqual([
922 {
923 collectionId: `sync-collection`,
924 mode: `sync-present`,
925 schemaVersion: 7,
926 },
927 {
928 collectionId: `local-collection`,
929 mode: `sync-absent`,
930 schemaVersion: 3,
931 },
932 ])
933 })
934​
935 it(`throws for invalid coordinator implementations`, () => {
936 const invalidCoordinator = {
937 getNodeId: () => `node-1`,
938 subscribe: () => () => {},
939 publish: () => {},
940 isLeader: () => true,
941 ensureLeadership: async () => {},
942 // requestEnsurePersistedIndex is intentionally missing
943 } as unknown as PersistedCollectionCoordinator
944​
945 expect(() =>
946 persistedCollectionOptions<Todo, string>({
947 id: `invalid-coordinator`,
948 getKey: (item) => item.id,
949 persistence: {
950 adapter: createNoopAdapter(),
951 coordinator: invalidCoordinator,
952 },
953 }),
954 ).toThrow(InvalidPersistedCollectionCoordinatorError)
955 })
956​
957 // Every coordinator method the runtime calls is part of the contract, so a
958 // coordinator missing any one of them fails at configuration, naming it,
959 // rather than later inside message dispatch.
960 it.each([
961 `getNodeId`,
962 `subscribe`,
963 `publish`,
964 `isLeader`,
965 `ensureLeadership`,
966 `requestEnsureRemoteSubset`,
967 `requestReleaseRemoteSubset`,
968 `registerRemoteSubsetOwner`,
969 `requestEnsurePersistedIndex`,
970 `requestApplyCommittedTx`,
971 ] as const)(`rejects a coordinator without %s`, (method) => {
972 const complete: Record<string, unknown> = {
973 getNodeId: () => `node-1`,
974 subscribe: () => () => {},
975 publish: () => {},
976 isLeader: () => true,
977 ensureLeadership: async () => {},
978 requestEnsureRemoteSubset: async () => {},
979 requestReleaseRemoteSubset: async () => {},
980 registerRemoteSubsetOwner: () => () => {},
981 requestEnsurePersistedIndex: async () => {},
982 requestApplyCommittedTx: async () => ({ term: 1, seq: 1 }),
983 }
984 delete complete[method]
985​
986 expect(() =>
987 persistedCollectionOptions<Todo, string>({
988 id: `coordinator-without-${method}`,
989 getKey: (item) => item.id,
990 persistence: {
991 adapter: createNoopAdapter(),
992 coordinator: complete as unknown as PersistedCollectionCoordinator,
993 },
994 }),
995 ).toThrow(
996 `Invalid persisted collection coordinator: missing required "${method}" method`,
997 )
998 })
999​
1000 it(`rejects an incomplete coordinator before starting a rich sync source`, async () => {
1001 type SourceParams = Parameters<SyncConfig<Todo, string>[`sync`]>[0]
1002​
1003 const adapter = createRecordingAdapter()
1004 const applyCommittedTx = adapter.applyCommittedTx
1005 let adapterApplies = 0
1006 adapter.applyCommittedTx = (...args) => {
1007 adapterApplies++
1008 return applyCommittedTx(...args)
1010 let sourceCalls = 0
1011 let legacyCalls = 0
1012 let sourceParams: SourceParams | undefined
1013 let collectionConstructed = false
1014 let visible = false
1015 let configurationError: { name: string; message: string } | null = null
1016 let collection: Collection<Todo, string> | undefined
1017​
1018 const incompleteCoordinator = {
1019 getNodeId: () => `incomplete-rich-sync`,
1020 subscribe: () => () => {},
1021 publish: () => {},
1022 isLeader: () => false,
1023 ensureLeadership: () => Promise.resolve(),
1024 requestEnsurePersistedIndex: () => Promise.resolve(),
1025 // Remote subset routing is complete so this fixture isolates the
1026 // required committed-transaction method named by the assertion.
1027 requestEnsureRemoteSubset: () => Promise.resolve(),
1028 requestReleaseRemoteSubset: () => Promise.resolve(),
1029 registerRemoteSubsetOwner: () => () => {},
1030 requestApplyLocalMutations: () => {
1031 legacyCalls++
1032 return Promise.resolve({
1033 type: `rpc:applyLocalMutations:res` as const,
1034 rpcId: `legacy`,
1035 ok: true as const,
1036 term: 1,
1037 seq: 1,
1038 latestRowVersion: 1,
1039 acceptedMutationIds: [],
1040 })
1041 },
1042 } as unknown as PersistedCollectionCoordinator
1043​
1044 try {
1045 try {
1046 const options = persistedCollectionOptions<Todo, string>({
1047 id: `incomplete-rich-sync`,
1048 getKey: (todo) => todo.id,
1049 sync: {
1050 sync: (params) => {
1051 sourceCalls++
1052 sourceParams = params
1053 params.markReady()
1054 },
1055 },
1056 persistence: { adapter, coordinator: incompleteCoordinator },
1057 })
1058 collection = createCollection(options)
1059 collectionConstructed = true
1060 } catch (error) {
1061 const resolvedError =
1062 error instanceof Error ? error : new Error(String(error))
1063 configurationError = {
1064 name: resolvedError.name,
1065 message: resolvedError.message,
1068​
1069 if (collection) {
1070 collection.startSyncImmediate()
1071 await vi.waitFor(() => expect(sourceParams).toBeDefined())
1072 sourceParams!.begin()
1073 sourceParams!.metadata?.collection.set(`resume`, { offset: 7 })
1074 sourceParams!.truncate()
1075 sourceParams!.write({
1076 type: `insert`,
1077 value: { id: `rich`, title: `Visible before rejection` },
1078 metadata: { source: `remote` },
1079 })
1080 await Promise.resolve(sourceParams!.commit()).catch(() => undefined)
1081 visible = collection.has(`rich`)
1083 } finally {
1084 await collection?.cleanup()
1086​
1087 expect({
1088 configurationError,
1089 sourceCalls,
1090 collectionConstructed,
1091 visible,
1092 adapterApplies,
1093 legacyCalls,
1094 }).toEqual({
1095 configurationError: {
1096 name: `InvalidPersistedCollectionCoordinatorError`,
1097 message:
1098 'Invalid persisted collection coordinator: missing required "requestApplyCommittedTx" method',
1099 },
1100 sourceCalls: 0,
1101 collectionConstructed: false,
1102 visible: false,
1103 adapterApplies: 0,
1104 legacyCalls: 0,
1105 })
1106 })
1107​
1108 it(`preserves valid sync config in sync-present mode`, async () => {
1109 const adapter = createRecordingAdapter()
1110 const sync: SyncConfig<Todo, string> = {
1111 sync: ({ begin, write, commit, markReady }) => {
1112 begin()
1113 write({
1114 type: `insert`,
1115 value: {
1116 id: `remote-1`,
1117 title: `From remote`,
1118 },
1119 })
1120 commit()
1121 markReady()
1122 },
1124​
1125 const options = persistedCollectionOptions<Todo, string>({
1126 id: `sync-present`,
1127 getKey: (item: Todo) => item.id,
1128 sync,
1129 persistence: {
1130 adapter,
1131 },
1132 })
1133​
1134 const collection = createCollection(options)
1135 await collection.stateWhenReady()
1136 await flushAsyncWork()
1137​
1138 expect(stripVirtualProps(collection.get(`remote-1`))).toEqual({
1139 id: `remote-1`,
1140 title: `From remote`,
1141 })
1142 expect(adapter.applyCommittedTxCalls).toHaveLength(1)
1143 // A source insert names the whole row, so storage replaces any cached row
1144 // instead of merging over it (decision C1 of 2026-10-23); the adapter's
1145 // insert is an upsert, so cache and snapshot overlap stays safe.
1146 expect(adapter.applyCommittedTxCalls[0]?.tx.mutations[0]?.type).toBe(
1147 `insert`,
1149 })