Skip to main content

cognee.run_migrations

Applies all pending database schema migrations before the rest of your application starts.
In releases before Cognee 1.5.0 this function was named run_startup_migrations. That name is gone — update calls to cognee.run_migrations() when you upgrade.
It runs two steps in sequence:
  1. Relational schema — executes alembic upgrade head against your configured relational database (SQLite by default, or Postgres).
    • Cognee first checks whether the database already holds its schema. A database counts as fresh only in two cases: it is a local SQLite database whose file does not exist yet (a filesystem check made before connecting, so the probe never creates the file), or it is a database Cognee could inspect that has neither a users table nor an alembic_version table. A fresh database gets its schema built by running the entire migration chain — the initial revision carries the base schema, and alembic_version only ever records revisions that actually executed, so nothing is stamped. Anything else is migrated normally, so a pre-Alembic legacy database is upgraded rather than mistaken for a fresh one.
    • A database Cognee cannot inspect — unreachable, still starting up, or rejecting the connection — is not treated as fresh. The inspection error propagates and the call fails; see Errors.
    • Applying pending revisions to an existing database is this call’s job alone. The write paths also make sure the relational database exists: setup() before add(), and every pipeline run, call the same table-creation step. That step only builds a fresh database (the same check as above); against a database that already holds the schema it does a single table inspection and returns without touching Alembic, so ordinary requests no longer replay (or log) the migration chain on every call. Pending revisions on an existing database are applied only by run_migrations() — which the first add(), cognify(), or remember() in a process triggers once, unless automatic migrations are disabled — or by cognee-cli upgrade.
    • Revisions c5d7e9f1a3b5 and d6e8f0a2b4c6 complete the dataset-scoping of the data table — see Dataset-scoping upgrade below.
    • This step also heals the SQL session-cache table on existing deployments. Revision c3d5e7f9a1b2 deletes all but the newest row per (user_id, session_id, entry_id) in cache_session_context and creates the uq_cache_session_context_entry unique index that the cache adapter’s upsert targets. It covers both the database Alembic is connected to and the standalone SQLite cache.db that CACHE_BACKEND=sqlite (the default) keeps next to the relational database. Cache tables are created on init rather than managed by Alembic, so fresh databases already get the index from the table definition and only pre-existing tables are touched. Because the migration mutates data and builds a unique index, it can take time and hold locks on a large cache_session_context table — back up the database and run it in a maintenance window.
  2. Vector schema — runs the vector adapter’s run_migrations method for every database that needs it:
    • Single-user mode (ENABLE_BACKEND_ACCESS_CONTROL=False): migrates the single default vector engine.
    • Multi-user mode (ENABLE_BACKEND_ACCESS_CONTROL=True, the default): iterates over every dataset database and migrates each one individually. A failure for one dataset is logged and skipped; the remaining datasets continue to migrate.
    • LanceDB (the default) reads only each table’s schema. If a table’s payload struct no longer matches its model (a field was added or removed, or its type or nullability changed), only that payload column is changed, in place. The vector column is never read or rewritten, and payload exists at every committed version, so readers never see a table without it. Kept fields are cast to their new type, new fields take the model’s default, or null when the field may be null, and removed fields are dropped. A null in a field that becomes required is filled from the model default when there is one.
      • An interrupted migration leaves the table readable. The next migration of that table finishes it first: a leftover __payload_migrating column is dropped and computed again, and a leftover __payload_old column is dropped once the rows written in the meantime are repaired. The startup run logs Proactive LanceDB migration for '<table>' (finishing an interrupted migration). A run interrupted right after the column swap, before it recorded which rows were written meanwhile, cannot be finished safely. It fails with SchemaEvolutionError and keeps __payload_old, and the message explains how to restore those rows.
      • A table whose data cannot be migrated does not stop the rest. Every table is visited, then the failure is raised: that table’s own error when one table failed, or one RuntimeError naming each table when several did (see Errors). run_migrations() does not raise that error. It logs it and records it as the database’s last migration error, which cognee-cli current shows. This vector step runs only when the Cognee version changes, so a later run_migrations() on the same version does not retry it. The next write that hits the old payload shape runs the migration again.
      • The same migration also runs when a write hits a table with an older payload shape. In subprocess mode it runs on the LanceDB worker.
    • If the active vector engine has no run_migrations method, Cognee logs a warning and skips that engine.
    • If the dataset_database table does not exist yet (a fresh database), the vector migration step is skipped with a warning instead of raising. This is handled on both SQLite (OperationalError, “no such table”) and PostgreSQL/pgvector (ProgrammingError / UndefinedTableError).
