@powersync/service-module-mongodb-storage 0.25.0 → 0.26.1

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 (96) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/storage/MongoBucketStorage.d.ts +6 -0
  3. package/dist/storage/MongoBucketStorage.js +8 -29
  4. package/dist/storage/MongoBucketStorage.js.map +1 -1
  5. package/dist/storage/implementation/MongoBucketBatch.d.ts +24 -18
  6. package/dist/storage/implementation/MongoBucketBatch.js +25 -127
  7. package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
  8. package/dist/storage/implementation/MongoStorageProvider.js +1 -0
  9. package/dist/storage/implementation/MongoStorageProvider.js.map +1 -1
  10. package/dist/storage/implementation/MongoSyncBucketStorage.js +1 -0
  11. package/dist/storage/implementation/MongoSyncBucketStorage.js.map +1 -1
  12. package/dist/storage/implementation/MongoSyncRulesLock.d.ts +9 -2
  13. package/dist/storage/implementation/MongoSyncRulesLock.js +17 -4
  14. package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
  15. package/dist/storage/implementation/OperationBatch.d.ts +10 -3
  16. package/dist/storage/implementation/OperationBatch.js +22 -13
  17. package/dist/storage/implementation/OperationBatch.js.map +1 -1
  18. package/dist/storage/implementation/ReplicationBatchLimits.d.ts +24 -0
  19. package/dist/storage/implementation/ReplicationBatchLimits.js +25 -0
  20. package/dist/storage/implementation/ReplicationBatchLimits.js.map +1 -0
  21. package/dist/storage/implementation/common/BatchOperationBuffer.d.ts +17 -1
  22. package/dist/storage/implementation/common/BatchOperationBuffer.js +22 -24
  23. package/dist/storage/implementation/common/BatchOperationBuffer.js.map +1 -1
  24. package/dist/storage/implementation/common/PersistedBatch.d.ts +2 -0
  25. package/dist/storage/implementation/common/PreparedPublication.d.ts +17 -9
  26. package/dist/storage/implementation/v1/MongoBucketBatchV1.d.ts +18 -1
  27. package/dist/storage/implementation/v1/MongoBucketBatchV1.js +99 -14
  28. package/dist/storage/implementation/v1/MongoBucketBatchV1.js.map +1 -1
  29. package/dist/storage/implementation/v1/PersistedBatchV1.js +1 -1
  30. package/dist/storage/implementation/v1/PersistedBatchV1.js.map +1 -1
  31. package/dist/storage/implementation/v3/CompactionLease.d.ts +17 -4
  32. package/dist/storage/implementation/v3/CompactionLease.js +76 -13
  33. package/dist/storage/implementation/v3/CompactionLease.js.map +1 -1
  34. package/dist/storage/implementation/v3/MongoBucketBatchV3.d.ts +39 -3
  35. package/dist/storage/implementation/v3/MongoBucketBatchV3.js +374 -95
  36. package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
  37. package/dist/storage/implementation/v3/MongoCompactorV3.d.ts +5 -3
  38. package/dist/storage/implementation/v3/MongoCompactorV3.js +169 -82
  39. package/dist/storage/implementation/v3/MongoCompactorV3.js.map +1 -1
  40. package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +15 -6
  41. package/dist/storage/implementation/v3/PersistedBatchV3.js +29 -16
  42. package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
  43. package/dist/storage/implementation/v3/ReplicationPipelineV3.d.ts +84 -0
  44. package/dist/storage/implementation/v3/ReplicationPipelineV3.js +187 -0
  45. package/dist/storage/implementation/v3/ReplicationPipelineV3.js.map +1 -0
  46. package/dist/storage/implementation/v3/SourceRecordStoreV3.d.ts +4 -4
  47. package/dist/storage/implementation/v3/SourceRecordStoreV3.js +4 -4
  48. package/dist/storage/implementation/v3/chunking.js +7 -3
  49. package/dist/storage/implementation/v3/chunking.js.map +1 -1
  50. package/dist/types/types.d.ts +5 -0
  51. package/dist/types/types.js +4 -0
  52. package/dist/types/types.js.map +1 -1
  53. package/dist/utils/collection-sizes.d.ts +9 -0
  54. package/dist/utils/collection-sizes.js +95 -0
  55. package/dist/utils/collection-sizes.js.map +1 -0
  56. package/dist/utils/test-utils.js +1 -0
  57. package/dist/utils/test-utils.js.map +1 -1
  58. package/package.json +7 -7
  59. package/src/storage/MongoBucketStorage.ts +19 -30
  60. package/src/storage/implementation/MongoBucketBatch.ts +50 -139
  61. package/src/storage/implementation/MongoStorageProvider.ts +1 -0
  62. package/src/storage/implementation/MongoSyncBucketStorage.ts +1 -0
  63. package/src/storage/implementation/MongoSyncRulesLock.ts +18 -4
  64. package/src/storage/implementation/OperationBatch.ts +23 -15
  65. package/src/storage/implementation/ReplicationBatchLimits.ts +45 -0
  66. package/src/storage/implementation/common/BatchOperationBuffer.ts +21 -26
  67. package/src/storage/implementation/common/PersistedBatch.ts +2 -0
  68. package/src/storage/implementation/common/PreparedPublication.ts +17 -9
  69. package/src/storage/implementation/v1/MongoBucketBatchV1.ts +135 -17
  70. package/src/storage/implementation/v1/PersistedBatchV1.ts +2 -1
  71. package/src/storage/implementation/v3/CompactionLease.ts +91 -15
  72. package/src/storage/implementation/v3/MongoBucketBatchV3.ts +455 -107
  73. package/src/storage/implementation/v3/MongoCompactorV3.ts +217 -127
  74. package/src/storage/implementation/v3/PersistedBatchV3.ts +30 -17
  75. package/src/storage/implementation/v3/ReplicationPipelineV3.ts +220 -0
  76. package/src/storage/implementation/v3/SourceRecordStoreV3.ts +4 -4
  77. package/src/storage/implementation/v3/chunking.ts +8 -3
  78. package/src/types/types.ts +7 -0
  79. package/src/utils/collection-sizes.ts +114 -0
  80. package/src/utils/test-utils.ts +1 -0
  81. package/test/src/concurrent_writers.test.ts +22 -15
  82. package/test/src/helpers/PublicationCommandMonitor.ts +18 -3
  83. package/test/src/operation_batch.test.ts +207 -0
  84. package/test/src/prepared_publication.test.ts +210 -7
  85. package/test/src/replication_batch_config.test.ts +117 -0
  86. package/test/src/replication_pipeline.test.ts +738 -0
  87. package/test/src/replication_pipeline_benchmark.test.ts +133 -0
  88. package/test/src/replication_preparation.test.ts +4 -2
  89. package/test/src/replication_publication_baseline.test.ts +26 -16
  90. package/test/src/replication_publication_batching.test.ts +6 -2
  91. package/test/src/replication_uploads.test.ts +28 -3
  92. package/test/src/storage.test.ts +24 -5
  93. package/test/src/storage_compacting.test.ts +269 -47
  94. package/test/src/storage_metrics.test.ts +88 -0
  95. package/tsconfig.json +1 -0
  96. 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,8 +137,11 @@ 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 () => {
142
+ const states = db.createWriteBatch(session, { ordered: true });
143
+ publication!.queueBucketStates(states);
144
+ await states.execute();
140
145
  expect(await publication!.publish(session)).toEqual({
141
146
  bucketDataCount: 6,
142
147
  parameterDataCount: 0,
@@ -303,9 +308,14 @@ streams:
303
308
  expect(indexId).toBeDefined();
304
309
  const parameters = db.parameterIndex(streamId, indexId);
305
310
  expect(await parameters.countDocuments()).toBe(0);
306
- await publication!.preparePayloads();
311
+ await publication!.packAndUploadPayloads();
307
312
  await db.client.withSession(async (session) => {
308
- await session.withTransaction(() => publication!.publish(session));
313
+ await session.withTransaction(async () => {
314
+ const states = db.createWriteBatch(session, { ordered: true });
315
+ publication!.queueBucketStates(states);
316
+ await states.execute();
317
+ await publication!.publish(session);
318
+ });
309
319
  });
310
320
  const documents = await parameters.find({}).sort({ _id: 1 }).toArray();
311
321
  expect(documents.map((doc) => doc._id)).toEqual([1n, 2n, 3n]);
@@ -325,6 +335,199 @@ streams:
325
335
  }
326
336
  );
327
337
 
338
+ test('finishes preparation before packing and uploads in the publishing stage', async () => {
339
+ const objectStorage = new MemoryObjectStorage();
340
+ const context = await openStream(storageVersion, objectStorage);
341
+ await using _factory = context.factory;
342
+ await using writer = context.writer;
343
+ // Force small read blocks without changing production input/batch targets.
344
+ using _blocks = vi.spyOn(OperationBatch.prototype, 'batched').mockImplementation(function* (this: OperationBatch) {
345
+ for (const op of this.batch) {
346
+ yield [op];
347
+ }
348
+ });
349
+ using reads = vi.spyOn(SourceRecordStoreV3.prototype, 'loadDocuments');
350
+ using publish = vi.spyOn(PersistedBatchV3.prototype, 'publish');
351
+ const groupSizes: { transaction: number; retained: number }[] = [];
352
+ const seal = PersistedBatchV3.prototype.seal;
353
+ using _seal = vi.spyOn(PersistedBatchV3.prototype, 'seal').mockImplementation(function (this: PersistedBatchV3) {
354
+ groupSizes.push({ transaction: this.currentSize, retained: this.estimatedRetainedBytes });
355
+ return seal.call(this);
356
+ });
357
+ const started = Array.from({ length: 3 }, () => Promise.withResolvers<void>());
358
+ const release = Array.from({ length: 3 }, () => Promise.withResolvers<void>());
359
+ const put = objectStorage.put.bind(objectStorage);
360
+ let uploads = 0;
361
+ using _put = vi.spyOn(objectStorage, 'put').mockImplementation(async (...args) => {
362
+ const index = uploads++;
363
+ started[index].resolve();
364
+ await release[index].promise;
365
+ return put(...args);
366
+ });
367
+ for (const id of ['A', 'B', 'C']) {
368
+ await writer.save({
369
+ sourceTable: context.table,
370
+ tag: storage.SaveOperationTag.INSERT,
371
+ after: { id, description: id },
372
+ afterReplicaId: test_utils.rid(id)
373
+ });
374
+ }
375
+ const commit = writer.commit('1/2');
376
+ try {
377
+ await started[0].promise;
378
+ expect(reads).toHaveBeenCalledTimes(3);
379
+ expect(uploads).toBe(1);
380
+ expect(publish).not.toHaveBeenCalled();
381
+ expect(writer.last_flushed_op).toBeNull();
382
+ release[0].resolve();
383
+ await started[1].promise;
384
+ expect(uploads).toBe(2);
385
+ expect(publish).not.toHaveBeenCalled();
386
+ } finally {
387
+ for (const gate of release) {
388
+ gate.resolve();
389
+ }
390
+ await commit;
391
+ }
392
+ expect(publish).toHaveBeenCalledTimes(3);
393
+ expect(uploads).toBe(3);
394
+ // Equal-size rows in separate read groups retain equal work. Transaction
395
+ // sizing still accumulates, but must not be charged repeatedly to memory.
396
+ expect(groupSizes).toHaveLength(3);
397
+ expect(groupSizes[2].transaction).toBeGreaterThan(groupSizes[0].transaction);
398
+ expect(groupSizes[0].retained).toBeGreaterThan(0);
399
+ expect(groupSizes.map((group) => group.retained)).toEqual(Array(3).fill(groupSizes[0].retained));
400
+ expect(await context.bucketStorage.getCheckpoint()).toMatchObject({ checkpoint: 3n, lsn: '1/2' });
401
+ const definitionId = context.stream.syncConfigContent[0].mapping.allBucketDefinitionIds()[0];
402
+ const documents = await context.bucketStorage.db
403
+ .bucketData(context.stream.replicationStreamId, definitionId)
404
+ .find({})
405
+ .sort({ first_op: 1 })
406
+ .toArray();
407
+ expect(documents).toHaveLength(3);
408
+ expect(
409
+ documents
410
+ .map(
411
+ (doc) =>
412
+ bson.deserialize(
413
+ objectStorage.store.get(doc.storage_ref!.path)!.data,
414
+ storage.BSON_DESERIALIZE_INTERNAL_OPTIONS
415
+ ).ops[0].row_id
416
+ )
417
+ .sort()
418
+ ).toEqual(['A', 'B', 'C']);
419
+ });
420
+
421
+ test('retains partial-row state across eagerly prepared groups', async () => {
422
+ const objectStorage = new MemoryObjectStorage();
423
+ const context = await openStream(storageVersion, objectStorage);
424
+ await using _factory = context.factory;
425
+ await using writer = context.writer;
426
+ using _blocks = vi.spyOn(OperationBatch.prototype, 'batched').mockImplementation(function* (this: OperationBatch) {
427
+ for (const op of this.batch) {
428
+ yield [op];
429
+ }
430
+ });
431
+ // Both read groups touch the same bucket. Its final delta must already
432
+ // be visible inside the transaction before the first payload write.
433
+ const publish = PersistedBatchV3.prototype.publish;
434
+ using _publish = vi.spyOn(PersistedBatchV3.prototype, 'publish').mockImplementationOnce(async function (
435
+ this: PersistedBatchV3,
436
+ ...args
437
+ ) {
438
+ const states = context.bucketStorage.db.bucketState(context.stream.replicationStreamId);
439
+ expect(await states.findOne({}, { session: args[0] })).toMatchObject({
440
+ last_op: 2n,
441
+ bucket_stats: { count: 2, chunks: 2 }
442
+ });
443
+ return publish.apply(this, args);
444
+ });
445
+ for (const after of [
446
+ { id: 'A', description: 'first' },
447
+ { id: undefined, description: 'second' }
448
+ ]) {
449
+ await writer.save({
450
+ sourceTable: context.table,
451
+ tag: storage.SaveOperationTag.UPDATE,
452
+ after,
453
+ afterReplicaId: test_utils.rid('A')
454
+ });
455
+ }
456
+ await writer.commit('1/2');
457
+ const { db } = context.bucketStorage;
458
+ const streamId = context.stream.replicationStreamId;
459
+ const records = await db
460
+ .sourceRecords(streamId, context.table.id as bson.ObjectId)
461
+ .find({})
462
+ .toArray();
463
+ expect(records).toHaveLength(1);
464
+ expect(bson.deserialize(records[0].data!.buffer)).toEqual({ id: 'A', description: 'second' });
465
+ expect(records[0].buckets).toHaveLength(1);
466
+ const definitionId = context.stream.syncConfigContent[0].mapping.allBucketDefinitionIds()[0];
467
+ const documents = await db.bucketData(streamId, definitionId).find({}).toArray();
468
+ const operations = documents
469
+ .flatMap(
470
+ (doc) =>
471
+ bson.deserialize(
472
+ objectStorage.store.get(doc.storage_ref!.path)!.data,
473
+ storage.BSON_DESERIALIZE_INTERNAL_OPTIONS
474
+ ).ops
475
+ )
476
+ .sort((a, b) => Number(a.o - b.o));
477
+ expect(operations).toMatchObject([
478
+ { o: 1n, op: 'PUT', row_id: 'A', data: '{"id":"A","description":"first"}' },
479
+ { o: 2n, op: 'PUT', row_id: 'A', data: '{"id":"A","description":"second"}' }
480
+ ]);
481
+ expect(await context.bucketStorage.getCheckpoint()).toMatchObject({ checkpoint: 2n, lsn: '1/2' });
482
+ });
483
+
484
+ test.each(['read', 'upload'])('does not publish after a %s failure', async (stage) => {
485
+ const objectStorage = new MemoryObjectStorage();
486
+ const context = await openStream(storageVersion, objectStorage);
487
+ await using _factory = context.factory;
488
+ await using writer = context.writer;
489
+ using _blocks = vi.spyOn(OperationBatch.prototype, 'batched').mockImplementation(function* (this: OperationBatch) {
490
+ for (const op of this.batch) yield [op];
491
+ });
492
+ const failure = new Error('failed ' + stage);
493
+ const load = SourceRecordStoreV3.prototype.loadDocuments;
494
+ let reads = 0;
495
+ using _read = vi.spyOn(SourceRecordStoreV3.prototype, 'loadDocuments').mockImplementation(async function (
496
+ this: SourceRecordStoreV3,
497
+ ...args
498
+ ) {
499
+ if (++reads === 2 && stage === 'read') throw failure;
500
+ return load.apply(this, args);
501
+ });
502
+ const put = objectStorage.put.bind(objectStorage);
503
+ let uploads = 0;
504
+ using _put = vi.spyOn(objectStorage, 'put').mockImplementation(async (...args) => {
505
+ if (++uploads === 2 && stage === 'upload') throw failure;
506
+ return put(...args);
507
+ });
508
+ using publish = vi.spyOn(PersistedBatchV3.prototype, 'publish');
509
+ for (const id of ['A', 'B']) {
510
+ await writer.save({
511
+ sourceTable: context.table,
512
+ tag: storage.SaveOperationTag.INSERT,
513
+ after: { id },
514
+ afterReplicaId: test_utils.rid(id)
515
+ });
516
+ }
517
+ await expect(writer.commit('1/2')).rejects.toThrow(failure);
518
+ expect(writer.last_flushed_op).toBeNull();
519
+ expect((await context.bucketStorage.getCheckpoint()).checkpoint).toBe(0n);
520
+ expect(publish).not.toHaveBeenCalled();
521
+ // Read failure starts no uploads. A successful PUT preceding upload failure
522
+ // remains protected as an orphan, with no published references or progress.
523
+ expect(uploads).toBe(stage === 'read' ? 0 : 2);
524
+ expect(
525
+ await context.bucketStorage.db
526
+ .pendingObjectStorageDeletes(context.stream.replicationStreamId)
527
+ .countDocuments({ path: { $in: [...objectStorage.store.keys()] } })
528
+ ).toBe(stage === 'read' ? 0 : 1);
529
+ });
530
+
328
531
  test.each([false, true])('joins sibling uploads before rejecting readiness (cancellation: %s)', async (cancelled) => {
329
532
  const objectStorage = new MemoryObjectStorage();
330
533
  const context = await openStream(storageVersion, objectStorage);
@@ -366,7 +569,7 @@ streams:
366
569
  const rejected = expect(commit).rejects.toThrow(failure);
367
570
  await siblingStarted.promise;
368
571
  let readySettled = false;
369
- const readiness = publication!.preparePayloads().then(
572
+ const readiness = publication!.packAndUploadPayloads().then(
370
573
  () => {
371
574
  readySettled = true;
372
575
  },
@@ -381,7 +584,7 @@ streams:
381
584
  await readiness;
382
585
  expect(siblingFinished).toBe(true);
383
586
  expect(uploadSpy).toHaveBeenCalledTimes(2);
384
- await expect(publication!.preparePayloads()).rejects.toThrow(failure);
587
+ await expect(publication!.packAndUploadPayloads()).rejects.toThrow(failure);
385
588
  expect(uploadSpy).toHaveBeenCalledTimes(2);
386
589
  expect((await context.bucketStorage.getCheckpoint()).checkpoint).toBe(0n);
387
590
  });
@@ -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
+ });