@powersync/service-module-mongodb-storage 0.24.2 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/migrations/db/migrations/1684951997326-init.js +3 -29
  3. package/dist/migrations/db/migrations/1684951997326-init.js.map +1 -1
  4. package/dist/migrations/db/migrations/1741697235857-bucket-state-index.js +3 -24
  5. package/dist/migrations/db/migrations/1741697235857-bucket-state-index.js.map +1 -1
  6. package/dist/migrations/db/migrations/1760433882550-bucket-state-index2.js +3 -24
  7. package/dist/migrations/db/migrations/1760433882550-bucket-state-index2.js.map +1 -1
  8. package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.d.ts +3 -0
  9. package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.js +21 -0
  10. package/dist/migrations/db/migrations/1794268800000-v1-storage-collections.js.map +1 -0
  11. package/dist/storage/MongoBucketStorage.d.ts +9 -0
  12. package/dist/storage/MongoBucketStorage.js +60 -30
  13. package/dist/storage/MongoBucketStorage.js.map +1 -1
  14. package/dist/storage/implementation/MongoBucketBatch.d.ts +21 -16
  15. package/dist/storage/implementation/MongoBucketBatch.js +22 -125
  16. package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
  17. package/dist/storage/implementation/MongoStorageProvider.js +1 -0
  18. package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
  19. package/dist/storage/implementation/MongoSyncBucketStorage.js +12 -5
  20. package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
  21. package/dist/storage/implementation/MongoSyncRulesLock.d.ts +9 -2
  22. package/dist/storage/implementation/MongoSyncRulesLock.js +12 -3
  23. package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
  24. package/dist/storage/implementation/OperationBatch.d.ts +10 -3
  25. package/dist/storage/implementation/OperationBatch.js +22 -13
  26. package/dist/storage/implementation/OperationBatch.js.map +1 -1
  27. package/dist/storage/implementation/ReplicationBatchLimits.d.ts +24 -0
  28. package/dist/storage/implementation/ReplicationBatchLimits.js +25 -0
  29. package/dist/storage/implementation/ReplicationBatchLimits.js.map +1 -0
  30. package/dist/storage/implementation/common/BatchOperationBuffer.d.ts +17 -1
  31. package/dist/storage/implementation/common/BatchOperationBuffer.js +22 -24
  32. package/dist/storage/implementation/common/BatchOperationBuffer.js.map +1 -1
  33. package/dist/storage/implementation/common/PersistedBatch.d.ts +2 -0
  34. package/dist/storage/implementation/common/PreparedPublication.d.ts +13 -9
  35. package/dist/storage/implementation/db.d.ts +2 -0
  36. package/dist/storage/implementation/db.js +14 -0
  37. package/dist/storage/implementation/db.js.map +1 -1
  38. package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +18 -1
  39. package/dist/storage/implementation/v1/MongoBucketBatchV1.js +99 -14
  40. package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
  41. package/dist/storage/implementation/v1/PersistedBatchV1.js +1 -1
  42. package/dist/storage/implementation/v1/PersistedBatchV1.js.map +1 -1
  43. package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.js +3 -1
  44. package/dist/storage/implementation/v1/VersionedPowerSyncMongoV1.js.map +1 -1
  45. package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +39 -3
  46. package/dist/storage/implementation/v3/MongoBucketBatchV3.js +356 -90
  47. package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
  48. package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +14 -5
  49. package/dist/storage/implementation/v3/PersistedBatchV3.js +26 -13
  50. package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
  51. package/dist/storage/implementation/v3/ReplicationPipelineV3.d.ts +84 -0
  52. package/dist/storage/implementation/v3/ReplicationPipelineV3.js +187 -0
  53. package/dist/storage/implementation/v3/ReplicationPipelineV3.js.map +1 -0
  54. package/dist/storage/implementation/v3/SourceRecordStoreV3.d.ts +4 -4
  55. package/dist/storage/implementation/v3/SourceRecordStoreV3.js +4 -4
  56. package/dist/storage/implementation/v3/chunking.js +7 -3
  57. package/dist/storage/implementation/v3/chunking.js.map +1 -1
  58. package/dist/types/types.d.ts +5 -0
  59. package/dist/types/types.js +4 -0
  60. package/dist/types/types.js.map +1 -1
  61. package/dist/utils/collection-sizes.d.ts +9 -0
  62. package/dist/utils/collection-sizes.js +95 -0
  63. package/dist/utils/collection-sizes.js.map +1 -0
  64. package/dist/utils/test-utils.js +1 -4
  65. package/dist/utils/test-utils.js.map +1 -1
  66. package/package.json +7 -7
  67. package/src/migrations/db/migrations/1684951997326-init.ts +3 -36
  68. package/src/migrations/db/migrations/1741697235857-bucket-state-index.ts +3 -31
  69. package/src/migrations/db/migrations/1760433882550-bucket-state-index2.ts +3 -31
  70. package/src/migrations/db/migrations/1794268800000-v1-storage-collections.ts +22 -0
  71. package/src/storage/MongoBucketStorage.ts +80 -31
  72. package/src/storage/implementation/MongoBucketBatch.ts +47 -137
  73. package/src/storage/implementation/MongoStorageProvider.ts +1 -0
  74. package/src/storage/implementation/MongoSyncBucketStorage.ts +13 -5
  75. package/src/storage/implementation/MongoSyncRulesLock.ts +13 -3
  76. package/src/storage/implementation/OperationBatch.ts +23 -15
  77. package/src/storage/implementation/ReplicationBatchLimits.ts +45 -0
  78. package/src/storage/implementation/common/BatchOperationBuffer.ts +21 -26
  79. package/src/storage/implementation/common/PersistedBatch.ts +2 -0
  80. package/src/storage/implementation/common/PreparedPublication.ts +13 -9
  81. package/src/storage/implementation/db.ts +15 -0
  82. package/src/storage/implementation/v1/MongoBucketBatchV1.ts +135 -17
  83. package/src/storage/implementation/v1/PersistedBatchV1.ts +2 -1
  84. package/src/storage/implementation/v1/VersionedPowerSyncMongoV1.ts +3 -1
  85. package/src/storage/implementation/v3/MongoBucketBatchV3.ts +433 -101
  86. package/src/storage/implementation/v3/PersistedBatchV3.ts +26 -13
  87. package/src/storage/implementation/v3/ReplicationPipelineV3.ts +220 -0
  88. package/src/storage/implementation/v3/SourceRecordStoreV3.ts +4 -4
  89. package/src/storage/implementation/v3/chunking.ts +8 -3
  90. package/src/types/types.ts +7 -0
  91. package/src/utils/collection-sizes.ts +114 -0
  92. package/src/utils/test-utils.ts +1 -5
  93. package/test/src/concurrent_writers.test.ts +9 -15
  94. package/test/src/operation_batch.test.ts +207 -0
  95. package/test/src/prepared_publication.test.ts +187 -6
  96. package/test/src/replication_batch_config.test.ts +117 -0
  97. package/test/src/replication_pipeline.test.ts +738 -0
  98. package/test/src/replication_pipeline_benchmark.test.ts +133 -0
  99. package/test/src/replication_preparation.test.ts +4 -2
  100. package/test/src/replication_uploads.test.ts +28 -3
  101. package/test/src/storage.test.ts +24 -5
  102. package/test/src/storage_compacting.test.ts +16 -0
  103. package/test/src/storage_metrics.test.ts +88 -0
  104. package/test/src/v1_collections.test.ts +233 -0
  105. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,207 @@