Migrations that re-embed batch their embedding requests. Some data migrations re-embed rows through cognify’s indexing path; those embeddings are sent in batches, so a large migration no longer fails on provider request-size or rate limits. Batching follows the same EMBEDDING_BATCH_SIZE and EMBEDDING_MAX_CONCURRENT_DATA_POINTS settings as normal indexing; there is no migration-specific setting to tune.

Dataset-scoping upgrade

Cognee 1.5.0 makes Data rows dataset-scoped: a row belongs to exactly one dataset, and the same content added to two datasets is two independent rows (see deduplication). Databases created by an earlier release stored one row shared across datasets through a dataset_data membership table, so upgrading needs a data migration, not just a schema change. Two Alembic revisions do the relational half: The backfill splits rows per dataset:
  • One membership (the overwhelming majority) — the row keeps its original id and is stamped with that dataset, so data ids you stored externally stay valid.
  • Several memberships — the oldest membership keeps the original id; every other dataset gets a fresh row with a new id, all columns copied, and legacy_id recording the pre-split id. Relational ledger rows for those datasets are repointed to the new ids.
  • No memberships — unreachable orphans, left untouched.
Because legacy_id is preserved, every id ever issued keeps resolving within its dataset: Cognee matches the exact id first, then falls back to legacy_id. The graph and vector stores are then brought in line by the rekey_fork_document_ids migration in Cognee’s data-migration chain, which runs after the relational step. For each split (“fork”) document it re-keys the graph document node to the canonical relational id, updates the ledger’s node/edge references, refreshes the document_id property on the document’s chunk nodes, and re-upserts the chunks’ vector index rows — in batched embedding requests, as described above — so their document_id payload cites the canonical id. Chunk point ids are unchanged. Fork rows are rare — same user, identical content, several datasets, all before the upgrade — so on most deployments this is one indexed relational query and no per-document work. When a fork does exist on a large graph, the graph half of that re-key is real work. Its edge-identity and node-id lookups run as chunked index seeks and its provenance restore is attached in batches grouped by pipeline run, so the re-key completes within the worker subprocess deadline instead of timing out — but on a graph of ~100k nodes and ~300k edges it can still run for tens of minutes. On the default embedded Ladybug backend (this does not apply to Neo4j or Postgres graph stores, which have no such cap), give the store headroom under its size cap — the kuzu_max_db_size setting (KUZU_MAX_DB_SIZE) — before starting, and let the run finish: killing a worker mid-checkpoint can leave .lbug.shadow / .wal.checkpoint recovery files behind that block the next open, and repeated interrupted runs can exhaust the cap even while the database is small on disk. Much of that graph work is set-based rather than row-by-row. On Ladybug, the provenance move is one replace() statement over the nodes and one over the edges still carrying the pre-fork key, so the batched restore described above handles only the residue: artifacts that already carry both keys are deliberately left to that generic attach-then-remove sweep, which dedupes them, so the migration still converges on re-run. Every other graph backend — and any engine that rejects those statements — takes the unchanged generic path for the whole move, and the migrated result is identical either way. The survivor-edge repair in the sibling namespace_entity_type_node_ids migration is trimmed the same way on any backend that can list its edges in one scan: it asks which at-risk edges were actually dropped and re-asserts only those, and blind-upserts every at-risk edge only where that scan isn’t answerable. On a large fork subgraph these shortcuts make the migration substantially faster. On the Postgres graph store (postgres_demo), this migration runs before the source-ref table migration. A graph upgraded from an older release therefore still has the source_ref_keys column layout, which the current adapter refuses. For such a graph, the migration re-keys the graph in SQL against that layout instead of going through the adapter. It runs the same steps in the same order and gives the same result. It reads only the fork documents and their chunks. Each document’s re-key commits in its own transaction, so a run that stops partway converges when you run it again. A Postgres graph already in the new layout, and every other graph backend, goes through the adapter as before. Both migrations are reversible, but the rollback order is the inverse of the upgrade order: run the rekey_fork_document_ids downgrade before the d6e8f0a2b4c6 downgrade. The reverse map is built from legacy_id, so dropping that column first strands fork graphs on canonical ids with no way back. Downgrading also loses fork lineage permanently — the old schema has nowhere to keep it — so a later re-upgrade re-splits shared rows with fresh ids.
The backfill is not an online migration: an old-version replica still writes shared rows and reads dataset_data, both of which the migration retires. Stop all replicas, upgrade, then start them again. A concurrent second run self-cancels — both transactions contain the dataset_data drop, and the loser rolls back whole — and an interrupted run rolls back cleanly and simply reruns.

