Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(db): env-overridable mass-pending-migrations threshold (#3416) (#3827)

Diego Rodrigues de Sa e Souza3e79d9274406
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ed2a5016c6..f69979e282 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@
### 🐛 Fixed
- **fix(intelligence): run pricing + models.dev sync from the live startup path** — like the Arena ELO sync (v3.8.24), the external **pricing sync** (`PRICING_SYNC_ENABLED`) and the **models.dev capability sync** (Settings → AI toggle) were only initialized from `server-init.ts`, which the Next standalone runtime never executes — and models.dev had no caller at all. Their toggles were inert in production. Both are now initialized from `instrumentation-node.ts` (self-gated, opt-in preserved, non-blocking, never fatal). (thanks @diegosouzapw)
+- **fix(db): make the mass-pending-migrations safety threshold env-overridable** — restoring a backup DB from an older version could trip "Detected N pending migrations … threshold is 50" with no way to override the hardcoded `50`. The threshold is now configurable via `OMNIROUTE_MAX_PENDING_MIGRATIONS` (resolved at startup; `0` disables the check). ([#3416](https://github.com/diegosouzapw/OmniRoute/issues/3416) — thanks @samuraiIT)
- **test(proxy): cover the Vercel-relay `proxyFetch` path** — net-new tests for `buildVercelRelayHeaders` and the `vercel`-type relay short-circuit (`x-relay-target`/`-path`/`-auth`, TCP-skip, missing-auth fail-closed), closing one of the deferred test gaps tracked in [#2743](https://github.com/diegosouzapw/OmniRoute/issues/2743). (thanks @diegosouzapw)
- **fix(cli): surface `omniroute runtime repair` in the native-module error messages** — after a Node major upgrade, `better-sqlite3`'s prebuilt binary mismatches the ABI and the service can crash-loop; the error only mentioned `npm rebuild better-sqlite3` (which fails for global / no-toolchain installs). The startup + SQLite error hints now also point to the existing self-heal command `omniroute runtime repair` (rebuilds into a user-writable runtime), and a top-level `omniroute repair` alias was added. ([#3476](https://github.com/diegosouzapw/OmniRoute/issues/3476) — thanks @Rahulsharma0810)
- **fix(antigravity): per-request Pro-family upstream-id fallback chain (`gemini-3.1-pro-high` 400)** — Antigravity silently renamed the Gemini 3.1 Pro-high upstream id, so `gemini-3.1-pro-high` started returning HTTP 400 (while `-low` still worked) and the live id can't be determined statically (competitor proxies disagree). The executor now retries alternative ids on a 400 (`gemini-3.1-pro-high` → `gemini-pro-agent` → `gemini-3-pro-high`, analogous for pro-low), bounded and only on a 400, with zero extra cost on the happy path; the 1:1 tier-passthrough invariant is preserved (the chain is request-time, not a static alias remap). ([#3786](https://github.com/diegosouzapw/OmniRoute/issues/3786) — thanks @aliaksandrsen)
diff --git a/file-size-baseline.json b/file-size-baseline.json
index 90df1d6251..0e7a9f926a 100644
--- a/file-size-baseline.json
+++ b/file-size-baseline.json
@@ -78,7 +78,7 @@
"src/lib/cloudflaredTunnel.ts": 934,
"src/lib/db/apiKeys.ts": 1633,
"src/lib/db/core.ts": 1820,
- "src/lib/db/migrationRunner.ts": 1100,
+ "src/lib/db/migrationRunner.ts": 1125,
"src/lib/db/models.ts": 1180,
"src/lib/db/providers.ts": 1050,
"src/lib/db/proxies.ts": 1048,
@@ -115,5 +115,6 @@
"_rebaseline_2026_06_13_v3824_3776": "Re-baseline v3.8.24 pós #3776 (strict-mode controls Claude Code default models: ApiManagerPageClient.tsx 2701→2909 = UI de famílias bloqueáveis cc/* + chips; apiKeys.ts 1490→1633 = blocked_models deny-list + candidatos de permissão claude-code; schemas.ts 2515→2519 = reformatação Prettier + reasoningTokenBufferEnabled restaurado) + carry-over base.ts 1205→1218 do #3780 (enforceThinkingTemperature no chokepoint, drift de baseline não bumpado no merge). Crescimento de feature; sem god-component novo.",
"_rebaseline_2026_06_13_3786_agy_fallback": "Re-baseline #3786 (agy Pro-family upstream-id fallback chain): antigravity.ts 1572→1649 (+77). Crescimento = split de execute() em driver + executeOnce(modelIdOverride) para retentar ids alternativos no 400 (gemini-3.1-pro-high→gemini-pro-agent→gemini-3-pro-high), threading do override em transformRequest/cleanModelName. Lógica coesa de retry no executor — não é bloco movível (chama this.executeOnce). A parte pura (ANTIGRAVITY_PRO_FALLBACK_CHAINS + getAntigravityModelFallbacks) ficou em antigravityModelAliases.ts. Os 3 drifts release-wide (ProxyRegistryManager/sidebarVisibility/schemas) são do #3809 do owner, não deste PR.",
"_rebaseline_2026_06_13_3782_hide_persist": "Re-baseline #3782 (preservar modelos eye-hidden no auto-sync): models.ts 1132→1180 (+48). Crescimento = flag distinto isDeleted em ModelCompatOverride/ModelCompatPatch + handling em mergeModelCompatOverride + helper getModelIsDeleted, para separar 'deletado' (trash, dropado no re-sync #3199) de 'oculto' (eye toggle, preservado). Lógica coesa de visibilidade no módulo db; não-extraível. Os 3 drifts release-wide (ProxyRegistryManager/sidebarVisibility/schemas) são do #3809 do owner, não deste PR.",
- "_rebaseline_2026_06_13_3758_chat_early_eof": "Re-baseline #3758 (#3817 mergeado): chat.ts 1392→1425 (+33). Crescimento = retry bounded de STREAM_EARLY_EOF no handleSingleModelChat (contador streamEarlyEofRetries + bloco de retry guardado por shouldRetryStreamEarlyEof). Lógica coesa no handler de chat; não-extraível. Reconciliação tardia — o bump foi esquecido no PR do fix (o de antigravity/models foi feito)."
+ "_rebaseline_2026_06_13_3758_chat_early_eof": "Re-baseline #3758 (#3817 mergeado): chat.ts 1392→1425 (+33). Crescimento = retry bounded de STREAM_EARLY_EOF no handleSingleModelChat (contador streamEarlyEofRetries + bloco de retry guardado por shouldRetryStreamEarlyEof). Lógica coesa no handler de chat; não-extraível. Reconciliação tardia — o bump foi esquecido no PR do fix (o de antigravity/models foi feito).",
+ "_rebaseline_2026_06_13_3416_migration_threshold": "Re-baseline #3416 (threshold de migrações pendentes via env): migrationRunner.ts 1100→1125 (+25). Crescimento = helper resolveMaxPendingMigrations() que lê OMNIROUTE_MAX_PENDING_MIGRATIONS em call-time (valida finito+>=0, fallback 50) + JSDoc. Lógica coesa de config no runner; não-extraível."
}
diff --git a/src/lib/db/migrationRunner.ts b/src/lib/db/migrationRunner.ts
index f5e874f8a7..7acfc7c666 100644
--- a/src/lib/db/migrationRunner.ts
+++ b/src/lib/db/migrationRunner.ts
@@ -101,14 +101,34 @@ function resolveMigrationsDir(): string {
const MIGRATIONS_DIR = resolveMigrationsDir();
/**
- * Maximum number of migrations allowed to run in a single startup on an
+ * Default maximum number of migrations allowed to run in a single startup on an
* existing database. If more migrations are pending than this threshold,
* it likely means the migration tracking table was accidentally wiped,
* and running all migrations from scratch could cause data loss.
*
- * Set to 0 to disable this safety check.
+ * Set the threshold to 0 (via `OMNIROUTE_MAX_PENDING_MIGRATIONS`) to disable
+ * this safety check.
*/
-const MAX_PENDING_MIGRATIONS_ON_EXISTING_DB = 50;
+const DEFAULT_MAX_PENDING_MIGRATIONS_ON_EXISTING_DB = 50;
+
+/**
+ * Resolve the mass-migration safety threshold, allowing an operator to override
+ * the default via the `OMNIROUTE_MAX_PENDING_MIGRATIONS` env var (#3416). This
+ * is read at CALL TIME inside runMigrations() so a backup restore can raise the
+ * limit (or `0` to disable the check) without a code change. Mirrors the
+ * `OMNIROUTE_MIGRATIONS_DIR` convention used in resolveMigrationsDir(). Falls
+ * back to the default on missing or invalid (non-numeric / negative) input.
+ */
+function resolveMaxPendingMigrations(): number {
+ const raw = process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS;
+ if (typeof raw === "string" && raw.trim().length > 0) {
+ const parsed = Number.parseInt(raw.trim(), 10);
+ if (Number.isFinite(parsed) && parsed >= 0) {
+ return parsed;
+ }
+ }
+ return DEFAULT_MAX_PENDING_MIGRATIONS_ON_EXISTING_DB;
+}
const RENAMED_MIGRATION_COMPATIBILITY = [
{
@@ -940,13 +960,18 @@ export function runMigrations(db: SqliteAdapter, options?: { isNewDb?: boolean }
process.env.VITEST !== undefined ||
(typeof process.argv !== "undefined" && process.argv.some((arg) => arg.includes("test")));
+ // #3416: resolve the threshold at call time so OMNIROUTE_MAX_PENDING_MIGRATIONS
+ // can override the default (0 disables the check). The abort message below
+ // interpolates this resolved value, so it auto-reflects any override.
+ const maxPendingMigrations = resolveMaxPendingMigrations();
+
if (
!isTestEnvironment &&
!isNewDb &&
process.env.DISABLE_SQLITE_AUTO_BACKUP !== "true" &&
- MAX_PENDING_MIGRATIONS_ON_EXISTING_DB > 0 &&
+ maxPendingMigrations > 0 &&
applied.size > 0 &&
- actionablePending.length > MAX_PENDING_MIGRATIONS_ON_EXISTING_DB
+ actionablePending.length > maxPendingMigrations
) {
const physicalBaseline = inferPhysicalSchemaBaseline(db);
const plausiblePendingCount = physicalBaseline
@@ -968,7 +993,7 @@ export function runMigrations(db: SqliteAdapter, options?: { isNewDb?: boolean }
: "";
const msg =
`[Migration] 🛑 ABORT: Detected ${actionablePending.length} pending migrations on an existing database ` +
- `(threshold is ${MAX_PENDING_MIGRATIONS_ON_EXISTING_DB}). ` +
+ `(threshold is ${maxPendingMigrations}). ` +
`This usually means the migration tracking table was accidentally wiped. ` +
`Running all migrations from scratch will cause data loss or schema errors.` +
schemaHint;
diff --git a/tests/unit/db-migration-runner.test.ts b/tests/unit/db-migration-runner.test.ts
index 7fb4f7b86c..2c830969c0 100644
--- a/tests/unit/db-migration-runner.test.ts
+++ b/tests/unit/db-migration-runner.test.ts
@@ -1350,3 +1350,141 @@ test(
}
}
);
+
+// ── #3416: OMNIROUTE_MAX_PENDING_MIGRATIONS env override ─────────────────────
+// The mass-migration safety threshold must be overridable at runtime so a user
+// restoring a backup can raise (or lower) the limit without code changes. The
+// resolver reads the env var at CALL TIME inside runMigrations(), so these tests
+// set/delete the env around the call and assert the abort message reflects the
+// resolved threshold.
+
+// Build an "existing DB" with only the migrations table + one applied row and no
+// physical-schema sentinel tables, so inferPhysicalSchemaBaseline() returns null
+// and the abort decision depends purely on the resolved threshold.
+function seedExistingDbWithoutPhysicalBaseline(db) {
+ db.exec(`
+ CREATE TABLE _omniroute_migrations (
+ version TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ applied_at TEXT NOT NULL DEFAULT (datetime('now'))
+ );
+ `);
+ db.prepare("INSERT INTO _omniroute_migrations (version, name) VALUES (?, ?)").run(
+ "001",
+ "initial_schema"
+ );
+}
+
+test(
+ "runMigrations aborts when OMNIROUTE_MAX_PENDING_MIGRATIONS lowers the threshold (#3416)",
+ serial,
+ async () => {
+ const runner = await importFresh("src/lib/db/migrationRunner.ts");
+ const db = createDb();
+ const original = process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS;
+
+ try {
+ seedExistingDbWithoutPhysicalBaseline(db);
+ process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS = "5";
+
+ // 1 applied (001) + files 001..011 → 10 actionable pending > threshold 5.
+ assert.throws(
+ () =>
+ withNonTestEnvironment(() =>
+ withMockedMigrationFs(buildMockMigrationFiles(1, 11, "lower_threshold"), () =>
+ runner.runMigrations(db)
+ )
+ ),
+ /threshold is 5/i
+ );
+ } finally {
+ if (original === undefined) delete process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS;
+ else process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS = original;
+ db.close();
+ }
+ }
+);
+
+test(
+ "runMigrations allows a large pending set when OMNIROUTE_MAX_PENDING_MIGRATIONS raises the threshold (#3416)",
+ serial,
+ async () => {
+ const runner = await importFresh("src/lib/db/migrationRunner.ts");
+ const db = createDb();
+ const original = process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS;
+
+ try {
+ seedExistingDbWithoutPhysicalBaseline(db);
+ process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS = "500";
+
+ // 1 applied (001) + 60 plain pending files at versions 100..159 (chosen to
+ // avoid the special-cased migration versions 032/041/042). All 60 exceed the
+ // default 50 threshold but stay well under the raised 500 limit, so they apply.
+ const pendingFiles = {};
+ for (let v = 100; v < 160; v++) {
+ pendingFiles[`${v}_raise_threshold_${v}.sql`] =
+ `CREATE TABLE raise_threshold_${v} (id INTEGER);`;
+ }
+
+ const count = withNonTestEnvironment(() =>
+ withMockedMigrationFs(pendingFiles, () => runner.runMigrations(db))
+ );
+
+ assert.equal(count, 60);
+ } finally {
+ if (original === undefined) delete process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS;
+ else process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS = original;
+ db.close();
+ }
+ }
+);
+
+test(
+ "runMigrations keeps the default 50 threshold when OMNIROUTE_MAX_PENDING_MIGRATIONS is unset or invalid (#3416)",
+ serial,
+ async () => {
+ const runner = await importFresh("src/lib/db/migrationRunner.ts");
+ const original = process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS;
+
+ try {
+ // Case 1: env unset → default 50 abort message.
+ delete process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS;
+ const dbUnset = createDb();
+ try {
+ seedExistingDbWithoutPhysicalBaseline(dbUnset);
+ assert.throws(
+ () =>
+ withNonTestEnvironment(() =>
+ withMockedMigrationFs(buildMockMigrationFiles(1, 60, "default_unset"), () =>
+ runner.runMigrations(dbUnset)
+ )
+ ),
+ /threshold is 50/i
+ );
+ } finally {
+ dbUnset.close();
+ }
+
+ // Case 2: invalid (non-numeric) → fall back to default 50.
+ process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS = "abc";
+ const dbInvalid = createDb();
+ try {
+ seedExistingDbWithoutPhysicalBaseline(dbInvalid);
+ assert.throws(
+ () =>
+ withNonTestEnvironment(() =>
+ withMockedMigrationFs(buildMockMigrationFiles(1, 60, "default_invalid"), () =>
+ runner.runMigrations(dbInvalid)
+ )
+ ),
+ /threshold is 50/i
+ );
+ } finally {
+ dbInvalid.close();
+ }
+ } finally {
+ if (original === undefined) delete process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS;
+ else process.env.OMNIROUTE_MAX_PENDING_MIGRATIONS = original;
+ }
+ }
+);