Skip to content
View as Markdown

Operating TailorDB Migrations (Beta) ​

Beta: The tailordb migration command and the migration runtime are beta features. They may introduce breaking changes in future releases. The CLI emits a beta warning on every invocation.

This page covers deploying the migrations that TailorDB Migrations describes how to write, and recovering when one fails. For testing them first, see Testing TailorDB Migrations.

Automatic Migration Execution ​

When you run tailor deploy, the SDK detects pending migrations (anything past the current sdk-migration label on the deployed namespace) and runs them in order before continuing with the rest of the apply.

Per-migration phases ​

For each pending migration:

  1. Pre-migration: Schema changes that would be breaking are applied in a relaxed form first. A verified in-place field type change keeps its complete previous field contract until Post-migration, including field and table-level hooks or validators changed by the same migration. Newly-required fields are added as optional; fields whose optional → required transition is breaking are temporarily kept optional. Fields that are being removed in this migration are temporarily kept on the table so that migrate.ts can still read them (for example, to innerJoin through a foreign key that is about to be dropped); members removed from a nested field are kept the same way, and the new member of a confirmed nested rename is added as optional and non-unique. Added or newly required nested members are optional, newly unique nested members are not yet unique, and removed nested enum values remain allowed until Post-migration. For a renamed field, the old field is kept and the new field is added with its constraints relaxed, so the script can read the old field and write the new one. For a renamed table, the new table is created with its full constraints while the old table stays on the namespace until post-migration cleanup, so the script can copy rows between them. A foreign key added to an existing top-level field, or moved to another table or key (including one that follows a renamed table), is withheld until Post-migration, so migrate.ts can update rows whose values point at no record of the target; Post-migration adds it without checking the stored values. Breaking table-level index changes are relaxed the same way: a newly-added unique index is withheld, and an index gaining a unique constraint (or a unique index changing its field set) keeps its previous definition, so migrate.ts can resolve duplicates first. Non-breaking changes that are part of the same migration are also applied here. A table the migration adds is created here even when a later pending migration of the same deploy removes or renames it away again, so migrate.ts can use it.
  2. Script execution: If migrate.ts exists on disk for this migration, it is bundled and runs on the platform as the configured machine user inside a transaction — or, for a script that exports steps, one transaction per step. The script is hard-required for breaking changes (diff.requiresMigrationScript) — deploy fails if the file is missing, unless a --no-script acknowledgment was recorded (see Breaking changes without a script). It is also executed when present for warning-tier diffs — see Warnings and optional migration scripts.
  3. Post-migration schema: Required constraints and the target field definitions are applied. Do not assume that removing a field clears its underlying stored JSON value.
  4. Checkpoint and cleanup: The sdk-migration label is bumped to this migration's number, then removed GQL permissions and tables — including the old table left behind by a rename — are deleted. Advancing the checkpoint first prevents a failed checkpoint write from requiring the SDK to recreate irreversibly deleted records. A table that an earlier pending migration of the same deploy added is deleted here too. A removed table that a later pending migration adds back is deleted here too, with its records, and the migration that adds it back creates it again without them, the same as when each migration is deployed on its own. When the workspace has such a table, the deploy plan lists it as deleted and created.

This split is what allows existing rows to be backfilled before the database starts rejecting nulls, and what lets migrate.ts traverse foreign-key fields that the same migration removes.

Maintenance mode ​

maintenanceMode in defineConfig decides whether tailor deploy puts each namespace with pending migrations into maintenance mode while it applies them. A table in maintenance mode accepts no GraphQL create, update, delete, or bulk upsert operation and publishes no record events; its read setting is left as it is.

ValueMaintenance mode
falseNone. Nothing is restricted while migrations run.
"migration" (default)From before the first pending migration runs until the last one completes.
"deploy"From before the first pending migration runs until the deploy has applied every other change, including resolvers, executors, and workflows, and has removed the resources it deletes.

A deploy without pending migrations never enters maintenance mode. When maintenanceMode is unset, it behaves as "migration", preserving the existing deployment behavior. The value is read from the config like any other, so it can differ per environment (see Multi-Environment Configuration):

typescript
export default defineConfig({
  name: "my-app",
  maintenanceMode: process.env.APP_ENV === "production" ? "deploy" : false,
});

Without maintenance mode, the SDK does not guarantee what requests that run during the migration observe. A table can still have its pre-migration shape, with new required fields optional and removed fields present; a client can write rows after migrate.ts has already read the table; and the records migrate.ts writes publish events to the executors of the previous deploy, which were written for the old shape. Use it only where clients and executors tolerate that.

"migration" vs "deploy": the new resolvers and executors are deployed after the migrations. With "migration", the migrated tables accept requests and publish events again while the resolvers and executors of the previous deploy are still in place. "deploy" keeps the tables in maintenance mode until they are replaced.

Maintenance mode restricts GraphQL writes and record events only. Resolvers, executors (including scheduled and webhook triggers), and workflows keep running, and the writes they make through Kysely are not blocked.

