@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
@@ -7,7 +7,7 @@ import {
7
7
  ServiceError
8
8
  } from '@powersync/lib-services-framework';
9
9
  import { InternalOpId, storage } from '@powersync/service-core';
10
- import { EventDefinitionId } from '@powersync/service-sync-rules';
10
+ import { EventDefinitionId, HydratedEventDescriptor } from '@powersync/service-sync-rules';
11
11
  import * as bson from 'bson';
12
12
  import { mongoTableId } from '../../../utils/util.js';
13
13
  import { canCheckpointState } from '../CheckpointState.js';
@@ -16,11 +16,13 @@ import { OpIdRangeExhausted } from '../MongoIdSequence.js';
16
16
  import { MongoParsedSyncConfigSet } from '../MongoParsedSyncConfigSet.js';
17
17
  import { MongoWriteBatch } from '../MongoWriteBatch.js';
18
18
  import { OperationBatch } from '../OperationBatch.js';
19
+ import { RETAINED_BYTES_FACTOR } from '../ReplicationBatchLimits.js';
19
20
  import { stopReplicationStreamPipeline } from '../SyncRuleStateUpdate.js';
20
21
  import { PreparedPublication } from '../common/PreparedPublication.js';
21
22
  import { LoadedSourceRecord } from '../common/SourceRecordStore.js';
22
23
  import { SyncRuleDocumentBase } from '../models.js';
23
24
  import { PersistedBatchV3 } from './PersistedBatchV3.js';
25
+ import { ReplicationPipelineV3 } from './ReplicationPipelineV3.js';
24
26
  import { SourceRecordStoreV3 } from './SourceRecordStoreV3.js';
25
27
  import { VersionedPowerSyncMongoV3 } from './VersionedPowerSyncMongoV3.js';
26
28
  import { CustomCheckpointRequestDocumentV3, ReplicationStreamDocumentV3, SourceTableDocumentV3 } from './models.js';
@@ -33,10 +35,27 @@ import {
33
35
  SourceTableReconciliationContext
34
36
  } from './source-table-utils.js';
35
37
 
