@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,133 @@
1
+ import { mongoTestStorageFactoryGenerator } from '@module/utils/test-utils.js';
2
+ import { storage, updateSyncRulesFromYaml } from '@powersync/service-core';
3
+ import { getTestStorage, test_utils } from '@powersync/service-core-tests';
4
+ import { writeFile } from 'node:fs/promises';
5
+ import { setTimeout } from 'node:timers/promises';
6
+ import { expect, test, vi } from 'vitest';
7
+ import { DEFAULT_REPLICATION_BATCH_LIMITS } from '../../src/storage/implementation/ReplicationBatchLimits.js';
8
+ import { PersistedBatchV3 } from '../../src/storage/implementation/v3/PersistedBatchV3.js';
9
+ import { SourceRecordStoreV3 } from '../../src/storage/implementation/v3/SourceRecordStoreV3.js';
10
+ import { env } from './env.js';
11
+ import { MemoryObjectStorage } from './helpers/MemoryObjectStorage.js';
12
+ import { PublicationCommandMonitor } from './helpers/PublicationCommandMonitor.js';
13
+
14
+ /**
15
+ * Opt-in scheduling experiment with real MongoDB and injected I/O latency.
16
+ * Run with POWERSYNC_PIPELINE_BENCHMARK=1 and --silent=false through the MongoDB test wrapper.
17
+ * Set POWERSYNC_PIPELINE_BENCHMARK_OUTPUT to also save the JSON report.
18
+ * Serial mode drains at every input boundary; both modes keep production batch
19
+ * targets and identical offloaded payloads and command instrumentation. Timing ends at durable commit.
20
+ * This isolates overlap, rather than predicting production throughput or RSS.
21
+ */
22
+ test.skipIf(!process.env.POWERSYNC_PIPELINE_BENCHMARK)(
23
+ 'measures serial versus pipelined v4 publication',
24
+ async () => {
25
+ const batchRows = DEFAULT_REPLICATION_BATCH_LIMITS.maxInputBatchCount;
26
+ const totalRows = 10 * batchRows;
27
+ const readDelayMs = 10;
28
+ const publicationDelayMs = 20;
29
+ const uploadDelayMs = 10;
30
+ const results: unknown[] = [];
31
+ for (const serial of [true, false]) {
32
+ const objects = new MemoryObjectStorage();
33
+ const gen = mongoTestStorageFactoryGenerator({
34
+ url: env.MONGO_TEST_URL,
35
+ isCI: env.CI,
36
+ monitorCommands: true,
37
+ objectStorage: objects,
38
+ inlineThresholdBytes: 0
39
+ });
40
+ await using factory = await gen.factory();
41
+ const stream = await factory.updateSyncRules(
42
+ updateSyncRulesFromYaml(
43
+ `
44
+ config:
45
+ edition: 3
46
+ streams:
47
+ items:
48
+ query: SELECT * FROM items
49
+ `,
50
+ { storageVersion: 4 }
51
+ )
52
+ );
53
+ const buckets = await getTestStorage(factory, stream);
54
+ await using writer = await buckets.createWriter(test_utils.BATCH_OPTIONS);
55
+ const table = await test_utils.resolveTestTable(writer, 'items', ['id'], gen, 1);
56
+ await writer.markAllSnapshotDone('1/1');
57
+ await writer.save({
58
+ sourceTable: table,
59
+ tag: storage.SaveOperationTag.INSERT,
60
+ after: { id: 'warmup', description: 'warmup' },
61
+ afterReplicaId: 'warmup'
62
+ });
63
+ await writer.commit('1/1');
64
+ const load = SourceRecordStoreV3.prototype.loadDocuments;
65
+ using _read = vi.spyOn(SourceRecordStoreV3.prototype, 'loadDocuments').mockImplementation(async function (
66
+ this: SourceRecordStoreV3,
67
+ ...args
68
+ ) {
69
+ await setTimeout(readDelayMs);
70
+ return load.apply(this, args);
71
+ });
72
+ const publish = PersistedBatchV3.prototype.publish;
73
+ using _publish = vi.spyOn(PersistedBatchV3.prototype, 'publish').mockImplementation(async function (
74
+ this: PersistedBatchV3,
75
+ ...args
76
+ ) {
77
+ await setTimeout(publicationDelayMs);
78
+ return publish.apply(this, args);
79
+ });
80
+ const put = objects.put.bind(objects);
81
+ let uploadCount = 0;
82
+ using _upload = vi.spyOn(objects, 'put').mockImplementation(async (...args) => {
83
+ uploadCount++;
84
+ await setTimeout(uploadDelayMs);
85
+ return put(...args);
86
+ });
87
+ using monitor = new PublicationCommandMonitor(factory.db.client);
88
+ const peak = process.memoryUsage();
89
+ const startedAt = performance.now();
90
+ const description = 'x'.repeat(128);
91
+ for (let i = 0; i < totalRows; i++) {
92
+ await writer.save({
93
+ sourceTable: table,
94
+ tag: storage.SaveOperationTag.INSERT,
95
+ after: { id: String(i), description },
96
+ afterReplicaId: String(i)
97
+ });
98
+ if ((i + 1) % batchRows === 0) {
99
+ if (serial) {
100
+ await writer.flush();
101
+ }
102
+ const memory = process.memoryUsage();
103
+ for (const key of ['rss', 'heapUsed', 'external', 'arrayBuffers'] as const) {
104
+ peak[key] = Math.max(peak[key], memory[key]);
105
+ }
106
+ }
107
+ }
108
+ await writer.commit('1/2');
109
+ const elapsedMs = performance.now() - startedAt;
110
+ const summary = monitor.summary();
111
+ expect((await buckets.getCheckpoint()).lsn).toBe('1/2');
112
+ results.push({
113
+ serial,
114
+ totalRows,
115
+ batchRows,
116
+ readDelayMs,
117
+ publicationDelayMs,
118
+ uploadDelayMs,
119
+ uploadCount,
120
+ elapsedMs,
121
+ rowsPerSecond: (totalRows * 1000) / elapsedMs,
122
+ sampledProcessMemoryPeak: peak,
123
+ ...summary
124
+ });
125
+ }
126
+ const report = { benchmark: 'v4-publication-pipeline', node: process.version, results };
127
+ console.info(JSON.stringify(report));
128
+ if (process.env.POWERSYNC_PIPELINE_BENCHMARK_OUTPUT) {
129
+ await writeFile(process.env.POWERSYNC_PIPELINE_BENCHMARK_OUTPUT, JSON.stringify(report, null, 2));
130
+ }
131
+ },
132
+ 120_000
133
+ );
@@ -157,6 +157,9 @@ describe.each([3, 4])('eager replication preparation v%s', (version) => {
157
157
  after: { id: 'A', description: '"'.repeat(8 * 1024 * 1024), retained: 'old' },
158
158
  afterReplicaId: test_utils.rid('A')
159
159
  });
