@powersync/service-module-mongodb-storage 0.26.0 → 0.26.2-dev-20261127124135

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 (34) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/storage/implementation/MongoBucketBatch.d.ts +5 -4
  3. package/dist/storage/implementation/MongoBucketBatch.js +5 -4
  4. package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
  5. package/dist/storage/implementation/MongoSyncRulesLock.js +5 -1
  6. package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
  7. package/dist/storage/implementation/common/PreparedPublication.d.ts +6 -2
  8. package/dist/storage/implementation/v3/CompactionLease.d.ts +17 -4
  9. package/dist/storage/implementation/v3/CompactionLease.js +76 -13
  10. package/dist/storage/implementation/v3/CompactionLease.js.map +1 -1
  11. package/dist/storage/implementation/v3/MongoBucketBatchV3.js +19 -6
  12. package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
  13. package/dist/storage/implementation/v3/MongoCompactorV3.d.ts +5 -3
  14. package/dist/storage/implementation/v3/MongoCompactorV3.js +169 -82
  15. package/dist/storage/implementation/v3/MongoCompactorV3.js.map +1 -1
  16. package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +1 -1
  17. package/dist/storage/implementation/v3/PersistedBatchV3.js +3 -3
  18. package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
  19. package/package.json +5 -5
  20. package/src/storage/implementation/MongoBucketBatch.ts +5 -4
  21. package/src/storage/implementation/MongoSyncRulesLock.ts +5 -1
  22. package/src/storage/implementation/common/PreparedPublication.ts +6 -2
  23. package/src/storage/implementation/v3/CompactionLease.ts +91 -15
  24. package/src/storage/implementation/v3/MongoBucketBatchV3.ts +23 -7
  25. package/src/storage/implementation/v3/MongoCompactorV3.ts +217 -127
  26. package/src/storage/implementation/v3/PersistedBatchV3.ts +4 -4
  27. package/test/src/concurrent_writers.test.ts +13 -0
  28. package/test/src/helpers/PublicationCommandMonitor.ts +18 -3
  29. package/test/src/prepared_publication.test.ts +23 -1
  30. package/test/src/replication_publication_baseline.test.ts +26 -16
  31. package/test/src/replication_publication_batching.test.ts +6 -2
  32. package/test/src/storage_compacting.test.ts +253 -47
  33. package/tsconfig.json +1 -0
  34. 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
  /**
@@ -191,9 +191,6 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
191
191
  if (this.currentData.size > 0) {
192
192
  this.queueCurrentData(writes);
193
193
  }
194
- if (this.operations.bucketStates.size > 0) {
195
- this.queueBucketStates(writes);
196
- }
197
194
  await writes.execute();
198
195
  return this.operations.logFlush(startAt, this.currentData.size, options);
199
196
  }
@@ -490,7 +487,10 @@ export class PersistedBatchV3 implements PersistedBatch, PreparedPublication {
490
487
  }
491
488
  }
492
489
 
493
- 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
+ }
494
494
  writes.bulkWriteUnordered(this.db.bucketState(this.group_id), this.getBucketStateUpdates());
495
495
  }
496
496
 
@@ -12,6 +12,7 @@ import { MongoPersistedReplicationStream } from '../../src/storage/implementatio
12
12
  import { PersistedBatchV1 } from '../../src/storage/implementation/v1/PersistedBatchV1.js';
13
13
  import { VersionedPowerSyncMongoV1 } from '../../src/storage/implementation/v1/VersionedPowerSyncMongoV1.js';
14
14
  import { PersistedBatchV3 } from '../../src/storage/implementation/v3/PersistedBatchV3.js';
15
+ import { VersionedPowerSyncMongoV3 } from '../../src/storage/implementation/v3/VersionedPowerSyncMongoV3.js';
15
16
  import { mongoTestStorageFactoryGenerator } from '../../src/utils/test-utils.js';
16
17
  import { env } from './env.js';
17
18
 
@@ -497,8 +498,20 @@ describe.each([1, 2, 4])('concurrent writers v%s', (version) => {
497
498
  await insert(nextWriter, nextTable, 'new');
498
499
  await nextWriter.commit('1/2');
499
500
  expect(nextWriter.last_flushed_op).toBeGreaterThan(abandonedEnd);
501
+ const db = factory.db.versioned(stream.getStorageConfig());
502
+ const bucketState =
503
+ db instanceof VersionedPowerSyncMongoV3 ? db.bucketState(stream.replicationStreamId) : undefined;
504
+ const stateBefore = await bucketState?.findOne({});
505
+ if (bucketState != null) {
506
+ expect(stateBefore).not.toBeNull();
507
+ }
500
508
  await insert(oldWriter, oldTable, 'stale');
501
509
  await expect(oldWriter.flush()).rejects.toThrow('no longer owns');
510
+ if (bucketState != null) {
511
+ // The stale publication wrote bucket state inside its transaction before
512
+ // the fence rejected it. Neither its counters nor its head may leak.
513
+ expect(await bucketState.findOne({})).toEqual(stateBefore);
514
+ }
502
515
  await expect(oldWriter.setResumeLsn('9/9')).rejects.toBeInstanceOf(ReplicationAbortedError);
503
516
  await expect(oldWriter.markAllSnapshotDone('9/9')).rejects.toBeInstanceOf(ReplicationAbortedError);
504
517
  await expect(oldWriter.markTableSnapshotRequired(oldTable)).rejects.toBeInstanceOf(ReplicationAbortedError);
@@ -74,9 +74,20 @@ export class PublicationCommandMonitor implements Disposable {
74
74
  transaction = { key, startedAt, replication: false, commands: [] };
75
75
  this.transactions.set(key, transaction);
76
76
  }
77
- // The writer's first command is the conditional stream fence. Compaction
78
- // shares the client but does not fence the replication stream document.
79
- transaction.replication ||= event.commandName === 'findAndModify' && command.findAndModify === 'sync_rules';
77
+ // A publication can abort on bucket state before reaching the fence.
78
+ // Replication advances last_op, while compaction updates the lease and stats.
79
+ transaction.replication ||=
80
+ (event.commandName === 'findAndModify' && command.findAndModify === 'sync_rules') ||
81
+ (event.commandName === 'update' &&
82
+ command.update.startsWith('bucket_state_') &&
83
+ command.updates.some(({ u }: { u: unknown }) => advancesBucketHead(u))) ||
84
+ (event.commandName === 'bulkWrite' &&
85
+ command.ops.some(
86
+ ({ update, updateMods }: { update?: number; updateMods?: unknown }) =>
87
+ update != null &&
88
+ command.nsInfo[update].ns.split('.')[1]?.startsWith('bucket_state_') &&
89
+ advancesBucketHead(updateMods)
90
+ ));
80
91
  }
81
92
  const sample: CommandSample = { name: event.commandName, startedAt, transaction };
82
93
  this.commands.push(sample);
@@ -117,3 +128,7 @@ export class PublicationCommandMonitor implements Disposable {
117
128
  this.client.off('commandFailed', this.failed);
118
129
  }
119
130
  }
131
+
132
+ function advancesBucketHead(update: unknown) {
133
+ return Array.isArray(update) && update.some((stage) => Object.hasOwn(stage.$set ?? {}, 'last_op'));
134
+ }
@@ -139,6 +139,9 @@ describe.each([3, 4])('sealed publication v%s', (storageVersion) => {
139
139
  let attempts = 0;
140
140
  await publication!.packAndUploadPayloads();
141
141
  await session.withTransaction(async () => {
142
+ const states = db.createWriteBatch(session, { ordered: true });
143
+ publication!.queueBucketStates(states);
144
+ await states.execute();
142
145
  expect(await publication!.publish(session)).toEqual({
143
146
  bucketDataCount: 6,
144
147
  parameterDataCount: 0,
@@ -307,7 +310,12 @@ streams:
307
310
  expect(await parameters.countDocuments()).toBe(0);
308
311
  await publication!.packAndUploadPayloads();
309
312
  await db.client.withSession(async (session) => {
310
- await session.withTransaction(() => publication!.publish(session));
313
+ await session.withTransaction(async () => {
314
+ const states = db.createWriteBatch(session, { ordered: true });
315
+ publication!.queueBucketStates(states);
316
+ await states.execute();
317
+ await publication!.publish(session);
318
+ });
311
319
  });
312
320
  const documents = await parameters.find({}).sort({ _id: 1 }).toArray();
313
321
  expect(documents.map((doc) => doc._id)).toEqual([1n, 2n, 3n]);
@@ -420,6 +428,20 @@ streams:
420
428
  yield [op];
421
429
  }
422
430
  });
431
+ // Both read groups touch the same bucket. Its final delta must already
432
+ // be visible inside the transaction before the first payload write.
433
+ const publish = PersistedBatchV3.prototype.publish;
434
+ using _publish = vi.spyOn(PersistedBatchV3.prototype, 'publish').mockImplementationOnce(async function (
435
+ this: PersistedBatchV3,
436
+ ...args
437
+ ) {
438
+ const states = context.bucketStorage.db.bucketState(context.stream.replicationStreamId);
439
+ expect(await states.findOne({}, { session: args[0] })).toMatchObject({
440
+ last_op: 2n,
441
+ bucket_stats: { count: 2, chunks: 2 }
442
+ });
443
+ return publish.apply(this, args);
444
+ });
423
445
  for (const after of [
424
446
  { id: 'A', description: 'first' },
425
447
  { id: undefined, description: 'second' }