Postgres graph source-ref tables

This applies only if you use the Postgres graph store (postgres_demo). Earlier releases stored a node’s or edge’s source refs in four array columns on graph_node and graph_edge: source_ref_keys, source_dataset_ids, source_run_ids and source_run_refs. Cognee now stores each ref as its own row, in graph_node_source_ref or graph_edge_source_ref. The postgres_graph_source_ref_tables data migration creates the two tables, copies every ref into them and drops the old columns. It runs with the rest of the migration chain (run_migrations(), cognee-cli upgrade, or automatic migrations at startup) and applies to every Postgres graph that still has the source_ref_keys column, including graphs stored in a per-dataset schema. The migration is built for large graphs:
  • It copies in batches. It copies refs in batches of 1,000 graph_node rows, then 1,000 graph_edge rows at a time. Each batch runs in its own transaction, and the copy runs inside Postgres. The ref tables’ lookup indexes are dropped during the copy and built once at the end.
  • An interrupted run can simply be started again. The old columns are dropped last, together with the index builds. A run that stops before that point starts over on the next run, skips the refs it already copied, and produces the same result.
  • A malformed dataset id or run id in a stored ref fails its batch.
Until the migration has run, the adapter refuses the graph with PostgresGraphLayoutError (see Errors). The earlier rekey_fork_document_ids migration handles the old layout itself, so it does not raise this error (see Dataset-scoping upgrade).
Like the other data migrations, this one expects that no older Cognee release writes to the graph while it runs. A ref that an old-version writer adds to an already-copied row is not carried over. Stop old replicas before upgrading. The downgrade restores the array columns and their GIN indexes from the ref rows. However, the per-write stamps and descriptions that the new layout keeps on node ref rows have no place in those columns, so the downgrade loses them.

Local default embedding model re-embed

With no embedding setting and no usable LLM key, embeddings run on a keyless local default. Cognee 1.6.11 changed that default from BAAI/bge-small-en-v1.5 (384 dimensions) to perplexity-ai/pplx-embed-v1-0.6b (1024 dimensions). A collection’s vector width is fixed when it is created, so a dataset built with the previous default can be neither written to nor searched with the new one. The reembed_local_default_embedding_model data migration computes those vectors again from the text stored next to them. It runs with the rest of the migration chain (run_migrations(), cognee-cli upgrade, or automatic migrations).
  • It runs only where the local default is in force, which means nothing about embeddings is configured for the installation. A configured model is used as it is, and its datasets are left alone.
  • It only re-embeds datasets recorded as built with BAAI/bge-small-en-v1.5. Every other dataset is left alone, so a second run changes nothing and a new deployment does nothing.
  • It takes time and downloads the model. Each re-embedded dataset logs a WARNING; the model (about 0.7 GB) is downloaded on first use. The cost is one embedding per stored row, on the local CPU. No document is read again, no LLM is called, and the graph is not touched.
  • The dataset routing collection is dropped when it holds vectors of the old width. Each re-embedded dataset writes its routes to it again at the new width.
To keep the previous model and skip the re-embed, set:
Failures and resuming. A failed re-embed fails the migration, which blocks writes to the dataset. The error (also shown by cognee-cli current) says how to get out of it. A dataset that is still as it was can be kept on the previous model with the setting above. For a dataset that is partly re-embedded, run cognee-cli upgrade again: the next run continues where the last one stopped. If you configure a model between runs, a re-embed that has not replaced any collection yet is undone, so the dataset keeps the previous model. A re-embed that has already started replacing collections raises instead, because only the local default can finish it. Backend access control off. With ENABLE_BACKEND_ACCESS_CONTROL=False, every dataset shares one vector store, so there is no single dataset to re-embed. If that shared store holds 384-dimensional vectors, the migration raises CogneeConfigurationError. Either set the two variables above, or delete the stored data (cognee.prune) and ingest it again. Datasets from before Cognee 1.6.0. Their record does not name the model that built them, so they are not re-embedded. A dataset that holds 384-dimensional vectors only gets a WARNING, and it cannot be used with the new default. If bge-small-en-v1.5 built it, keep that model with the setting above, or re-embed the dataset with reembed_dataset (below). Downgrade. The downgrade re-embeds datasets built with the new default back to BAAI/bge-small-en-v1.5, for going back to a release whose default is that model.