38
+ interface PreparedRows {
39
+ publications: PreparedPublication[];
40
+ repairs: storage.SaveUpdate[];
41
+ resumeBatch: OperationBatch | null;
42
+ lastOp: InternalOpId;
43
+ hasWrites: boolean;
44
+ changes: Map<string, LoadedSourceRecord>;
45
+ retainedBytes: number;
46
+ }
47
+
36
48
  export class MongoBucketBatchV3 extends MongoBucketBatch {
37
49
  declare readonly db: VersionedPowerSyncMongoV3;
38
50
 
39
51
  private readonly store: SourceRecordStoreV3;
52
+ private readonly pipeline: ReplicationPipelineV3;
53
+ private enqueuePublication = false;
54
+ private pendingPublications = 0;
55
+ private pendingInputs = 0;
56
+ /** Owned by the current mutex operation; saves only append to this.batch. */
57
+ private capturedInput: OperationBatch | null = null;
58
+
40
59
  /** Avoid repeating idempotent createIndexes calls for every checkpoint flush. */
41
60
  private readonly initializedCustomCheckpointEventIds = new Set<EventDefinitionId>();
42
61
  // Used only to validate supplied checkpoint ids; it does not initialize collections.
@@ -47,6 +66,11 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
47
66
 
48
67
  constructor(options: MongoBucketBatchOptions) {
49
68
  super(options);
69
+ this.pipeline = options.replicationLock.replicationPipeline ??= new ReplicationPipelineV3(
70
+ options.replicationLock,
71
+ options.opIdAllocator,
72
+ options.batchLimits
73
+ );
50
74
  const syncConfigIds = options.syncConfigIds ?? [];
51
75
  if (syncConfigIds.length == 0) {
52
76
  throw new ReplicationAssertionError('Missing sync config id for v3 batch');
@@ -54,11 +78,171 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
54
78
  this.syncConfigIds = syncConfigIds;
55
79
  this.knownEventIds = new Set(this.mapping.allEventDefinitionIds());
56
80
  this.store = new SourceRecordStoreV3(this.db, this.replicationStreamId, this.mapping);
81
+ this.pipeline.registerWriter(this);
82
+ }
83
+
84
+ protected override getTableEvents(
85
+ table: storage.SourceTable
86
+ ): { event: HydratedEventDescriptor; eventId: EventDefinitionId }[] {
87
+ // V3 storage assigns event-definition ids to each source table, so membership is authoritative.
88
+ // Iterate the table's distinct ids and resolve each through the stream's deduped event map, so a
89
+ // definition reused across configs has one evaluator for that id. The evaluator may still return
90
+ // multiple payloads from matching queries.
91
+ const ids = table.eventDefinitionIds;
92
+ if (ids == null) {
93
+ throw new ReplicationAssertionError('Expected assigned event-definition ids for a v3 source table');
94
+ }
95
+ const eventById = this.options.parsedSyncConfig.eventById;
96
+ const events: { event: HydratedEventDescriptor; eventId: EventDefinitionId }[] = [];
97
+ for (const id of ids) {
98
+ const event = eventById.get(id);
99
+ if (event != null && event.tableTriggersEvent(table.ref)) {
100
+ events.push({ event, eventId: id });
101
+ }
102
+ }
103
+ return events;
104
+ }
105
+
106
+ override async save(record: storage.SaveOptions): Promise<storage.FlushedResult | null> {
107
+ try {
108
+ this.options.replicationLock.throwIfAborted();
109
+ // No await or mutex is needed to append an input event. Flushes detach their
110
+ // input before yielding, so preparation never reads this mutable buffer.
111
+ // A full buffer still waits for preparation capacity, bounding read-ahead.
112
+ if (this.bufferRecord(record)) {
113
+ return await this.automaticFlush();
114
+ }
115
+ return null;
116
+ } catch (error) {
117
+ this.pipeline.fail(error);
118
+ throw error;
119
+ }
120
+ }
121
+
122
+ override async commit(lsn: string, options?: storage.BucketBatchCommitOptions): Promise<storage.CheckpointResult> {
123
+ this.options.replicationLock.throwIfAborted();
124
+ if (this.markRecordUnavailable != null && (this.batch?.length ?? 0) > 0) {
125
+ // A combined data+checkpoint commit cannot return control to the connector
126
+ // to process repair notifications between those two durable boundaries.
127
+ // Require its explicit flush -> repair -> commit ordering even when this
128
+ // particular input might turn out not to need repair. An empty batch does
129
+ // not prove its external repair queue is drained; that remains the caller's
130
+ // responsibility. keepalive() delegates here and has the same requirement.
131
+ throw new ReplicationAssertionError(
132
+ 'Flush pending rows and process markRecordUnavailable repairs before committing source progress'
133
+ );
134
+ }
135
+ // Reject invalid repair ordering before detaching input, so the connector
136
+ // can still flush, repair, and retry its commit on this writer.
137
+ return this.withWriterLock(() => this.commitInternal(lsn, options), false);
138
+ }
139
+
140
+ /**
141
+ * Capture this writer's rows/checkpoints and queue preparation under writerMutex.
142
+ * Capture and enqueue happen before yielding, establishing the input's place
143
+ * relative to metadata barriers. Wait for preparation/admission, not necessarily
144
+ * publication. Repairs retain their synchronous flush path.
145
+ */
146
+ async flushBufferedInputToPipeline(): Promise<storage.FlushedResult | null> {
147
+ if (!this.batch?.hasData()) {
148
+ return null;
149
+ }
150
+ return this.withCapturedInputLock(this.takeBufferedInput(), () => this.flushInternal(), true);
151
+ }
152
+
153
+ protected override async automaticFlush(): Promise<storage.FlushedResult | null> {
154
+ return this.flushBufferedInputToPipeline();
155
+ }
156
+
157
+ /**
158
+ * Metadata operations capture all live writers before changing shared table state.
159
+ * Explicit flush/commit pass false: they drain admitted work and flush their own
160
+ * input in the callback, without forcing other writers' partial buffers to publish.
161
+ */
162
+ protected override withWriterLock<T>(callback: () => Promise<T>, flushAllWriters = true): Promise<T> {
163
+ // Queue all captured inputs before queueing the metadata operation itself.
164
+ // Saves after this synchronous boundary use fresh buffers and queue behind it.
165
+ if (flushAllWriters) {
166
+ this.pipeline.enqueueBufferedInputs();
167
+ }
168
+ return this.withCapturedInputLock(this.takeBufferedInput(), async () => {
169
+ await this.pipeline.drain();
170
+ return callback();
171
+ });
172
+ }
173
+
174
+ private takeBufferedInput(): OperationBatch | null {
175
+ const input = this.batch;
176
+ this.batch = null;
177
+ return input;
178
+ }
179
+
180
+ /** Only captured batches and metadata operations acquire/trace the writer lock. */
181
+ private async withCapturedInputLock<T>(
182
+ input: OperationBatch | null,
183
+ callback: () => Promise<T>,
184
+ enqueuePublication = false
185
+ ): Promise<T> {
186
+ const hasInput = input?.hasData() ?? false;
187
+ if (hasInput) {
188
+ this.pendingInputs++;
189
+ }
190
+ try {
191
+ using lockSpan = this.tracer.span('storage', 'internal_lock');
192
+ this.options.replicationLock.throwIfAborted();
193
+ return await this.options.replicationLock.writerMutex.exclusiveLock(async () => {
194
+ lockSpan.end();
195
+ this.options.replicationLock.throwIfAborted();
196
+ this.capturedInput = input;
197
+ this.enqueuePublication = enqueuePublication;
198
+ try {
199
+ return await callback();
200
+ } finally {
201
+ this.capturedInput = null;
202
+ this.enqueuePublication = false;
203
+ }
204
+ });
205
+ } catch (error) {
206
+ // A captured input must never disappear after failure while other writers
207
+ // continue advancing source progress. Replay it under a fresh lease. An
208
+ // input-free metadata rejection can be retried, e.g. snapshot completion
209
+ // rejected because a table still needs snapshotting.
210
+ if (hasInput) {
211
+ this.pipeline.fail(error);
212
+ }
213
+ throw error;
214
+ } finally {
215
+ if (hasInput) {
216
+ this.pendingInputs--;
217
+ }
218
+ }
219
+ }
220
+
221
+ override async [Symbol.asyncDispose](): Promise<void> {
222
+ const pending = this.pendingInputs > 0 || this.pendingPublications > 0 || this.batch?.hasData();
223
+ if (pending) {
224
+ this.pipeline.fail(new ReplicationAbortedError('Disposed writer with pending replication work'));
225
+ }
226
+ await this.options.replicationLock.writerMutex.exclusiveLock(async () => {
227
+ if (pending || this.options.replicationLock.signal.aborted) {
228
+ await this.pipeline.join();
229
+ }
230
+ this.pipeline.unregisterWriter(this);
231
+ if (this.batch?.hasData()) {
232
+ // We don't error here, since:
233
+ // 1. In error states, this is expected (we can't distinguish between disposing after success or error).
234
+ // 2. SuppressedError is messy to deal with.
235
+ this.logger.warn('Disposing writer with unflushed changes');
236
+ }
237
+ // The lease owns the shared session and ends it after all writers stop.
238
+ super.clearListeners();
239
+ });
57
240
  }
58
241
 
59
242
  protected createPersistedBatch(writtenSize: number): PersistedBatchV3 {
60
243
  return new PersistedBatchV3(this.db, this.replicationStreamId, this.mapping, writtenSize, {
61
244
  logger: this.logger,
245
+ batchLimits: this.options.batchLimits,
62
246
  objectStorage: this.options.objectStorage,
63
247
  inlineThresholdBytes: this.options.inlineThresholdBytes,
64
248
  signal: this.options.signal,
@@ -84,22 +268,76 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
84
268
  );
85
269
  }
86
270
 
87
- protected override async flushInner(
271
+ /** Internal helpers require the public operation to hold the writer mutex. */
272
+ protected override async flushInternal(
273
+ options?: storage.BatchBucketFlushOptions
274
+ ): Promise<storage.FlushedResult | null> {
275
+ let result: storage.FlushedResult | null = null;
276
+ // One captured input may be split over multiple publications. Each
277
+ // flushInner() consumes a prefix, retaining its remainder for this operation.
278
+ while (this.capturedInput != null) {
279
+ let r = await this.flushInner(options);
280
+ if (r) {
281
+ result = r;
282
+ }
283
+ }
284
+ return result;
285
+ }
286
+
287
+ /** Publish the checkpoint in the final flush transaction, or use the empty-commit path. */
288
+ private async flushAndCommit<T>(
289
+ checkpoint: (stream: SyncRuleDocumentBase, lastOp: InternalOpId, writes?: MongoWriteBatch) => Promise<T>,
290
+ commitWithoutFlush: () => Promise<T>,
291
+ options?: storage.BatchBucketFlushOptions,
292
+ projection?: lib_mongo.mongo.Document
293
+ ): Promise<T> {
294
+ if (this.capturedInput == null) {
295
+ return commitWithoutFlush();
296
+ }
297
+ let result!: T;
298
+ while (this.capturedInput != null) {
299
+ await this.flushInner(
300
+ options,
301
+ async (stream, lastOp, writes) => {
302
+ result = await checkpoint(stream, lastOp, writes);
303
+ },
304
+ projection
305
+ );
306
+ }
307
+ return result;
308
+ }
309
+
310
+ private async flushInner(
88
311
  options?: storage.BatchBucketFlushOptions,
89
312
  checkpoint?: (stream: SyncRuleDocumentBase, lastOp: InternalOpId, writes?: MongoWriteBatch) => Promise<void>,
90
313
  projection?: lib_mongo.mongo.Document
91
314
  ): Promise<storage.FlushedResult | null> {
92
315
  using _span = this.tracer.span('storage', 'flush');
93
316
  await this.hooks?.beforeBatchFlush?.(this);
94
- const input = this.batch;
95
- const checkpoints = this.write_checkpoint_batch.slice();
96
- const allocator = this.options.opIdAllocator;
317
+ const input = this.capturedInput;
318
+ const checkpoints = input?.customWriteCheckpoints ?? [];
319
+ const allocator = this.pipeline.allocator;
97
320
  await allocator.ensureCapacity();
98
321
  const contextProjection = { ...projection, state: 1, last_persisted_op: 1, sync_configs: 1 };
99
322
  if (checkpoints.length > 0) {
100
- await this.prepareCustomWriteCheckpoints();
323
+ await this.prepareCustomWriteCheckpoints(checkpoints);
324
+ }
325
+ await this.pipeline.capacity();
326
+ const overlay = this.pipeline.beginRead();
327
+ let prepared: PreparedRows;
328
+ try {
329
+ prepared = await this.prepareRows(this.session, input, overlay);
330
+ } finally {
331
+ this.pipeline.endRead();
101
332
  }
102
- const prepared = await this.prepareRows(this.session, input);
333
+ const { publications, repairs, resumeBatch, changes, hasWrites } = prepared;
334
+ const retainedBytes =
335
+ prepared.retainedBytes +
336
+ checkpoints.reduce(
337
+ (bytes, checkpoint) => bytes + (bson.calculateObjectSize(checkpoint) + 256) * RETAINED_BYTES_FACTOR,
338
+ 0
339
+ );
340
+ const publishCheckpoint = checkpoint != null && resumeBatch == null;
103
341
  let lastOp = prepared.lastOp;
104
342
  let checkpointOp: bigint | undefined;
105
343
  if (checkpoints.length > 0) {
@@ -118,66 +356,101 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
118
356
  }
119
357
  // Reservations are globally disjoint and this lease's allocator consumes IDs
120
358
  // assigned to sealed work, even if publication is abandoned. The writer mutex
121
- // excludes other writers under this lease during preparation and publication;
359
+ // serializes preparation under this lease; the shared overlay covers pending writes;
122
360
  // the transaction fence excludes a different lease owner. Thus preparation
123
361
  // does not need to read the persisted head to allocate IDs or reuse records.
124
362
  allocator.consume(lastOp);
125
- const clearError = !this.clearedError && prepared.hasWrites;
126
- await this.publishPrepared(lastOp, contextProjection, prepared.publications, options, async (stream, writes) => {
127
- // An empty flush allocates no ID. Use the durable head from the
128
- // fresh fence for its checkpoint and returned flushed operation.
129
- if (lastOp === 0n) {
130
- lastOp = this.persistedOpHead(stream);
131
- }
132
- if (clearError) {
133
- writes.updateOne(
134
- this.db.sync_rules,
135
- { _id: this.replicationStreamId },
136
- {
137
- $set: { last_fatal_error: null, last_fatal_error_ts: null }
363
+ const clearError = !this.clearedError && hasWrites;
364
+ const publish = async (session: lib_mongo.mongo.ClientSession) => {
365
+ await this.publishPrepared(
366
+ lastOp,
367
+ contextProjection,
368
+ publications,
369
+ options,
370
+ async (stream, writes) => {
371
+ // An empty flush allocates no ID. Use the durable head from the
372
+ // fresh fence for its checkpoint and returned flushed operation.
373
+ if (lastOp === 0n) {
374
+ lastOp = this.persistedOpHead(stream);
375
+ }
376
+ if (clearError) {
377
+ writes.updateOne(
378
+ this.db.sync_rules,
379
+ { _id: this.replicationStreamId },
380
+ {
381
+ $set: { last_fatal_error: null, last_fatal_error_ts: null }
382
+ }
383
+ );
384
+ }
385
+ if (checkpointOp != null) {
386
+ this.queueCustomWriteCheckpoints(writes, checkpointOp, checkpoints);
387
+ }
388
+ if (publishCheckpoint) {
389
+ // Checkpoint decisions use this attempt's freshly fenced state.
390
+ await checkpoint(stream, lastOp, writes);
391
+ } else {
392
+ this.onReplicationTransactionFlush(writes, lastOp);
393
+ }
394
+ },
395
+ session
396
+ );
397
+ this.clearedError ||= clearError;
398
+ this.last_flushed_op = lastOp;
399
+ // markRecordUnavailable only synchronously queues connector-owned repair
400
+ // keys. It must not mutate input, perform async work, or re-enter storage:
401
+ // publication is serialized, but queued publication does not hold the
402
+ // writer mutex. Delivery must finish before flush() returns;
403
+ // WalStream drains that queue before commit()/ack().
404
+ // Once committed, these writes cannot be rolled back if the callback
405
+ // throws. Invalidate the whole local lease before publication completes, so
406
+ // no writer sharing it (including queued calls) can advance progress
407
+ // past an undelivered repair. A fresh replication attempt must replay
408
+ // from the old source position and redetect incomplete rows.
409
+ try {
410
+ const notify = this.markRecordUnavailable;
411
+ if (notify != null) {
412
+ for (const record of repairs) {
413
+ notify(record);
138
414
  }
139
- );
140
- }
141
- if (checkpointOp != null) {
142
- this.queueCustomWriteCheckpoints(writes, checkpointOp, checkpoints);
143
- }
144
- if (checkpoint != null && prepared.resumeBatch == null) {
145
- // Checkpoint decisions use this attempt's freshly fenced state.
146
- await checkpoint(stream, lastOp, writes);
147
- } else {
148
- this.onReplicationTransactionFlush(writes, lastOp);
149
- }
150
- });
151
- this.batch = prepared.resumeBatch;
152
- this.write_checkpoint_batch.splice(0, checkpoints.length);
153
- this.clearedError ||= clearError;
154
- this.last_flushed_op = lastOp;
155
- // markRecordUnavailable only synchronously queues connector-owned repair
156
- // keys. It must not mutate input, perform async work, or re-enter storage:
157
- // the writer mutex is still held. Delivery must finish before flush() returns;
158
- // WalStream drains that queue before commit()/ack().
159
- // Once committed, these writes cannot be rolled back if the callback
160
- // throws. Invalidate the whole local lease while the mutex is held, so
161
- // no writer sharing it (including queued calls) can advance progress
162
- // past an undelivered repair. A fresh replication attempt must replay
163
- // from the old source position and redetect incomplete rows.
164
- try {
165
- const notify = this.markRecordUnavailable;
166
- if (notify != null) {
167
- for (const record of prepared.repairs) {
168
- notify(record);
169
415
  }
416
+ } catch (error) {
417
+ this.options.replicationLock.invalidate(
418
+ new ReplicationAbortedError(
419
+ 'Committed replication repair notification failed; restart replication before advancing source progress',
420
+ error
421
+ )
422
+ );
423
+ throw error;
170
424
  }
171
- } catch (error) {
172
- this.options.replicationLock.invalidate(
173
- new ReplicationAbortedError(
174
- 'Committed replication repair notification failed; restart replication before advancing source progress',
175
- error
176
- )
425
+ await this.hooks?.afterBatchFlush?.(this);
426
+ };
427
+ // Repairs stay synchronous so the connector can repair rows before source
428
+ // progress advances. Ordinary rows may pipeline even for repair-capable sources.
429
+ const shouldQueue = this.enqueuePublication && repairs.length === 0;
430
+ if (shouldQueue) {
431
+ await this.pipeline.capacity(retainedBytes);
432
+ this.capturedInput = resumeBatch;
433
+ this.pendingPublications++;
434
+ const receipt = this.pipeline.enqueue(
435
+ changes,
436
+ retainedBytes,
437
+ async () => {
438
+ for (const publication of publications) {
439
+ await publication.packAndUploadPayloads();
440
+ }
441
+ },
442
+ publish
177
443
  );
178
- throw error;
444
+ void receipt
445
+ .finally(() => {
446
+ this.pendingPublications--;
447
+ })
448
+ .catch(() => {});
449
+ return null;
179
450
  }
180
- await this.hooks?.afterBatchFlush?.(this);
451
+ await this.pipeline.drain();
452
+ await publish(this.session);
453
+ this.capturedInput = resumeBatch;
181
454
  return { flushed_op: lastOp };
182
455
  }
183
456
 
@@ -189,7 +462,7 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
189
462
  }
190
463
 
191
464
  /**
192
- * Internal publisher: the public operation holds the mutex through commit.
465
+ * Internal publisher: called either by a durable barrier or by the lease FIFO.
193
466
  * finish() must only queue writes independent of the final data group, using
194
467
  * the fresh fence and planned IDs; it must not execute the supplied batch or
195
468
  * read results from unpublished data. Activation and cleanup remain separate.
@@ -199,20 +472,23 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
199
472
  projection: lib_mongo.mongo.Document,
200
473
  publications: PreparedPublication[],
201
474
  options: storage.BatchBucketFlushOptions | undefined,
202
- finish: (stream: ReplicationStreamDocumentV3, writes: MongoWriteBatch) => Promise<void>
475
+ finish: (stream: ReplicationStreamDocumentV3, writes: MongoWriteBatch) => Promise<void>,
476
+ session = this.session
203
477
  ): Promise<void> {
478
+ const tracer = session === this.session ? this.tracer : this.pipeline.tracer;
204
479
  // This gate covers every sealed batch in the prefix, including truncate/drop.
205
480
  // The transaction must never wait for source reads, evaluation or S3 PUTs.
206
- // Sequential preparation also avoids leaving another group's uploads running
207
- // when one group fails; each group's readiness joins all of its own uploads.
208
- for (const publication of publications) {
209
- await publication.preparePayloads();
210
- }
481
+ // Queued work can pack/upload ahead of its publication turn. This idempotent
482
+ // gate also handles synchronous flushes and truncate/drop, which start their
483
+ // payload work here. Every upload must finish before opening the transaction.
211
484
  let attempts = 0;
212
485
  const retryDeadline = Date.now() + 90_000;
213
486
  try {
487
+ for (const publication of publications) {
488
+ await publication.packAndUploadPayloads();
489
+ }
214
490
  await this.withFencedTransaction(
215
- () => this.fence(this.session, projection),
491
+ () => this.fence(session, projection),
216
492
  async (document) => {
217
493
  attempts++;
218
494
  if (attempts > 20 && Date.now() > retryDeadline) {
@@ -230,25 +506,26 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
230
506
  // Preserve their execution order; only the final group's writes are
231
507
  // independent of the head/checkpoint tail built from this fresh fence.
232
508
  for (const publication of publications.slice(0, -1)) {
233
- using _persist = this.tracer.span('storage', 'persist_flush');
234
- await publication.publish(this.session, options);
509
+ using _persist = tracer.span('storage', 'persist_flush');
510
+ await publication.publish(session, options);
235
511
  }
236
- const writes = this.db.createWriteBatch(this.session, { ordered: false });
512
+ const writes = this.db.createWriteBatch(session, { ordered: false });
237
513
  await finish(stream, writes);
238
514
  const finalPublication = publications.at(-1);
239
515
  if (finalPublication != null) {
240
- using _persist = this.tracer.span('storage', 'persist_flush');
241
- await finalPublication.publish(this.session, options, writes);
516
+ using _persist = tracer.span('storage', 'persist_flush');
517
+ await finalPublication.publish(session, options, writes);
242
518
  } else {
243
519
  await writes.execute();
244
520
  }
245
521
  },
246
- this.session,
247
- 'Publishing prepared work'
522
+ session,
523
+ 'Publishing prepared work',
524
+ tracer
248
525
  );
249
526
  } catch (error) {
250
- // Publication failed after the driver's retries or our attempt limit.
251
- // Leave uploaded objects and markers alone: the commit may have succeeded.
527
+ // Packing, upload or MongoDB publication failed. Marker registration or the
528
+ // commit may have succeeded, so leave uploaded objects and markers alone.
252
529
  // Stop every writer on this lease and recover from persisted source progress.
253
530
  this.options.replicationLock.invalidate(
254
531
  new ReplicationAbortedError('Publication failed; restart replication from persisted progress', error)
@@ -257,17 +534,31 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
257
534
  }
258
535
  }
259
536
 
260
- private async prepareRows(session: lib_mongo.mongo.ClientSession, input: OperationBatch | null) {
537
+ private async prepareRows(
538
+ session: lib_mongo.mongo.ClientSession,
539
+ input: OperationBatch | null,
540
+ overlay: ReadonlyMap<string, LoadedSourceRecord>
541
+ ): Promise<PreparedRows> {
261
542
  const publications: PreparedPublication[] = [];
262
543
  const repairs: storage.SaveUpdate[] = [];
263
544
  let resumeBatch: OperationBatch | null = null;
264
545
  let lastOp = 0n;
265
546
  let hasWrites = false;
547
+ let retainedBytes = 0;
548
+ const changes = new Map<string, LoadedSourceRecord>();
266
549
  if (input == null) {
267
- return { publications, repairs, resumeBatch, lastOp, hasWrites };
550
+ return {
551
+ publications,
552
+ repairs,
553
+ resumeBatch,
554
+ lastOp,
555
+ hasWrites,
556
+ changes,
557
+ retainedBytes
558
+ };
268
559
  }
269
560
  using _preparation = this.tracer.span('storage', 'prepare');
270
- const allocator = this.options.opIdAllocator;
561
+ const allocator = this.pipeline.allocator;
271
562
  let sizes: Map<string, number> | undefined;
272
563
  // Keep the existing size-based read partitioning, including per-table raw
273
564
  // data storage and snapshot skip-existing exceptions. Move these reads;
@@ -284,10 +575,19 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
284
575
  .map((op) => ({ sourceTableId: mongoTableId(op.record.sourceTable.id), replicaId: op.beforeId }))
285
576
  );
286
577
  }
287
- // Only this bounded publication's observations/evaluated rows are retained.
288
- // No state is shared with another pending publication or another writer.
289
- const records = new Map<string, LoadedSourceRecord | null>();
578
+ // The predecessor's immutable delta overrides durable records. Its lifetime
579
+ // is pinned through this preparation, including reads that straddle commit.
580
+ for (const [key, record] of overlay) {
581
+ sizes?.set(key, record.data?.length() ?? 0);
582
+ }
583
+ const records = new Map<string, LoadedSourceRecord | null>(overlay);
290
584
  let writtenSize = 0;
585
+ // Sealing is pure. After capacity is checked and ownership transfers to the
586
+ // pipeline, packing/uploads can overlap the predecessor's remaining work.
587
+ const prepareGroup = (group: PersistedBatchV3) => {
588
+ retainedBytes += group.estimatedRetainedBytes;
589
+ publications.push(group.seal());
590
+ };
291
591
  for (const block of input.batched(sizes)) {
292
592
  if (resumeBatch != null) {
293
593
  for (const op of block) {
@@ -295,6 +595,8 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
295
595
  }
296
596
  continue;
297
597
  }
598
+ this.options.replicationLock.throwIfAborted();
599
+ this.pipeline.advanceReadTime();
298
600
  const missing = block.filter((op) => !records.has(op.internalBeforeKey));
299
601
  if (missing.length > 0) {
300
602
  using _lookup = this.tracer.span('storage', 'lookup');
@@ -343,7 +645,7 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
343
645
  if (!(error instanceof OpIdRangeExhausted)) {
344
646
  throw error;
345
647
  }
346
- // Retry only the unfinished row; no payload has been uploaded yet.
648
+ // Retry only the unfinished row; its payload has not been uploaded.
347
649
  this.options.replicationLock.throwIfAborted();
348
650
  await allocator.reserve();
349
651
  }
@@ -352,30 +654,69 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
352
654
  // Preserve evaluation's existing repeated-row behavior: a deleted
353
655
  // identity no longer supplies raw values or membership to later rows.
354
656
  records.set(op.internalBeforeKey, null);
657
+ // Persisted soft deletes still exist for snapshot skip-existing
658
+ // lookups, even though repeated streaming updates use empty state.
659
+ changes.set(op.internalBeforeKey, {
660
+ sourceTableId: mongoTableId(op.record.sourceTable.id),
661
+ replicaId: op.beforeId,
662
+ cacheKey: op.internalBeforeKey,
663
+ data: null,
664
+ buckets: [],
665
+ lookups: []
666
+ });
355
667
  }
356
668
  if (next != null) {
357
669
  records.set(op.internalAfterKey!, next);
670
+ changes.set(op.internalAfterKey!, next);
358
671
  sizes?.set(op.internalAfterKey!, next.data?.length() ?? 0);
359
672
  }
360
673
  if (group!.shouldFlushTransaction()) {
361
- publications.push(group!.seal());
674
+ prepareGroup(group!);
362
675
  group = null;
363
- resumeBatch = new OperationBatch();
676
+ resumeBatch = new OperationBatch(this.options.batchLimits);
364
677
  }
365
678
  }
366
679
  if (group != null) {
367
680
  writtenSize = group.currentSize;
368
- publications.push(group.seal());
681
+ prepareGroup(group);
369
682
  }
370
683
  }
371
- return { publications, repairs, resumeBatch: resumeBatch?.hasData() ? resumeBatch : null, lastOp, hasWrites };
684
+ return {
685
+ publications,
686
+ repairs,
687
+ resumeBatch: resumeBatch?.hasData() ? resumeBatch : null,
688
+ lastOp,
689
+ hasWrites,
690
+ changes,
691
+ retainedBytes
692
+ };
693
+ }
694
+
695
+ protected override async truncateInternal(
696
+ sourceTables: storage.SourceTable[]
697
+ ): Promise<storage.FlushedResult | null> {
698
+ // The metadata barrier has already published every captured input. Rows
699
+ // buffered after that boundary belong to later operations and stay untouched.
700
+
701
+ let last_op: InternalOpId | null = null;
702
+ for (let table of sourceTables) {
703
+ last_op = await this.truncateSingleInternal(table);
704
+ }
705
+
706
+ if (last_op) {
707
+ return {
708
+ flushed_op: last_op
709
+ };
710
+ } else {
711
+ return null;
712
+ }
372
713
  }
373
714
 
374
715
  protected override async truncateSingleInternal(sourceTable: storage.SourceTable): Promise<InternalOpId> {
375
716
  const sourceId = mongoTableId(sourceTable.id);
376
717
  const session = this.session;
377
718
  const projection = { state: 1, sync_configs: 1, last_persisted_op: 1 };
378
- const allocator = this.options.opIdAllocator;
719
+ const allocator = this.pipeline.allocator;
379
720
  while (true) {
380
721
  await allocator.ensureCapacity();
381
722
  // Preserve the existing bounded table scan. Hard deletion lets the next
@@ -648,17 +989,6 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
648
989
  options?: storage.BucketBatchCommitOptions
649
990
  ): Promise<storage.CheckpointResult> {
650
991
  this.options.replicationLock.throwIfAborted();
651
- if (this.markRecordUnavailable != null && this.batch?.hasData()) {
652
- // A combined data+checkpoint commit cannot return control to the connector
653
- // to process repair notifications between those two durable boundaries.
654
- // Require its explicit flush -> repair -> commit ordering even when this
655
- // particular input might turn out not to need repair. An empty batch does
656
- // not prove its external repair queue is drained; that remains the caller's
657
- // responsibility. keepalive() delegates here and has the same requirement.
658
- throw new ReplicationAssertionError(
659
- 'Flush pending rows and process markRecordUnavailable repairs before committing source progress'
660
- );
661
- }
662
992
  const { createEmptyCheckpoints } = { ...storage.DEFAULT_BUCKET_BATCH_COMMIT_OPTIONS, ...options };
663
993
 
664
994
  using _ = this.tracer.span('storage', 'commit');
@@ -1084,12 +1414,14 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
1084
1414
  }
1085
1415
  }
1086
1416
 
1087
- protected override async prepareCustomWriteCheckpoints(): Promise<void> {
1417
+ protected override async prepareCustomWriteCheckpoints(
1418
+ checkpoints: readonly storage.CustomWriteCheckpointOptions[]
1419
+ ): Promise<void> {
1088
1420
  // Most events never produce custom checkpoints, so create collections lazily
1089
1421
  // only for the event ids present in this batch. This hook runs before the
1090
1422
  // replication transaction because MongoDB cannot create indexes within it.
1091
1423
  const eventIds = new Set(
1092
- this.write_checkpoint_batch.map((checkpoint) => this.validateCustomCheckpointEventId(checkpoint.event_id))
1424
+ checkpoints.map((checkpoint) => this.validateCustomCheckpointEventId(checkpoint.event_id))
1093
1425
  );
1094
1426
  for (const eventId of eventIds) {
1095
1427
  if (this.initializedCustomCheckpointEventIds.has(eventId)) {