@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
@@ -2,7 +2,7 @@ import { mongo } from '@powersync/lib-service-mongodb';
2
2
  import { ReplicationAssertionError, ServiceAssertionError } from '@powersync/lib-services-framework';
3
3
  import { acquireSemaphoreAbortable, addChecksums, formatBytes, InternalOpId, utils } from '@powersync/service-core';
4
4
  import { BucketDefinitionId } from '@powersync/service-sync-rules';
5
- import { setImmediate } from 'node:timers/promises';
5
+ import { setImmediate, setTimeout } from 'node:timers/promises';
6
6
  import { BucketDataDoc } from '../common/BucketDataDoc.js';
7
7
  import { BucketDataKey } from '../models.js';
8
8
  import { ConcurrentCompactionError, MongoCompactOptions, MongoCompactor } from '../MongoCompactor.js';
@@ -27,6 +27,8 @@ import {
27
27
  CompactTargetConfig,
28
28
  emptyBucketStats,
29
29
  firstUncompactedWrite,
30
+ FULL_COMPACT_RESCHEDULE_MARGIN_MS,
31
+ fullCompactionCheckAt,
30
32
  PendingCompactionGroup,
31
33
  readCompactionBatch,
32
34
  ScheduledCompactionOptions,
@@ -35,7 +37,7 @@ import {
35
37
  unclaimedSnapshotFilter
36
38
  } from './compact-utils.js';
37
39
  import { DEFAULT_MIN_COMPACT_CHUNK_INTERVAL_MS } from './compaction-constants.js';
38
- import { AVAILABLE_LEASE_EXPR, CompactionLease } from './CompactionLease.js';
40
+ import { AVAILABLE_LEASE_EXPR, CompactionLease, withBucketStateTransaction } from './CompactionLease.js';
39
41
  import { BucketDataDocumentV3, BucketStateDocumentV3 } from './models.js';
40
42
  import type { MongoSyncBucketStorageV3 } from './MongoSyncBucketStorageV3.js';
41
43
  import { BucketDataObjectStorage, hydrateBucketDataDocuments } from './object-storage/BucketDataObjectStorage.js';
@@ -47,6 +49,14 @@ const DEFAULT_MIN_COMPACT_FULL_INTERVAL_MS = 2 * 60 * 60 * 1000;
47
49
  const DEFAULT_MAX_COMPACT_FULL_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
48
50
  const DEFAULT_COMPACT_LEASE_DURATION_MS = 10 * 60 * 1000;
49
51
  const SCHEDULED_COMPACTION_BATCH_SIZE = 100;
52
+ const MIN_CHUNK_LEASE_GROUP_SIZE = 32;
53
+ const MAX_CHUNK_GROUP_PAUSE_MS = 50;
54
+
55
+ interface BucketCompactionUpdate {
56
+ fields: mongo.Document;
57
+ /** Present when the bucket was compacted, absent for a reschedule. */
58
+ completedMessage?: string;
59
+ }
50
60
 
51
61
  interface CompactionGroupResult {
52
62
  documentId: BucketDataKey;
@@ -154,7 +164,8 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
154
164
  continue;
155
165
  }
156
166
  const decision = chooseCompactionKind(lease.state, lease.startedAt, this);
157
- await this.compactClaimedBucket(lease, CompactionKind.Full, decision);
167
+ const update = await this.compactClaimedBucket(lease, CompactionKind.Full, decision);
168
+ await this.publishSingleBucket(lease, update);
158
169
  }
159
170
  }
160
171
  }
@@ -189,6 +200,7 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
189
200
  { length: this.storage.factory.chunkCompactionConcurrency },
190
201
  () => new ObjectStorageUsage(this.db, this.group_id, createObjectStorageUsageWriterId())
191
202
  );
