@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
@@ -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,25 +472,44 @@ 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
- const retryDeadline = Date.now() + 90_000;
485
+ const startedAt = Date.now();
213
486
  try {
487
+ for (const publication of publications) {
488
+ await publication.packAndUploadPayloads();
489
+ }
490
+ // Groups can update the same bucket. Preserve the order of their deltas
491
+ // and reuse the same write models on every transaction attempt.
492
+ const bucketStates = this.db.createWriteBatch(session, { ordered: true });
493
+ for (const publication of publications) {
494
+ publication.queueBucketStates(bucketStates);
495
+ }
214
496
  await this.withFencedTransaction(
215
- () => this.fence(this.session, projection),
216
- async (document) => {
217
- attempts++;
218
- if (attempts > 20 && Date.now() > retryDeadline) {
219
- throw new ServiceError(ErrorCode.PSYNC_S1402, 'Max transaction tries exceeded');
497
+ async () => {
498
+ const elapsedMs = Date.now() - startedAt;
499
+ if (attempts >= 20 && elapsedMs > 90_000) {
500
+ throw new ServiceError(
501
+ ErrorCode.PSYNC_S1402,
502
+ `Publication retry limit reached after ${attempts} attempts (${elapsedMs} ms since publication started)`
503
+ );
220
504
  }
505
+ attempts++;
506
+ // Start with the bucket writes to minimize the time compaction has
507
+ // to modify them after the transaction starts. The fence still
508
+ // protects the entire transaction, including these writes.
509
+ await tracer.span('storage', 'publish_bucket_state').with(() => bucketStates.execute());
510
+ return tracer.span('storage', 'publish_fence').with(() => this.fence(session, projection));
511
+ },
512
+ async (document) => {
221
513
  const stream = document as ReplicationStreamDocumentV3;
222
514
  this.assertPreparationContext(stream);
223
515
  const head = this.persistedOpHead(stream);
@@ -226,29 +518,30 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
226
518
  `Prepared operation ${lastOp} does not advance persisted stream head ${head}`
227
519
  );
228
520
  }
229
- // Earlier groups may replace the same source record or bucket state.
521
+ // Earlier groups may replace the same source record.
230
522
  // Preserve their execution order; only the final group's writes are
231
523
  // independent of the head/checkpoint tail built from this fresh fence.
232
524
  for (const publication of publications.slice(0, -1)) {
233
- using _persist = this.tracer.span('storage', 'persist_flush');
234
- await publication.publish(this.session, options);
525
+ using _persist = tracer.span('storage', 'persist_flush');
526
+ await publication.publish(session, options);
235
527
  }
236
- const writes = this.db.createWriteBatch(this.session, { ordered: false });
528
+ const writes = this.db.createWriteBatch(session, { ordered: false });
237
529
  await finish(stream, writes);
238
530
  const finalPublication = publications.at(-1);
239
531
  if (finalPublication != null) {
240
- using _persist = this.tracer.span('storage', 'persist_flush');
241
- await finalPublication.publish(this.session, options, writes);
532
+ using _persist = tracer.span('storage', 'persist_flush');
533
+ await finalPublication.publish(session, options, writes);
242
534
  } else {
243
535
  await writes.execute();
244
536
  }
245
537
  },
246
- this.session,
247
- 'Publishing prepared work'
538
+ session,
539
+ 'Publishing prepared work',
540
+ tracer
248
541
  );
249
542
  } 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.
543
+ // Packing, upload or MongoDB publication failed. Marker registration or the
544
+ // commit may have succeeded, so leave uploaded objects and markers alone.
252
545
  // Stop every writer on this lease and recover from persisted source progress.
253
546
  this.options.replicationLock.invalidate(
254
547
  new ReplicationAbortedError('Publication failed; restart replication from persisted progress', error)
@@ -257,17 +550,31 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
257
550
  }
258
551
  }
259
552
 
