@powersync/service-module-mongodb-storage 0.26.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.
- package/CHANGELOG.md +8 -0
- package/dist/storage/implementation/MongoBucketBatch.d.ts +5 -4
- package/dist/storage/implementation/MongoBucketBatch.js +5 -4
- package/dist/storage/implementation/MongoBucketBatch.js.map +1 -1
- package/dist/storage/implementation/MongoSyncRulesLock.js +5 -1
- package/dist/storage/implementation/MongoSyncRulesLock.js.map +1 -1
- package/dist/storage/implementation/common/PreparedPublication.d.ts +6 -2
- package/dist/storage/implementation/v3/CompactionLease.d.ts +17 -4
- package/dist/storage/implementation/v3/CompactionLease.js +76 -13
- package/dist/storage/implementation/v3/CompactionLease.js.map +1 -1
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js +19 -6
- package/dist/storage/implementation/v3/MongoBucketBatchV3.js.map +1 -1
- package/dist/storage/implementation/v3/MongoCompactorV3.d.ts +5 -3
- package/dist/storage/implementation/v3/MongoCompactorV3.js +169 -82
- package/dist/storage/implementation/v3/MongoCompactorV3.js.map +1 -1
- package/dist/storage/implementation/v3/PersistedBatchV3.d.ts +1 -1
- package/dist/storage/implementation/v3/PersistedBatchV3.js +3 -3
- package/dist/storage/implementation/v3/PersistedBatchV3.js.map +1 -1
- package/package.json +2 -2
- package/src/storage/implementation/MongoBucketBatch.ts +5 -4
- package/src/storage/implementation/MongoSyncRulesLock.ts +5 -1
- package/src/storage/implementation/common/PreparedPublication.ts +6 -2
- package/src/storage/implementation/v3/CompactionLease.ts +91 -15
- package/src/storage/implementation/v3/MongoBucketBatchV3.ts +23 -7
- package/src/storage/implementation/v3/MongoCompactorV3.ts +217 -127
- package/src/storage/implementation/v3/PersistedBatchV3.ts +4 -4
- package/test/src/concurrent_writers.test.ts +13 -0
- package/test/src/helpers/PublicationCommandMonitor.ts +18 -3
- package/test/src/prepared_publication.test.ts +23 -1
- package/test/src/replication_publication_baseline.test.ts +26 -16
- package/test/src/replication_publication_batching.test.ts +6 -2
- package/test/src/storage_compacting.test.ts +253 -47
- package/tsconfig.json +1 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -3,7 +3,6 @@ import { PerformanceTracer, Span, storage, updateSyncRulesFromYaml } from '@powe
|
|
|
3
3
|
import { compactActive, getTestStorage, test_utils } from '@powersync/service-core-tests';
|
|
4
4
|
import { describe, expect, test, vi } from 'vitest';
|
|
5
5
|
import { MongoSyncBucketStorageV3 } from '../../src/storage/implementation/v3/MongoSyncBucketStorageV3.js';
|
|
6
|
-
import { PersistedBatchV3 } from '../../src/storage/implementation/v3/PersistedBatchV3.js';
|
|
7
6
|
import { env } from './env.js';
|
|
8
7
|
import { MemoryObjectStorage } from './helpers/MemoryObjectStorage.js';
|
|
9
8
|
import { PublicationCommandMonitor } from './helpers/PublicationCommandMonitor.js';
|
|
@@ -110,17 +109,22 @@ describe.each([3, 4])('replication publication baseline v%s', (storageVersion) =
|
|
|
110
109
|
await put(...args);
|
|
111
110
|
sample.endedAt = performance.now();
|
|
112
111
|
});
|
|
113
|
-
const
|
|
114
|
-
using
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
112
|
+
const createWriteBatch = factory.db.createWriteBatch.bind(factory.db);
|
|
113
|
+
using _writeSpy = vi.spyOn(factory.db, 'createWriteBatch').mockImplementation((session, options) => {
|
|
114
|
+
const batch = createWriteBatch(session, options);
|
|
115
|
+
if (options.ordered && compaction && !offloaded) {
|
|
116
|
+
const execute = batch.execute.bind(batch);
|
|
117
|
+
batch.execute = async () => {
|
|
118
|
+
if (!compacted) {
|
|
119
|
+
// Pin the snapshot with a test-only read so compaction can commit
|
|
120
|
+
// before the first bucket write and force that write to retry.
|
|
121
|
+
await bucketStates.findOne({ _id: stateBefore!._id }, { session });
|
|
122
|
+
await compactOnce();
|
|
123
|
+
}
|
|
124
|
+
await execute();
|
|
125
|
+
};
|
|
122
126
|
}
|
|
123
|
-
return
|
|
127
|
+
return batch;
|
|
124
128
|
});
|
|
125
129
|
|
|
126
130
|
await save('c');
|
|
@@ -128,7 +132,7 @@ describe.each([3, 4])('replication publication baseline v%s', (storageVersion) =
|
|
|
128
132
|
const summary = monitor.summary();
|
|
129
133
|
const attempts = monitor.replicationAttempts;
|
|
130
134
|
// Compaction during an offloaded PUT now finishes before replication opens
|
|
131
|
-
// its transaction.
|
|
135
|
+
// its transaction. The test-only read makes the inline attempt stale.
|
|
132
136
|
const conflict = compaction && !offloaded;
|
|
133
137
|
expect(compacted).toBe(compaction);
|
|
134
138
|
expect(attempts).toHaveLength(conflict ? 2 : 1);
|
|
@@ -151,7 +155,7 @@ describe.each([3, 4])('replication publication baseline v%s', (storageVersion) =
|
|
|
151
155
|
expect(tracer.stack).toHaveLength(0);
|
|
152
156
|
expect(uploads).toHaveLength(offloaded ? 1 : 0);
|
|
153
157
|
// Real compaction can run throughout a replication PUT without extending or
|
|
154
|
-
// invalidating a replication transaction:
|
|
158
|
+
// invalidating a replication transaction: publication has not started yet.
|
|
155
159
|
for (const upload of uploads) {
|
|
156
160
|
expect(upload.transactions).toHaveLength(0);
|
|
157
161
|
expect(attempts[0].startedAt).toBeGreaterThanOrEqual(upload.endedAt);
|
|
@@ -164,8 +168,8 @@ describe.each([3, 4])('replication publication baseline v%s', (storageVersion) =
|
|
|
164
168
|
// commit but adds an abort command; replay sends no source reads. The
|
|
165
169
|
// final data group now executes the independent head/checkpoint tail too.
|
|
166
170
|
expect(summary.replicationAttempts.map((attempt) => attempt.commands)).toEqual([
|
|
167
|
-
...(conflict ? [{
|
|
168
|
-
{ findAndModify: 1, bulkWrite:
|
|
171
|
+
...(conflict ? [{ find: 1, bulkWrite: 1, abortTransaction: 1 }] : []),
|
|
172
|
+
{ findAndModify: 1, bulkWrite: 2, commitTransaction: 1 }
|
|
169
173
|
]);
|
|
170
174
|
}
|
|
171
175
|
|
|
@@ -178,7 +182,13 @@ describe.each([3, 4])('replication publication baseline v%s', (storageVersion) =
|
|
|
178
182
|
compaction,
|
|
179
183
|
...summary,
|
|
180
184
|
uploads: uploads.map((upload) => ({ bytes: upload.bytes, durationMs: upload.endedAt - upload.startedAt })),
|
|
181
|
-
transactionBodyMs: bodies.map((span) => (span.endAt - span.startAt) / 1000)
|
|
185
|
+
transactionBodyMs: bodies.map((span) => (span.endAt - span.startAt) / 1000),
|
|
186
|
+
bucketStateMs: spans
|
|
187
|
+
.filter((span) => span.name === 'storage:publish_bucket_state')
|
|
188
|
+
.map((span) => (span.endAt - span.startAt) / 1000),
|
|
189
|
+
fenceMs: spans
|
|
190
|
+
.filter((span) => span.name === 'storage:publish_fence')
|
|
191
|
+
.map((span) => (span.endAt - span.startAt) / 1000)
|
|
182
192
|
})
|
|
183
193
|
);
|
|
184
194
|
}
|
|
@@ -102,6 +102,10 @@ describe.each([3, 4])('publication batching v%s', (version) => {
|
|
|
102
102
|
await writer.commit('1/3');
|
|
103
103
|
expect(reads.count).toBe(0);
|
|
104
104
|
expect(registration).toHaveBeenCalledTimes(mode === 'offloaded' ? 1 : 0);
|
|
105
|
+
expect(monitor.replicationAttempts[0].commands.slice(0, 2).map((command) => command.name)).toEqual([
|
|
106
|
+
clientBulks ? 'bulkWrite' : 'update',
|
|
107
|
+
'findAndModify'
|
|
108
|
+
]);
|
|
105
109
|
expect(monitor.summary().replicationAttempts.map((attempt) => attempt.commands)).toEqual([
|
|
106
110
|
!clientBulks
|
|
107
111
|
? {
|
|
@@ -112,7 +116,7 @@ describe.each([3, 4])('publication batching v%s', (version) => {
|
|
|
112
116
|
...(mode === 'offloaded' ? { delete: 1 } : {}),
|
|
113
117
|
commitTransaction: 1
|
|
114
118
|
}
|
|
115
|
-
: { findAndModify: 1, bulkWrite:
|
|
119
|
+
: { findAndModify: 1, bulkWrite: 2, commitTransaction: 1 }
|
|
116
120
|
]);
|
|
117
121
|
const checkpoint = await context.bucketStorage.getCheckpoint();
|
|
118
122
|
expect(checkpoint).toMatchObject({ checkpoint: 3n, lsn: '1/3' });
|
|
@@ -204,7 +208,7 @@ describe.each([3, 4])('publication batching v%s', (version) => {
|
|
|
204
208
|
expect(put).toHaveBeenCalledTimes(1);
|
|
205
209
|
expect(monitor.summary().replicationAttempts.map((attempt) => attempt.commands)).toEqual([
|
|
206
210
|
clientBulks
|
|
207
|
-
? { findAndModify: 1, bulkWrite:
|
|
211
|
+
? { findAndModify: 1, bulkWrite: 2, commitTransaction: 1 }
|
|
208
212
|
: { findAndModify: 1, update: 5, delete: 1, insert: 1, commitTransaction: 1 }
|
|
209
213
|
]);
|
|
210
214
|
expect((await context.bucketStorage.getCheckpoint()).checkpoint).toBe(1002n);
|
|
@@ -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
|
-
|
|
530
|
+
await using lease = await CompactionLease.claim(
|
|
492
531
|
bucketStateCollection,
|
|
493
532
|
{ _id: { d: ctx.definitionId, b: BUCKET } },
|
|
494
533
|
undefined,
|
|
495
|
-
|
|
534
|
+
200
|
|
496
535
|
);
|
|
497
536
|
expect(lease).not.toBeNull();
|
|
498
537
|
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
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
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
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
|
|
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);
|
|
@@ -1329,7 +1358,9 @@ bucket_definitions:
|
|
|
1329
1358
|
{ $set: { first_uncompacted_write: new Date(0), next_compact_check: new Date(0) } }
|
|
1330
1359
|
);
|
|
1331
1360
|
|
|
1361
|
+
using claim = vi.spyOn(CompactionLease, 'claim');
|
|
1332
1362
|
await bucketStorage.compact({ maxOpId: 1n });
|
|
1363
|
+
expect(claim).not.toHaveBeenCalled();
|
|
1333
1364
|
|
|
1334
1365
|
const rescheduledState = await bucketStateCollection.findOne({ _id: { d: ctx.definitionId, b: BUCKET } });
|
|
1335
1366
|
expect(rescheduledState?.last_full_compact?.at).toEqual(lastFullCompactAt);
|
|
@@ -1889,7 +1920,58 @@ bucket_definitions:
|
|
|
1889
1920
|
expect(state?.last_full_compact).toBeUndefined();
|
|
1890
1921
|
});
|
|
1891
1922
|
|
|
1892
|
-
test('
|
|
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 () => {
|
|
1893
1975
|
const { bucketStorage, collection, bucketStateCollection, ctx, sourceTableId } = await setupV3();
|
|
1894
1976
|
await insertDocs(collection, [
|
|
1895
1977
|
serializeBucketData(BUCKET, [makeOp(1, 'A', 'a', ctx, sourceTableId), makeOp(2, 'B', 'b', ctx, sourceTableId)]),
|
|
@@ -1897,9 +1979,30 @@ bucket_definitions:
|
|
|
1897
1979
|
]);
|
|
1898
1980
|
await insertBucketState(bucketStateCollection, ctx.definitionId, 4n);
|
|
1899
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');
|
|
1900
1997
|
const result = await bucketStorage.compactInitialReplication({ forceChunkCompaction: true, maxOpId: 4n });
|
|
1901
1998
|
|
|
1902
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();
|
|
1903
2006
|
const documents = await collection.find({ '_id.b': BUCKET }).sort({ '_id.o': 1 }).toArray();
|
|
1904
2007
|
expect(documents).toHaveLength(1);
|
|
1905
2008
|
expect(documents[0].ops!.map((op) => op.o)).toEqual([1n, 2n, 3n, 4n]);
|
|
@@ -1912,13 +2015,107 @@ bucket_definitions:
|
|
|
1912
2015
|
});
|
|
1913
2016
|
});
|
|
1914
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
|
+
|
|
1915
2111
|
test.each([
|
|
1916
2112
|
{ payloadSize: 100, workers: undefined, abort: false },
|
|
1917
2113
|
{ payloadSize: 450_000, workers: undefined, abort: false },
|
|
1918
2114
|
{ payloadSize: 450_000, workers: 4, abort: false },
|
|
1919
2115
|
{ payloadSize: 100, workers: 1, abort: false },
|
|
2116
|
+
{ payloadSize: 100, workers: 17, abort: false, jobCount: 1 },
|
|
1920
2117
|
{ payloadSize: 450_000, workers: 4, abort: true }
|
|
1921
|
-
])('chunk compaction
|
|
2118
|
+
])('chunk compaction uses the configured concurrency: %o', async ({ payloadSize, workers, abort, jobCount = 2 }) => {
|
|
1922
2119
|
const concurrency = workers ?? 4;
|
|
1923
2120
|
const objectStorage = new MemoryObjectStorage();
|
|
1924
2121
|
const generator = mongoTestStorageFactoryGenerator({
|
|
@@ -1930,7 +2127,7 @@ bucket_definitions:
|
|
|
1930
2127
|
});
|
|
1931
2128
|
const { bucketStorage, syncRules, collection, bucketStateCollection, ctx, sourceTableId, db } =
|
|
1932
2129
|
await setupV3(generator);
|
|
1933
|
-
const bucketCount = 12;
|
|
2130
|
+
const bucketCount = Math.max(12, concurrency);
|
|
1934
2131
|
for (let i = 0; i < bucketCount; i++) {
|
|
1935
2132
|
const bucket = `global[${i}]`;
|
|
1936
2133
|
const documents = [1, 2].map((id) =>
|
|
@@ -1961,7 +2158,7 @@ bucket_definitions:
|
|
|
1961
2158
|
const controller = new AbortController();
|
|
1962
2159
|
let settled = false;
|
|
1963
2160
|
const runs = Promise.allSettled(
|
|
1964
|
-
Array.from({ length:
|
|
2161
|
+
Array.from({ length: jobCount }, () =>
|
|
1965
2162
|
bucketStorage.factory
|
|
1966
2163
|
.getInstance(syncRules)
|
|
1967
2164
|
.compactInitialReplication({ forceChunkCompaction: true, maxOpId: 2n, signal: controller.signal })
|
|
@@ -1972,12 +2169,12 @@ bucket_definitions:
|
|
|
1972
2169
|
try {
|
|
1973
2170
|
await vi.waitFor(() => expect(uploads).toBe(concurrency));
|
|
1974
2171
|
// Let other ready workers reach admission; the held uploads must prevent
|
|
1975
|
-
// any additional payloads from reaching S3,
|
|
2172
|
+
// any additional payloads from reaching S3, even with competing runs.
|
|
1976
2173
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
1977
2174
|
expect(uploads).toBe(concurrency);
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
);
|
|
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);
|
|
1981
2178
|
expect(await collection.countDocuments()).toBe(bucketCount * 2);
|
|
1982
2179
|
if (abort) {
|
|
1983
2180
|
controller.abort();
|
|
@@ -1992,7 +2189,9 @@ bucket_definitions:
|
|
|
1992
2189
|
|
|
1993
2190
|
const results = await runs;
|
|
1994
2191
|
if (abort) {
|
|
1995
|
-
|
|
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);
|
|
1996
2195
|
expect(await bucketStateCollection.countDocuments({ compact_lease: { $exists: true } })).toBe(0);
|
|
1997
2196
|
// Cancellation must return all worker slots.
|
|
1998
2197
|
expect(await bucketStorage.compactInitialReplication({ forceChunkCompaction: true, maxOpId: 2n })).toEqual({
|
|
@@ -2032,8 +2231,12 @@ bucket_definitions:
|
|
|
2032
2231
|
Array.from({ length: workerCount }, () => compactor.objectStorageUsage),
|
|
2033
2232
|
async (bucket: number) => {
|
|
2034
2233
|
started.push(bucket);
|
|
2035
|
-
if (bucket === 0)
|
|
2036
|
-
|
|
2234
|
+
if (bucket === 0) {
|
|
2235
|
+
await failing.promise;
|
|
2236
|
+
}
|
|
2237
|
+
if (bucket === 1) {
|
|
2238
|
+
await draining.promise;
|
|
2239
|
+
}
|
|
2037
2240
|
}
|
|
2038
2241
|
)
|
|
2039
2242
|
.then(
|
|
@@ -2087,9 +2290,12 @@ bucket_definitions:
|
|
|
2087
2290
|
// changing bucket state. A fixed scan timestamp would retry forever.
|
|
2088
2291
|
serverTime = new Date(jobStartedAt.getTime() + 3 * 60 * 60 * 1000);
|
|
2089
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;
|
|
2090
2296
|
const lease = await originalClaim(...args);
|
|
2091
2297
|
if (lease != null) {
|
|
2092
|
-
Object.defineProperty(lease, 'startedAt', { value:
|
|
2298
|
+
Object.defineProperty(lease, 'startedAt', { value: claimedAt });
|
|
2093
2299
|
}
|
|
2094
2300
|
return lease;
|
|
2095
2301
|
});
|