Testing migrations

Running migrations in unit tests, checking a whole chain, and finding schema changes that lose data.

A migration that fails on real documents is caught by the server's verification before it can be activated, but a test catches it sooner. This page shows the tools @voidhash/mimic-server/migrate gives you for testing migrations in Node.

Running one migration

runDirectMigration(migration, value) runs a migration on one encoded document, the same way the server's runner does, and returns the migrated value. It never changes its input.

import { expect, it } from "vitest";
import { runDirectMigration } from "@voidhash/mimic-server/migrate";
import { NoteV0 } from "../schema/note-v0";
import { addSlug, NoteV1 } from "./0001_add_slug";

it("derives the slug from the title", () => {
  const before = NoteV0.encode({ title: "Write Tests" });

  const after = runDirectMigration(addSlug, before);

  expect(NoteV1.decode(after)).toEqual({ title: "Write Tests", slug: "write-tests" });
});

When the migration cannot produce a valid result, it throws InvalidDirectMigrationError with a code and, for a problem with a value, the path to it:

codeMeaning
invalid_sourceThe input does not match the migration's from schema
invalid_targetThe result does not match the to schema
async_migrationmigrate returned a promise or wrote after it returned
read_only_writemigrate wrote through oldRoot

These are the codes the server reports for a failing document, so a test that reproduces a failure locally tells you exactly what verification will say.

Reproducing the server's randomness and clock

A migration that generates ids or reads the clock gets seeded randomness and a fixed clock on the server. withSeededRuntime from @voidhash/mimic-server/migrate/artifact installs the same sources for the duration of a function, so a test sees the values the server would produce:

import { withSeededRuntime } from "@voidhash/mimic-server/migrate/artifact";

const context = {
  documentKey: "doc-1",
  incarnation: 1n,
  artifactHash: "00".repeat(32),
  stagedAt: 1_767_225_600_000,
};

const first = withSeededRuntime(context, () => runDirectMigration(addIds, before));
const second = withSeededRuntime(context, () => runDirectMigration(addIds, before));

expect(second).toEqual(first); // same ids both times

The function must be synchronous. Math.random, crypto.randomUUID, crypto.getRandomValues, Date.now() and new Date() are replaced while it runs and restored afterwards. @voidhash/mimic-server/migrate/artifact is for Node only: import it from tests and build scripts.

Checking a whole chain

A migration registry describes a collection's baseline schema and all its migrations in order. defineMigrationRegistry checks the chain's shape when it is built, and throws if:

  • the versions are not 1, 2, 3 and so on without gaps;
  • a migration's from is not the schema the previous one produced;
  • a collection is listed twice.
import { defineMigrationRegistry, validateMigrationRegistry } from "@voidhash/mimic-server/migrate";

export const registry = defineMigrationRegistry([
  {
    database: "production",
    collection: "notes",
    baseline: NoteV0,
    migrations: [addSlug, addPinned],
  },
]);

validateMigrationRegistry then runs every chain and returns a list of issues, empty when all is well:

it("every migration produces its target schema", () => {
  const issues = validateMigrationRegistry(registry, {
    samples: () => [NoteV0.encode({ title: "A realistic note" }), NoteV0.encode({ title: "" })],
  });

  expect(issues).toEqual([]);
});

It reports two kinds of issue:

  • required-field-without-default: a migration without a migrate function whose target adds a required field that has no default. Such a migration fails on every document.
  • migration-failed: a step threw when the chain was run. The chain is run on the baseline schema's default value, when it has one, and on every sample you supply.

Samples are encoded for the baseline schema and are migrated through the whole chain. Add samples that look like your oldest and oddest documents.

latestMigrationPrimitive(definition) returns the schema at the end of a collection's chain: the to of its last migration, or the baseline.

Finding lossy schema changes

analyzeMigration({ oldSchema, newSchema }) compares two schemas without looking at any document and lists the changes that can make documents fail or lose data:

codeMeaning
incompatible-typeA value's kind or literal changed, or a union or either variant was removed
required-field-without-defaultA field became required and has no default
removed-fieldStored data under this path has no place in the new schema
invalid-treeA tree lost a node type, or a parent no longer allows a child type
invalid-valueA validator is new; stored values were never checked against it
import { analyzeMigration } from "@voidhash/mimic-server/migrate";

const issues = analyzeMigration({ oldSchema: NoteV0.schema, newSchema: NoteV1.schema });
// [{ code, path, message }]

An issue is a warning, not an error: a migrate function may handle exactly what the analysis reports.

reconcileMigrationValue({ oldSchema, newSchema, value }) does the same for one document. It returns the reconciled value together with dropped, the paths of stored data the new schema no longer holds, or the issue that makes reconciliation fail.

Record migrations

runRecordMigration(migration, document, context) from @voidhash/mimic-server/migrate/artifact runs a record migration on a whole encoded document as the server does: one run per record, each under that record's seeded runtime, with the result checked against the target schema.

import { runRecordMigration } from "@voidhash/mimic-server/migrate/artifact";

const after = runRecordMigration(boardRecords, BoardV1.encode(board), {
  documentKey: "board-1",
  incarnation: 1n,
  artifactHash: "00".repeat(32),
  stagedAt: 1_767_225_600_000,
});

Next