When a deploy stops early:

  • If a migration fails, the tables leave maintenance mode before the error is reported: they return to the settings of the last checkpoint that completed. A migration that did not reach its checkpoint returns existing tables to their previous settings and drops the tables it created (see Failure Recovery). A created table that the rollback cannot drop stays in maintenance mode, and the deploy names it; deploying again runs the migration again. The settings are not restored if the checkpoint number or migration history changed concurrently, or if checkpoint ownership cannot be verified. A table left behind by a failed post-checkpoint deletion stays in maintenance mode until the next deploy deletes it (see Failure Recovery).
  • With --no-schema-check, if a local table definition that the migrations do not include cannot be applied after they complete, the existing tables leave maintenance mode with the definitions of the last migration before the error is reported (see Schema verification).
  • A multi-step migration left in progress keeps its tables in maintenance mode until a deploy completes it.
  • A migration whose script run a deploy could not confirm keeps its tables in maintenance mode until you settle it with tailor tailordb migration resolve (see Failure Recovery).
  • With "deploy", if a later part of the deploy fails, the tables leave maintenance mode before the error is reported. When the deploy ends maintenance mode, it leaves the tables of a namespace unchanged if that namespace's checkpoint number or migration history changed concurrently, or if checkpoint ownership cannot be verified, and reports it.
  • If the deploy process is interrupted after a namespace's migrations completed but before maintenance mode ended, that namespace's tables stay in maintenance mode until a later tailor deploy releases them when it applies its TailorDB changes, before it replaces resolvers and executors. A namespace whose migrations had not all completed is not released this way: the next deploy resumes a multi-step migration left in progress, and stops at a migration whose script was running until you settle it. Every migration checkpoint of a namespace records the maintenance mode, so with pending migrations 0001 and 0002, a deploy interrupted right after the checkpoint of 0001 leaves the tables in maintenance mode; the next deploy keeps them there while it applies 0002 and releases them afterwards (with "deploy", after the whole deploy).
  • A deploy interrupted before it recorded a migration as in progress (for example, right after the migration's pre-migration schema changes reached some or all of its tables) leaves no record of that migration. The next deploy accepts tables that have the schema of the checkpoint or the migration's pre-migration schema, and runs the migration again from the start. To return the tables to the checkpoint without deploying, run tailor tailordb migration resolve --rollback (see Settling a migration that stays in progress).

Keeping maintenance mode short ​

Maintenance mode lasts for the whole migration job, including the time the platform takes to start it, which can far exceed the time migrate.ts itself needs. Keep in migrate.ts only the work that must be done before the post-migration schema is applied, and move the rest into a workflow that you start after the deploy (for example with tailor workflow start).

  • Must stay in migrate.ts: anything the post-migration schema enforces or removes — filling a field that becomes required, resolving duplicates before a unique index, converting values for a field type change, and copying data out of a field or table that the migration renames or removes.
  • Can move to a workflow: work the post-migration schema does not depend on, such as filling an optional field, recomputing derived values, or cleaning up rows. Requests that run before the workflow finishes see the data in its unfixed state.

Time spent in maintenance mode ​

When maintenance mode is on, tailor deploy reports how long the migrating namespaces' tables were restricted, split into phases. With "deploy", the window also includes the remaining deployment changes and ends when their restrictions are lifted. No maintenance report is emitted with maintenanceMode: false.

PhaseCovers
restrictPutting the tables into maintenance mode
pre-migrationPre-migration schema changes
job setupBundling migrate.ts and registering it as a job
waiting to startTime when the platform has accepted the job but none of its code runs yet
runningTime when the script runs
job cleanupCollecting the script's logs and removing its job, unless its steps run as separate jobs
post-migrationPost-migration schema changes, the checkpoint update, cleanup, and local definitions no migration includes
remaining deployWith "deploy", applying the remaining deployment changes while tables stay restricted
restoreTaking the tables out of maintenance mode

Phases that repeat across several migrations are added up. The report is printed only after the migrations succeed and the tables leave maintenance mode; when a migration fails, deploy reports the error instead (see Failure Recovery). When deploy resumes a migration that an earlier deploy left in progress, the tables were already in maintenance mode before it started, and the report covers only this deploy. A job can be reported as started on the platform well before its code runs, so deploy tells waiting from running by a line every job of a migration logs before your script: [tailor-sdk] migration script started. You may see that line in function execution logs; deploy leaves it out of the logs it prints. A script that exports steps waits for each step's job to start, and that time counts as waiting to start too. Time when deploy cannot tell whether the script is running — because the run or a running job's logs could not be read, or because an older SDK version started the run and it never logs the line — is reported as waiting to start or running instead.

Deploy checks the run every few seconds, so a boundary between waiting to start and running can be off by that much. With --json, the same breakdown is in tailordbMaintenance (see Deploy JSON result). Add --verbose to also print how long each phase took and every change in the job's status.

Schema verification ​

Before running migrations, apply performs two checks:

  1. Local schema check — your current table definitions must match the latest snapshot in migrations/. If they don't, you forgot to run migration generate.
  2. Remote schema check — the deployed schema is reconstructed from migration history; the actual remote schema must match. Drift here means someone applied a different set of migrations or edited the schema out-of-band. A namespace that has tables but no migration label yet must match 0000 (see Adding migrations to an existing project). When no migration is recorded as in progress, a table may also have the pre-migration schema of the next migration, which an interrupted or failed deploy left; the deploy then runs that migration again from the start (see Maintenance mode). With maintenance mode on, such a table must be in maintenance mode.

On drift you'll see something like:

✖ Remote schema drift detected:
Namespace: tailordb
  Remote migration: 0007
  Differences:
  Table 'User':
    - Field 'email': required: remote=false, expected=true

The error also points you at migration status, migration generate, and migration sync — see Remote schema drift detected for which one applies.

To run the same checks without deploying — plus migration file integrity (numbering, parseable contents, a migrate.ts or a recorded --no-script acknowledgment for every migration that requires a script, and no TODO() call left in a migrate.ts):

bash
tailor tailordb migration validate

It reports issues per namespace, exits with a non-zero code when any check fails, and supports --json for machine-readable output.

With --strict, validation additionally fails when a migration not yet applied to the remote has data-loss warnings (see Warnings and optional migration scripts) but neither a migrate.ts nor a recorded --no-script acknowledgment. The failure names the affected table and field and prints the exact commands to add a script and to record the acknowledgment.

To bypass both checks during deploy (not recommended outside of recovery scenarios):

bash
tailor deploy --no-schema-check

With pending migrations, each migration still applies its own table definitions in its phases, so migrate.ts sees the schema it was written for. Local table definitions that differ from the last pending migration are applied after every pending migration has completed, and the deploy lists those tables. A table that a pending migration removes or renames away is deleted with its records even when the local definitions still have it; unless a later pending migration adds it back, its local definition then creates it again. Tables that the local definitions no longer have are deleted after that in the same deploy, even when no migration removes them. With maintenance mode on, existing tables stay in it until their local definitions are applied. If one of them cannot be applied, for example a unique constraint on a field whose records hold duplicate values, the deploy fails with MIGRATION_LOCAL_DEFINITIONS_FAILED: the migrations stay applied, tables already created for their local definitions remain, the existing tables keep the definitions of the last migration and leave maintenance mode, and tables that no migration removes are not deleted.

--no-schema-check does not bypass the check that the remote migration checkpoint is in the local migration history. See "Remote migration checkpoint is not in the local migration history" error.

Example output ​

ℹ Executing 1 data migration(s)...

ℹ Using machine user: admin-machine-user for namespace 'tailordb'
10:42:31 AM ℹ Migration tailordb/0002 started running after waiting 15m02s for its job to start.
✓ Migration tailordb/0002 completed successfully (waiting to start 15m02s, running 1m41s)

✔ All data migrations completed successfully.
ℹ Tables of namespace tailordb were in maintenance mode for 16m56s (restrict 1.2s, pre-migration 3.4s, job setup 2.1s, waiting to start 15m02s, running 1m41s, job cleanup 0.8s, post-migration 4.0s, restore 1.1s).
✔ Successfully applied changes.

Re-baselining a deployed migration history ​

tailor tailordb migration rebaseline collapses the complete history into a new 0000/schema.json in the current migration format. It does not modify the deployed schema or data.

Before running it:

  1. Apply the latest migration to every environment. The CLI verifies the connected workspace, but it cannot inspect other workspaces.
  2. Commit or otherwise preserve the existing migration history. Files after 0000, including migrate.ts and db.ts, disappear from the working tree; Git history retains committed files.
  3. Make sure local table changes have been captured with tailor tailordb migration generate.

Then re-baseline one namespace:

bash
tailor tailordb migration rebaseline --namespace tailordb

The command validates the migration files, verifies that replaying the latest migration exactly reproduces the local table definitions, and checks that the connected workspace is at that latest migration with no schema drift. After confirmation, it replaces the local history with the reconstructed baseline, records a new migration history ID in both 0000/schema.json and remote metadata, and resets the connected workspace's sdk-migration label to 0000. Use --yes only after arranging the same operational preconditions in non-interactive automation.

When the connected workspace records another migration history ID, or one that cannot be read, the command refuses to run. Run it from a checkout of the migration history deployed to that workspace. To replace the workspace's history with the local one on purpose, first run tailor tailordb migration sync <N> --force with the latest local migration as <N>, which rewrites the workspace's tables to that migration, removing the fields it does not have and deleting the tables it does not have together with their data (see migration sync Semantics). When the workspace's tables differ from the latest migration, the command also refuses to run; see Remote schema drift detected, where tailor tailordb migration sync <N> rewrites the tables to the latest migration.

Commit the resulting migrations/ change before generating any new migrations. For another environment still carrying the exact checkpoint and history ID that the new baseline replaced, the next tailor deploy checks whether its remote schema exactly matches the new 0000. If it does, deploy offers to reset the checkpoint to 0000 and move the environment to the new history ID before applying any later local migrations. Until then, tailor tailordb migration status for that environment reports the reset the next deploy makes and lists the migrations after 0000 as pending; it does not compare the schema, which tailor tailordb migration validate checks. A markerless history is eligible only for the first rebaseline, at the exact migration recorded as replaced. Any other checkpoint or history ID is rejected without changing remote metadata, even if its schema happens to match the baseline.

Partial squashing is not supported: re-baselining always replaces the full history for one namespace.

migration sync Semantics ​

tailor tailordb migration sync <N> reconstructs the schema snapshot at migration N from the working tree's migration history and overwrites the remote schema to match it, then sets the sdk-migration label to N and records the migration history ID of the local baseline. It never runs migrate.ts scripts itself — it only changes what the next apply considers pending:

MovementEffect on next applyEffect on data
Backward (e.g., 0003 → 0001)Migrations 0002 and 0003 become pending and re-execute, including their migrate.ts.Tables absent from snapshot 0001 are deleted along with their data. Fields absent from it are removed, and may come back with their earlier values when a re-executed migration adds them again; re-executed scripts may rewrite data.
Forward (e.g., 0001 → 0003)Migrations 0002 and 0003 are skipped — their migrate.ts scripts will not run.Data the skipped scripts would have migrated stays as-is.

Before anything is sent to the remote, sync verifies that replaying the full migration history reproduces the current local table definitions. If it does not — because migration files were edited and no longer match, or because a schema change has not been recorded with migration generate yet — the command fails without touching the remote. This means a rewritten migration history is validated before it can overwrite the deployed schema.

sync refuses to run when the namespace records another migration history ID, or one that cannot be read, before it reads or changes any table, unless the namespace has neither a checkpoint nor a history ID yet. Run it from a checkout of the migration history deployed to the workspace. To write the local history over another one on purpose, for example after migration rebaseline re-baselined the local history but could not update the workspace, pass --force: it overwrites the tables with those of the local history and replaces the history ID with the local one, or removes it when the local history has none, and still asks for confirmation unless you pass --yes.

Because syncing backward causes already-applied scripts to re-execute on the next deploy, write migrate.ts scripts to be idempotent (see Performance and Large Tables for resumable where clauses).

The main use cases are:

  • Recovering from drift after a deploy --no-schema-check, which deploys the local table definitions without checking them against the migration snapshots: run migration sync <N> to restore the remote to a known snapshot, then tailor deploy to apply the remaining migrations from the working tree.
  • Moving a checkpoint that tailor deploy reports as not in the local migration history back to that history on purpose (see "Remote migration checkpoint is not in the local migration history" error).
  • Recording that the tables already match migration N, for example after you fixed them by hand or applied a migration outside the migration history. sync <N> sends the same table definitions again, so only the checkpoint changes, although its confirmation still lists the tables as updated.
  • Re-running a faulty migration in a development workspace (see Rollback Strategy).

Team Workflow and CI/CD ​

Branch coordination ​

Migration numbers are assigned sequentially, so two developers branching off the same point and each generating 0005 will collide. Conventions that work:

  • Don't generate migrations on long-lived feature branches. Generate them just before merge, after rebasing onto main.
  • Resolve collisions by re-generating. If your branch has 0005 but main now has 0005 from another PR, regenerate yours as 0006 — see Resolving a migration number conflict.
  • Treat migration files as merge-conflict-prone. They are committed JSON and TypeScript, so review them in PRs. The diff.json is the source of truth — if review focuses there, regenerating after rebase is straightforward.

Resolving a migration number conflict ​

When your branch and main each generated the same number, merging or rebasing stops with an add/add conflict on migrations/0005/diff.json. Resolve it by re-generating your migration on top of main's:

  1. Save your script edits aside. If you customized 0005/migrate.ts, keep a copy before touching the directory — during a rebase, git show ORIG_HEAD:migrations/0005/migrate.ts prints the version from your pre-rebase branch tip.
  2. Take main's 0005/ directory in full. Accept main's version of every conflicting file. Then check for files only your side added: if your migration has a migrate.ts and main's does not, that file never conflicts — it silently stays next to main's diff.json. Delete such leftovers explicitly.
  3. Finish the rebase or merge, then re-run migration generate. With main's migration now part of local history, the diff is computed against the correct base — including main's changes — and your migration lands as the next number (0006).
  4. Port your script. Copy the logic saved in step 1 into the newly scaffolded 0006/migrate.ts. For a warning-tier change, migration generate does not scaffold a script — recreate it first with tailor tailordb migration script 0006.

When a plain rename is enough. If the two migrations touch disjoint tables and fields, renaming your directory to the next free number (keeping main's 0005/) can be acceptable. Run tailor tailordb migration validate after the rename: if it reports a mismatch, the migrations were not disjoint — discard the rename and re-generate as above. A passing check covers only the schema history, not your script: migrate.ts now runs after main's migration, so confirm it does not read or write tables that migration touches — when in doubt, re-generate.

CI / CD ​

  • For non-interactive environments, pass --yes to migration generate and --yes to apply. apply runs migrations automatically when the migrations/ directory is configured.
  • Run tailor tailordb migration validate in CI to catch, before deploying, uncommitted migrations, broken migration files, unreviewed generated normalization logic, remote schema drift, and pending migration scripts that tailor deploy could not run. It exits with a non-zero code when validation fails and supports --json. Add --strict to also require an explicit acknowledgment (a migrate.ts or a recorded --no-script reason) for every pending migration that can drop data, so destructive changes cannot merge unnoticed.
  • tailor tailordb migration status validates the layout and file-format compatibility of the full local history, compares its history ID with the deployed namespace, and shows applied and pending migrations for a human-readable comparison. Its exit code is non-zero on invalid or incompatible files, migration history mismatches, a remote checkpoint ahead of the latest local migration, and remote read errors, so check the output. A namespace still at the checkpoint and migration history that the local baseline replaced is not a mismatch (see Re-baselining a deployed migration history), but the command also exits non-zero when such a namespace records a migration in progress, because the next deploy refuses to reset its checkpoint.
  • Avoid running migrations in parallel against the same workspace — there is no locking. Serialize deploys per environment.

Resetting a deployed project ​

Use tailor tailordb migration rebaseline rather than combining migration generate --init with a manual checkpoint change. See Re-baselining a deployed migration history for the required cross-environment coordination and verification.

Failure Recovery ​

A script that exports steps follows different rules once one of its steps has completed: the migration stays in progress and the next deploy resumes it, unless the script exports onFailure = "rollback". See Splitting a migration into steps and Rolling back instead of resuming. Otherwise, if the pre-migration phase or migrate.ts fails:

  • The transaction rolls back for that migration's script. Database changes the script made are undone.
  • The pre-migration schema changes are rolled back to the prior checkpoint: tables that already existed are restored to their previous shape and GraphQL permissions, and tables the migration newly introduced are dropped. The workspace is left at its prior checkpoint and prior schema — not half-applied.
  • The whole apply aborts and the checkpoint label is not bumped. Subsequent migrations in the same run do not execute.

The rollback is best-effort per table; if reverting a table fails, a warning is logged and the original migration error is still reported. A table left with the migration's pre-migration schema does not stop the next deploy, which runs the failed migration again from the start. This happens, for example, when the script wrote records without a value for a field the migration makes required: the platform refuses to make the field required again while such records exist. tailor tailordb migration resolve --rollback returns such tables to the checkpoint without deploying, once those records have a value. A table left in any other shape makes the next deploy stop with remote schema drift on that table. Run tailor tailordb migration validate to see which tables differ, return the namespace to its checkpoint with tailor tailordb migration sync <N>, where <N> is the checkpoint tailor tailordb migration status reports, and deploy again. sync removes the fields that are not in that migration's snapshot and deletes the tables that are not in it together with any rows the failed migration wrote to them; the next deploy runs the failed migration again.

If tailor deploy cannot tell whether a main script ran, for example because the connection dropped while it started or waited for the script, it does not roll anything back: the pre-migration schema changes stay, the namespace's tables stay in maintenance mode if it is on, the migration stays recorded as in progress, and the deploy reports that it could not confirm the outcome. The same holds when the deploy process stops while the script runs. Until you settle the migration, tailor deploy stops before changing anything, including the other namespaces and resources of the application, and reports how the run stands, even with --no-schema-check. Run tailor workflow executions --workflow-name <name> with the workflow name the error reports until the execution has finished. If it succeeded, run tailor tailordb migration resolve --complete, which applies the migration's schema without running the script again; otherwise run tailor tailordb migration resolve --rollback, and the next deploy runs the script again. See Settling a migration that stays in progress, which also lists the commands that refuse to run until then.

If the post-migration schema changes fail after a main script succeeded and the deploy cannot clear the in-progress record, it keeps the pre-migration schema instead of rolling it back, so the data the script wrote stays. Settle the migration as above: --complete once the data meets the migration's schema, or --rollback.

When a steps migration's post-migration schema changes fail and the deploy cannot return its tables to the pre-migration schema, it logs a warning. The next deploy accepts each table in either the pre-migration or the post-migration schema: it applies the pre-migration schema again and retries the post-migration schema changes without running the completed steps again unless you add, remove, or rename a step, change the order the steps run in, or the earlier run is no longer available.

After a failure:

  1. Read the Logs: block in the apply output to find the cause.
  2. Fix migrate.ts (or the data it depends on).
  3. Re-run tailor deploy. The same migration runs again because its label was never bumped, and the prior-checkpoint schema is a clean baseline to retry against.

If a migration succeeds in script but its reversible post-migration schema update fails (rare; usually a constraint violation the script should have prevented), the SDK makes the same best-effort restoration to the prior-checkpoint schema. The script's committed data changes remain, so write migration scripts to tolerate re-execution.

Before a migration's script starts, tailor deploy checks that the namespace's checkpoint and migration history are still the ones it read before applying, or the checkpoint it committed itself. If another deploy or a tailor tailordb migration command changed them in the meantime, or the deploy cannot read them, the script does not start and the migration is not recorded as in progress: the deploy handles the pre-migration schema as for a script that failed before it ran, and fails with MIGRATION_CHECKPOINT_CONFLICT (MIGRATION_CHECKPOINT_UNVERIFIED when it cannot read them). Run tailor tailordb migration status to see the checkpoint. Wait for the other deploy to finish, or, when no other deploy is running, return the namespace to the checkpoint the error names with tailor tailordb migration sync <N>, which also lifts the maintenance mode the deploy left in place, and deploy again. If the error says the checkpoint changed in a different migration history, or with a migration history label that cannot be read, sync also needs --force, which replaces the workspace's migration history ID with the local one. Pass it only when the local migration history should replace the deployed one; otherwise deploy from a checkout of the migration history deployed to the workspace.

The checkpoint is advanced only after the reversible post-migration schema updates succeed. If the checkpoint write reports an error, the SDK reads it back: a matching value is treated as committed. Any other observed value leaves the post-migration schema unchanged rather than risk rolling back a concurrent deployment; a value beyond the current migration confirms a concurrent deploy, while an older or missing value means the checkpoint must be repaired before retrying, unless the value is the previous checkpoint and the multi-step migration is still recorded as in progress, which the next deploy resumes. If read-back also fails, the SDK likewise leaves the post-migration schema unchanged; verify the remote checkpoint before retrying.

Removed tables are deleted only after the checkpoint is committed. The deploy records with the checkpoint that these deletions are still to run, and clears the record once they finish. If that cleanup fails or the deploy is interrupted, the checkpoint remains at the new migration, and the next deploy finishes the cleanup: it lists the tables that migration removed among the tables to delete, and deletes them and their GQL permissions with their data before it runs any pending migration. A leftover table that a later migration adds back is deleted the same way and created again when that migration runs, so it starts without the old rows. tailor tailordb migration validate reports them as tables the next deploy deletes. To delete them without deploying, run tailor tailordb migration sync <N> with the committed migration as <N> (when the cleanup fails, the deploy error's suggestion names the command). A same-named remote table is still reported as remote schema drift when no unfinished cleanup is recorded, for example a table created again after the cleanup completed or one left by an SDK version that did not record the cleanup; delete it with migration sync <N> or by hand, and then deploy again. A deploy with --no-schema-check does not finish the cleanup first: when the namespace has pending migrations, it deletes the leftover tables that the local definitions no longer have after those migrations complete (see Schema verification).

With --no-schema-check, local table definitions that the pending migrations do not include are applied after every migration has committed (see Schema verification). If one of them cannot be applied, the deploy fails with MIGRATION_LOCAL_DEFINITIONS_FAILED: the migrations stay committed, the existing tables go back to the definitions of the last migration, and tables already created for their local definitions remain. Fix the cause and deploy again. When existing records refuse the definition, for example a unique constraint on a field whose records hold duplicate values, run tailor tailordb migration generate to add the change in a migration whose script updates those records, then deploy again; the error's suggestion names the command.

Rollback Strategy ​

There is no automatic down-migration. To roll back a schema/data change in production, write a new forward migration that reverses the previous one. For example, to undo a 0005 that added a required email field:

  1. Edit your table definitions to remove the field.
  2. migration generate --name "rollback 0005 email" produces 0006 with a removal diff.
  3. Apply.

In development workspaces, a quicker option is to fix 0005/migrate.ts in place, run migration sync <previous> to return the tables to the previous migration and re-mark 0005 pending, and apply. sync removes the fields 0005 added and deletes the tables it added together with their data, and stops before moving the checkpoint when existing rows have no value for a field the previous migration requires. When 0005 is applied again, the fields it added may come back with the values the faulty script wrote (see migration sync Semantics), so make the fixed script overwrite them instead of skipping records that already have a value. Do not do this on production — it confuses migration history across environments.

Machine User and Permissions ​

Migration scripts execute server-side under a machine user identity. The CLI selects the user in this priority order:

  1. db.<namespace>.migration.machineUser if set in tailor.config.ts.
  2. The first entry in auth.machineUsers otherwise.

The selected user must be defined in auth.machineUsers. The CLI logs the selected user before running scripts (Using machine user: ...).

In a defineWorkspace() config with several Auth services (Beta), there is no first entry to fall back to, so set migration.machineUser on each namespace with migration scripts; tailor deploy stops with MACHINE_USER_REQUIRED otherwise. The name must be defined by exactly one of the Auth services (MACHINE_USER_AMBIGUOUS), since migration.machineUser takes no Auth service name.

When a pending migration has a migrate.ts, tailor deploy checks while planning that auth is configured, that a machine user is selected and defined in auth.machineUsers, and that each script can be bundled. A failure stops the deploy before anything is applied, and tailor deploy --dry-run reports it too. tailor tailordb migration validate runs the same checks for the migrations that are pending in the workspace it validates.

Permissions required

The machine user needs read/write access to every table the migration script touches. If your migrations alter data across multiple tables, the simplest path is to give the migration user broad access (e.g., an ADMIN role) and restrict day-to-day machine users separately. If the user lacks permission, the script fails with a permission error in Logs:.

If you see No machine user available for migration execution, either:

  • Add machineUsers: { ... } to your auth config and tailor deploy it, or
  • Set migration.machineUser to a machine user defined in auth.machineUsers.

Multi-Namespace Coordination ​

If your project defines multiple TailorDB namespaces (db: { ns1: { ... }, ns2: { ... } }), each has its own migrations/ directory and its own migration label. During apply:

  • Pending migrations run one namespace at a time, in alphabetical order of the namespace names, and within a namespace in migration number order. With pending migrations in inventory and billing, every one of billing runs before any of inventory.
  • With maintenance mode on, every namespace of the config that has pending migrations enters maintenance mode before the first migration runs, and they leave it together: after the last migration with "migration", and after the whole deploy with "deploy". Maintenance mode describes the exceptions when a deploy stops early.
  • The order follows the namespace names, not dependencies between namespaces. Do not write a migration in ns1 that depends on data produced by a migration in ns2 running first.
  • Each namespace can specify its own migration.machineUser.

Several configs in one deploy ​

When one deploy applies several configs (see Multiple Config Deploys), it applies each kind of resource for every config, in the order the configs are listed, before it moves on to the next kind. For tailor deploy --config supplier.ts,buyer.ts, the secrets, static websites, AI gateways, IdPs, auth services and machine users, and function registries of both configs are applied first. Then the TailorDB changes and migrations of supplier are applied, then those of buyer, then the resolvers of supplier and buyer, and so on through the applications, executors, and workflows. Each config's maintenanceMode covers only its own namespaces, so with "deploy" in supplier, its tables stay in maintenance mode while the migrations of buyer run.

If a migration of buyer fails, the deploy stops there and leaves supplier in this state: its migrations have completed and its checkpoint has advanced, its tables are out of maintenance mode even with "deploy", and nothing after TailorDB has been applied, including its resolvers, executors, and workflows. Its tables therefore have the new schema while the resolvers and executors of the previous deploy still use them. When you fix the migration of buyer and deploy both configs again, supplier has no pending migrations, and the deploy applies the rest of its changes. If the migration of buyer must first be settled with tailor tailordb migration resolve (see Failure Recovery), every deploy of the two configs stops before changing anything until then.

Performance and Large Tables ​

The migration script runs in a single transaction. For tables with many rows:

  • Prefer set-based SQL (updateTable(...).set(...).where(...)) over per-row loops.
  • If a per-row loop is unavoidable, batch by primary key range. Avoid OFFSET-based pagination — it scans previously-seen rows on every page.
  • Long-running transactions can hit platform timeouts and hold locks. For very large backfills, consider splitting the work into steps or across multiple migrations, each operating on a subset.
  • Add LIMIT and resumability (idempotent where clauses) so a re-run after a transient failure converges.

Migrations that take longer than a minute ​

Migration scripts run as workflow jobs, so they are not bound by the 60-second limit that applies to synchronous script execution. tailor deploy waits for the migration and reports its logs as usual. Execution time is still bounded — a workflow job has its own execution-time limit.

A main script still runs in a single transaction, so the guidance above about locks and transaction size continues to apply. When a migration's work does not fit one job, split it into steps: each step runs as its own job and transaction.

Environment-Specific Strategies ​

A migration script is a function — branching on environment (e.g., to skip a backfill in dev) is just normal TypeScript. For environment awareness, use the env values defined in defineConfig({ env }), exposed via the optional second argument { env }: MigrationContext (see Migration Script Anatomy). These are resolved at deploy time and inlined into the bundle. Do not read process.env inside migrate.ts — Node-side environment access is unavailable at runtime; only the injected env (and the data itself) reflect the target environment.

For genuinely different schemas across environments, prefer separate workspaces with the same migration history rather than divergent migrations/ directories.

Troubleshooting ​

MIGRATION_DIRECTORY_CONFLICT error ​

Cause: Two or more TailorDB namespaces set migration.directory to the same directory (after resolving it against the config file's directory). For example, tailordb and analyticsdb both set "./migrations". Both namespaces would read and write the same 0000/schema.json, so migration generate could not tell them apart and migration generate --init would rebuild the history of both. Every tailor tailordb migration command and tailor deploy fail with this error before touching any migration files. The error lists every shared directory with the namespaces that use it.

Resolution: Give each namespace its own directory in tailor.config.ts, for example "./migrations/tailordb" and "./migrations/analyticsdb".

Remote schema drift detected ​

Cause: Remote schema doesn't match what the migration history says it should be. When tailor deploy shows Remote migration: <unset>, or migration validate shows no checkpoint yet, the namespace has no migration label yet and its tables differ from 0000; see Adding migrations to an existing project instead of the steps below.

Resolution:

  1. tailor tailordb migration status to see local vs remote.
  2. Compare with teammates — has someone applied different migrations?
  3. If remote was changed manually, decide whether to update the local tables to match and run migration generate, or to return the remote to a snapshot as in the next step.
  4. To force the remote schema back to a known snapshot, use migration sync <N> (see migration sync Semantics). If the drift follows a failed deploy that warned it could not restore a table's schema, see Failure Recovery instead.
  5. As a last resort in non-production environments, --no-schema-check skips both checks. Do not use this as a routine workaround. It does not skip the checkpoint check described next.

"Remote migration checkpoint is not in the local migration history" error ​

Cause: The deployed namespace's checkpoint refers to a migration number, or a migration history ID, that the local migrations/ directory no longer has a record of. This is a different code path from schema drift above: it fires before any schema comparison, because the CLI cannot even locate the remote's recorded position in the local history. tailor deploy stops with this error even with --no-schema-check, so a deploy from an outdated checkout never moves the checkpoint back or overwrites the tables with an older schema.

One specific cause is a migration rebaseline run on a different environment while this one had not yet caught up to the latest pre-rebaseline migration. migration rebaseline requires every other environment to already be at the latest migration (see Re-baselining a deployed migration history), but the CLI only verifies the one workspace it runs against. If this environment was behind, the error message names the migration this environment must reach (the migration every environment was required to be at before the rebaseline) alongside the migration it is actually at.

Resolution (fell behind before a rebaseline):

  1. Restore the pre-rebaseline migrations/ directory from git history — check out the commit before migration rebaseline ran. Re-baselining removes migration files after 0000 from the working tree but Git history retains everything that was committed.
  2. Deploy this environment against that restored history until its checkpoint reaches the migration named in the error, running any migrate.ts scripts it still needs.
  3. Switch back to the current (rebaselined) migration files and deploy again. The remote schema now matches the new baseline, so this deploy offers the automatic checkpoint reset to 0000 under the new history ID.

Resolution (any other cause): Run tailor tailordb migration status to compare local and remote, and pull the latest migration files if your checkout is stale. To move the checkpoint back to the local migration history on purpose, run tailor tailordb migration sync <N> with the latest local migration as <N> (the error suggests the command). It also rewrites the tables to snapshot <N>, removing the fields that snapshot does not have and deleting the tables it does not have together with their data. When the namespace records another migration history ID, or one that cannot be read, the command also needs --force, which replaces that history ID with the local one, or removes it when the local history has none (see migration sync Semantics). Pass --force only when the local migration history should replace the deployed one; otherwise work from a checkout of the migration history deployed to the workspace. Then deploy again.

MIGRATION_FILES_INVALID error ​

Cause: The migrations/ directory of a namespace does not form a valid history: a migration number is missing, 0000 has no schema.json or has a diff.json, or a later migration has a schema.json or no diff.json. A deleted directory or a merge that kept only part of a migration is a common cause. tailor deploy and the tailor tailordb migration commands that read the history report this error, listing every problem.

Resolution: Follow the suggestion for each problem in the error. Otherwise restore the migration files from version control. If no workspace has been deployed with these migrations, you can instead recreate 0000 from the local tables with tailor tailordb migration generate --init --namespace <name>, which deletes every migration of the namespace.

"Invalid schema snapshot" or "Invalid migration diff" error ​

Cause: A schema.json or diff.json file in the migrations/ directory is corrupted or does not match the expected structure. Merge conflicts left in these files are a common cause.

Resolution:

  1. Read the error message — it includes the file path and the offending field.
  2. Restore the file from version control (git checkout -- <path>); migration generate reads every migration file and stops with the same error until then. If the broken file belongs to the latest migration and no environment has deployed it, you can instead recreate that migration: copy out the files you edited in its directory (such as migrate.ts and its tests), delete the directory, run migration generate with the options that created it (such as --data-only, --rename, or --drop), copy your edits back, and record any --no-script reason again with migration script. A migration pair created with --expand-contract cannot be recreated this way, so restore its files from version control.
  3. Do not hand-edit schema.json or diff.json; they are managed by the CLI.

"Unsupported migration file format version" error ​

Cause: A schema.json or diff.json file is older or newer than the format versions supported by the installed SDK.

Resolution: Follow the ordering in the error message. For an older history, restore an SDK version that can read every file, run migration rebaseline, commit and deploy the new baseline everywhere, and then upgrade. For a file produced by a newer SDK, upgrade the SDK that is reading it. Do not hand-edit the version field.

"No machine user available for migration execution" ​

Cause: Neither migration.machineUser is set nor are there any machine users in auth.machineUsers. tailor deploy reports this while planning, including with --dry-run, before anything is applied, and tailor tailordb migration validate reports it too. tailor tailordb migration test checks the users needed for seed, migration, and assertion scripts before creating or modifying its target workspace.

Resolution: Add a machine user to auth.machineUsers, then run tailor deploy again. The deploy creates the machine user before it runs the migration scripts.

"Machine user for migration execution is not defined in auth" ​

Cause: migration.machineUser, or the --machine-user override or seed plugin's machineUserName used by tailor tailordb migration test, names a machine user that is not in auth.machineUsers. tailor deploy reports this while planning, including with --dry-run, before anything is applied, and tailor tailordb migration validate reports it too. The migration test reports it during preparation, before creating or modifying its target workspace.

Resolution: Either add the machine user to auth.machineUsers, or name one that is defined there.

Migration script execution fails ​

Cause: Runtime error in your migrate.ts, a permission error from the machine user, or a constraint violation when post-migration tightens tables.

Resolution: Read the Logs: block. Fix the script or the data assumption it relies on, and re-run tailor deploy. The label is not bumped on failure, so the same migration retries. For a script that exports steps, the logs of each step are prefixed with its name, and the error names the failed step; the retry resumes from that step (see Splitting a migration into steps).

migrate.ts not found for a migration that needs one ​

Cause: diff.requiresMigrationScript is true but migrate.ts is missing from the migration directory.

Resolution: Restore the file from version control, or create it with tailor tailordb migration script <N> --namespace <namespace>. If the migration intentionally needs no data transformation, record that decision with tailor tailordb migration script <N> --namespace <namespace> --no-script --reason "<why no data migration is needed>" instead.