1
+ import { mongoTestStorageFactoryGenerator } from '@module/utils/test-utils.js';
2
+ import { mongo } from '@powersync/lib-service-mongodb';
3
+ import { storage, updateSyncRulesFromYaml } from '@powersync/service-core';
4
+ import { getTestStorage, test_utils } from '@powersync/service-core-tests';
5
+ import { describe, expect, test, vi } from 'vitest';
6
+ import { MongoSyncBucketStorage } from '../../src/storage/implementation/createMongoSyncBucketStorage.js';
7
+ import { OperationBatch } from '../../src/storage/implementation/OperationBatch.js';
8
+ import { DEFAULT_REPLICATION_BATCH_LIMITS } from '../../src/storage/implementation/ReplicationBatchLimits.js';
9
+ import { SourceRecordStoreV3 } from '../../src/storage/implementation/v3/SourceRecordStoreV3.js';
10
+ import { VersionedPowerSyncMongoV3 } from '../../src/storage/implementation/v3/VersionedPowerSyncMongoV3.js';
11
+ import { env } from './env.js';
12
+
13
+ const { maxInputBatchBytes: MAX_INPUT_BATCH_BYTES, maxInputBatchCount: MAX_INPUT_BATCH_COUNT } =
14
+ DEFAULT_REPLICATION_BATCH_LIMITS;
15
+
16
+ const CONFIG = /* yaml */ `
17
+ # Sync config fixture.
18
+ config:
19
+ edition: 3
20
+ streams:
21
+ items:
22
+ query: SELECT * FROM items
23
+ event_definitions:
24
+ write_checkpoints:
25
+ payloads:
26
+ - SELECT user_id, checkpoint FROM checkpoints
27
+ `;
28
+
29
+ async function open(storageVersion: number) {
30
+ const gen = mongoTestStorageFactoryGenerator({ url: env.MONGO_TEST_URL, isCI: env.CI });
31
+ const factory = await gen.factory();
32
+ const stream = await factory.updateSyncRules(updateSyncRulesFromYaml(CONFIG, { storageVersion }));
33
+ const buckets = (await getTestStorage(factory, stream)) as MongoSyncBucketStorage;
34
+ const observed: bigint[] = [];
35
+ // A repair-capable writer must still allow a checkpoint-only commit: there are no rows to repair.
36
+ const writer = await buckets.createWriter({
37
+ ...test_utils.BATCH_OPTIONS,
38
+ markRecordUnavailable: () => {},
39
+ hooks: {
40
+ afterBatchFlush: async () => {
41
+ const checkpoint = await checkpoints.findOne({ user_id: 'user-1' });
42
+ if (checkpoint != null) {
43
+ observed.push(checkpoint.checkpoint);
44
+ }
45
+ }
46
+ }
47
+ });
48
+ const table = await test_utils.resolveTestTable(writer, 'checkpoints', ['id'], gen, 1);
49
+ const eventId = table.eventDefinitionIds?.values().next().value;
50
+ const checkpoints =
51
+ storageVersion >= 3
52
+ ? (buckets.db as VersionedPowerSyncMongoV3).customCheckpointRequests({
53
+ replicationStreamId: stream.replicationStreamId,
54
+ eventId: eventId!
55
+ })
56
+ : factory.db.custom_write_checkpoints;
57
+ writer.registerListener({
58
+ replicationEvent: ({ batch, data, event_id }) => {
59
+ batch.addCustomWriteCheckpoint({
60
+ user_id: String(data.after!.user_id),
61
+ checkpoint: data.after!.checkpoint as bigint,
62
+ event_id
63
+ });
64
+ }
65
+ });
66
+ await writer.markAllSnapshotDone('1/1');
67
+ await writer.commit('1/1');
68
+ const save = (checkpoint: number) =>
69
+ writer.save({
70
+ sourceTable: table,
71
+ tag: storage.SaveOperationTag.INSERT,
72
+ afterReplicaId: String(checkpoint),
73
+ after: { id: String(checkpoint), user_id: 'user-1', checkpoint: BigInt(checkpoint) }
74
+ });
75
+ return { factory, stream, buckets, writer, table, checkpoints, observed, save };
76
+ }
77
+
78
+ test('checkpoint-only input is bounded by bytes and produces no row lookup blocks', () => {
79
+ const input = new OperationBatch();
80
+ input.addCustomWriteCheckpoint({ sync_rules_id: 1, user_id: 'x'.repeat(MAX_INPUT_BATCH_BYTES), checkpoint: 1n });
81
+ expect(input.hasData()).toBe(true);
82
+ expect(input.shouldFlush()).toBe(true);
83
+ expect([...input.batched(undefined)]).toEqual([]);
84
+ });
85
+
86
+ describe.each([1, 2, 3, 4])('input batch v%i', (storageVersion) => {
87
+ test('automatically flushes event-only checkpoints and commits the next checkpoint-only input', async () => {
88
+ const c = await open(storageVersion);
89
+ await using _factory = c.factory;
90
+ await using writer = c.writer;
91
+ expect(c.table.syncData).toBe(false);
92
+ expect(c.table.syncParameters).toBe(false);
93
+ expect(c.table.syncEvent).toBe(true);
94
+ for (let i = 1; i < MAX_INPUT_BATCH_COUNT; i++) {
95
+ await c.save(i);
96
+ }
97
+ expect(await c.checkpoints.findOne({ user_id: 'user-1' })).toBeNull();
98
+ await c.save(MAX_INPUT_BATCH_COUNT);
99
+ await writer.flush();
100
+ expect(await c.checkpoints.findOne({ user_id: 'user-1' })).toMatchObject({
101
+ checkpoint: BigInt(MAX_INPUT_BATCH_COUNT)
102
+ });
103
+ // The first input has detached. A new checkpoint must create and belong to a new input.
104
+ await c.save(MAX_INPUT_BATCH_COUNT + 1);
105
+ await writer.commit('1/2');
106
+ expect(await c.checkpoints.findOne({ user_id: 'user-1' })).toMatchObject({
107
+ checkpoint: BigInt(MAX_INPUT_BATCH_COUNT + 1)
108
+ });
109
+ expect((await c.buckets.getCheckpoint()).lsn).toBe('1/2');
110
+ });
111
+ });
112
+
113
+ describe.each([3, 4])('checkpoint input ownership v%i', (storageVersion) => {
114
+ test('metadata includes a checkpoint-only writer that has never called save', async () => {
115
+ const c = await open(storageVersion);
116
+ await using _factory = c.factory;
117
+ await using writer = c.writer;
118
+ await using other = await c.buckets.createWriter(test_utils.BATCH_OPTIONS);
119
+ const eventId = c.table.eventDefinitionIds!.values().next().value!;
120
+ other.addCustomWriteCheckpoint({ user_id: 'user-1', checkpoint: 5n, event_id: eventId });
121
+ expect(await c.checkpoints.findOne({ user_id: 'user-1' })).toBeNull();
122
+
123
+ // A metadata read must see a consistent state across every live writer, including
124
+ // input added directly without a preceding save() call.
125
+ await writer.getSourceTableStatus(c.table);
126
+ expect(await c.checkpoints.findOne({ user_id: 'user-1' })).toMatchObject({ checkpoint: 5n });
127
+ expect(c.stream.current_lock!.replicationPipeline!.pendingCount).toBe(0);
128
+ });
129
+
130
+ test('metadata captures checkpoints before queued publication, leaving later events in a fresh input', async () => {
131
+ const c = await open(storageVersion);
132
+ await using _factory = c.factory;
133
+ await using writer = c.writer;
134
+ await c.save(1);
135
+ const session = c.stream.current_lock!.replicationPipeline!.publicationSession;
136
+ const entered = Promise.withResolvers<void>();
137
+ const release = Promise.withResolvers<void>();
138
+ const transaction = session.withTransaction.bind(session);
139
+ using _transaction = vi.spyOn(session, 'withTransaction').mockImplementationOnce(async (...args) => {
140
+ entered.resolve();
141
+ await release.promise;
142
+ return transaction(...args);
143
+ });
144
+ const metadata = writer.getSourceTableStatus(c.table);
145
+ try {
146
+ await entered.promise;
147
+ await c.save(2);
148
+ } finally {
149
+ release.resolve();
150
+ await metadata;
151
+ }
152
+ expect(await c.checkpoints.findOne({ user_id: 'user-1' })).toMatchObject({ checkpoint: 1n });
153
+ await writer.commit('1/2');
154
+ expect(await c.checkpoints.findOne({ user_id: 'user-1' })).toMatchObject({ checkpoint: 2n });
155
+ expect(c.observed).toEqual([1n, 2n]);
156
+ });
157
+
158
+ test('keeps the admitted checkpoints stable through retry while the next input fills', async () => {
159
+ const c = await open(storageVersion);
160
+ await using _factory = c.factory;
161
+ await using writer = c.writer;
162
+ const pipeline = c.stream.current_lock!.replicationPipeline!;
163
+ const session = pipeline.publicationSession;
164
+ const entered = Promise.withResolvers<void>();
165
+ const release = Promise.withResolvers<void>();
166
+ const transaction = session.withTransaction.bind(session);
167
+ let attempts = 0;
168
+ using _transaction = vi.spyOn(session, 'withTransaction').mockImplementationOnce(async (callback, options) => {
169
+ entered.resolve();
170
+ await release.promise;
171
+ return transaction(async (activeSession) => {
172
+ const result = await callback(activeSession);
173
+ if (++attempts == 1) {
174
+ throw new mongo.MongoServerError({
175
+ message: 'retry checkpoint publication',
176
+ code: 112,
177
+ errorLabels: ['TransientTransactionError']
178
+ });
179
+ }
180
+ return result;
181
+ }, options);
182
+ });
183
+ using _reads = vi.spyOn(SourceRecordStoreV3.prototype, 'loadDocuments');
184
+ let flushing: Promise<unknown> | undefined;
185
+ try {
186
+ for (let i = 1; i <= MAX_INPUT_BATCH_COUNT; i++) {
187
+ await c.save(i);
188
+ }
189
+ await entered.promise;
190
+ await c.save(MAX_INPUT_BATCH_COUNT + 1);
191
+ expect(await c.checkpoints.findOne({ user_id: 'user-1' })).toBeNull();
192
+ // Start the barrier while the next input is already populated.
193
+ flushing = writer.flush();
194
+ } finally {
195
+ release.resolve();
196
+ await flushing;
197
+ }
198
+ expect(attempts).toBe(2);
199
+ expect(c.observed).toEqual([BigInt(MAX_INPUT_BATCH_COUNT), BigInt(MAX_INPUT_BATCH_COUNT + 1)]);
200
+ expect(await c.checkpoints.findOne({ user_id: 'user-1' })).toMatchObject({
201
+ checkpoint: BigInt(MAX_INPUT_BATCH_COUNT + 1)
202
+ });
203
+ expect(await c.checkpoints.countDocuments()).toBe(1);
204
+ expect(_reads).not.toHaveBeenCalled();
205
+ expect(pipeline.pendingCount).toBe(0);
206
+ });
207
+ });
@@ -6,9 +6,11 @@ import * as bson from 'bson';
6
6
  import { describe, expect, test, vi } from 'vitest';