260
- private async prepareRows(session: lib_mongo.mongo.ClientSession, input: OperationBatch | null) {
553
+ private async prepareRows(
554
+ session: lib_mongo.mongo.ClientSession,
555
+ input: OperationBatch | null,
556
+ overlay: ReadonlyMap<string, LoadedSourceRecord>
557
+ ): Promise<PreparedRows> {
261
558
  const publications: PreparedPublication[] = [];
262
559
  const repairs: storage.SaveUpdate[] = [];
263
560
  let resumeBatch: OperationBatch | null = null;
264
561
  let lastOp = 0n;
265
562
  let hasWrites = false;
563
+ let retainedBytes = 0;
564
+ const changes = new Map<string, LoadedSourceRecord>();
266
565
  if (input == null) {
267
- return { publications, repairs, resumeBatch, lastOp, hasWrites };
566
+ return {
567
+ publications,
568
+ repairs,
569
+ resumeBatch,
570
+ lastOp,
571
+ hasWrites,
572
+ changes,
573
+ retainedBytes
574
+ };
268
575
  }
269
576
  using _preparation = this.tracer.span('storage', 'prepare');
270
- const allocator = this.options.opIdAllocator;
577
+ const allocator = this.pipeline.allocator;
271
578
  let sizes: Map<string, number> | undefined;
272
579
  // Keep the existing size-based read partitioning, including per-table raw
273
580
  // data storage and snapshot skip-existing exceptions. Move these reads;
@@ -284,10 +591,19 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
284
591
  .map((op) => ({ sourceTableId: mongoTableId(op.record.sourceTable.id), replicaId: op.beforeId }))
285
592
  );
286
593
  }
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>();
594
+ // The predecessor's immutable delta overrides durable records. Its lifetime
595
+ // is pinned through this preparation, including reads that straddle commit.
596
+ for (const [key, record] of overlay) {
597
+ sizes?.set(key, record.data?.length() ?? 0);
598
+ }
599
+ const records = new Map<string, LoadedSourceRecord | null>(overlay);
290
600
  let writtenSize = 0;
601
+ // Sealing is pure. After capacity is checked and ownership transfers to the
602
+ // pipeline, packing/uploads can overlap the predecessor's remaining work.
603
+ const prepareGroup = (group: PersistedBatchV3) => {
604
+ retainedBytes += group.estimatedRetainedBytes;
605
+ publications.push(group.seal());
606
+ };
291
607
  for (const block of input.batched(sizes)) {
292
608
  if (resumeBatch != null) {
293
609
  for (const op of block) {
@@ -295,6 +611,8 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
295
611
  }
296
612
  continue;
297
613
  }
614
+ this.options.replicationLock.throwIfAborted();
615
+ this.pipeline.advanceReadTime();
298
616
  const missing = block.filter((op) => !records.has(op.internalBeforeKey));
299
617
  if (missing.length > 0) {
300
618
  using _lookup = this.tracer.span('storage', 'lookup');
@@ -343,7 +661,7 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
343
661
  if (!(error instanceof OpIdRangeExhausted)) {
344
662
  throw error;
345
663
  }
346
- // Retry only the unfinished row; no payload has been uploaded yet.
664
+ // Retry only the unfinished row; its payload has not been uploaded.
347
665
  this.options.replicationLock.throwIfAborted();
348
666
  await allocator.reserve();
349
667
  }
@@ -352,30 +670,69 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
352
670
  // Preserve evaluation's existing repeated-row behavior: a deleted
353
671
  // identity no longer supplies raw values or membership to later rows.
354
672
  records.set(op.internalBeforeKey, null);
673
+ // Persisted soft deletes still exist for snapshot skip-existing
674
+ // lookups, even though repeated streaming updates use empty state.
675
+ changes.set(op.internalBeforeKey, {
676
+ sourceTableId: mongoTableId(op.record.sourceTable.id),
677
+ replicaId: op.beforeId,
678
+ cacheKey: op.internalBeforeKey,
679
+ data: null,
680
+ buckets: [],
681
+ lookups: []
682
+ });
355
683
  }
