Files
wekan/tests/migrationCopyShortfall.test.cjs
T
Lauri Ojansivu c783829823 Snap: a migration may not resume onto a database the source has outgrown.
"Our snap updated automatically from 10.81 yesterday to 10.85 this morning. Data
in the DB is from about 2 - 3 weeks ago. Many cards and work is lost."

Nothing was lost: the MongoDB data is in $SNAP_COMMON and untouched. What the
update completed was a migration that had been interrupted weeks earlier.

The MongoDB -> FerretDB migration is resumable, and has to be - it can run for
hours, and a snap refresh, a stop or a reboot part-way through is normal rather
than exceptional (migration-control's interrupted_keep_progress). So the importer
records every finished collection in $SNAP_COMMON/migration-progress.json and
skips those next time.

That checkpoint was only ever checked against the TARGET. migration-control
deletes it whenever it discards a partial SQLite (discard_partial_ferretdb), so it
can never name collections that are not there. Nothing checked it against the
SOURCE - and between an interrupted migration and its retry the snap hands WeKan
back to MongoDB and people go on using it (fail_3x_keep_progress,
resume_next_start). A migration interrupted in July and resumed in August
therefore skipped every collection it had finished in July, copied only the rest,
and reported success. finish_success then switched the snap onto that copy:
boards and cards as they stood in July, with three weeks of work still in MongoDB
and simply not being served.

A new snap revision is usually what sets the resume going again, because the
per-revision failure counter starts at zero (bin/stale-marker) - which is why
this reads as "the update lost my data". The update is when the weeks-old copy
finally got served. Same family as #6583, and the same answer: a copy made at one
time may not be used as if it were current.

Two checks, because they fail differently.

bin/migration-checkpoint-stale.mjs asks whether the checkpoint is too old to
resume from at all. mongod rewrites its WiredTiger files whenever it commits, so
the newest mtime among them is when MongoDB was last written to - the evidence
bin/ferretdb-migration-stale already uses for the finished-migration case. Later
than the checkpoint (by more than a margin, since the migration's own temporary
mongod writes on the way out) means the collections it lists are copies of an
older database, so the collection half is dropped and they are copied again. The
checkpoint's age is the OLDER of its updatedAt and the file's mtime: the two
disagreeing is a reason to doubt it, and a needless re-copy costs minutes while a
wrong skip costs weeks. The file half is kept - attachments are written once and
re-verified on disk at the recorded size, and re-extracting gigabytes is the
slowest part of a resume.

migration-control runs it as its first step, before it starts any mongod of its
own: starting one rewrites those files, and after that the question can no longer
be asked. It is the only way into a text migration - snap run wekan.migrate,
auto-migration and mongodb-control's fallback all arrive through it.

verifyCollectionCounts, in both importers, then asks the two databases themselves
once the copying is done, when both are quiet: a collection whose copy holds fewer
documents than the source is copied again from the source as it is now. It does
not care WHY a copy came up short, which is the point of a check standing behind
another one. Only a shortfall is acted on - a copy holding MORE is a resume
carrying documents deleted from MongoDB since, and deleting on that evidence is
the guess this whole family of bugs is made of - and a shortfall that survives the
second copy is reported rather than fatal, so one document FerretDB will not
accept cannot leave the snap in a migration it can never finish. It sits inside
the same "not repair mode" block as the copying it verifies, since a FILES_ONLY
repair (#6473) must never write text over a FerretDB people have been using.

tests/migrationCheckpointStale.test.cjs runs the detector against synthesised
$SNAP_COMMON directories: the reported case, an ordinary resume minutes later, the
margin that covers the migration stopping its own source mongod, a mongodb.log
that must not count as somebody using the database, and that migration-control
asks before it starts a mongod. tests/migrationCopyShortfall.test.cjs extracts
verifyCollectionCounts from BOTH importers and exercises it behaviourally.

Verified by running both suites and the whole node suite (374 suites, 0 failed).
The snap itself cannot be built or refreshed in this sandbox.

Thanks to Alishara and xet7 !

Fixes #6585.
2026-08-12 14:05:34 +03:00

224 lines
11 KiB
JavaScript

'use strict';
// wekan/wekan#6585 "Data Lost in DB after Update 10.81 to 10.85": the snap
// refreshed overnight and came up serving boards and cards as they had been two to
// three weeks earlier.
// Run: node tests/migrationCopyShortfall.test.cjs
//
// The MongoDB -> FerretDB migration is resumable and skips every collection an
// earlier run finished. Between an interrupted migration and its retry the snap
// hands WeKan back to MongoDB and people go on using it - so weeks later those skips
// leave out everything written in between, and the migration still reports success.
//
// tests/migrationCheckpointStale.test.cjs covers the first answer to that: a
// checkpoint the source has outgrown loses its collection half before the migration
// starts, judged from the mtimes of the MongoDB data files. This covers the second,
// which asks the two databases themselves once the copying is done - a collection
// whose copy holds fewer documents than the source is copied again from the source
// as it is now. It does not care WHY the copy was short, which is what makes it
// worth having behind the first check.
//
// verifyCollectionCounts is extracted from each importer's source text and exercised
// BEHAVIOURALLY in a VM, so these tests fail if the logic regresses, not only if it
// is renamed.
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const repoRoot = path.resolve(__dirname, '..');
const read = rel => fs.readFileSync(path.join(repoRoot, rel), 'utf8');
const IMPORTERS = {
modern: 'releases/migrate-mongodb-to-ferretdb.mjs', // MongoDB 4.x/6/7 source
mongo3: 'snap-src/bin/migrate-mongo3-to-ferretdb.mjs', // MongoDB 3.x source
};
// The checks are async (the real function awaits its counts), so they are queued and
// run in order at the end: a failed assertion inside an un-awaited async test would
// otherwise be an unhandled rejection that the suite still reports as passing.
let passed = 0;
const queued = [];
function test(name, fn) { queued.push([name, fn]); }
// Pull the function out of the real file and make it callable on its own.
function extract(rel) {
const src = read(rel);
const start = src.indexOf('async function verifyCollectionCounts(');
assert.notStrictEqual(start, -1,
`${rel} must carry verifyCollectionCounts - it is what stops a short copy being ` +
'declared a successful migration');
// The parameter list is itself a destructuring pattern with braces in it, so the
// body starts at the first brace AFTER the parameter list closes.
const paren = src.indexOf('(', start);
let parens = 0, afterParams = -1;
for (let i = paren; i < src.length; i++) {
if (src[i] === '(') parens++;
else if (src[i] === ')') { parens--; if (parens === 0) { afterParams = i; break; } }
}
assert.ok(afterParams > 0, `could not find the parameter list of verifyCollectionCounts in ${rel}`);
// Balance braces from the body's opening one to its close.
const open = src.indexOf('{', afterParams);
let depth = 0, end = -1;
for (let i = open; i < src.length; i++) {
if (src[i] === '{') depth++;
else if (src[i] === '}') { depth--; if (depth === 0) { end = i + 1; break; } }
}
assert.ok(end > 0, `could not find the end of verifyCollectionCounts in ${rel}`);
const ctx = { module: { exports: {} } };
vm.createContext(ctx);
vm.runInContext(`${src.slice(start, end)}\nmodule.exports = verifyCollectionCounts;`, ctx);
return ctx.module.exports;
}
// A source and a target as document counts, with a recopy that makes the target
// match the source - which is what copying a collection again really does.
function harness({ source, target, recopyTo = null, isText = () => true, dropped = () => 0 }) {
const tgt = { ...target };
const log = [];
const recopied = [];
return {
log, recopied, tgt,
args: {
names: Object.keys(source),
isText,
countSource: async (n) => source[n],
countTarget: async (n) => tgt[n],
droppedFor: dropped,
recopy: async (n) => {
recopied.push(n);
tgt[n] = recopiedValue(n, source, recopyTo);
},
log: (m) => log.push(m),
},
};
}
// The function under test runs in a VM, so the array it returns has that realm's
// Array prototype and deepStrictEqual would refuse it on that alone. Compare values.
const plain = (v) => JSON.parse(JSON.stringify(v));
function recopiedValue(name, source, recopyTo) {
if (recopyTo === null) return source[name];
return typeof recopyTo === 'function' ? recopyTo(name) : recopyTo;
}
for (const [label, rel] of Object.entries(IMPORTERS)) {
const verify = extract(rel);
test(`${label}: a collection short of the source is copied again - the #6585 case`, async () => {
// The resume skipped `cards` because a run three weeks ago finished it; 400 cards
// have been made since, in MongoDB, and are not in the copy.
const h = harness({ source: { boards: 20, cards: 1400 }, target: { boards: 20, cards: 1000 } });
const short = plain(await verify(h.args));
assert.deepStrictEqual(h.recopied, ['cards'],
'the collection that is behind is the one to copy again; the rest is untouched work');
assert.strictEqual(h.tgt.cards, 1400, 'and afterwards the copy holds what MongoDB holds');
assert.deepStrictEqual(short, [], 'nothing is left to report once the copy is complete');
assert.match(h.log[0], /cards: the copy holds 1000 of 1400/,
'the log has to name the collection and both counts - it is the only trace an ' +
'admin gets of why the migration took another minute');
});
test(`${label}: a copy that matches, or holds more, is left alone`, async () => {
const h = harness({ source: { boards: 20, cards: 1400, users: 5 },
target: { boards: 20, cards: 1400, users: 9 } });
const short = plain(await verify(h.args));
assert.deepStrictEqual(h.recopied, [],
're-copying a collection that is not behind is pure cost');
assert.deepStrictEqual(short, []);
assert.strictEqual(h.tgt.users, 9,
'a copy holding MORE than the source is a resume carrying documents deleted from ' +
'MongoDB since; deleting them here on that evidence is exactly the guess that ' +
'loses data');
});
test(`${label}: a shortfall that survives the second copy is reported, not thrown`, async () => {
// FerretDB refusing one particular document is not a reason to fail a migration
// forever - that would leave the snap retrying a migration it can never finish.
const h = harness({ source: { cards: 1400 }, target: { cards: 1000 }, recopyTo: 1399 });
const short = plain(await verify(h.args));
assert.deepStrictEqual(short, [{ collection: 'cards', source: 1400, target: 1399 }],
'what is still missing has to come back as data the caller can report');
assert.deepStrictEqual(h.recopied, ['cards'], 'and it is tried exactly once, not in a loop');
});
test(`${label}: documents a transformer dropped are not counted as missing`, async () => {
// The schema upgrades may drop a document on purpose. A copy short by exactly
// those is not short at all, and copying it again would only drop them again.
const h = harness({ source: { cards: 1400 }, target: { cards: 1398 }, dropped: () => 2 });
assert.deepStrictEqual(plain(await verify(h.args)), []);
assert.deepStrictEqual(h.recopied, [], 'a deliberate drop is not a shortfall');
const worse = harness({ source: { cards: 1400 }, target: { cards: 1000 }, dropped: () => 2 });
await verify(worse.args);
assert.deepStrictEqual(worse.recopied, ['cards'],
'but 400 missing is not explained by 2 dropped');
});
test(`${label}: only text collections are counted`, async () => {
// GridFS chunks and dotted collections become files and bare records in the file
// phase, so their document counts never match and never should.
const h = harness({
source: { cards: 1400, 'cfs_gridfs.attachments.chunks': 900 },
target: { cards: 1400, 'cfs_gridfs.attachments.chunks': 0 },
isText: (n) => !n.includes('.'),
});
assert.deepStrictEqual(plain(await verify(h.args)), []);
assert.deepStrictEqual(h.recopied, []);
});
test(`${label}: a count that cannot be taken stops nothing`, async () => {
const src = { cards: 1400, missingHere: 3 };
const tgt = { cards: 1000 };
const recopied = [];
const short = plain(await verify({
names: Object.keys(src),
isText: () => true,
countSource: async (n) => src[n],
countTarget: async (n) => {
if (n === 'missingHere') throw new Error('no such collection');
return tgt[n];
},
droppedFor: () => 0,
recopy: async (n) => { recopied.push(n); tgt[n] = src[n]; },
log: () => {},
}));
assert.deepStrictEqual(recopied, ['cards'],
'one collection that cannot be counted must not stop the collection that can');
assert.deepStrictEqual(short, [],
'and a collection nothing could be learned about is not reported as short');
});
}
test('both importers call it, and only where re-copying text is allowed', () => {
const modern = read(IMPORTERS.modern);
const mongo3 = read(IMPORTERS.mongo3);
for (const [label, src] of [['modern', modern], ['mongo3', mongo3]]) {
assert.ok(/await verifyCollectionCounts\(\{/.test(src),
`${label} defines the check but never runs it`);
}
// Repair mode (#6473) exists precisely because people have been using FerretDB
// since the migration: re-copying text from the frozen MongoDB there would
// overwrite or resurrect their work. The count check re-copies text, so it belongs
// inside the same "not repair mode" block as the copying it verifies.
const repairBlock = modern.slice(modern.indexOf('if (!repairMode) {'),
modern.indexOf('// end !repairMode (text collections)'));
assert.ok(repairBlock.includes('verifyCollectionCounts'),
'the count check must sit inside !repairMode, or a FILES_ONLY repair would ' +
'start copying text over a FerretDB that people have been using');
const filesOnlyBlock = mongo3.slice(mongo3.indexOf("logline('FILES_ONLY:"),
mongo3.indexOf('// end !FILES_ONLY (text collections)'));
assert.ok(filesOnlyBlock.includes('verifyCollectionCounts'),
'same for the mongo3 importer, whose FILES_ONLY branch skips the text phase');
assert.ok(/if \(!DRY_RUN\) \{\s*\n\s*state\.phase = 'verifying-collections';/.test(modern),
'a dry run writes no target, so counting one would only report every collection short');
});
(async () => {
for (const [name, fn] of queued) {
await fn();
passed += 1;
console.log(' ok -', name);
}
console.log(`\n${passed} passed`);
})().catch(e => { console.error(e); process.exit(1); });