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

transaction-serializer.property.test.ts

1,395 lines41.7 KB

1import { createCollection, createTransaction } from '@tanstack/db'
2import fc from 'fast-check'
3import { expect, it, vi } from 'vitest'
4import { OutboxManager } from '../src/outbox/OutboxManager'
5import {
6 MissingTemporalConstructorError,
7 TransactionSerializer,
8} from '../src/outbox/TransactionSerializer'
9import { cleanupOfflineOracle } from './oracle-lifecycle'
10import { FakeStorageAdapter } from './harness'
11import { readOfflineOracleConfig } from './oracle-config'
12import type { OfflineTransaction } from '../src/types'
13import type { PendingMutation } from '@tanstack/db'
14​
15/**
16 * # Does an offline transaction survive durable serialization exactly?
17 *
18 * Contract and source: SerializedOfflineTransaction and the established restart
19 * contract preserve mutation meaning across process boundaries. Encoding v3
20 * supports JSON trees, Date, and the eight restorable Temporal scalar types.
21 * Marker-shaped user objects remain data. Unversioned and v2 records retain
22 * their prior meanings. Unsupported or malformed encodings fail visibly.
23 *
24 * Model: each generated Pair derives runtime and wire values from one semantic
25 * leaf. It never walks production output or imports serializer helpers. Focused
26 * metadata witnesses use JSON's toJSON, boxed-scalar, and array-index rules.
27 * Mutation values deliberately retain the package's structural encoding rules.
28 *
29 * History grammar: insert, update, and delete edits span two collection registry
30 * keys. Trees contain bounded arrays, objects, hostile keys, Date values, and
31 * date-like strings. Separate histories cover unversioned, v2, and v3 records,
32 * metadata replacements, Temporal constructors, and corrupted wire markers.
33 *
34 * Production driver and refinement check: real Collections create mutations.
35 * TransactionSerializer writes the record. New Collection identities then read
36 * it through the same registry keys. Each checkpoint compares the wire tree,
37 * decoded transaction fields, registry binding, order, errors, and retained
38 * storage after a failed read.
39 *
40 * Reach and controls: pinned histories force every edit kind and hostile marker.
41 * Fixed and random lanes support seed/path replay. Encoder and decoder faults
42 * inject Date/string confusion, wrong registry, omitted changes, and unknown
43 * versions. Malformed markers and missing Temporal constructors test failure
44 * paths before durable data can be replaced.
45 *
46 * Limits: undefined, non-finite numbers, arbitrary native objects, and
47 * cross-realm boxed values are outside current evidence. Cycles must fail
48 * visibly while repeated non-cyclic references retain their values. This
49 * oracle does not claim byte stability for object key order beyond JSON's
50 * established rules.
51 */
52​
53type Value =
54 | null
55 | boolean
56 | number
57 | string
58 | Date
59 | Array<Value>
60 | { [key: string]: Value }
61type Pair = { runtime: Value; wire: Value }
62type Row = { id: string; revision: number; payload: Value }
63type Edit = {
64 kind: `insert` | `update` | `delete`
65 slot: number
66 before: Pair
67 after: Pair
69type Fault =
70 | `none`
71 | `date-as-string`
72 | `string-as-date`
73 | `wrong-registry`
74 | `omit-changes`
75 | `unknown-encoding`
76​
77// Construct both representations from semantic leaves, not production output.
78const datePair = (time: number): Pair => ({
79 runtime: new Date(time),
80 wire: { __type: `Date`, value: new Date(time).toISOString() },
81})
82const scalar = fc.oneof(
83 fc.constant(null),
84 fc.boolean(),
85 fc.integer(),
86 fc
87 .double({ noNaN: true, noDefaultInfinity: true })
88 .filter((value) => !Object.is(value, -0)),
89 fc.string({ maxLength: 30 }),
91const leaf: fc.Arbitrary<Pair> = fc.oneof(
92 scalar.map((value) => ({ runtime: value, wire: value })),
93 fc.integer({ min: -2000000000000, max: 2000000000000 }).map(datePair),
94 fc.integer({ min: -2000000000000, max: 2000000000000 }).map((time) => {
95 const value = new Date(time).toISOString()
96 return { runtime: value, wire: value }
97 }),
99function tree(depth: number): fc.Arbitrary<Pair> {
100 if (depth === 0) return leaf
101 const child = tree(depth - 1)
102 return fc.oneof(
103 leaf,
104 fc.tuple(fc.constantFrom(`Date`, `Object`), child).map(([tag, value]) => ({
105 runtime: { __type: tag, value: value.runtime },
106 wire: { __type: `Object`, value: { __type: tag, value: value.wire } },
107 })),
108 fc.array(child, { maxLength: 3 }).map((items) => ({
109 runtime: items.map((item) => item.runtime),
110 wire: items.map((item) => item.wire),
111 })),
112 fc
113 .dictionary(
114 fc.oneof(
115 fc.constantFrom(
116 `__proto__`,
117 `constructor`,
118 `toString`,
119 `left`,
120 `date`,
121 `__type`,
122 ),
123 fc.string({ maxLength: 12 }),
124 ),
125 child,
126 { maxKeys: 3 },
127 )
128 .map((fields) => ({
129 runtime: Object.fromEntries(
130 Object.entries(fields).map(([key, value]) => [key, value.runtime]),
131 ),
132 wire: objectWire(
133 Object.fromEntries(
134 Object.entries(fields).map(([key, value]) => [key, value.wire]),
135 ),
136 ),
137 })),
138 )
140​
141function objectWire(fields: { [key: string]: Value }): Value {
142 return Object.hasOwn(fields, `__type`)
143 ? { __type: `Object`, value: fields }
144 : fields
146​
147// Model law: v3 wire values escape marker-shaped objects exactly once. The
148// expected tree is built from semantic Pairs, independently of production.
149async function checkRoundtrip(
150 edits: Array<Edit>,
151 time: number,
152 fault: Fault = `none`,
153 boundary: `encoder` | `decoder` = `encoder`,
154 legacy = false,
155 versionTwo = false,
156) {
157 const row = (index: number, revision: number, payload: Value): Row => ({
158 id: `row:${index}`,
159 revision,
160 payload,
161 })
162 const writers = [0, 1].map((slot) =>
163 createCollection<Row>({
164 id: `writer:${slot}`,
165 getKey: (item) => item.id,
166 startSync: true,
167 sync: {
168 sync: ({ begin, write, commit, markReady }) => {
169 begin()
170 edits.forEach((edit, index) => {
171 if (edit.slot === slot && edit.kind !== `insert`)
172 write({
173 type: `insert`,
174 value: row(index, 0, edit.before.runtime),
175 })
176 })
177 commit()
178 markReady()
179 },
180 },
181 }),
182 )
183 // A restart has different object and collection IDs, but the same registry keys.
184 const readers = [0, 1].map((slot) =>
185 createCollection<Row>({
186 id: `reader:${slot}`,
187 getKey: (item) => item.id,
188 sync: { sync: ({ markReady }) => markReady() },
189 }),
190 )
191 const registry = (collections: typeof writers) =>
192 Object.fromEntries(
193 collections.map((collection, slot) => [`slot:${slot}`, collection]),
194 )
195 const serializer = new TransactionSerializer(registry(writers))
196 const transaction = createTransaction({
197 autoCommit: false,
198 mutationFn: async () => {},
199 })
200 const rollback = transaction.isPersisted.promise.catch(() => undefined)
201 let hasPrimaryFailure = false
202 try {
203 transaction.mutate(() => {
204 edits.forEach((edit, index) => {
205 const collection = writers[edit.slot]!
206 if (edit.kind === `insert`)
207 collection.insert(row(index, 1, edit.after.runtime))
208 else if (edit.kind === `delete`) collection.delete(`row:${index}`)
209 else
210 collection.update(`row:${index}`, (draft) => {
211 draft.revision = 1 // Even equal payloads produce a real mutation.
212 draft.payload = edit.after.runtime
213 })
214 })
215 })
216 expect(transaction.mutations).toHaveLength(edits.length)
217 const envelope = {
218 id: `offline`,
219 mutationFnName: `persist`,
220 keys: transaction.mutations.map((mutation) => mutation.globalKey),
221 idempotencyKey: `once`,
222 retryCount: 2,
223 nextAttemptAt: 123,
224 version: 1 as const,
225 metadata: { note: `2024-01-01T00:00:00.000Z` },
226 lastError: { name: `Error`, message: `retry`, stack: `original stack` },
227 }
228 const offline: OfflineTransaction = {
229 ...envelope,
230 createdAt: new Date(time),
231 mutations: transaction.mutations,
232 }
233 const data = (edit: Edit, index: number, form: keyof Pair) => {
234 const original =
235 edit.kind === `insert` ? {} : row(index, 0, edit.before[form])
236 const modified =
237 edit.kind === `delete` ? original : row(index, 1, edit.after[form])
238 // Update tracking may omit an unchanged payload. Read the field presence
239 // from the input mutation; the serializer's law is preserving its data,
240 // not independently specifying the core mutation-composition contract.
241 const changes =
242 edit.kind !== `update`
243 ? modified
244 : {
245 revision: 1,
246 ...(`payload` in transaction.mutations[index]!.changes
247 ? { payload: edit.after[form] }
248 : {}),
249 }
250 return { original, modified, changes }
251 }
252 const expectedWire = {
253 ...envelope,
254 valueEncoding: 3,
255 createdAt: new Date(time).toISOString(),
256 mutations: edits.map((edit, index) => ({
257 globalKey: transaction.mutations[index]!.globalKey,
258 type: edit.kind,
259 collectionId: `slot:${edit.slot}`,
260 ...data(edit, index, `wire`),
261 })),
262 }
263 const corrupt = (input: string) => {
264 let encoded = input
265 if (fault === `date-as-string`)
266 encoded = encoded.replace(
267 // Mutate the semantic payload, not a Date-shaped user object inside
268 // an Object escape: the latter would test malformed wire instead.
269 /("payload":)\{"__type":"Date","value":"([^"]+)"\}/g,
270 `$1"$2"`,
271 )
272 if (fault === `string-as-date`)
273 encoded = encoded.replace(
274 `"payload":"2024-01-01T00:00:00.000Z"`,
275 `"payload":{"__type":"Date","value":"2024-01-01T00:00:00.000Z"}`,
276 )
277 if (fault === `wrong-registry`)
278 encoded = encoded.replace(
279 `"collectionId":"slot:0"`,
280 `"collectionId":"writer:0"`,
281 )
282 if (fault === `omit-changes`)
283 encoded = encoded.replaceAll(`"changes":`, `"lostChanges":`)
284 if (fault === `unknown-encoding`)
285 encoded = encoded.replace(`"valueEncoding":3`, `"valueEncoding":4`)
286 return encoded
287 }
288 const serialized = serializer.serialize(offline)
289 const encoded = boundary === `encoder` ? corrupt(serialized) : serialized
290 expect(JSON.parse(encoded)).toEqual(expectedWire)
291 const fresh = new TransactionSerializer(registry(readers))
292 // Also decode independently constructed wire data, so two matching wrong
293 // halves cannot establish the format's compatibility by roundtrip alone.
294 // Decoder calibration starts with authored wire, not a faulty encoder.
295 // A Date/string swap is valid wire: the semantic oracle must reject its
296 // changed meaning; the decoder itself need not throw.
297 const wires =
298 boundary === `decoder`
299 ? [corrupt(JSON.stringify(expectedWire))]
300 : [encoded, JSON.stringify(expectedWire)]
301 if (legacy) {
302 const { valueEncoding: _encoding, ...oldWire } = expectedWire
303 wires.push(JSON.stringify(oldWire))
304 }
305 if (versionTwo)
306 wires.push(JSON.stringify({ ...expectedWire, valueEncoding: 2 }))
307 for (const wire of wires) {
308 const decoded = fresh.deserialize(wire)
309 const { mutations, ...rest } = decoded
310 expect(rest).toEqual({ ...envelope, createdAt: new Date(time) })
311 expect(mutations).toHaveLength(edits.length)
312 edits.forEach((edit, index) => {
313 const mutation = mutations[index]!
314 expect(mutation.collection).toBe(readers[edit.slot])
315 expect(mutation.key).toBe(`row:${index}`)
316 expect(mutation.globalKey).toBe(transaction.mutations[index]!.globalKey)
317 expect(mutation.type).toBe(edit.kind)
318 expect({
319 original: mutation.original,
320 modified: mutation.modified,
321 changes: mutation.changes,
322 }).toEqual(data(edit, index, `runtime`))
323 })
324 }
325 } catch (error) {
326 hasPrimaryFailure = true
327 throw error
328 } finally {
329 await cleanupOfflineOracle(
330 [
331 () => {
332 transaction.rollback()
333 },
334 () => rollback,
335 ...[...writers, ...readers].map(
336 (collection) => () => collection.cleanup(),
337 ),
338 ],
339 hasPrimaryFailure,
340 )
341 }
343​
344const twin: Pair = {
345 runtime: `2024-01-01T00:00:00.000Z`,
346 wire: `2024-01-01T00:00:00.000Z`,
348​
349const temporalCases = [
350 [`Duration`, `PT1H30M`],
351 [`Instant`, `2026-09-16T12:34:56Z`],
352 [`PlainDate`, `2026-09-16`],
353 [`PlainDateTime`, `2026-09-16T12:34:56`],
354 [`PlainMonthDay`, `09-16`],
355 [`PlainTime`, `12:34:56`],
356 [`PlainYearMonth`, `2026-09`],
357 [`ZonedDateTime`, `2026-09-16T12:34:56-06:00[America/Denver]`],
358] as const
359​
360type TemporalName = (typeof temporalCases)[number][0]
361​
362class TemporalStub {
363 readonly #name: TemporalName
364 readonly #value: string
365​
366 constructor(name: TemporalName, value: string) {
367 this.#name = name
368 this.#value = value
369 }
370​
371 get [Symbol.toStringTag](): `Temporal.${TemporalName}` {
372 return `Temporal.${this.#name}`
373 }
374​
375 toString(): string {
376 return this.#value
377 }
379​
380function temporalStubConstructor(name: TemporalName) {
381 return class extends TemporalStub {
382 constructor(value: string) {
383 super(name, value)
384 }
385​
386 static from(value: string): TemporalStub {
387 return new TemporalStub(name, value)
388 }
389 }
391​
392function metadataTransaction(
393 metadata: Record<string, unknown>,
394): OfflineTransaction {
395 return {
396 id: `metadata-json`,
397 mutationFnName: `persist`,
398 mutations: [],
399 keys: [],
400 idempotencyKey: `once`,
401 createdAt: new Date(0),
402 retryCount: 0,
403 nextAttemptAt: 0,
404 metadata,
405 version: 1,
406 }
408​
409it(`rejects cyclic metadata with a bounded JSON-style error`, () => {
410 const metadata: Record<string, unknown> = {}
411 metadata.self = metadata
412​
413 expect(() =>
414 new TransactionSerializer({}).serialize(metadataTransaction(metadata)),
415 ).toThrowError(new TypeError(`Converting circular structure to JSON`))
416})
417​
418it(`rejects cyclic mutation values with a bounded JSON-style error`, () => {
419 const collection = { id: `cycle-writer` } as any
420 const modified: Record<string, unknown> = { id: `one` }
421 modified.self = modified
422 const transaction: OfflineTransaction = {
423 ...metadataTransaction({}),
424 mutations: [
425 {
426 globalKey: `cycle-writer:one`,
427 type: `insert`,
428 modified,
429 original: {},
430 changes: modified,
431 collection,
432 } as PendingMutation,
433 ],
434 keys: [`cycle-writer:one`],
435 }
436​
437 expect(() =>
438 new TransactionSerializer({ rows: collection }).serialize(transaction),
439 ).toThrowError(new TypeError(`Converting circular structure to JSON`))
440})
441​
442it(`preserves repeated references that do not form a cycle`, () => {
443 const shared = { nested: [`value`] }
444 const transaction = metadataTransaction({ left: shared, right: shared })
445​
446 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
447​
448 expect(wire.metadata).toEqual({
449 left: { nested: [`value`] },
450 right: { nested: [`value`] },
451 })
452})
453​
454it(`preserves spoofed Temporal tags as data while restoring branded values`, async () => {
455 class PlainDateStub {
456 readonly #value: string
457​
458 constructor(value: string) {
459 this.#value = value
460 }
461​
462 static from(value: string): PlainDateStub {
463 return new PlainDateStub(value)
464 }
465​
466 get [Symbol.toStringTag](): `Temporal.PlainDate` {
467 return `Temporal.PlainDate`
468 }
469​
470 toString(): string {
471 return this.#value
472 }
473 }
474​
475 const temporalGlobal = globalThis as { Temporal?: Record<string, unknown> }
476 const previousTemporal = temporalGlobal.Temporal
477 temporalGlobal.Temporal = { PlainDate: PlainDateStub }
478 const storage = new FakeStorageAdapter()
479 const outbox = new OutboxManager(storage, {})
480 const transaction = metadataTransaction({
481 spoofed: {
482 keep: `user data`,
483 [Symbol.toStringTag]: `Temporal.PlainDate`,
484 toString: () => `not-a-date`,
485 },
486 genuine: new PlainDateStub(`2026-09-22`),
487 })
488​
489 try {
490 await outbox.add(transaction)
491 const restored = await outbox.get(transaction.id)
492​
493 expect(restored?.metadata).toMatchObject({
494 spoofed: { keep: `user data` },
495 genuine: expect.any(PlainDateStub),
496 })
497 expect(String((restored?.metadata as any).genuine)).toBe(`2026-09-22`)
498 } finally {
499 if (previousTemporal === undefined) delete temporalGlobal.Temporal
500 else temporalGlobal.Temporal = previousTemporal
501 }
502})
503​
504it(`preserves plain user data with a Temporal tag when Temporal is unavailable`, () => {
505 const temporalGlobal = globalThis as { Temporal?: Record<string, unknown> }
506 const previousTemporal = temporalGlobal.Temporal
507 delete temporalGlobal.Temporal
508 const transaction = metadataTransaction({
509 spoofed: {
510 keep: `user data`,
511 [Symbol.toStringTag]: `Temporal.Instant`,
512 },
513 })
514​
515 try {
516 const wire = JSON.parse(
517 new TransactionSerializer({}).serialize(transaction),
518 )
519​
520 expect(wire.metadata).toEqual({ spoofed: { keep: `user data` } })
521 } finally {
522 if (previousTemporal === undefined) delete temporalGlobal.Temporal
523 else temporalGlobal.Temporal = previousTemporal
524 }
525})
526​
527it(`does not invoke a mutation value's plain Symbol.toStringTag getter`, () => {
528 let reads = 0
529 const value = { keep: `user data` }
530 Object.defineProperty(value, Symbol.toStringTag, {
531 get() {
532 reads++
533 throw new Error(`do not inspect user getters`)
534 },
535 })
536 const collection = { id: `tag-getter-writer` } as any
537 const modified = { id: `one`, value }
538 const transaction: OfflineTransaction = {
539 ...metadataTransaction({}),
540 mutations: [
541 {
542 globalKey: `tag-getter-writer:one`,
543 type: `insert`,
544 modified,
545 original: {},
546 changes: modified,
547 collection,
548 } as unknown as PendingMutation,
549 ],
550 keys: [`tag-getter-writer:one`],
551 }
552​
553 const wire = JSON.parse(
554 new TransactionSerializer({ rows: collection }).serialize(transaction),
555 )
556​
557 expect({ reads, modified: wire.mutations[0].modified }).toEqual({
558 reads: 0,
559 modified: { id: `one`, value: { keep: `user data` } },
560 })
561})
562​
563it(`rejects native scalars before storage when global restoration is unavailable`, async () => {
564 const temporalGlobal = globalThis as { Temporal?: Record<string, unknown> }
565 const previousTemporal = temporalGlobal.Temporal
566 temporalGlobal.Temporal = {}
567 const storage = new FakeStorageAdapter()
568 const outbox = new OutboxManager(storage, {})
569 const transaction: OfflineTransaction = {
570 id: `unrestorable-native-scalar`,
571 mutationFnName: `persist`,
572 mutations: [],
573 keys: [],
574 idempotencyKey: `once`,
575 createdAt: new Date(0),
576 retryCount: 0,
577 nextAttemptAt: 0,
578 metadata: {
579 due: new TemporalStub(`PlainDate`, `2026-09-16`),
580 },
581 version: 1,
582 }
583​
584 try {
585 await expect(outbox.add(transaction)).rejects.toThrow(
586 MissingTemporalConstructorError,
587 )
588 expect(storage.snapshot()).toEqual({})
589 } finally {
590 if (previousTemporal === undefined) delete temporalGlobal.Temporal
591 else temporalGlobal.Temporal = previousTemporal
592 }
593})
594​
595it(`uses one validated Temporal tag when writing a marker`, () => {
596 const temporalGlobal = globalThis as { Temporal?: Record<string, unknown> }
597 const previousTemporal = temporalGlobal.Temporal
598 let reads = 0
599 class PlainDateStub {
600 readonly #value: string
601​
602 constructor(value: string) {
603 this.#value = value
604 }
605​
606 static from(value: string): PlainDateStub {
607 return new PlainDateStub(value)
608 }
609​
610 get [Symbol.toStringTag]() {
611 reads++
612 return reads === 1 ? `Temporal.PlainDate` : `Temporal.Invalid`
613 }
614​
615 toString(): string {
616 return this.#value
617 }
618 }
619 temporalGlobal.Temporal = { PlainDate: PlainDateStub }
620 const value = new PlainDateStub(`2026-09-16`)
621​
622 try {
623 const wire = JSON.parse(
624 new TransactionSerializer({}).serialize(metadataTransaction({ value })),
625 )
626 expect(wire.metadata.value).toEqual({
627 __type: `Temporal`,
628 type: `Temporal.PlainDate`,
629 value: `2026-09-16`,
630 })
631 expect(reads).toBe(1)
632 } finally {
633 if (previousTemporal === undefined) delete temporalGlobal.Temporal
634 else temporalGlobal.Temporal = previousTemporal
635 }
636})
637​
638it(`preserves metadata toJSON values without changing mutation value semantics`, () => {
639 class JsonValue {
640 toJSON(key: string) {
641 return `from-toJSON:${key}`
642 }
643 }
644 const collection = {
645 id: `metadata-json-writer`,
646 getKeyFromItem: (value: { id: string }) => value.id,
647 } as any
648 const serializer = new TransactionSerializer({ rows: collection })
649 const url = new URL(`https://example.com/path`)
650 const jsonValue = new JsonValue()
651 const metadata = {
652 url,
653 jsonValue,
654 nested: [jsonValue],
655 boxed: [Object(7), Object(`value`), Object(false)],
656 }
657 Object.defineProperty(metadata, `toJSON`, {
658 value: (key: string) => ({ ...metadata, metadataKey: key }),
659 })
660 const transaction: OfflineTransaction = {
661 id: `metadata-json`,
662 mutationFnName: `persist`,
663 mutations: [
664 {
665 globalKey: `metadata-json-writer:one`,
666 type: `insert`,
667 modified: { id: `one`, url, jsonValue },
668 original: {},
669 changes: {},
670 collection,
671 } as unknown as PendingMutation,
672 ],
673 keys: [`metadata-json-writer:one`],
674 idempotencyKey: `once`,
675 createdAt: new Date(0),
676 retryCount: 0,
677 nextAttemptAt: 0,
678 metadata,
679 version: 1,
680 }
681​
682 const encoded = serializer.serialize(transaction)
683 const wire = JSON.parse(encoded)
684 expect(wire.metadata).toEqual({
685 url: `https://example.com/path`,
686 jsonValue: `from-toJSON:jsonValue`,
687 nested: [`from-toJSON:0`],
688 boxed: [7, `value`, false],
689 metadataKey: `metadata`,
690 })
691 expect(wire.mutations[0].modified).toEqual({
692 id: `one`,
693 url: {},
694 jsonValue: {},
695 })
696​
697 const decoded = serializer.deserialize(encoded)
698 expect(decoded.metadata).toEqual(wire.metadata)
699 expect(decoded.mutations[0]!.modified).toEqual(wire.mutations[0].modified)
700})
701​
702it(`does not invoke toJSON again on its immediate replacement`, () => {
703 const nested = {
704 toJSON(key: string) {
705 return `nested:${key}`
706 },
707 }
708 const replacement = {
709 nested,
710 toJSON() {
711 return `incorrect second invocation`
712 },
713 }
714 const transaction = metadataTransaction({
715 value: {
716 toJSON(key: string) {
717 return key === `value` ? replacement : `incorrect key:${key}`
718 },
719 },
720 })
721​
722 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
723​
724 expect(wire.metadata).toEqual({ value: { nested: `nested:nested` } })
725})
726​
727it(`rejects a toJSON replacement that references its receiver`, () => {
728 const source = {
729 toJSON() {
730 return { back: source }
731 },
732 }
733​
734 expect(() =>
735 new TransactionSerializer({}).serialize(
736 metadataTransaction({ value: source }),
737 ),
738 ).toThrowError(new TypeError(`Converting circular structure to JSON`))
739})
740​
741it(`treats immediate native-scalar replacements as ordinary JSON values`, () => {
742 const temporalReplacement = {
743 [Symbol.toStringTag]: `Temporal.PlainDate`,
744 toString() {
745 return `2026-09-16`
746 },
747 }
748 const transaction = metadataTransaction({
749 date: { toJSON: () => new Date(0) },
750 temporal: { toJSON: () => temporalReplacement },
751 })
752​
753 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
754​
755 expect(wire.metadata).toEqual({ date: {}, temporal: {} })
756})
757​
758it(`preserves JSON array length and indexed-property semantics in metadata`, () => {
759 const values = Array(3) as Array<string | undefined>
760 Object.defineProperty(values, 0, { enumerable: false, value: `hidden` })
761 values[1] = `visible`
762 const shrinking = Array(3) as Array<string | undefined>
763 Object.defineProperty(shrinking, 0, {
764 enumerable: true,
765 get() {
766 shrinking.length = 1
767 return `first`
768 },
769 })
770 const transaction = metadataTransaction({ values, shrinking })
771​
772 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
773​
774 expect(wire.metadata).toEqual({
775 values: [`hidden`, `visible`, null],
776 shrinking: [`first`, null, null],
777 })
778})
779​
780it(`retains JSON's error for boxed BigInt metadata`, () => {
781 const transaction = metadataTransaction({ value: Object(1n) })
782​
783 expect(() => new TransactionSerializer({}).serialize(transaction)).toThrow(
784 TypeError,
785 )
786})
787​
788it(`does not recurse through fresh toJSON replacement objects`, () => {
789 const freshReplacement = (): Record<string, unknown> => ({
790 toJSON: freshReplacement,
791 })
792 const transaction = metadataTransaction({
793 value: { toJSON: freshReplacement },
794 })
795​
796 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
797​
798 expect(wire.metadata).toEqual({ value: {} })
799})
800​
801it(`reads metadata toJSON once with its object as the receiver`, () => {
802 let reads = 0
803 let selfCalls = 0
804 const value = {
805 marker: `receiver`,
806 get toJSON() {
807 reads++
808 if (reads > 1) throw new Error(`toJSON read more than once`)
809 return function (this: { marker: string }, key: string) {
810 return `${this.marker}:${key}`
811 }
812 },
813 }
814 const self = {
815 keep: `value`,
816 toJSON() {
817 selfCalls++
818 return this
819 },
820 }
821 const transaction = metadataTransaction({ value, self })
822​
823 const wire = JSON.parse(new TransactionSerializer({}).serialize(transaction))
824​
825 expect(wire.metadata).toEqual({
826 value: `receiver:value`,
827 self: { keep: `value` },
828 })
829 expect(reads).toBe(1)
830 expect(selfCalls).toBe(1)
831})
832​
833it(`preserves native scalar identity across storage restart`, async () => {
834 type NativeRow = {
835 id: string
836 values: Record<TemporalName, TemporalStub>
837 }
838 const writer = createCollection<NativeRow>({
839 id: `native-scalar-writer`,
840 getKey: (row) => row.id,
841 sync: { sync: ({ markReady }) => markReady() },
842 })
843 const reader = createCollection<NativeRow>({
844 id: `native-scalar-reader`,
845 getKey: (row) => row.id,
846 sync: { sync: ({ markReady }) => markReady() },
847 })
848 const previousTemporal = (
849 globalThis as { Temporal?: Record<string, unknown> }
850 ).Temporal
851 ;(globalThis as { Temporal?: Record<string, unknown> }).Temporal =
852 Object.fromEntries(
853 temporalCases.map(([name]) => [name, temporalStubConstructor(name)]),
854 )
855​
856 const values = Object.fromEntries(
857 temporalCases.map(([name, value]) => [name, new TemporalStub(name, value)]),
858 ) as NativeRow[`values`]
859 const mutation = {
860 globalKey: `native-scalar-writer:one`,
861 type: `update`,
862 modified: { id: `one`, values },
863 original: { id: `one`, values },
864 changes: { values },
865 collection: writer,
866 } as unknown as PendingMutation
867 const transaction: OfflineTransaction = {
868 id: `native-scalars`,
869 mutationFnName: `persist`,
870 mutations: [mutation],
871 keys: [mutation.globalKey],
872 idempotencyKey: `once`,
873 createdAt: new Date(0),
874 retryCount: 0,
875 nextAttemptAt: 0,
876 metadata: { nested: { values } },
877 version: 1,
878 }
879​
880 try {
881 const encoded = new TransactionSerializer({ rows: writer }).serialize(
882 transaction,
883 )
884 const wire = JSON.parse(encoded)
885 expect(wire.valueEncoding).toBe(3)
886 const encodedLocations = [
887 wire.mutations[0].modified.values,
888 wire.mutations[0].original.values,
889 wire.mutations[0].changes.values,
890 wire.metadata.nested.values,
891 ] as Array<Record<TemporalName, unknown>>
892 for (const location of encodedLocations)
893 for (const [name, value] of temporalCases)
894 expect(location[name]).toEqual({
895 __type: `Temporal`,
896 type: `Temporal.${name}`,
897 value,
898 })
899​
900 const restarted = new TransactionSerializer({ rows: reader })
901 const decoded = restarted.deserialize(encoded)
902 const decodedMutation = decoded.mutations[0]!
903 const restored = [
904 (decodedMutation.modified as NativeRow).values,
905 (decodedMutation.original as NativeRow).values,
906 (decodedMutation.changes as { values: NativeRow[`values`] }).values,
907 (
908 decoded.metadata as {
909 nested: { values: NativeRow[`values`] }
910 }
911 ).nested.values,
912 ] as Array<Record<TemporalName, unknown>>
913​
914 for (const location of restored) {
915 for (const [name, value] of temporalCases) {
916 expect(location[name]).toBeInstanceOf(TemporalStub)
917 expect(Object.prototype.toString.call(location[name])).toBe(
918 `[object Temporal.${name}]`,
919 )
920 expect(String(location[name])).toBe(value)
921 }
922 }
923 } finally {
924 if (previousTemporal === undefined)
925 delete (globalThis as { Temporal?: Record<string, unknown> }).Temporal
926 else
927 (globalThis as { Temporal?: Record<string, unknown> }).Temporal =
928 previousTemporal
929 await writer.cleanup()
930 await reader.cleanup()
931 }
932})
933​
934it(`preserves marker-shaped user data through current wire encoding`, async () => {
935 const runtime = {
936 __type: `Temporal`,
937 type: `Temporal.PlainDate`,
938 value: `2026-09-16`,
939 }
940 await checkRoundtrip(
941 [
942 {
943 kind: `insert`,
944 slot: 0,
945 before: twin,
946 after: { runtime, wire: objectWire(runtime) },
947 },
948 ],
949 0,
950 )
951})
952​
953it(`preserves prior wire meanings when reading native scalar markers`, async () => {
954 const collection = createCollection<{
955 id: string
956 due: unknown
957 createdAt: unknown
958 }>({
959 id: `native-scalar-compatibility`,
960 getKey: (row) => row.id,
961 sync: { sync: ({ markReady }) => markReady() },
962 })
963 const serializer = new TransactionSerializer({ rows: collection })
964 const temporalData = {
965 __type: `Temporal`,
966 type: `Temporal.PlainDate`,
967 value: `2026-09-16`,
968 }
969 const dateMarker = {
970 __type: `Date`,
971 value: `2026-09-16T12:34:56.000Z`,
972 }
973 const baseWire = {
974 id: `compatibility`,
975 mutationFnName: `persist`,
976 mutations: [
977 {
978 globalKey: `rows:one`,
979 type: `insert`,
980 modified: { id: `one`, due: temporalData, createdAt: dateMarker },
981 original: {},
982 changes: {},
983 collectionId: `rows`,
984 },
985 ],
986 keys: [`rows:one`],
987 idempotencyKey: `once`,
988 createdAt: new Date(0).toISOString(),
989 retryCount: 0,
990 nextAttemptAt: 0,
991 metadata: { due: temporalData, createdAt: dateMarker },
992 version: 1,
993 }
994​
995 try {
996 const unversioned = serializer.deserialize(JSON.stringify(baseWire))
997 expect(unversioned.mutations[0]!.modified).toEqual({
998 id: `one`,
999 due: temporalData,
1000 createdAt: new Date(dateMarker.value),
1001 })
1002 expect(unversioned.metadata).toEqual(baseWire.metadata)
1003​
1004 const versionTwo = serializer.deserialize(
1005 JSON.stringify({
1006 ...baseWire,
1007 valueEncoding: 2,
1008 mutations: [
1010 ...baseWire.mutations[0],
1011 modified: {
1012 id: `one`,
1013 due: { __type: `Object`, value: temporalData },
1014 createdAt: dateMarker,
1015 },
1016 },
1017 ],
1018 }),
1020 expect(versionTwo.mutations[0]!.modified).toEqual({
1021 id: `one`,
1022 due: temporalData,
1023 createdAt: new Date(dateMarker.value),
1024 })
1025 expect(versionTwo.metadata).toEqual(baseWire.metadata)
1026 } finally {
1027 await collection.cleanup()
1030​
1031it(`fails visibly with the retained native scalar transaction id`, async () => {
1032 const collection = createCollection<{ id: string; due: unknown }>({
1033 id: `native-scalar-missing-runtime`,
1034 getKey: (row) => row.id,
1035 sync: { sync: ({ markReady }) => markReady() },
1036 })
1037 const marker = {
1038 __type: `Temporal`,
1039 type: `Temporal.PlainDate`,
1040 value: `2026-09-16`,
1042 const wire = JSON.stringify({
1043 valueEncoding: 3,
1044 id: `missing-runtime`,
1045 mutationFnName: `persist`,
1046 mutations: [
1048 globalKey: `rows:one`,
1049 type: `insert`,
1050 modified: { id: `one`, due: marker },
1051 original: {},
1052 changes: {},
1053 collectionId: `rows`,
1054 },
1055 ],
1056 keys: [`rows:one`],
1057 idempotencyKey: `once`,
1058 createdAt: new Date(0).toISOString(),
1059 retryCount: 0,
1060 nextAttemptAt: 0,
1061 metadata: { due: marker },
1062 version: 1,
1063 })
1064 const temporalGlobal = globalThis as { Temporal?: Record<string, unknown> }
1065 const previousTemporal = temporalGlobal.Temporal
1066 temporalGlobal.Temporal = {}
1067 const storage = new FakeStorageAdapter()
1068 await storage.set(`tx:missing-runtime`, wire)
1069 const outbox = new OutboxManager(storage, { rows: collection })
1070​
1071 try {
1072 expect(() =>
1073 new TransactionSerializer({ rows: collection }).deserialize(wire),
1074 ).toThrow(MissingTemporalConstructorError)
1075 await expect(outbox.get(`missing-runtime`)).rejects.toThrow(
1076 /transaction missing-runtime/,
1078 await expect(outbox.getAll()).rejects.toThrow(/transaction missing-runtime/)
1079 expect(storage.snapshot()).toHaveProperty(`tx:missing-runtime`, wire)
1080 } finally {
1081 if (previousTemporal === undefined) delete temporalGlobal.Temporal
1082 else temporalGlobal.Temporal = previousTemporal
1083 await collection.cleanup()
1086​
1087it(`rejects malformed native scalar markers and constructor failures`, async () => {
1088 const collection = createCollection<{ id: string; due: unknown }>({
1089 id: `native-scalar-invalid`,
1090 getKey: (row) => row.id,
1091 sync: { sync: ({ markReady }) => markReady() },
1092 })
1093 const serializer = new TransactionSerializer({ rows: collection })
1094 const wire = (marker: unknown) =>
1095 JSON.stringify({
1096 valueEncoding: 3,
1097 id: `invalid-native-scalar`,
1098 mutationFnName: `persist`,
1099 mutations: [
1101 globalKey: `rows:one`,
1102 type: `insert`,
1103 modified: { id: `one`, due: marker },
1104 original: {},
1105 changes: {},
1106 collectionId: `rows`,
1107 },
1108 ],
1109 keys: [`rows:one`],
1110 idempotencyKey: `once`,
1111 createdAt: new Date(0).toISOString(),
1112 retryCount: 0,
1113 nextAttemptAt: 0,
1114 version: 1,
1115 })
1116​
1117 try {
1118 expect(() =>
1119 serializer.deserialize(
1120 wire({
1121 __type: `Temporal`,
1122 type: `Temporal.Calendar`,
1123 value: `iso8601`,
1124 }),
1125 ),
1126 ).toThrow(`Corrupted Temporal marker: invalid type field`)
1127 expect(() =>
1128 serializer.deserialize(
1129 wire({ __type: `Temporal`, type: `Temporal.PlainDate` }),
1130 ),
1131 ).toThrow(`Corrupted Temporal marker: missing value field`)
1132​
1133 const temporalGlobal = globalThis as {
1134 Temporal?: Record<string, unknown>
1136 const previousTemporal = temporalGlobal.Temporal
1137 const constructorFailure = new Error(`constructor rejected value`)
1138 temporalGlobal.Temporal = {
1139 PlainDate: {
1140 from: () => {
1141 throw constructorFailure
1142 },
1143 },
1145 try {
1146 expect(() =>
1147 serializer.deserialize(
1148 wire({
1149 __type: `Temporal`,
1150 type: `Temporal.PlainDate`,
1151 value: `not-a-date`,
1152 }),
1153 ),
1154 ).toThrow(constructorFailure)
1155 } finally {
1156 if (previousTemporal === undefined) delete temporalGlobal.Temporal
1157 else temporalGlobal.Temporal = previousTemporal
1159 } finally {
1160 await collection.cleanup()
1163​
1164// Roundtrips generate valid envelopes. Corrupted wire must be rejected before
1165// it can replace any mutation field with an invented empty object.
1166it.each([`modified`, `original`, `changes`] as const)(
1167 `rejects malformed escaped objects anywhere in %s`,
1168 async (field) => {
1169 const collection = createCollection<Row>({
1170 getKey: (row) => row.id,
1171 sync: { sync: ({ markReady }) => markReady() },
1172 })
1173 const serializer = new TransactionSerializer({ rows: collection })
1174 try {
1175 fc.assert(
1176 fc.property(
1177 fc.constantFrom(undefined, null, 1, `text`, false, []),
1178 fc.array(fc.boolean(), { maxLength: 4 }),
1179 (invalid, containers) => {
1180 let payload: unknown =
1181 invalid === undefined
1182 ? { __type: `Object` }
1183 : { __type: `Object`, value: invalid }
1184 for (const array of containers)
1185 payload = array ? [payload] : { child: payload }
1186 const mutation = {
1187 globalKey: `rows:one`,
1188 type: `update`,
1189 collectionId: `rows`,
1190 modified: { id: `one`, revision: 1, payload: null as unknown },
1191 original: { id: `one`, revision: 0, payload: null as unknown },
1192 changes: { payload: null as unknown },
1194 mutation[field].payload = payload
1195 expect(() =>
1196 serializer.deserialize(
1197 JSON.stringify({
1198 id: `bad`,
1199 createdAt: new Date(0).toISOString(),
1200 valueEncoding: 3,
1201 mutations: [mutation],
1202 }),
1203 ),
1204 ).toThrow(`Corrupted Object marker`)
1205 },
1206 ),
1208 seed: 20260914,
1209 numRuns: 100,
1210 examples: [undefined, null, 1, `text`, false, []].map(
1211 (value): [typeof value, Array<boolean>] => [value, []],
1212 ),
1213 },
1215 } finally {
1216 await collection.cleanup()
1218 },
1220const pinned: Array<Edit> = [
1221 { kind: `insert`, slot: 1, before: twin, after: { runtime: 0.5, wire: 0.5 } },
1222 { kind: `insert`, slot: 0, before: twin, after: datePair(1704067200000) },
1223 { kind: `update`, slot: 1, before: datePair(0), after: twin },
1224 { kind: `delete`, slot: 0, before: datePair(1), after: twin },
1225 ...([`insert`, `update`, `delete`] as const).map((kind): Edit => {
1226 const runtime = { __type: `Date`, value: `2024-01-01T00:00:00.000Z` }
1227 const pair = { runtime, wire: objectWire(runtime) }
1228 return { kind, slot: 0, before: pair, after: pair }
1229 }),
1230 ...([`insert`, `update`, `delete`] as const).map((kind): Edit => {
1231 const runtime = Object.fromEntries([[`__proto__`, { nested: 1 }]])
1232 const wire = Object.fromEntries([[`__proto__`, { nested: 1 }]])
1233 return {
1234 kind,
1235 slot: 0,
1236 before: { runtime, wire },
1237 after: { runtime, wire },
1239 }),
1241// This package's test root is separate from core's named replay portfolio.
1242// Keep a local replay entry point rather than importing files outside rootDir.
1243const {
1244 runs: numRuns,
1245 seed: replaySeed,
1246 path: replayPath,
1247} = readOfflineOracleConfig({
1248 prefix: `OFFLINE_ORACLE`,
1249 defaultRuns: 100,
1251it.each([20260914, undefined])(
1252 `preserves mutation wire meaning across restart (seed %s)`,
1253 async (seed) => {
1254 await fc.assert(
1255 fc.asyncProperty(
1256 fc.array(
1257 fc.record({
1258 kind: fc.constantFrom<Edit[`kind`]>(`insert`, `update`, `delete`),
1259 slot: fc.integer({ min: 0, max: 1 }),
1260 before: tree(2),
1261 after: tree(2),
1262 }),
1263 { maxLength: 6 },
1264 ),
1265 fc.integer({ min: -2000000000000, max: 2000000000000 }),
1266 (edits, time) => checkRoundtrip(edits, time),
1267 ),
1269 numRuns,
1270 seed: seed ?? replaySeed,
1271 ...(seed === undefined && replayPath !== undefined
1272 ? { path: replayPath }
1273 : {}),
1274 examples: [[pinned, 1704067200000]],
1275 },
1277 },
1279​
1280it.each([20260915, undefined])(
1281 `reads unversioned Date-marker records across restart (seed %s)`,
1282 async (seed) => {
1283 await fc.assert(
1284 fc.asyncProperty(
1285 fc.array(
1286 fc.record({
1287 kind: fc.constantFrom<Edit[`kind`]>(`insert`, `update`, `delete`),
1288 slot: fc.integer({ min: 0, max: 1 }),
1289 before: leaf,
1290 after: leaf,
1291 }),
1292 { minLength: 1, maxLength: 6 },
1293 ),
1294 async (edits) => {
1295 // Old records had no object escape. Use only unambiguous legacy trees,
1296 // but cross nested arrays, ordinary objects, Dates and date-like strings.
1297 const nest = (pair: Pair): Pair => ({
1298 runtime: { nested: [pair.runtime] },
1299 wire: { nested: [pair.wire] },
1300 })
1301 await checkRoundtrip(
1302 edits.map((edit) => ({
1303 ...edit,
1304 before: nest(edit.before),
1305 after: nest(edit.after),
1306 })),
1307 0,
1308 `none`,
1309 `encoder`,
1310 true,
1312 },
1313 ),
1315 seed: seed ?? replaySeed,
1316 numRuns,
1317 ...(seed === undefined && replayPath !== undefined
1318 ? { path: replayPath }
1319 : {}),
1320 examples: [
1321 [[{ kind: `update`, slot: 0, before: datePair(0), after: twin }]],
1322 ],
1323 },
1325 },
1327​
1328it.each([20260916, undefined])(
1329 `reads version-two escaped values across restart (seed %s)`,
1330 async (seed) => {
1331 await fc.assert(
1332 fc.asyncProperty(
1333 fc.array(
1334 fc.record({
1335 kind: fc.constantFrom<Edit[`kind`]>(`insert`, `update`, `delete`),
1336 slot: fc.integer({ min: 0, max: 1 }),
1337 before: tree(2),
1338 after: tree(2),
1339 }),
1340 { minLength: 1, maxLength: 6 },
1341 ),
1342 async (edits) =>
1343 checkRoundtrip(edits, 0, `none`, `encoder`, false, true),
1344 ),
1346 seed: seed ?? replaySeed,
1347 numRuns,
1348 ...(seed === undefined && replayPath !== undefined
1349 ? { path: replayPath }
1350 : {}),
1351 examples: [[pinned]],
1352 },
1354 },
1356​
1357it.each(
1360 `date-as-string`,
1361 `string-as-date`,
1362 `wrong-registry`,
1363 `omit-changes`,
1364 `unknown-encoding`,
1365 ] as const
1366 ).flatMap((fault) =>
1367 ([`encoder`, `decoder`] as const).map((boundary) => ({
1368 fault,
1369 boundary,
1370 })),
1371 ),
1373 `rejects the $fault $boundary mutant at its own boundary`,
1374 async ({ fault, boundary }) => {
1375 const decode = vi.spyOn(TransactionSerializer.prototype, `deserialize`)
1376 try {
1377 const expectedFailure =
1378 boundary === `encoder` ||
1379 (fault !== `wrong-registry` && fault !== `unknown-encoding`)
1380 ? { name: `AssertionError` }
1381 : {
1382 message:
1383 fault === `wrong-registry`
1384 ? `Collection with id writer:0 not found`
1385 : `Unsupported transaction value encoding: 4`,
1387 await expect(
1388 checkRoundtrip(pinned, 0, fault, boundary),
1389 ).rejects.toMatchObject(expectedFailure)
1390 expect(decode).toHaveBeenCalledTimes(boundary === `encoder` ? 0 : 1)
1391 } finally {
1392 decode.mockRestore()
1394 },