356
684
  if (next != null) {
357
685
  records.set(op.internalAfterKey!, next);
686
+ changes.set(op.internalAfterKey!, next);
358
687
  sizes?.set(op.internalAfterKey!, next.data?.length() ?? 0);
359
688
  }
360
689
  if (group!.shouldFlushTransaction()) {
361
- publications.push(group!.seal());
690
+ prepareGroup(group!);
362
691
  group = null;
363
- resumeBatch = new OperationBatch();
692
+ resumeBatch = new OperationBatch(this.options.batchLimits);
364
693
  }
365
694
  }
366
695
  if (group != null) {
367
696
  writtenSize = group.currentSize;
368
- publications.push(group.seal());
697
+ prepareGroup(group);
369
698
  }
370
699
  }
371
- return { publications, repairs, resumeBatch: resumeBatch?.hasData() ? resumeBatch : null, lastOp, hasWrites };
700
+ return {
701
+ publications,
702
+ repairs,
703
+ resumeBatch: resumeBatch?.hasData() ? resumeBatch : null,
704
+ lastOp,
705
+ hasWrites,
706
+ changes,
707
+ retainedBytes
708
+ };
709
+ }
710
+
711
+ protected override async truncateInternal(
712
+ sourceTables: storage.SourceTable[]
713
+ ): Promise<storage.FlushedResult | null> {
714
+ // The metadata barrier has already published every captured input. Rows
715
+ // buffered after that boundary belong to later operations and stay untouched.
716
+
717
+ let last_op: InternalOpId | null = null;
718
+ for (let table of sourceTables) {
719
+ last_op = await this.truncateSingleInternal(table);
720
+ }
721
+
722
+ if (last_op) {
723
+ return {
724
+ flushed_op: last_op
725
+ };
726
+ } else {
727
+ return null;
728
+ }
372
729
  }
373
730
 
374
731
  protected override async truncateSingleInternal(sourceTable: storage.SourceTable): Promise<InternalOpId> {
375
732
  const sourceId = mongoTableId(sourceTable.id);
376
733
  const session = this.session;
377
734
  const projection = { state: 1, sync_configs: 1, last_persisted_op: 1 };
378
- const allocator = this.options.opIdAllocator;
735
+ const allocator = this.pipeline.allocator;
379
736
  while (true) {
380
737
  await allocator.ensureCapacity();
381
738
  // Preserve the existing bounded table scan. Hard deletion lets the next
@@ -648,17 +1005,6 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
648
1005
  options?: storage.BucketBatchCommitOptions
649
1006
  ): Promise<storage.CheckpointResult> {
650
1007
  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
1008
  const { createEmptyCheckpoints } = { ...storage.DEFAULT_BUCKET_BATCH_COMMIT_OPTIONS, ...options };
663
1009
 
664
1010
  using _ = this.tracer.span('storage', 'commit');
@@ -1084,12 +1430,14 @@ export class MongoBucketBatchV3 extends MongoBucketBatch {
1084
1430
  }
1085
1431
  }
1086
1432
 
1087
- protected override async prepareCustomWriteCheckpoints(): Promise<void> {
1433
+ protected override async prepareCustomWriteCheckpoints(
1434
+ checkpoints: readonly storage.CustomWriteCheckpointOptions[]
1435
+ ): Promise<void> {
1088
1436
  // Most events never produce custom checkpoints, so create collections lazily
1089
1437
  // only for the event ids present in this batch. This hook runs before the
1090
1438
  // replication transaction because MongoDB cannot create indexes within it.
1091
1439
  const eventIds = new Set(
1092
- this.write_checkpoint_batch.map((checkpoint) => this.validateCustomCheckpointEventId(checkpoint.event_id))
1440
+ checkpoints.map((checkpoint) => this.validateCustomCheckpointEventId(checkpoint.event_id))
1093
1441
  );
1094
1442
  for (const eventId of eventIds) {
1095
1443
  if (this.initializedCustomCheckpointEventIds.has(eventId)) {