Re-embedding a dataset manually

The migration is built on reembed_dataset, an internal method with no SDK, CLI, or HTTP surface yet:
It rebuilds every collection of the dataset’s vector store from the text its rows hold, with the deployment’s configured embedding model unless embedding_config names another. The dataset then records the new model. No collection is dropped before its replacement is complete. It returns a ReembeddedDataset with the new model, its dimensions, the collections rebuilt, and the number of rows embedded.
  • It needs backend access control on and a vector store that can list its collections and rows (LanceDB, pgvector or Turso; any other adapter raises NotImplementedError), and it is refused (CogneeValidationError) for a dataset with a truth subspace. A collection holding a row with no text raises CollectionNotReembeddableError.
  • A failure before the first collection is replaced leaves the dataset as it was. While a re-embed runs, and after one that stopped later, every other use of the dataset raises DatasetReembedIncompleteError (HTTP 409). Call reembed_dataset again with the same model to continue where it stopped. For a re-embed that began during an upgrade, run cognee-cli upgrade instead.
  • Run it where nothing else uses the dataset. It takes the dataset lock and checks no permission, but it does not stop an operation that is already inside the dataset. A row such an operation deletes or changes can be written back as it was.

Entrypoints

All migration functions live in the cognee.run_migrations module. run_migrations is also re-exported at the top level as cognee.run_migrations, so it is the recommended entrypoint for most applications.

When to call it

For the default local setup (SQLite + LanceDB), Cognee handles migrations automatically when the API server starts. You only need to call run_migrations() explicitly in server deployments or CI pipelines where you manage database lifecycle yourself.

Disabling automatic migrations

run_migrations() is called for you in a few places: the FastAPI server’s startup lifespan, the first write call in a process (add(), cognify(), remember(), improve(), or memify()), and — in the Docker image — the container entrypoint before the server binds its port. Set ENABLE_AUTO_MIGRATIONS=false to disable all of those automatic runs:
The variable defaults to true. It is disabled by false, 0, or no (case-insensitive); any other value leaves automatic migrations on. When disabled, run_migrations() logs that it was skipped and returns an empty list without touching any database.
Disabling automatic migrations does not migrate anything on its own — Cognee will run against whatever schema already exists, and nothing else will move it forward: add(), cognify(), and pipeline runs build the schema only on a fresh database and never apply pending revisions to an existing one. Pair it with an explicit cognee-cli upgrade step before rolling out a new version: the CLI deliberately ignores this flag and runs the same locked relational + graph/vector sequence regardless. Note that the init container below calls run_migrations(), so it is gated by this flag too — use cognee-cli upgrade as its command, or leave the flag unset in the init container’s own environment.
For the container-startup side of this flag, see Docker → Database Migrations on Startup.

Example

Kubernetes init container

Run migrations as a one-shot init container so the main pod only starts after the schema is ready:

Concurrency

Every migration flow runs under a single cross-process lock, so a host performs at most one migration of any kind at a time. If several processes start at once — multiple workers of the same server, parallel SDK runs, or several init containers — only one acquires the lock and migrates; the others block until it finishes, then re-read the stored revision and skip work that is already done. Nothing runs migrations in parallel. Because of this, startup can block (and time-to-ready can increase) while another process holds the lock and migrates. This is expected under the Kubernetes init container and multi-worker scenarios above — the wait is the coordination working as intended, not a hang. The lock backend depends on your relational database:
  • Postgres — a session-scoped advisory lock, which also serializes migrations across hosts. Use Postgres metadata when multiple hosts may start and migrate at the same time.
  • SQLite — an OS advisory file lock placed next to the database file. It serializes multiple processes on a single host (multi-worker servers, parallel SDK runs) but not across hosts or over NFS.

Errors

Set LOG_LEVEL=DEBUG to see the full Alembic output when diagnosing migration failures.
The relational step logs the database it is migrating at INFO, with the password masked:
Only the log line is masked — migrations still connect with the full URL, so this changes nothing about how they run. Read connection credentials from your configuration or environment (see Relational Databases) rather than from migration logs.