Skip to content
Latchkey

Knex "The migration directory is corrupt" in CI

Knex compared the knex_migrations table to the files on disk and found migrations recorded as run that have no matching file. It refuses to continue because the history and the directory disagree.

What this error means

knex migrate:latest fails immediately listing migration filenames that are "missing", before applying anything. It is deterministic - those files are genuinely absent from the checked-out tree.

knex output
migration directory is corrupt, the following files are missing:
20240115_add_orders.js

Common causes

A recorded migration file is missing

A migration that already ran (and is in knex_migrations) was deleted, renamed, or lives on an unmerged branch, so its file is not on disk.

Database ahead of the code

CI points at a shared database that ran migrations the current branch does not contain, so those filenames have no file here.

Renamed migration changes the recorded name

Knex keys on the filename; renaming an applied migration makes the recorded name unresolvable against the new file.

How to fix it

Restore the missing migration files

Bring the recorded files back - usually by merging the branch that contains them or reverting the deletion.

Terminal
git log -- migrations/                 # find when files were removed
git checkout <commit> -- migrations/   # restore the missing migration

Use a clean database in CI

  1. Start each CI run from an empty database so knex_migrations is rebuilt from the files present.
  2. Run knex migrate:latest against that clean database.
  3. Avoid pointing CI at a shared database migrated by other branches.

How to prevent it

  • Treat applied migration files as immutable - never delete or rename them.
  • Use an ephemeral database per CI run.
  • Merge migration files deliberately so the directory matches knex_migrations.

Frequently asked questions

What causes ""migration directory is corrupt""?
A migration that already ran (and is in knex_migrations) was deleted, renamed, or lives on an unmerged branch, so its file is not on disk.
How do I fix "migration directory is corrupt"?
Bring the recorded files back - usually by merging the branch that contains them or reverting the deletion.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card