203
+ const groupSize = Math.max(MIN_CHUNK_LEASE_GROUP_SIZE, workerUsage.length);
192
204
  while (true) {
193
205
  this.signal?.throwIfAborted();
194
206
  const states = await this.findScheduledBucketBatch(dueBefore);
@@ -199,91 +211,170 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
199
211
  // server time so buckets that age into full compaction can advance.
200
212
  const batchStartedAt = await this.readCompactionTime();
201
213
 
202
- const scheduled: {
203
- state: BucketStateDocumentV3;
204
- decision: CompactionDecision;
205
- selectedKind: CompactionKind | null;
206
- }[] = [];
214
+ const noOpStates: { state: BucketStateDocumentV3; decision: CompactionDecision }[] = [];
215
+ const chunkBuckets: BucketStateDocumentV3[] = [];
216
+ const sequentialBuckets: BucketStateDocumentV3[] = [];
207
217
  for (const state of states) {
208
218
  try {
209
- scheduled.push({
210
- state,
211
- decision: chooseCompactionKind(state, batchStartedAt, this),
212
- selectedKind: chooseRequestedCompactionKind(state, requestedKind, this)
213
- });
219
+ const decision = chooseCompactionKind(state, batchStartedAt, this);
220
+ const kind =
221
+ requestedKind == null ? decision.kind : chooseRequestedCompactionKind(state, requestedKind, this);
222
+ // A due bucket may already cover this run's checkpoint. Reschedule
223
+ // from the snapshot unless an expired lease needs to be reclaimed.
224
+ if (state.compact_lease == null && (kind == null || this.isCompactionTargetCovered(state, kind))) {
225
+ noOpStates.push({ state, decision });
226
+ } else if (kind === CompactionKind.Chunks) {
227
+ chunkBuckets.push(state);
228
+ } else {
229
+ sequentialBuckets.push(state);
230
+ }
214
231
  } catch (error) {
215
232
  await this.rescheduleFailedBucket(state, rescheduleNotBefore, error);
216
233
  }
217
234
  }
218
- const noOpStates = scheduled.filter(
219
- ({ state, decision, selectedKind }) =>
220
- state.compact_lease == null && (requestedKind == null ? decision.kind : selectedKind) == null
221
- );
222
235
  await this.rescheduleUnclaimedBuckets(noOpStates, rescheduleNotBefore);
223
236
 
224
- const processBucket = async (
225
- { state, decision, selectedKind }: (typeof scheduled)[number],
226
- objectStorageUsage: ObjectStorageUsage,
227
- chunksOnly = false
228
- ) => {
229
- const kind = requestedKind == null ? decision.kind : selectedKind;
230
- if (state.compact_lease == null && kind == null) {
231
- return;
232
- }
233
-
237
+ // One group can use every configured worker. Publish and release its
238
+ // leases before claiming the next group.
239
+ for (let i = 0; i < chunkBuckets.length; i += groupSize) {
240
+ await this.compactChunkGroup(
241
+ chunkBuckets.slice(i, i + groupSize),
242
+ workerUsage,
243
+ dueBefore,
244
+ requestedKind,
245
+ rescheduleNotBefore
246
+ );
247
+ // Give replication a window to update bucket state after releasing the group's leases.
248
+ await setTimeout(Math.random() * MAX_CHUNK_GROUP_PAUSE_MS, undefined, { signal: this.signal });
249
+ }
250
+ // Full compaction cannot overlap chunk workers from this job, and only
251
+ // one full bucket is processed at a time.
252
+ for (const state of sequentialBuckets) {
234
253
  try {
254
+ this.signal?.throwIfAborted();
235
255
  await using lease = await this.claimBucket({ _id: state._id, next_compact_check: { $lte: dueBefore } });
236
256
  if (lease == null) {
237
- return;
238
- }
239
- const claimedDecision = chooseCompactionKind(lease.state, lease.startedAt, this);
240
- const claimedKind =
241
- requestedKind == null
242
- ? claimedDecision.kind
243
- : chooseRequestedCompactionKind(lease.state, requestedKind, this);
244
- if (chunksOnly && claimedKind === CompactionKind.Full) {
245
- // The decision changed after scanning. Release the lease without
246
- // rescheduling; the next batch will classify it with a fresh timestamp.
247
- return;
257
+ continue;
248
258
  }
249
- if (claimedKind == null) {
250
- await this.rescheduleClaimedBucket(lease, claimedDecision, rescheduleNotBefore);
251
- } else if (this.isCompactionTargetCovered(lease.state, claimedKind)) {
252
- // The run cannot advance this kind's watermark without regressing
253
- // already-published progress. Keep any newer work scheduled.
254
- await this.rescheduleClaimedBucket(lease, claimedDecision, rescheduleNotBefore);
255
- } else {
256
- await this.compactClaimedBucket(
257
- lease,
258
- claimedKind,
259
- claimedDecision,
260
- rescheduleNotBefore,
261
- objectStorageUsage
262
- );
259
+ const update = await this.processScheduledLease(
260
+ lease,
261
+ requestedKind,
262
+ rescheduleNotBefore,
263
+ this.objectStorageUsage,
264
+ false
265
+ );
266
+ if (update != null) {
267
+ await this.publishSingleBucket(lease, update);
263
268
  }
264
269
  } catch (error) {
265
270
  if (this.signal?.aborted) {
266
- // When aborted, stop completely, rather than logging and re-scheduling individual buckets.
267
- // The lease on the current bucket is still released automatically.
268
271
  throw error;
269
272
  }
270
273
  await this.rescheduleFailedBucket(state, rescheduleNotBefore, error);
271
274
  }
275
+ }
276
+ }
277
+ }
278
+
279
+ private async processScheduledLease(
280
+ lease: CompactionLease,
281
+ requestedKind: CompactionKind | undefined,
282
+ rescheduleNotBefore: Date,
283
+ usage: ObjectStorageUsage,
284
+ chunksOnly: boolean
285
+ ): Promise<BucketCompactionUpdate | undefined> {
286
+ await lease.throwIfLost();
287
+ const decision = chooseCompactionKind(lease.state, lease.startedAt, this);
288
+ const kind =
289
+ requestedKind == null ? decision.kind : chooseRequestedCompactionKind(lease.state, requestedKind, this);
290
+ if (chunksOnly && kind === CompactionKind.Full) {
291
+ // The decision changed after scanning. Release without rescheduling so
292
+ // the next batch can classify it with a fresh timestamp.
293
+ return;
294
+ }
295
+ if (kind == null || this.isCompactionTargetCovered(lease.state, kind)) {
296
+ // The run cannot advance this kind's watermark. Keep any newer work scheduled.
297
+ return {
298
+ fields: { next_compact_check: this.rescheduleAtOrAfter(decision.nextCompactCheck, rescheduleNotBefore) }
272
299
  };
300
+ }
301
+ return this.compactClaimedBucket(lease, kind, decision, rescheduleNotBefore, usage);
302
+ }
273
303
 
274
- const chunkBuckets = scheduled.filter(
275
- ({ decision, selectedKind }) => (requestedKind == null ? decision.kind : selectedKind) === CompactionKind.Chunks
276
- );
277
- const sequentialBuckets = scheduled.filter(
278
- ({ decision, selectedKind }) => (requestedKind == null ? decision.kind : selectedKind) !== CompactionKind.Chunks
279
- );
280
- await this.runChunkCompactionWorkers(chunkBuckets, workerUsage, (entry, usage) =>
281
- processBucket(entry, usage, true)
282
- );
283
- // Full compaction cannot overlap chunk workers from this job, and only
284
- // one full bucket is processed at a time.
285
- for (const entry of sequentialBuckets) {
286
- await processBucket(entry, this.objectStorageUsage);
304
+ private async publishSingleBucket(lease: CompactionLease, update: BucketCompactionUpdate) {
305
+ await lease.finalize(update.fields);
306
+ if (update.completedMessage != null) {
307
+ this.compactedBucketCount++;
308
+ this.logger.info(update.completedMessage);
309
+ }
310
+ }
311
+
312
+ private async compactChunkGroup(
313
+ states: BucketStateDocumentV3[],
314
+ workerUsage: ObjectStorageUsage[],
315
+ dueBefore: Date,
316
+ requestedKind: CompactionKind | undefined,
317
+ rescheduleNotBefore: Date
318
+ ) {
319
+ this.signal?.throwIfAborted();
320
+ await using owned = new AsyncDisposableStack();
321
+ // Each claim returns the state it actually acquired. Renew immediately,
322
+ // including while waiting for sibling claims, a worker slot, or publication.
323
+ const claims = await Promise.allSettled(
324
+ states.map(async (state) => {
325
+ const lease = await this.claimBucket({ _id: state._id, next_compact_check: { $lte: dueBefore } });
326
+ return owned.use(lease);
327
+ })
328
+ );
329
+ const leases: CompactionLease[] = [];
330
+ for (const [i, claim] of claims.entries()) {
331
+ this.signal?.throwIfAborted();
332
+ if (claim.status === 'rejected') {
333
+ await this.rescheduleFailedBucket(states[i], rescheduleNotBefore, claim.reason);
334
+ } else if (claim.value != null) {
335
+ leases.push(claim.value);
336
+ }
337
+ }
338
+
339
+ const updates: (BucketCompactionUpdate & { lease: CompactionLease })[] = [];
340
+ try {
341
+ await this.runChunkCompactionWorkers(leases, workerUsage, async (lease, usage) => {
342
+ try {
343
+ const update = await this.processScheduledLease(lease, requestedKind, rescheduleNotBefore, usage, true);
344
+ await lease.throwIfLost();
345
+ if (update != null) {
346
+ updates.push({ lease, ...update });
347
+ }
348
+ } catch (error) {
349
+ if (this.signal?.aborted) {
350
+ throw error;
351
+ }
352
+ // Release before the snapshot-conditional reschedule. Concurrent
353
+ // replication or takeover must be able to invalidate that update.
354
+ await lease[Symbol.asyncDispose]();
355
+ await this.rescheduleFailedBucket(lease.state, rescheduleNotBefore, error);
356
+ }
357
+ });
358
+ } finally {
359
+ // Workers have drained, even on cancellation. Publish completed work
360
+ // before disposing unused leases.
361
+ const collection = this.db.bucketState(this.group_id);
362
+ const rescheduleFailed = (lease: CompactionLease, error: unknown) =>
363
+ this.rescheduleFailedBucket(lease.state, rescheduleNotBefore, error);
364
+ const completed = updates.filter((update) => update.completedMessage != null);
365
+ const matched = await CompactionLease.finalizeBatch(collection, updates, rescheduleFailed);
366
+ // A partial match in a mixed batch only gives an upper bound on published compactions.
367
+ this.compactedBucketCount += Math.min(completed.length, matched);
368
+ if (matched === updates.length) {
369
+ for (const update of completed) {
370
+ this.logger.info(update.completedMessage!);
371
+ }
372
+ } else {
373
+ // This happens when the job lost ownership of a bucket or MongoDB rejected an update.
374
+ // If this repeats, check for competing compaction jobs and earlier per-bucket errors.
375
+ this.logger.warn(
376
+ `Published ${matched} of ${updates.length} compaction updates to bucket_state. Remaining work will be retried when due.`
377
+ );
287
378
  }
288
379
  }
289
380
  }
@@ -314,7 +405,7 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
314
405
  const bucket = buckets[nextBucket++];
315
406
 
316
407
  // This pool bounds one job; the factory semaphore bounds all jobs together.
317
- // Acquire before claiming the bucket lease, and hold until it is released.
408
+ // The group owns its leases; only active chunk work needs a slot.
318
409
  const acquired = await acquireSemaphoreAbortable(this.storage.factory.chunkCompactionSlots, signal);
319
410
  if (acquired === 'aborted') {
320
411
  signal?.throwIfAborted();
@@ -323,7 +414,9 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
323
414
  const [, releaseSlot] = acquired;
324
415
  try {
325
416
  // A sibling may have failed while this worker waited for a slot.
326
- if (failed) return;
417
+ if (failed) {
418
+ return;
419
+ }
327
420
  signal?.throwIfAborted();
328
421
  await processBucket(bucket, usage);
329
422
  } finally {
@@ -343,9 +436,7 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
343
436
  // Reuse one writer for each worker instead of creating one per bucket.
344
437
  const workers = workerUsage.map(runWorker);
345
438
 
346
- // Do not release the caller's replication lock or run cleanup while a
347
- // sibling worker still owns a bucket lease or is finishing a replacement.
348
- // Wait for every worker even on failure, then propagate the first error.
439
+ // Drain every sibling before releasing leases, including on failure.
349
440
  const results = await Promise.allSettled(workers);
350
441
  for (const result of results) {
351
442
  if (result.status === 'rejected') {
@@ -380,14 +471,15 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
380
471
  if (states.length == 0) {
381
472
  return;
382
473
  }
383
- await this.db.bucketState(this.group_id).bulkWrite(
384
- states.map(({ state, decision }) => ({
385
- updateOne: {
386
- filter: unclaimedSnapshotFilter(state),
387
- update: [{ $set: { next_compact_check: this.rescheduleAtOrAfter(decision.nextCompactCheck, notBefore) } }]
388
- }
389
- })),
390
- { ordered: false }
474
+ const collection = this.db.bucketState(this.group_id);
475
+ const operations = states.map(({ state, decision }) => ({
476
+ updateOne: {
477
+ filter: unclaimedSnapshotFilter(state),
478
+ update: [{ $set: { next_compact_check: this.rescheduleAtOrAfter(decision.nextCompactCheck, notBefore) } }]
479
+ }
480
+ }));
481
+ await withBucketStateTransaction(collection, (session) =>
482
+ collection.bulkWrite(operations, { ordered: false, session })
391
483
  );
392
484
  }
393
485
 
@@ -433,12 +525,7 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
433
525
  rescheduleNotBefore,
434
526
  this.compactionTarget(lease.state)
435
527
  );
436
- lease.startRenewal();
437
- await this.compactSingleBucket(context, objectStorageUsage);
438
- }
439
-
440
- private async rescheduleClaimedBucket(lease: CompactionLease, decision: CompactionDecision, notBefore?: Date) {
441
- await lease.reschedule(this.rescheduleAtOrAfter(decision.nextCompactCheck, notBefore));
528
+ return this.compactSingleBucket(context, objectStorageUsage);
442
529
  }
443
530
 
444
531
  private rescheduleAtOrAfter(nextCompactCheck: mongo.Document, notBefore: Date | undefined): mongo.Document {
@@ -613,8 +700,7 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
613
700
  }
614
701
 
615
702
  if (compactedOpId == null) {
616
- await this.finalizeSkippedBucket(context);
617
- return;
703
+ return this.skippedBucketUpdate(context);
618
704
  }
619
705
 
620
706
  const compactedState =
@@ -630,11 +716,10 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
630
716
  bucketStats: tailStats == null ? compactedState : combineAdjacentStats(compactedState, tailStats)
631
717
  };
632
718
 
633
- await this.finalizeCompactedBucket({ context, compactedOpId, compactionResult: result, puts: 0 });
634
- this.compactedBucketCount++;
635
- this.logger.info(
636
- `Compacted bucket chunks ${bucket}: ${result.bucketStats.count} ops, ${result.bucketStats.chunks} chunks, ${formatBytes(result.bucketStats.bytes)}`
637
- );
719
+ return {
720
+ fields: this.compactedBucketFields({ context, compactedOpId, compactionResult: result, puts: 0 }),
721
+ completedMessage: `Compacted bucket chunks ${bucket}: ${result.bucketStats.count} ops, ${result.bucketStats.chunks} chunks, ${formatBytes(result.bucketStats.bytes)}`
722
+ };
638
723
  }
639
724
 
640
725
  private async flushChunkMerge(
@@ -695,7 +780,7 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
695
780
  }
696
781
  }
697
782
 
698
- private async finalizeCompactedBucket({
783
+ private compactedBucketFields({
699
784
  context,
700
785
  compactedOpId,
701
786
  compactionResult,
@@ -706,7 +791,6 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
706
791
  compactionResult: CompactionResult;
707
792
  puts: number;
708
793
  }) {
709
- await context.lease.throwIfLost();
710
794
  const startedStats = bucketStats(context.state);
711
795
  const delta = {
712
796
  count: compactionResult.bucketStats.count - startedStats.count,
@@ -720,15 +804,24 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
720
804
  { $dateAdd: { startDate: '$$NOW', unit: 'millisecond', amount: this.minCompactChunkIntervalMs } },
721
805
  context.rescheduleNotBefore
722
806
  );
723
- const nextCheckForUncompactedWork = this.rescheduleAtOrAfter(
724
- {
725
- $min: [
726
- new Date(firstUncompactedWrite(context.state).getTime() + this.maxCompactFullIntervalMs),
727
- { $dateAdd: { startDate: '$$NOW', unit: 'millisecond', amount: this.minCompactChunkIntervalMs } }
807
+ let nextChunkCheck: mongo.Document = {
808
+ $min: [
809
+ new Date(firstUncompactedWrite(context.state).getTime() + this.maxCompactFullIntervalMs),
810
+ { $dateAdd: { startDate: '$$NOW', unit: 'millisecond', amount: this.minCompactChunkIntervalMs } }
811
+ ]
812
+ };
813
+ if (context.kind === CompactionKind.Chunks && coveredClaimedHead) {
814
+ // If the head still matches at finalization, every chunk is covered.
815
+ // A later replication write will bring the check forward again.
816
+ const fullCheckAt = fullCompactionCheckAt({ ...context.state, bucket_stats: compactionResult.bucketStats }, this);
817
+ nextChunkCheck = {
818
+ $cond: [
819
+ { $eq: ['$last_op', context.lastOp] },
820
+ new Date(fullCheckAt.getTime() + FULL_COMPACT_RESCHEDULE_MARGIN_MS),
821
+ nextChunkCheck
728
822
  ]
729
- },
730
- context.rescheduleNotBefore
731
- );
823
+ };
824
+ }
732
825
  const update: mongo.Document = {
733
826
  compacted_state: {
734
827
  op_id: compactedOpId,
@@ -750,7 +843,7 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
750
843
  next_compact_check:
751
844
  context.kind == CompactionKind.Full
752
845
  ? { $cond: [remainingFullWorkCheck, nextAfterPartialFullCompact, '$$REMOVE'] }
753
- : nextCheckForUncompactedWork
846
+ : this.rescheduleAtOrAfter(nextChunkCheck, context.rescheduleNotBefore)
754
847
  };
755
848
  if (context.kind == CompactionKind.Full) {
756
849
  update.last_full_compact = {
@@ -761,25 +854,25 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
761
854
  };
762
855
  }
763
856
 
764
- await context.lease.finalize(update);
857
+ return update;
765
858
  }
766
859
 
767
- private async finalizeSkippedBucket(context: CompactionContext) {
860
+ private skippedBucketUpdate(context: CompactionContext): BucketCompactionUpdate {
768
861
  // A maxOpId cap can exclude the first remaining document entirely. Avoid
769
862
  // immediately claiming the same no-progress bucket again in this run.
770
- await this.rescheduleClaimedBucket(
771
- context.lease,
772
- {
773
- ...context.decision,
774
- nextCompactCheck: {
775
- $max: [
776
- context.decision.nextCompactCheck,
777
- { $dateAdd: { startDate: '$$NOW', unit: 'millisecond', amount: this.minCompactChunkIntervalMs } }
778
- ]
779
- }
780
- },
781
- context.rescheduleNotBefore
782
- );
863
+ return {
864
+ fields: {
865
+ next_compact_check: this.rescheduleAtOrAfter(
866
+ {
867
+ $max: [
868
+ context.decision.nextCompactCheck,
869
+ { $dateAdd: { startDate: '$$NOW', unit: 'millisecond', amount: this.minCompactChunkIntervalMs } }
870
+ ]
871
+ },
872
+ context.rescheduleNotBefore
873
+ )
874
+ }
875
+ };
783
876
  }
784
877
 
785
878
  /**
@@ -1040,8 +1133,7 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
1040
1133
  }
1041
1134
  }
1042
1135
  if (compactedOpId == null) {
1043
- await this.finalizeSkippedBucket(context);
1044
- return;
1136
+ return this.skippedBucketUpdate(context);
1045
1137
  }
1046
1138
 
1047
1139
  // --- Clear: collapse leading MOVE/REMOVE/CLEAR sequence ---
@@ -1072,12 +1164,10 @@ export class MongoCompactorV3 extends MongoCompactor implements CompactIntervalC
1072
1164
  };
1073
1165
 
1074
1166
  // --- Finalize: update bucket checksums and state ---
1075
- await this.finalizeCompactedBucket({ context, compactedOpId, compactionResult: result, puts: putCount });
1076
-
1077
- this.compactedBucketCount++;
1078
- this.logger.info(
1079
- `Compacted bucket ${bucket}: ${totalOpCount} ops, ${result.bucketStats.chunks} chunks, ${formatBytes(result.bucketStats.bytes)}`
1080
- );
1167
+ return {
1168
+ fields: this.compactedBucketFields({ context, compactedOpId, compactionResult: result, puts: putCount }),
1169
+ completedMessage: `Compacted bucket ${bucket}: ${totalOpCount} ops, ${result.bucketStats.chunks} chunks, ${formatBytes(result.bucketStats.bytes)}`
1170
+ };
1081
1171
  }
1082
1172
 
1083
1173
  /**
@@ -17,6 +17,7 @@ import {
17
17
  import { PreparedPublication } from '../common/PreparedPublication.js';
18
18
  import { SourceRecordLookupState } from '../common/SourceRecordStore.js';
19
19
  import { MongoWriteBatch } from '../MongoWriteBatch.js';
20
+ import { RETAINED_BYTES_FACTOR } from '../ReplicationBatchLimits.js';
20
21
  import { serializeBucketData } from './bucket-format.js';
21
22
  import { chunkBucketData } from './chunking.js';
22
23
  import { DEFAULT_MIN_COMPACT_CHUNK_INTERVAL_MS } from './compaction-constants.js';
@@ -62,19 +63,19 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
62
63
  private readonly inlineThresholdBytes: number;
63
64
  private readonly signal?: AbortSignal;
64
65
  private sealed = false;
65
- private preparation?: Promise<void>;
66
+ private payloadsTask?: Promise<void>;
66
67
  private payloadsReady = false;
67
68
 
68
69
  constructor(
69
70
  private readonly db: VersionedPowerSyncMongoV3,
70
71
  private readonly group_id: number,
71
72
  private readonly mapping: BucketDefinitionMapping,
72
- writtenSize: number,
73
+ private readonly initialWrittenSize: number,
73
74
  options?: PersistedBatchV3Options
74
75
  ) {
75
76
  this.operations = new BatchOperationBuffer(
76
77
  group_id,
77
- writtenSize,
78
+ initialWrittenSize,
78
79
  {
79
80
  // V3-specific definition validation; v1 does not persist definition ids.
80
81
  checkDefinitionId: (definitionId) => {
@@ -85,7 +86,8 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
85
86
  },
86
87
  getBucketDefinitionId: (source) => mapping.bucketSourceId(source)
87
88
  },
88
- options?.logger
89
+ options?.logger,
90
+ options?.batchLimits
89
91
  );
90
92
  this.inlineThresholdBytes = options?.inlineThresholdBytes ?? DEFAULT_INLINE_THRESHOLD_BYTES;
91
93
  this.signal = options?.signal;
@@ -99,6 +101,17 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
99
101
  return this.operations.currentSize;
100
102
  }
101
103
 
104
+ /**
105
+ * Reuse the running size estimate with headroom for JS objects, membership
106
+ * maps, packed chunks and upload buffers, without traversing the batch again.
107
+ * Separate from transaction-size targets; this is not a measured heap size.
108
+ * This estimate intentionally charges superseded representations until commit.
109
+ * Exclude the carried transaction size: earlier groups account for themselves.
110
+ */
111
+ get estimatedRetainedBytes(): number {
112
+ return (this.currentSize - this.initialWrittenSize) * RETAINED_BYTES_FACTOR;
113
+ }
114
+
102
115
  saveBucketData(options: SaveBucketDataOptions): void {
103
116
  this.assertMutable();
104
117
  this.operations.saveBucketData(options);
@@ -133,13 +146,13 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
133
146
  }
134
147
  }
135
148
 
136
- /** Cache readiness, including failure; the v3 batch owns the entire lifecycle. */
137
- preparePayloads(): Promise<void> {
149
+ /** Cache packing/upload readiness, including failure; the v3 batch owns the lifecycle. */
150
+ packAndUploadPayloads(): Promise<void> {
138
151
  if (!this.sealed) {
139
- throw new ReplicationAssertionError('Cannot prepare an unsealed publication');
152
+ throw new ReplicationAssertionError('Cannot pack or upload an unsealed publication');
140
153
  }
141
- return (this.preparation ??= Promise.resolve()
142
- .then(() => this.preparePayloadsImpl())
154
+ return (this.payloadsTask ??= Promise.resolve()
155
+ .then(() => this.packAndUploadPayloadsImpl())
143
156
  .then(() => {
144
157
  this.payloadsReady = true;
145
158
  }));
@@ -150,10 +163,10 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
150
163
  options?: storage.BucketBatchCommitOptions,
151
164
  additionalWrites?: MongoWriteBatch
152
165
  ) {
153
- // Never start preparation from a transaction attempt. The eager coordinator
154
- // awaits readiness for the entire bounded prefix before opening a transaction.
166
+ // Preparation packs/uploads once, outside transaction retries. The
167
+ // coordinator awaits the entire bounded prefix before opening a transaction.
155
168
  if (!this.payloadsReady) {
156
- throw new ReplicationAssertionError('Prepare publication payloads before starting the transaction');
169
+ throw new ReplicationAssertionError('Pack and upload payloads before starting the transaction');
157
170
  }
158
171
  return this.write(session, options, additionalWrites);
159
172
  }
@@ -178,9 +191,6 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
178
191
  if (this.currentData.size > 0) {
179
192
  this.queueCurrentData(writes);
180
193
  }
181
- if (this.operations.bucketStates.size > 0) {
182
- this.queueBucketStates(writes);
183
- }
184
194
  await writes.execute();
185
195
  return this.operations.logFlush(startAt, this.currentData.size, options);
186
196
  }
@@ -343,7 +353,7 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
343
353
  private readonly preparedUsageDeltas = new Map<BucketDefinitionId, bigint>();
344
354
  private preparedUploads: PreparedObjectStorageUpload[] = [];
345
355
 
346
- private async preparePayloadsImpl(): Promise<void> {
356
+ private async packAndUploadPayloadsImpl(): Promise<void> {
347
357
  const operationsByDefinition = new Map<BucketDefinitionId, BucketDataDoc[]>();
348
358
  for (const document of this.operations.bucketData) {
349
359
  const existing = operationsByDefinition.get(document.bucketKey.definitionId) ?? [];
@@ -477,7 +487,10 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
477
487
  }
478
488
  }
479
489
 
480
- private queueBucketStates(writes: MongoWriteBatch): void {
490
+ queueBucketStates(writes: MongoWriteBatch): void {
491
+ if (!this.payloadsReady) {
492
+ throw new ReplicationAssertionError('Pack payloads before publishing bucket statistics');
493
+ }
481
494
  writes.bulkWriteUnordered(this.db.bucketState(this.group_id), this.getBucketStateUpdates());
482
495
  }
483
496