160
+ // Automatic save admission is speculative; the explicit barrier waits for
161
+ // the immutable publication and its transaction retry.
162
+ await writer.flush();
160
163
  expect(attempts).toBe(2);
161
164
  expect(logged).toHaveBeenCalledTimes(1);
162
165
  expect(logged).toHaveBeenCalledWith(expect.stringMatching(/^Row .* too large: .* bytes\. Removing\.$/));
@@ -532,8 +535,7 @@ describe.each([3, 4])('eager replication preparation v%s', (version) => {
532
535
  try {
533
536
  await entered.promise;
534
537
  using read = vi.spyOn(SourceRecordStoreV3.prototype, 'loadDocuments');
535
- await save(writer, context.table, 'after cleanup');
536
- pending.push(writer.flush());
538
+ pending.push(save(writer, context.table, 'after cleanup').then(() => writer.flush()));
537
539
  expect(read).not.toHaveBeenCalled();
538
540
  release.resolve();
539
541
  await Promise.all(pending);
@@ -3,7 +3,6 @@ import { PerformanceTracer, Span, storage, updateSyncRulesFromYaml } from '@powe
3
3
  import { compactActive, getTestStorage, test_utils } from '@powersync/service-core-tests';
4
4
  import { describe, expect, test, vi } from 'vitest';
5
5
  import { MongoSyncBucketStorageV3 } from '../../src/storage/implementation/v3/MongoSyncBucketStorageV3.js';
6
- import { PersistedBatchV3 } from '../../src/storage/implementation/v3/PersistedBatchV3.js';
7
6
  import { env } from './env.js';
8
7
  import { MemoryObjectStorage } from './helpers/MemoryObjectStorage.js';
9
8
  import { PublicationCommandMonitor } from './helpers/PublicationCommandMonitor.js';
@@ -110,17 +109,22 @@ describe.each([3, 4])('replication publication baseline v%s', (storageVersion) =
110
109
  await put(...args);
111
110
  sample.endedAt = performance.now();
112
111
  });
113
- const flush = PersistedBatchV3.prototype.publish;
114
- using _flushSpy = vi.spyOn(PersistedBatchV3.prototype, 'publish').mockImplementation(async function (
115
- this: PersistedBatchV3,
116
- ...args
117
- ) {
118
- // Inline batches have no PUT to pause. Compact after lookup/evaluation,
119
- // immediately before the writer persists its bucket-state delta instead.
120
- if (!offloaded) {
121
- await compactOnce();
112
+ const createWriteBatch = factory.db.createWriteBatch.bind(factory.db);
113
+ using _writeSpy = vi.spyOn(factory.db, 'createWriteBatch').mockImplementation((session, options) => {
114
+ const batch = createWriteBatch(session, options);
115
+ if (options.ordered && compaction && !offloaded) {
116
+ const execute = batch.execute.bind(batch);
117
+ batch.execute = async () => {
118
+ if (!compacted) {
119
+ // Pin the snapshot with a test-only read so compaction can commit
120
+ // before the first bucket write and force that write to retry.
121
+ await bucketStates.findOne({ _id: stateBefore!._id }, { session });
122
+ await compactOnce();
123
+ }
124
+ await execute();
125
+ };
122
126
  }
123
- return flush.apply(this, args);
127
+ return batch;
124
128
  });
125
129
 
126
130
  await save('c');
@@ -128,7 +132,7 @@ describe.each([3, 4])('replication publication baseline v%s', (storageVersion) =
128
132
  const summary = monitor.summary();
129
133
  const attempts = monitor.replicationAttempts;
130
134
  // Compaction during an offloaded PUT now finishes before replication opens
131
- // its transaction. Inline work still injects compaction after the fence.
135
+ // its transaction. The test-only read makes the inline attempt stale.
132
136
  const conflict = compaction && !offloaded;
133
137
  expect(compacted).toBe(compaction);
134
138
  expect(attempts).toHaveLength(conflict ? 2 : 1);
@@ -151,7 +155,7 @@ describe.each([3, 4])('replication publication baseline v%s', (storageVersion) =
151
155
  expect(tracer.stack).toHaveLength(0);
152
156
  expect(uploads).toHaveLength(offloaded ? 1 : 0);
153
157
  // Real compaction can run throughout a replication PUT without extending or
154
- // invalidating a replication transaction: the fence has not started yet.
158
+ // invalidating a replication transaction: publication has not started yet.
155
159
  for (const upload of uploads) {
156
160
  expect(upload.transactions).toHaveLength(0);
157
161
  expect(attempts[0].startedAt).toBeGreaterThanOrEqual(upload.endedAt);
@@ -164,8 +168,8 @@ describe.each([3, 4])('replication publication baseline v%s', (storageVersion) =
164
168
  // commit but adds an abort command; replay sends no source reads. The
165
169
  // final data group now executes the independent head/checkpoint tail too.
166
170
  expect(summary.replicationAttempts.map((attempt) => attempt.commands)).toEqual([
167
- ...(conflict ? [{ findAndModify: 1, bulkWrite: 1, abortTransaction: 1 }] : []),
168
- { findAndModify: 1, bulkWrite: 1, commitTransaction: 1 }
171
+ ...(conflict ? [{ find: 1, bulkWrite: 1, abortTransaction: 1 }] : []),
172
+ { findAndModify: 1, bulkWrite: 2, commitTransaction: 1 }
169
173
  ]);
170
174
  }
171
175
 
@@ -178,7 +182,13 @@ describe.each([3, 4])('replication publication baseline v%s', (storageVersion) =
178
182
  compaction,
179
183
  ...summary,
180
184
  uploads: uploads.map((upload) => ({ bytes: upload.bytes, durationMs: upload.endedAt - upload.startedAt })),
181
- transactionBodyMs: bodies.map((span) => (span.endAt - span.startAt) / 1000)
185
+ transactionBodyMs: bodies.map((span) => (span.endAt - span.startAt) / 1000),
186
+ bucketStateMs: spans
187
+ .filter((span) => span.name === 'storage:publish_bucket_state')
188
+ .map((span) => (span.endAt - span.startAt) / 1000),
189
+ fenceMs: spans
190
+ .filter((span) => span.name === 'storage:publish_fence')
191
+ .map((span) => (span.endAt - span.startAt) / 1000)
182
192
  })
183
193
  );
184
194
  }
@@ -102,6 +102,10 @@ describe.each([3, 4])('publication batching v%s', (version) => {
102
102
  await writer.commit('1/3');
103
103
  expect(reads.count).toBe(0);
104
104
  expect(registration).toHaveBeenCalledTimes(mode === 'offloaded' ? 1 : 0);
105
+ expect(monitor.replicationAttempts[0].commands.slice(0, 2).map((command) => command.name)).toEqual([
106
+ clientBulks ? 'bulkWrite' : 'update',
107
+ 'findAndModify'
108
+ ]);
105
109
  expect(monitor.summary().replicationAttempts.map((attempt) => attempt.commands)).toEqual([
106
110
  !clientBulks
107
111
  ? {
@@ -112,7 +116,7 @@ describe.each([3, 4])('publication batching v%s', (version) => {
112
116
  ...(mode === 'offloaded' ? { delete: 1 } : {}),
113
117
  commitTransaction: 1
114
118
  }
115
- : { findAndModify: 1, bulkWrite: 1, commitTransaction: 1 }
119
+ : { findAndModify: 1, bulkWrite: 2, commitTransaction: 1 }
116
120
  ]);
117
121
  const checkpoint = await context.bucketStorage.getCheckpoint();
118
122
  expect(checkpoint).toMatchObject({ checkpoint: 3n, lsn: '1/3' });
@@ -204,7 +208,7 @@ describe.each([3, 4])('publication batching v%s', (version) => {
204
208
  expect(put).toHaveBeenCalledTimes(1);
205
209
  expect(monitor.summary().replicationAttempts.map((attempt) => attempt.commands)).toEqual([
206
210
  clientBulks
207
- ? { findAndModify: 1, bulkWrite: 1, commitTransaction: 1 }
211
+ ? { findAndModify: 1, bulkWrite: 2, commitTransaction: 1 }
208
212
  : { findAndModify: 1, update: 5, delete: 1, insert: 1, commitTransaction: 1 }
209
213
  ]);
210
214
  expect((await context.bucketStorage.getCheckpoint()).checkpoint).toBe(1002n);
@@ -58,7 +58,20 @@ async function open(version: number, options: Partial<storage.CreateWriterOption
58
58
  after: { id: 'A', description: 'offloaded' },
59
59
  afterReplicaId: test_utils.rid('A')
60
60
  });
61
- return { factory, stream, bucketStorage, writer, table, db, objectStorage, markers, lifecycle, data, records };
61
+ return {
62
+ factory,
63
+ factoryGen,
64
+ stream,
65
+ bucketStorage,
66
+ writer,
67
+ table,
68
+ db,
69
+ objectStorage,
70
+ markers,
71
+ lifecycle,
72
+ data,
73
+ records
74
+ };
62
75
  }
63
76
 
64
77
  describe.each([3, 4])('replication uploads v%s', (version) => {
@@ -133,8 +146,20 @@ describe.each([3, 4])('replication uploads v%s', (version) => {
133
146
  expect(await context.markers.countDocuments()).toBe(1);
134
147
  expect(await context.records.countDocuments()).toBe(0);
135
148
  expect((await context.bucketStorage.getCheckpoint()).checkpoint).toBe(0n);
136
- // A later explicit retry reevaluates the retained input using a fresh path.
137
- await writer.commit('1/2');
149
+ // Ambiguous upload-marker registration invalidates the lease attempt. Replay
150
+ // under a fresh lease uses a new path and leaves the abandoned marker protected.
151
+ await expect(writer.commit('1/2')).rejects.toThrow('restart');
152
+ await test_utils.releaseTestStorageLease(context.factory, context.stream.replicationStreamId);
153
+ const restarted = await getTestStorage(context.factory, context.stream);
154
+ await using replay = await restarted.createWriter(test_utils.BATCH_OPTIONS);
155
+ const replayTable = await test_utils.resolveTestTable(replay, 'items', ['id'], context.factoryGen, 1);
156
+ await replay.save({
157
+ sourceTable: replayTable,
158
+ tag: storage.SaveOperationTag.INSERT,
159
+ after: { id: 'A', description: 'offloaded' },
160
+ afterReplicaId: test_utils.rid('A')
161
+ });
162
+ await replay.commit('1/2');
138
163
  expect(put).toHaveBeenCalledTimes(1);
139
164
  expect(await context.markers.countDocuments()).toBe(1);
140
165
  expect(await context.records.countDocuments()).toBe(1);
@@ -152,6 +152,30 @@ bucket_definitions:
152
152
  }
153
153
  });
154
154
 
155
+ test.runIf(storageVersion >= 3)('rejects custom checkpoints without an event definition id', async () => {
156
+ await using factory = await INITIALIZED_MONGO_STORAGE_FACTORY.factory();
157
+ const syncRules = await factory.updateSyncRules(
158
+ updateSyncRulesFromYaml(
159
+ `
160
+ config:
161
+ edition: 3
162
+
163
+ streams:
164
+ global:
165
+ query: SELECT * FROM checkpoints
166
+ `,
167
+ { storageVersion }
168
+ )
169
+ );
170
+ const bucketStorage = await getTestStorage(factory, syncRules);
171
+ const db = bucketStorage.db as VersionedPowerSyncMongoV3;
172
+ // Keep rejected input in its own test: disposal invalidates the shared lease.
173
+ await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
174
+ writer.addCustomWriteCheckpoint({ user_id: 'invalid', checkpoint: 1n });
175
+ await expect(writer.flush()).rejects.toThrow('require an event definition id');
176
+ await expect(db.listCustomCheckpointRequestCollections(syncRules.replicationStreamId)).resolves.toEqual([]);
177
+ });
178
+
155
179
  test.runIf(storageVersion >= 3)(
156
180
  'stores and streams checkpoints from different event definitions independently',
157
181
  async (context) => {
@@ -211,11 +235,6 @@ event_definitions:
211
235
  // they must not require the lazily-created collection to exist.
212
236
  await expect(bucketStorage.lastWriteCheckpoint({ user_id: 'user1' })).resolves.toBeNull();
213
237
 
214
- await using invalidWriter = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
215
- invalidWriter.addCustomWriteCheckpoint({ user_id: 'invalid', checkpoint: 1n });
216
- await expect(invalidWriter.flush()).rejects.toThrow('require an event definition id');
217
- await expect(db.listCustomCheckpointRequestCollections(syncRules.replicationStreamId)).resolves.toEqual([]);
218
-
219
238
  await using writer = await bucketStorage.createWriter(test_utils.BATCH_OPTIONS);
220
239
  await writer.markAllSnapshotDone('1/1');
221
240
  const abortController = new AbortController();