7
7
  import { PreparedPublication } from '../../src/storage/implementation/common/PreparedPublication.js';
8
8
  import { MongoWriteBatch } from '../../src/storage/implementation/MongoWriteBatch.js';
9
+ import { OperationBatch } from '../../src/storage/implementation/OperationBatch.js';
9
10
  import { MongoSyncBucketStorageV3 } from '../../src/storage/implementation/v3/MongoSyncBucketStorageV3.js';
10
11
  import { ObjectStorageUsage } from '../../src/storage/implementation/v3/object-storage/ObjectStorageUsage.js';
11
12
  import { PersistedBatchV3 } from '../../src/storage/implementation/v3/PersistedBatchV3.js';
13
+ import { SourceRecordStoreV3 } from '../../src/storage/implementation/v3/SourceRecordStoreV3.js';
12
14
  import { env } from './env.js';
13
15
  import { MemoryObjectStorage } from './helpers/MemoryObjectStorage.js';
14
16
 
@@ -73,8 +75,8 @@ describe.each([3, 4])('sealed publication v%s', (storageVersion) => {
73
75
  ) {
74
76
  builder = this;
75
77
  publication = this;
76
- const ready = publication.preparePayloads();
77
- expect(this.preparePayloads()).toBe(ready);
78
+ const ready = publication.packAndUploadPayloads();
79
+ expect(this.packAndUploadPayloads()).toBe(ready);
78
80
  await ready;
79
81
  await originalPublish.apply(this, args);
80
82
  throw aborted;
@@ -135,7 +137,7 @@ describe.each([3, 4])('sealed publication v%s', (storageVersion) => {
135
137
  expect(() => builder!.hardDeleteCurrentData(table.id as bson.ObjectId, test_utils.rid('C'))).toThrow('sealed');
136
138
  await db.client.withSession(async (session) => {
137
139
  let attempts = 0;
138
- await publication!.preparePayloads();
140
+ await publication!.packAndUploadPayloads();
139
141
  await session.withTransaction(async () => {
140
142
  expect(await publication!.publish(session)).toEqual({
141
143
  bucketDataCount: 6,
@@ -303,7 +305,7 @@ streams:
303
305
  expect(indexId).toBeDefined();
304
306
  const parameters = db.parameterIndex(streamId, indexId);
305
307
  expect(await parameters.countDocuments()).toBe(0);
306
- await publication!.preparePayloads();
308
+ await publication!.packAndUploadPayloads();
307
309
  await db.client.withSession(async (session) => {
308
310
  await session.withTransaction(() => publication!.publish(session));
309
311
  });
@@ -325,6 +327,185 @@ streams:
325
327
  }
326
328
  );
327
329
 
330
+ test('finishes preparation before packing and uploads in the publishing stage', async () => {
331
+ const objectStorage = new MemoryObjectStorage();
332
+ const context = await openStream(storageVersion, objectStorage);
333
+ await using _factory = context.factory;
334
+ await using writer = context.writer;
335
+ // Force small read blocks without changing production input/batch targets.
336
+ using _blocks = vi.spyOn(OperationBatch.prototype, 'batched').mockImplementation(function* (this: OperationBatch) {
337
+ for (const op of this.batch) {
338
+ yield [op];
339
+ }
340
+ });
341
+ using reads = vi.spyOn(SourceRecordStoreV3.prototype, 'loadDocuments');
342
+ using publish = vi.spyOn(PersistedBatchV3.prototype, 'publish');
343
+ const groupSizes: { transaction: number; retained: number }[] = [];
344
+ const seal = PersistedBatchV3.prototype.seal;
345
+ using _seal = vi.spyOn(PersistedBatchV3.prototype, 'seal').mockImplementation(function (this: PersistedBatchV3) {
346
+ groupSizes.push({ transaction: this.currentSize, retained: this.estimatedRetainedBytes });
347
+ return seal.call(this);
348
+ });
349
+ const started = Array.from({ length: 3 }, () => Promise.withResolvers<void>());
350
+ const release = Array.from({ length: 3 }, () => Promise.withResolvers<void>());
351
+ const put = objectStorage.put.bind(objectStorage);
352
+ let uploads = 0;
353
+ using _put = vi.spyOn(objectStorage, 'put').mockImplementation(async (...args) => {
354
+ const index = uploads++;
355
+ started[index].resolve();
356
+ await release[index].promise;
357
+ return put(...args);
358
+ });
359
+ for (const id of ['A', 'B', 'C']) {
360
+ await writer.save({
361
+ sourceTable: context.table,
362
+ tag: storage.SaveOperationTag.INSERT,
363
+ after: { id, description: id },
364
+ afterReplicaId: test_utils.rid(id)
365
+ });
366
+ }
367
+ const commit = writer.commit('1/2');
368
+ try {
369
+ await started[0].promise;
370
+ expect(reads).toHaveBeenCalledTimes(3);
371
+ expect(uploads).toBe(1);
372
+ expect(publish).not.toHaveBeenCalled();
373
+ expect(writer.last_flushed_op).toBeNull();
374
+ release[0].resolve();
375
+ await started[1].promise;
376
+ expect(uploads).toBe(2);
377
+ expect(publish).not.toHaveBeenCalled();
378
+ } finally {
379
+ for (const gate of release) {
380
+ gate.resolve();
381
+ }
382
+ await commit;
383
+ }
384
+ expect(publish).toHaveBeenCalledTimes(3);
385
+ expect(uploads).toBe(3);
386
+ // Equal-size rows in separate read groups retain equal work. Transaction
387
+ // sizing still accumulates, but must not be charged repeatedly to memory.
388
+ expect(groupSizes).toHaveLength(3);
389
+ expect(groupSizes[2].transaction).toBeGreaterThan(groupSizes[0].transaction);
390
+ expect(groupSizes[0].retained).toBeGreaterThan(0);
391
+ expect(groupSizes.map((group) => group.retained)).toEqual(Array(3).fill(groupSizes[0].retained));
392
+ expect(await context.bucketStorage.getCheckpoint()).toMatchObject({ checkpoint: 3n, lsn: '1/2' });
393
+ const definitionId = context.stream.syncConfigContent[0].mapping.allBucketDefinitionIds()[0];
394
+ const documents = await context.bucketStorage.db
395
+ .bucketData(context.stream.replicationStreamId, definitionId)
396
+ .find({})
397
+ .sort({ first_op: 1 })
398
+ .toArray();
399
+ expect(documents).toHaveLength(3);
400
+ expect(
401
+ documents
402
+ .map(
403
+ (doc) =>
404
+ bson.deserialize(
405
+ objectStorage.store.get(doc.storage_ref!.path)!.data,
406
+ storage.BSON_DESERIALIZE_INTERNAL_OPTIONS
407
+ ).ops[0].row_id
408
+ )
409
+ .sort()
410
+ ).toEqual(['A', 'B', 'C']);
411
+ });
412
+
413
+ test('retains partial-row state across eagerly prepared groups', async () => {
414
+ const objectStorage = new MemoryObjectStorage();
415
+ const context = await openStream(storageVersion, objectStorage);
416
+ await using _factory = context.factory;
417
+ await using writer = context.writer;
418
+ using _blocks = vi.spyOn(OperationBatch.prototype, 'batched').mockImplementation(function* (this: OperationBatch) {
419
+ for (const op of this.batch) {
420
+ yield [op];
421
+ }
422
+ });
423
+ for (const after of [
424
+ { id: 'A', description: 'first' },
425
+ { id: undefined, description: 'second' }
426
+ ]) {
427
+ await writer.save({
428
+ sourceTable: context.table,
429
+ tag: storage.SaveOperationTag.UPDATE,
430
+ after,
431
+ afterReplicaId: test_utils.rid('A')
432
+ });
433
+ }
434
+ await writer.commit('1/2');
435
+ const { db } = context.bucketStorage;
436
+ const streamId = context.stream.replicationStreamId;
437
+ const records = await db
438
+ .sourceRecords(streamId, context.table.id as bson.ObjectId)
439
+ .find({})
440
+ .toArray();
441
+ expect(records).toHaveLength(1);
442
+ expect(bson.deserialize(records[0].data!.buffer)).toEqual({ id: 'A', description: 'second' });
443
+ expect(records[0].buckets).toHaveLength(1);
444
+ const definitionId = context.stream.syncConfigContent[0].mapping.allBucketDefinitionIds()[0];
445
+ const documents = await db.bucketData(streamId, definitionId).find({}).toArray();
446
+ const operations = documents
447
+ .flatMap(
448
+ (doc) =>
449
+ bson.deserialize(
450
+ objectStorage.store.get(doc.storage_ref!.path)!.data,
451
+ storage.BSON_DESERIALIZE_INTERNAL_OPTIONS
452
+ ).ops
453
+ )
454
+ .sort((a, b) => Number(a.o - b.o));
455
+ expect(operations).toMatchObject([
456
+ { o: 1n, op: 'PUT', row_id: 'A', data: '{"id":"A","description":"first"}' },
457
+ { o: 2n, op: 'PUT', row_id: 'A', data: '{"id":"A","description":"second"}' }
458
+ ]);
459
+ expect(await context.bucketStorage.getCheckpoint()).toMatchObject({ checkpoint: 2n, lsn: '1/2' });
460
+ });
461
+
462
+ test.each(['read', 'upload'])('does not publish after a %s failure', async (stage) => {
463
+ const objectStorage = new MemoryObjectStorage();
464
+ const context = await openStream(storageVersion, objectStorage);
465
+ await using _factory = context.factory;
466
+ await using writer = context.writer;
467
+ using _blocks = vi.spyOn(OperationBatch.prototype, 'batched').mockImplementation(function* (this: OperationBatch) {
468
+ for (const op of this.batch) yield [op];
469
+ });
470
+ const failure = new Error('failed ' + stage);
471
+ const load = SourceRecordStoreV3.prototype.loadDocuments;
472
+ let reads = 0;
473
+ using _read = vi.spyOn(SourceRecordStoreV3.prototype, 'loadDocuments').mockImplementation(async function (
474
+ this: SourceRecordStoreV3,
475
+ ...args
476
+ ) {
477
+ if (++reads === 2 && stage === 'read') throw failure;
478
+ return load.apply(this, args);
479
+ });
480
+ const put = objectStorage.put.bind(objectStorage);
481
+ let uploads = 0;
482
+ using _put = vi.spyOn(objectStorage, 'put').mockImplementation(async (...args) => {
483
+ if (++uploads === 2 && stage === 'upload') throw failure;
484
+ return put(...args);
485
+ });
486
+ using publish = vi.spyOn(PersistedBatchV3.prototype, 'publish');
487
+ for (const id of ['A', 'B']) {
488
+ await writer.save({
489
+ sourceTable: context.table,
490
+ tag: storage.SaveOperationTag.INSERT,
491
+ after: { id },
492
+ afterReplicaId: test_utils.rid(id)
493
+ });
494
+ }
495
+ await expect(writer.commit('1/2')).rejects.toThrow(failure);
496
+ expect(writer.last_flushed_op).toBeNull();
497
+ expect((await context.bucketStorage.getCheckpoint()).checkpoint).toBe(0n);
498
+ expect(publish).not.toHaveBeenCalled();
499
+ // Read failure starts no uploads. A successful PUT preceding upload failure
500
+ // remains protected as an orphan, with no published references or progress.
501
+ expect(uploads).toBe(stage === 'read' ? 0 : 2);
502
+ expect(
503
+ await context.bucketStorage.db
504
+ .pendingObjectStorageDeletes(context.stream.replicationStreamId)
505
+ .countDocuments({ path: { $in: [...objectStorage.store.keys()] } })
506
+ ).toBe(stage === 'read' ? 0 : 1);
507
+ });
508
+
328
509
  test.each([false, true])('joins sibling uploads before rejecting readiness (cancellation: %s)', async (cancelled) => {
329
510
  const objectStorage = new MemoryObjectStorage();
330
511
  const context = await openStream(storageVersion, objectStorage);
@@ -366,7 +547,7 @@ streams:
366
547
  const rejected = expect(commit).rejects.toThrow(failure);
367
548
  await siblingStarted.promise;
368
549
  let readySettled = false;
369
- const readiness = publication!.preparePayloads().then(
550
+ const readiness = publication!.packAndUploadPayloads().then(
370
551
  () => {
371
552
  readySettled = true;
372
553
  },
@@ -381,7 +562,7 @@ streams:
381
562
  await readiness;
382
563
  expect(siblingFinished).toBe(true);
383
564
  expect(uploadSpy).toHaveBeenCalledTimes(2);
384
- await expect(publication!.preparePayloads()).rejects.toThrow(failure);
565
+ await expect(publication!.packAndUploadPayloads()).rejects.toThrow(failure);
385
566
  expect(uploadSpy).toHaveBeenCalledTimes(2);
386
567
  expect((await context.bucketStorage.getCheckpoint()).checkpoint).toBe(0n);
387
568
  });
@@ -0,0 +1,117 @@
1
+ import { MongoReplicationBatchSize, MongoStorageConfig } from '@module/types/types.js';
2
+ import { mongoTestStorageFactoryGenerator } from '@module/utils/test-utils.js';
3
+ import { storage, updateSyncRulesFromYaml } from '@powersync/service-core';
4
+ import { getTestStorage, test_utils } from '@powersync/service-core-tests';
5
+ import { describe, expect, test, vi } from 'vitest';
6
+ import { BatchOperationBuffer } from '../../src/storage/implementation/common/BatchOperationBuffer.js';
7
+ import { OperationBatch } from '../../src/storage/implementation/OperationBatch.js';
8
+ import {
9
+ DEFAULT_REPLICATION_BATCH_LIMITS,
10
+ REPLICATION_BATCH_LIMITS
11
+ } from '../../src/storage/implementation/ReplicationBatchLimits.js';
12
+ import { env } from './env.js';
13
+
14
+ const STORAGE_CONFIG = { type: 'mongodb', uri: 'mongodb://localhost:27017/powersync' } as const;
15
+ const PROFILES = ['small', 'medium', 'large'] as const;
16
+ const CONFIG = /* yaml */ `
17
+ # Sync config fixture.
18
+ config:
19
+ edition: 3
20
+ streams:
21
+ items:
22
+ query: SELECT * FROM items
23
+ `;
24
+
25
+ describe('replication batch configuration', () => {
26
+ test.each(PROFILES)('decodes %s', (profile) => {
27
+ const config = MongoStorageConfig.decode({ ...STORAGE_CONFIG, replication_batch_size: profile });
28
+ expect(config.replication_batch_size).toBe(profile);
29
+ });
30
+
31
+ test.each(['huge', '', 1, null])('rejects invalid profile %j', (profile) => {
32
+ expect(() =>
33
+ MongoStorageConfig.decode({ ...STORAGE_CONFIG, replication_batch_size: profile as MongoReplicationBatchSize })
34
+ ).toThrow();
35
+ });
36
+
37
+ test('defaults to medium and preserves the previous limits as large', () => {
38
+ expect(MongoStorageConfig.decode(STORAGE_CONFIG).replication_batch_size).toBeUndefined();
39
+ expect(DEFAULT_REPLICATION_BATCH_LIMITS).toBe(REPLICATION_BATCH_LIMITS.medium);
40
+ expect(REPLICATION_BATCH_LIMITS.large).toEqual({
41
+ maxInputBatchCount: 16_000,
42
+ maxInputBatchBytes: 8 * 1024 * 1024,
43
+ maxTransactionBatchCount: 16_000,
44
+ maxTransactionBatchBytes: 16 * 1024 * 1024,
45
+ maxPipelineBytes: 128 * 1024 * 1024
46
+ });
47
+ });
48
+
49
+ test.each(PROFILES)('%s uses its own input and transaction byte targets', (profile) => {
50
+ const limits = REPLICATION_BATCH_LIMITS[profile];
51
+ const input = new OperationBatch(limits);
52
+ input.currentSize = limits.maxInputBatchBytes;
53
+ expect(input.shouldFlush()).toBe(false);
54
+ input.currentSize++;
55
+ expect(input.shouldFlush()).toBe(true);
56
+
57
+ const writes = new BatchOperationBuffer(
58
+ 1,
59
+ limits.maxTransactionBatchBytes - 1,
60
+ { checkDefinitionId: (id) => id!, getBucketDefinitionId: () => '' },
61
+ undefined,
62
+ limits
63
+ );
64
+ expect(writes.shouldFlushTransaction(limits.maxTransactionBatchCount - 1)).toBe(false);
65
+ expect(writes.shouldFlushTransaction(limits.maxTransactionBatchCount)).toBe(true);
66
+ writes.currentSize++;
67
+ expect(writes.shouldFlushTransaction(0)).toBe(true);
68
+ });
69
+ });
70
+
71
+ describe.each([1, 4])('replication batch configuration v%s', (storageVersion) => {
72
+ test.each<MongoReplicationBatchSize | undefined>([undefined, ...PROFILES])(
73
+ 'automatically flushes at the configured row count (%s)',
74
+ async (profile) => {
75
+ const gen = mongoTestStorageFactoryGenerator({
76
+ url: env.MONGO_TEST_URL,
77
+ isCI: env.CI,
78
+ replicationBatchSize: profile
79
+ });
80
+ await using factory = await gen.factory();
81
+ const limits = REPLICATION_BATCH_LIMITS[profile ?? 'medium'];
82
+ expect(factory.replicationBatchLimits).toBe(limits);
83
+ const stream = await factory.updateSyncRules(updateSyncRulesFromYaml(CONFIG, { storageVersion }));
84
+ const buckets = await getTestStorage(factory, stream);
85
+ const beforeBatchFlush = vi.fn();
86
+ await using writer = await buckets.createWriter({
87
+ ...test_utils.BATCH_OPTIONS,
88
+ hooks: { beforeBatchFlush }
89
+ });
90
+ const table = await test_utils.resolveTestTable(writer, 'items', ['id'], gen, 1);
91
+ await writer.markAllSnapshotDone('1/1');
92
+ beforeBatchFlush.mockClear();
93
+
94
+ // Observe the real transaction splitting decision as well as the input flush.
95
+ using transaction = vi.spyOn(BatchOperationBuffer.prototype, 'shouldFlushTransaction');
96
+ const save = (id: number) =>
97
+ writer.save({
98
+ sourceTable: table,
99
+ tag: storage.SaveOperationTag.INSERT,
100
+ afterReplicaId: String(id),
101
+ after: { id: String(id) }
102
+ });
103
+ for (let i = 1; i < limits.maxInputBatchCount; i++) {
104
+ await save(i);
105
+ }
106
+ expect(beforeBatchFlush).not.toHaveBeenCalled();
107
+ await save(limits.maxInputBatchCount);
108
+ expect(beforeBatchFlush).toHaveBeenCalled();
109
+ expect(transaction.mock.results.some((result) => result.type === 'return' && result.value === true)).toBe(true);
110
+ await writer.commit('1/2');
111
+ expect(await buckets.getCheckpoint()).toMatchObject({
112
+ lsn: '1/2',
113
+ checkpoint: BigInt(limits.maxInputBatchCount)
114
+ });
115
+ }
116
+ );
117
+ });