@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,6 +2,7 @@ import { BucketDataDoc } from '@module/storage/implementation/common/BucketDataD
2
2
  import { MongoSyncBucketStorage } from '@module/storage/implementation/createMongoSyncBucketStorage.js';
3
3
  import { loadBucketDataDocument, serializeBucketData } from '@module/storage/implementation/v3/bucket-format.js';
4
4
  import { chunkBucketData, DEFAULT_MAX_DOC_SIZE_BYTES } from '@module/storage/implementation/v3/chunking.js';
5
+ import { FULL_COMPACT_RESCHEDULE_MARGIN_MS } from '@module/storage/implementation/v3/compact-utils.js';
5
6
  import { DEFAULT_MIN_COMPACT_CHUNK_INTERVAL_MS } from '@module/storage/implementation/v3/compaction-constants.js';
6
7
  import { CompactionLease } from '@module/storage/implementation/v3/CompactionLease.js';
7
8
  import { BucketDataDocumentV3 } from '@module/storage/implementation/v3/models.js';
@@ -485,32 +486,61 @@ bucket_definitions:
485
486
  }
486
487
  });
487
488
 
489
+ test('a covered chunk target skips the lease but a full compact at the same op can advance', async () => {
490
+ const { bucketStorage, collection, bucketStateCollection, ctx, sourceTableId } = await setupV3Storage();
491
+ const id = { d: ctx.definitionId, b: BUCKET };
492
+ const documents = Array.from({ length: 9 }, (_, i) =>
493
+ serializeBucketData(BUCKET, [makeOp(i + 1, 'A', 'data', ctx, sourceTableId)])
494
+ );
495
+ await collection.insertMany(documents);
496
+ const prefix = documents[0];
497
+ await bucketStateCollection.insertOne({
498
+ _id: id,
499
+ last_op: 9n,
500
+ next_compact_check: new Date(0),
501
+ first_uncompacted_write: new Date(),
502
+ bucket_stats: { count: 9, bytes: BigInt(documents.reduce((sum, doc) => sum + doc.size, 0)), chunks: 9 },
503
+ compacted_state: {
504
+ op_id: 1n,
505
+ checksum: prefix.checksum,
506
+ count: 1,
507
+ bytes: BigInt(prefix.size),
508
+ chunks: 1,
509
+ at: new Date(0)
510
+ }
511
+ });
512
+
513
+ using claim = vi.spyOn(CompactionLease, 'claim');
514
+ await bucketStorage.compact({ maxOpId: 1n });
515
+ expect(claim).not.toHaveBeenCalled();
516
+ const deferred = await bucketStateCollection.findOne({ _id: id });
517
+ expect(deferred?.next_compact_check!.getTime()).toBeGreaterThan(Date.now());
518
+ expect(deferred?.compacted_state?.op_id).toBe(1n);
519
+
520
+ // The checksum cache covers the cap, but the prefix has never been fully compacted.
521
+ await bucketStateCollection.updateOne({ _id: id }, { $set: { next_compact_check: new Date(0) } });
522
+ await bucketStorage.compact({ maxOpId: 1n, maxCompactFullIntervalMs: 0 });
523
+ expect(claim).toHaveBeenCalledTimes(1);
524
+ expect((await bucketStateCollection.findOne({ _id: id }))?.last_full_compact?.op_id).toBe(1n);
525
+ });
526
+
488
527
  test('a successful lease renewal clears a transient renewal error', async () => {
489
528
  const { bucketStateCollection, ctx } = await setupV3Storage();
490
529
  await insertBucketState(bucketStateCollection, ctx.definitionId, 1n);
491
- const lease = await CompactionLease.claim(
530
+ await using lease = await CompactionLease.claim(
492
531
  bucketStateCollection,
493
532
  { _id: { d: ctx.definitionId, b: BUCKET } },
494
533
  undefined,
495
- 10 * 60 * 1000
534
+ 200
496
535
  );
497
536
  expect(lease).not.toBeNull();
498
537
 
499
- try {
500
- const transientError = new Error('temporary MongoDB error');
501
- const renew = (lease as any).renew.bind(lease);
502
- const updateOne = vi.spyOn(bucketStateCollection, 'updateOne').mockRejectedValueOnce(transientError);
503
- await renew().catch((error: unknown) => {
504
- (lease as any).renewalError = error;
505
- });
506
- await expect(lease!.throwIfLost()).rejects.toBe(transientError);
507
-
508
- updateOne.mockRestore();
509
- await renew();
510
- await expect(lease!.throwIfLost()).resolves.toBeUndefined();
511
- } finally {
512
- await lease?.[Symbol.asyncDispose]();
538
+ const transientError = new Error('temporary MongoDB error');
539
+ {
540
+ using _failedRenewal = vi.spyOn(bucketStateCollection, 'updateOne').mockRejectedValue(transientError);
541
+ await vi.waitFor(() => expect(lease!.throwIfLost()).rejects.toBe(transientError));
513
542
  }
543
+ await vi.waitFor(() => expect(lease!.throwIfLost()).resolves.toBeUndefined());
514
544
  });
515
545
 
516
546
  test('a failed scheduled bucket does not block other scheduled buckets', async () => {
@@ -577,31 +607,30 @@ bucket_definitions:
577
607
 
578
608
  const abortController = new AbortController();
579
609
  const testLogger = defaultLogger.child({});
580
- vi.spyOn(testLogger, 'info').mockImplementation((message: unknown) => {
581
- if (typeof message == 'string' && message.startsWith('Compacted bucket chunks ')) {
582
- abortController.abort();
583
- }
584
- return testLogger;
585
- });
586
610
  const errorLog = vi.spyOn(testLogger, 'error');
587
-
588
- await expect(
589
- bucketStorage
590
- .createMongoCompactor({
591
- maxOpId: 2n,
592
- compactChunksOnly: true,
593
- forceChunkCompaction: true,
594
- signal: abortController.signal,
595
- logger: testLogger
596
- })
597
- .compact()
598
- ).rejects.toThrow();
611
+ const compactor = bucketStorage.createMongoCompactor({
612
+ maxOpId: 2n,
613
+ compactChunksOnly: true,
614
+ forceChunkCompaction: true,
615
+ signal: abortController.signal,
616
+ logger: testLogger
617
+ });
618
+ const internal = compactor as any;
619
+ const compactChunks = internal.compactSingleBucketChunks.bind(compactor);
620
+ using _abortAfterFirstBucket = vi
621
+ .spyOn(internal, 'compactSingleBucketChunks')
622
+ .mockImplementation(async (...args) => {
623
+ const update = await compactChunks(...args);
624
+ abortController.abort();
625
+ return update;
626
+ });
627
+ await expect(compactor.compact()).rejects.toThrow();
599
628
 
600
629
  const states = await bucketStateCollection.find({ '_id.b': { $in: buckets } }).toArray();
601
630
  const completed = states.filter((state) => state.compacted_state != null);
602
631
  const remaining = states.filter((state) => state.compacted_state == null);
603
632
  // Already-started buckets may finish after abort, but the queued remainder
604
- // must not be claimed or rescheduled.
633
+ // must be released with its original schedule.
605
634
  expect(completed.length).toBeGreaterThanOrEqual(1);
606
635
  expect(completed.length).toBeLessThanOrEqual(2);
607
636
  expect(remaining.length).toBeGreaterThanOrEqual(6);
@@ -861,6 +890,22 @@ bucket_definitions:
861
890
  expect(chunks[0]).toHaveLength(1);
862
891
  });
863
892
 
893
+ test('chunk targets count UTF-8 payload bytes rather than string length', () => {
894
+ const data = '界'.repeat(200_000);
895
+ const ops = [makeBucketDataDoc({ o: 1n, data }), makeBucketDataDoc({ o: 2n, data })];
896
+ expect(chunkBucketData(ops)).toEqual([[ops[0]], [ops[1]]]);
897
+ for (const chunk of chunkBucketData(ops)) {
898
+ const document = serializeBucketData('test[]', chunk);
899
+ expect(document.size).toBe(bson.calculateObjectSize(document.ops!));
900
+ }
901
+ });
902
+
903
+ test('chunk targets also account for large row identities', () => {
904
+ const row_id = 'x'.repeat(600_000);
905
+ const ops = [makeBucketDataDoc({ o: 1n, row_id }), makeBucketDataDoc({ o: 2n, row_id })];
906
+ expect(chunkBucketData(ops)).toEqual([[ops[0]], [ops[1]]]);
907
+ });
908
+
864
909
  test('9. serialization fidelity - null data preserved', () => {
865
910
  const ops = [makeBucketDataDoc({ o: 1n, data: null })];
866
911
  const doc = serializeBucketData('test[]', ops);
@@ -1313,7 +1358,9 @@ bucket_definitions:
1313
1358
  { $set: { first_uncompacted_write: new Date(0), next_compact_check: new Date(0) } }
1314
1359
  );
1315
1360
 
1361
+ using claim = vi.spyOn(CompactionLease, 'claim');
1316
1362
  await bucketStorage.compact({ maxOpId: 1n });
1363
+ expect(claim).not.toHaveBeenCalled();
1317
1364
 
1318
1365
  const rescheduledState = await bucketStateCollection.findOne({ _id: { d: ctx.definitionId, b: BUCKET } });
1319
1366
  expect(rescheduledState?.last_full_compact?.at).toEqual(lastFullCompactAt);
@@ -1873,7 +1920,58 @@ bucket_definitions:
1873
1920
  expect(state?.last_full_compact).toBeUndefined();
1874
1921
  });
1875
1922
 
1876
- test('initial compaction merges small chunks and refreshes bucket metadata', async () => {
1923
+ test.each(['caught up', 'capped', 'concurrent append'])(
1924
+ 'schedules the next check after a %s chunk pass',
1925
+ async (mode) => {
1926
+ const { bucketStorage, collection, bucketStateCollection, ctx, sourceTableId } = await setupV3();
1927
+ const id = { d: ctx.definitionId, b: BUCKET };
1928
+ const firstWrite = new Date();
1929
+ const documents = Array.from({ length: 8 }, (_, i) =>
1930
+ serializeBucketData(BUCKET, [makeOp(i + 1, 'A', 'data', ctx, sourceTableId)])
1931
+ );
1932
+ await insertDocs(collection, documents);
1933
+ await bucketStateCollection.insertOne({
1934
+ _id: id,
1935
+ last_op: 8n,
1936
+ first_uncompacted_write: firstWrite,
1937
+ next_compact_check: new Date(0),
1938
+ bucket_stats: { count: 8, chunks: 8, bytes: BigInt(documents.reduce((sum, doc) => sum + doc.size, 0)) }
1939
+ });
1940
+ const minCompactFullIntervalMs = 60 * 60 * 1000;
1941
+ const minCompactChunkIntervalMs = 60 * 1000;
1942
+ const compactor = bucketStorage.createMongoCompactor({
1943
+ maxOpId: mode === 'capped' ? 7n : 8n,
1944
+ minCompactChunkIntervalMs,
1945
+ minCompactFullIntervalMs
1946
+ });
1947
+ const finalize = CompactionLease.finalizeBatch;
1948
+ using finalizeSpy = vi.spyOn(CompactionLease, 'finalizeBatch');
1949
+ if (mode === 'concurrent append') {
1950
+ finalizeSpy.mockImplementationOnce(async (...args) => {
1951
+ const doc = serializeBucketData(BUCKET, [makeOp(9, 'A', 'new', ctx, sourceTableId)]);
1952
+ await collection.insertOne(doc);
1953
+ await bucketStateCollection.updateOne(
1954
+ { _id: id },
1955
+ {
1956
+ $set: { last_op: 9n },
1957
+ $inc: { 'bucket_stats.count': 1, 'bucket_stats.chunks': 1, 'bucket_stats.bytes': BigInt(doc.size) }
1958
+ }
1959
+ );
1960
+ return finalize(...args);
1961
+ });
1962
+ }
1963
+ expect(await compactor.compact()).toBe(1);
1964
+ const state = await bucketStateCollection.findOne({ _id: id });
1965
+ expect(state?.compacted_state?.op_id).toBe(mode === 'capped' ? 7n : 8n);
1966
+ expect(state?.next_compact_check?.getTime()).toBe(
1967
+ mode === 'caught up'
1968
+ ? firstWrite.getTime() + minCompactFullIntervalMs + FULL_COMPACT_RESCHEDULE_MARGIN_MS
1969
+ : state!.compacted_state!.at.getTime() + minCompactChunkIntervalMs
1970
+ );
1971
+ }
1972
+ );
1973
+
1974
+ test('initial compaction publishes a chunk merge and a reschedule in one batch', async () => {
1877
1975
  const { bucketStorage, collection, bucketStateCollection, ctx, sourceTableId } = await setupV3();
1878
1976
  await insertDocs(collection, [
1879
1977
  serializeBucketData(BUCKET, [makeOp(1, 'A', 'a', ctx, sourceTableId), makeOp(2, 'B', 'b', ctx, sourceTableId)]),
@@ -1881,9 +1979,30 @@ bucket_definitions:
1881
1979
  ]);
1882
1980
  await insertBucketState(bucketStateCollection, ctx.definitionId, 4n);
1883
1981
 
1982
+ // This bucket has no operations at or below the requested checkpoint.
1983
+ const laterBucket = 'later[]';
1984
+ const laterDoc = serializeBucketData(laterBucket, [
1985
+ makeOp(5, 'D', 'd', { ...ctx, bucket: laterBucket }, sourceTableId)
1986
+ ]);
1987
+ await collection.insertOne(laterDoc);
1988
+ const laterId = { d: ctx.definitionId, b: laterBucket };
1989
+ await bucketStateCollection.insertOne({
1990
+ _id: laterId,
1991
+ last_op: 5n,
1992
+ next_compact_check: new Date(0),
1993
+ first_uncompacted_write: new Date(),
1994
+ bucket_stats: { count: 1, bytes: BigInt(laterDoc.size), chunks: 1 }
1995
+ });
1996
+ using finalize = vi.spyOn(CompactionLease, 'finalizeBatch');
1884
1997
  const result = await bucketStorage.compactInitialReplication({ forceChunkCompaction: true, maxOpId: 4n });
1885
1998
 
1886
1999
  expect(result).toEqual({ buckets: 1 });
2000
+ expect(finalize).toHaveBeenCalledTimes(1);
2001
+ expect(finalize.mock.calls[0][1]).toHaveLength(2);
2002
+ const laterState = await bucketStateCollection.findOne({ _id: laterId });
2003
+ expect(laterState?.next_compact_check?.getTime()).toBeGreaterThan(0);
2004
+ expect(laterState?.compact_lease).toBeUndefined();
2005
+ expect(laterState?.compacted_state).toBeUndefined();
1887
2006
  const documents = await collection.find({ '_id.b': BUCKET }).sort({ '_id.o': 1 }).toArray();
1888
2007
  expect(documents).toHaveLength(1);
1889
2008
  expect(documents[0].ops!.map((op) => op.o)).toEqual([1n, 2n, 3n, 4n]);
@@ -1896,13 +2015,107 @@ bucket_definitions:
1896
2015
  });
1897
2016
  });
1898
2017
 
2018
+ test.each(['lease takeover', 'partial bulk error', 'invalid update', 'write conflict'])(
2019
+ 'publishes chunk groups safely after %s',
2020
+ async (failure) => {
2021
+ const { bucketStorage, bucketStateCollection, collection, db, ctx, sourceTableId } = await setupV3();
2022
+ const groupSize = 32;
2023
+ const bucketCount = groupSize + 2;
2024
+ for (let index = 0; index < bucketCount; index++) {
2025
+ const bucket = `batch[${index}]`;
2026
+ const docs = [1, 2].map((op) =>
2027
+ serializeBucketData(bucket, [makeOp(op, 'A', 'data', { ...ctx, bucket }, sourceTableId)])
2028
+ );
2029
+ await collection.insertMany(docs);
2030
+ await bucketStateCollection.insertOne({
2031
+ _id: { d: ctx.definitionId, b: bucket },
2032
+ last_op: 2n,
2033
+ next_compact_check: new Date(0),
2034
+ first_uncompacted_write: new Date(),
2035
+ bucket_stats: { count: 2, bytes: BigInt(docs[0].size + docs[1].size), chunks: 2 }
2036
+ });
2037
+ }
2038
+
2039
+ using _states = vi.spyOn(db, 'bucketState').mockReturnValue(bucketStateCollection);
2040
+ const bulkWrite = bucketStateCollection.bulkWrite.bind(bucketStateCollection);
2041
+ const replacement = new bson.ObjectId();
2042
+ using bulk = vi.spyOn(bucketStateCollection, 'bulkWrite').mockImplementationOnce(async (operations, options) => {
2043
+ expect(operations).toHaveLength(groupSize);
2044
+ expect(options?.ordered).toBe(false);
2045
+ expect(options?.session?.inTransaction()).toBe(true);
2046
+ expect(await bucketStateCollection.countDocuments({ compact_lease: { $exists: true } })).toBe(groupSize);
2047
+ expect(await bucketStateCollection.countDocuments({ compacted_state: { $exists: true } })).toBe(0);
2048
+ if (failure === 'partial bulk error') {
2049
+ await bulkWrite(operations.slice(0, 1), options);
2050
+ throw new Error('partial bulk error');
2051
+ }
2052
+ if (failure === 'write conflict') {
2053
+ const filter = { compact_lease: { $exists: true } };
2054
+ // Pin the transaction snapshot, then change the first bucket outside it.
2055
+ const state = await bucketStateCollection.findOne(filter, { session: options?.session });
2056
+ await bucketStateCollection.updateOne({ _id: state!._id }, { $set: { next_compact_check: new Date(1) } });
2057
+ return bulkWrite(operations, options);
2058
+ }
2059
+ if (failure === 'invalid update') {
2060
+ const first = operations[0];
2061
+ if (!('updateOne' in first)) {
2062
+ throw new Error('Expected bucket state update');
2063
+ }
2064
+ return bulkWrite(
2065
+ [
2066
+ { updateOne: { filter: first.updateOne.filter, update: [{ $set: { invalid: { $divide: [1, 0] } } }] } },
2067
+ ...operations.slice(1)
2068
+ ],
2069
+ options
2070
+ );
2071
+ }
2072
+ // The stale finalizer must neither apply its stats delta nor release the new owner's lease.
2073
+ await bucketStateCollection.updateOne(
2074
+ { compact_lease: { $exists: true } },
2075
+ { $set: { 'compact_lease.id': replacement } }
2076
+ );
2077
+ return bulkWrite(operations, options);
2078
+ });
2079
+ const run = () => bucketStorage.compactInitialReplication({ forceChunkCompaction: true, maxOpId: 2n });
2080
+ if (failure === 'partial bulk error') {
2081
+ await expect(run()).rejects.toThrow('partial bulk error');
2082
+ expect(await bucketStateCollection.countDocuments({ compact_lease: { $exists: true } })).toBe(0);
2083
+ expect(await bucketStateCollection.countDocuments({ 'compacted_state.op_id': 2n })).toBe(0);
2084
+ await expect(run()).resolves.toEqual({ buckets: bucketCount });
2085
+ expect(await bucketStateCollection.countDocuments({ 'bucket_stats.chunks': 1, 'bucket_stats.count': 2 })).toBe(
2086
+ bucketCount
2087
+ );
2088
+ } else if (failure === 'write conflict') {
2089
+ await expect(run()).resolves.toEqual({ buckets: bucketCount });
2090
+ expect(bulk.mock.calls.map(([ops]) => ops.length)).toEqual([groupSize, groupSize, 2]);
2091
+ expect(await bucketStateCollection.countDocuments({ 'bucket_stats.chunks': 1, 'bucket_stats.count': 2 })).toBe(
2092
+ bucketCount
2093
+ );
2094
+ } else {
2095
+ await expect(run()).resolves.toEqual({ buckets: bucketCount - 1 });
2096
+ expect(bulk.mock.calls.map(([ops]) => ops.length)).toEqual(
2097
+ failure === 'invalid update' ? [groupSize, groupSize - 1, 2] : [groupSize, 2]
2098
+ );
2099
+ if (failure === 'lease takeover') {
2100
+ expect(await bucketStateCollection.findOne({ 'compact_lease.id': replacement })).toMatchObject({
2101
+ bucket_stats: { chunks: 2 }
2102
+ });
2103
+ } else {
2104
+ expect(await bucketStateCollection.countDocuments({ compact_lease: { $exists: true } })).toBe(0);
2105
+ }
2106
+ expect(await bucketStateCollection.countDocuments({ 'compacted_state.op_id': 2n })).toBe(bucketCount - 1);
2107
+ }
2108
+ }
2109
+ );
2110
+
1899
2111
  test.each([
1900
2112
  { payloadSize: 100, workers: undefined, abort: false },
1901
2113
  { payloadSize: 450_000, workers: undefined, abort: false },
1902
2114
  { payloadSize: 450_000, workers: 4, abort: false },
1903
2115
  { payloadSize: 100, workers: 1, abort: false },
2116
+ { payloadSize: 100, workers: 17, abort: false, jobCount: 1 },
1904
2117
  { payloadSize: 450_000, workers: 4, abort: true }
1905
- ])('chunk compaction shares configured workers across runs: %o', async ({ payloadSize, workers, abort }) => {
2118
+ ])('chunk compaction uses the configured concurrency: %o', async ({ payloadSize, workers, abort, jobCount = 2 }) => {
1906
2119
  const concurrency = workers ?? 4;
1907
2120
  const objectStorage = new MemoryObjectStorage();
1908
2121
  const generator = mongoTestStorageFactoryGenerator({
@@ -1914,7 +2127,7 @@ bucket_definitions:
1914
2127
  });
1915
2128
  const { bucketStorage, syncRules, collection, bucketStateCollection, ctx, sourceTableId, db } =
1916
2129
  await setupV3(generator);
1917
- const bucketCount = 12;
2130
+ const bucketCount = Math.max(12, concurrency);
1918
2131
  for (let i = 0; i < bucketCount; i++) {
1919
2132
  const bucket = `global[${i}]`;
1920
2133
  const documents = [1, 2].map((id) =>
@@ -1945,7 +2158,7 @@ bucket_definitions:
1945
2158
  const controller = new AbortController();
1946
2159
  let settled = false;
1947
2160
  const runs = Promise.allSettled(
1948
- Array.from({ length: 2 }, () =>
2161
+ Array.from({ length: jobCount }, () =>
1949
2162
  bucketStorage.factory
1950
2163
  .getInstance(syncRules)
1951
2164
  .compactInitialReplication({ forceChunkCompaction: true, maxOpId: 2n, signal: controller.signal })
@@ -1956,12 +2169,12 @@ bucket_definitions:
1956
2169
  try {
1957
2170
  await vi.waitFor(() => expect(uploads).toBe(concurrency));
1958
2171
  // Let other ready workers reach admission; the held uploads must prevent
1959
- // any additional payloads from reaching S3, across both compactor instances.
2172
+ // any additional payloads from reaching S3, even with competing runs.
1960
2173
  await new Promise((resolve) => setTimeout(resolve, 50));
1961
2174
  expect(uploads).toBe(concurrency);
1962
- expect(await bucketStateCollection.countDocuments({ compact_lease: { $exists: true } })).toBeLessThanOrEqual(
1963
- concurrency
1964
- );
2175
+ // Queued buckets already have leases. Only the configured number of
2176
+ // workers can enter payload processing across all runs.
2177
+ expect(await bucketStateCollection.countDocuments({ compact_lease: { $exists: true } })).toBe(bucketCount);
1965
2178
  expect(await collection.countDocuments()).toBe(bucketCount * 2);
1966
2179
  if (abort) {
1967
2180
  controller.abort();
@@ -1976,7 +2189,9 @@ bucket_definitions:
1976
2189
 
1977
2190
  const results = await runs;
1978
2191
  if (abort) {
1979
- expect(results.every((result) => result.status === 'rejected')).toBe(true);
2192
+ // A competing run can finish early if the other run claimed every bucket.
2193
+ expect(results.some((result) => result.status === 'rejected')).toBe(true);
2194
+ expect(results.every((result) => result.status === 'rejected' || result.value.buckets === 0)).toBe(true);
1980
2195
  expect(await bucketStateCollection.countDocuments({ compact_lease: { $exists: true } })).toBe(0);
1981
2196
  // Cancellation must return all worker slots.
1982
2197
  expect(await bucketStorage.compactInitialReplication({ forceChunkCompaction: true, maxOpId: 2n })).toEqual({
@@ -2016,8 +2231,12 @@ bucket_definitions:
2016
2231
  Array.from({ length: workerCount }, () => compactor.objectStorageUsage),
2017
2232
  async (bucket: number) => {
2018
2233
  started.push(bucket);
2019
- if (bucket === 0) await failing.promise;
2020
- if (bucket === 1) await draining.promise;
2234
+ if (bucket === 0) {
2235
+ await failing.promise;
2236
+ }
2237
+ if (bucket === 1) {
2238
+ await draining.promise;
2239
+ }
2021
2240
  }
2022
2241
  )
2023
2242
  .then(
@@ -2071,9 +2290,12 @@ bucket_definitions:
2071
2290
  // changing bucket state. A fixed scan timestamp would retry forever.
2072
2291
  serverTime = new Date(jobStartedAt.getTime() + 3 * 60 * 60 * 1000);
2073
2292
  }
2293
+ // Claims for this group run together. Only the promoted bucket's
2294
+ // returned snapshot has aged past its full-compaction interval.
2295
+ const claimedAt = (args[1]._id as { b: string }).b.startsWith('chunk') ? jobStartedAt : serverTime;
2074
2296
  const lease = await originalClaim(...args);
2075
2297
  if (lease != null) {
2076
- Object.defineProperty(lease, 'startedAt', { value: serverTime });
2298
+ Object.defineProperty(lease, 'startedAt', { value: claimedAt });
2077
2299
  }
2078
2300
  return lease;
2079
2301
  });
@@ -0,0 +1,88 @@
1
+ import { mongo } from '@powersync/lib-service-mongodb';
2
+ import { describe, expect, test, vi } from 'vitest';
3
+ import { INITIALIZED_MONGO_STORAGE_FACTORY } from './util.js';
4
+
5
+ describe('storage metrics collection sizes', () => {
6
+ test('uses sequential estimated dataSize commands for logical sizes', async () => {
7
+ await using factory = await INITIALIZED_MONGO_STORAGE_FACTORY.factory();
8
+ const before = await factory.getStorageMetrics();
9
+ const document = { _id: new mongo.ObjectId(), value: 'payload' };
10
+ const names = ['bucket_data_999_metrics', 'parameter_index_999_metrics', 'source_records_999_metrics'];
11
+ for (const name of names) {
12
+ await factory.db.db.collection(name).insertOne(document);
13
+ }
14
+ const expectedSize = mongo.BSON.calculateObjectSize(document);
15
+ const command = factory.db.db.command.bind(factory.db.db);
16
+ let inFlight = 0;
17
+ let maxInFlight = 0;
18
+ using commands = vi.spyOn(factory.db.db, 'command').mockImplementation(async (...args) => {
19
+ inFlight++;
20
+ maxInFlight = Math.max(maxInFlight, inFlight);
21
+ try {
22
+ return await command(...args);
23
+ } finally {
24
+ inFlight--;
25
+ }
26
+ });
27
+
28
+ const after = await factory.getStorageMetrics();
29
+
30
+ expect(after.operations_size_bytes - before.operations_size_bytes).toBe(expectedSize);
31
+ expect(after.parameters_size_bytes - before.parameters_size_bytes).toBe(expectedSize);
32
+ expect(after.replication_size_bytes - before.replication_size_bytes).toBe(expectedSize);
33
+ expect(maxInFlight).toBe(1);
34
+ for (const name of names) {
35
+ expect(commands).toHaveBeenCalledWith(
36
+ { dataSize: `${factory.db.db.databaseName}.${name}`, estimate: true },
37
+ { readPreference: undefined }
38
+ );
39
+ }
40
+ });
41
+
42
+ test.each([
43
+ { code: 59, errmsg: 'no such command: dataSize' },
44
+ { code: 115, errmsg: 'Command dataSize is not supported' },
45
+ { code: 8000, errmsg: 'dataSize is not allowed in this atlas tier' }
46
+ ])('caches unsupported dataSize errors ($code) and falls back across union batches', async (response) => {
47
+ await using factory = await INITIALIZED_MONGO_STORAGE_FACTORY.factory();
48
+ const before = await factory.getStorageMetrics();
49
+ const document = { _id: new mongo.ObjectId(), value: 'payload' };
50
+ for (let index = 0; index < 101; index++) {
51
+ await factory.db.db.collection(`bucket_data_999_metrics_${index}`).insertOne(document);
52
+ }
53
+ const expectedSize = 101 * mongo.BSON.calculateObjectSize(document);
54
+ const command = factory.db.db.command.bind(factory.db.db);
55
+ // Fail after a successful size query to check that fallback doesn't double-count partial results.
56
+ using commands = vi
57
+ .spyOn(factory.db.db, 'command')
58
+ .mockImplementationOnce((...args) => command(...args))
59
+ .mockRejectedValueOnce(new mongo.MongoServerError(response));
60
+
61
+ const first = await factory.getStorageMetrics();
62
+ expect(first.operations_size_bytes - before.operations_size_bytes).toBe(expectedSize);
63
+ expect(commands).toHaveBeenCalledTimes(2);
64
+
65
+ const additionalDocument = { _id: new mongo.ObjectId() };
66
+ await factory.db.db.collection('bucket_data_999_metrics_0').insertOne(additionalDocument);
67
+ const second = await factory.getStorageMetrics();
68
+ expect(second.operations_size_bytes - first.operations_size_bytes).toBe(
69
+ mongo.BSON.calculateObjectSize(additionalDocument)
70
+ );
71
+ expect(commands).toHaveBeenCalledTimes(2);
72
+ });
73
+
74
+ test.each([
75
+ { code: 13, errmsg: 'not authorized to execute dataSize' },
76
+ { code: 8000, errmsg: 'unrelated Atlas error' },
77
+ { code: 11600, errmsg: 'interrupted at shutdown' }
78
+ ])('propagates other errors ($code) and retries dataSize on the next refresh', async (response) => {
79
+ await using factory = await INITIALIZED_MONGO_STORAGE_FACTORY.factory();
80
+ await factory.db.db.collection('bucket_data_999_metrics').insertOne({ _id: new mongo.ObjectId() });
81
+ const error = new mongo.MongoServerError(response);
82
+ using commands = vi.spyOn(factory.db.db, 'command').mockRejectedValueOnce(error);
83
+
84
+ await expect(factory.getStorageMetrics()).rejects.toBe(error);
85
+ await expect(factory.getStorageMetrics()).resolves.toHaveProperty('operations_size_bytes');
86
+ expect(commands.mock.calls.length).toBeGreaterThan(1);
87
+ });
88
+ });
package/tsconfig.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "extends": "../../tsconfig.base.json",
3
3
  "compilerOptions": {
4
+ "lib": ["es2024", "esnext.disposable"],
4
5
  "rootDir": "src",
5
6
  "outDir": "dist"
6
7
  },