Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(migrations): non-blocking background migration track (#15903)

Amr Elmohamady93826c55bb14
diff --git a/.claude/rules/data-isolation.md b/.claude/rules/data-isolation.md
deleted file mode 100644
index 1178656a136..00000000000
--- a/.claude/rules/data-isolation.md
+++ /dev/null
@@ -1,2 +0,0 @@
-ALL database queries MUST filter by `projectId` or `platformId` for multi-tenant safety.
-For connections with multi-project access, use `ArrayContains([projectId])` on the `projectIds` array column.
diff --git a/.claude/rules/database-first.md b/.claude/rules/database-first.md
new file mode 100644
index 00000000000..83fd47a2281
--- /dev/null
+++ b/.claude/rules/database-first.md
@@ -0,0 +1 @@
+Before writing any backend code that touches the DB (entities, queries, migrations, repositories, transactions), read `brain/knowledge/data-storage-observability/database.md`. It is the source of truth for multi-tenant isolation, entity registration, the two-track migration model (blocking + background), constraint recipes, and the CIC helper. Do not rely on scattered rules — this page supersedes them.
diff --git a/.claude/rules/entity-registration.md b/.claude/rules/entity-registration.md
deleted file mode 100644
index 1e30520b1a6..00000000000
--- a/.claude/rules/entity-registration.md
+++ /dev/null
@@ -1,4 +0,0 @@
-When creating a new TypeORM entity, you MUST do ALL of these:
-1. Add to `getEntities()` array in `packages/server/api/src/app/database/database-connection.ts`
-2. Create migration + import in `postgres-connection.ts` + add to `getMigrations()` array
-TypeORM does NOT auto-discover entities. Skipping step 1 causes silent failures at runtime.
diff --git a/CLAUDE.md b/CLAUDE.md
index f09401766b3..08c780fe238 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -112,7 +112,7 @@ When running in `--mode=cloud`, do not use OAuth2 connections — the OAuth prov
## Database Migrations
-- Before creating or modifying a database migration, **always read the [Database Migrations Playbook](https://www.activepieces.com/docs/handbook/engineering/playbooks/database-migration#database-migrations)** first. Follow its instructions for generating and structuring migrations.
+- Before creating or modifying a database migration, **always read `brain/knowledge/data-storage-observability/database.md`** first. It covers the two-track model (blocking + background), constraint recipes, the CIC helper, and cross-track dependency guards. The external [Database Migrations Playbook](https://www.activepieces.com/docs/handbook/engineering/playbooks/database-migration#database-migrations) covers general TypeORM mechanics.
## Verification
diff --git a/brain/knowledge/data-storage-observability/database.md b/brain/knowledge/data-storage-observability/database.md
new file mode 100644
index 00000000000..236dffb1cc9
--- /dev/null
+++ b/brain/knowledge/data-storage-observability/database.md
@@ -0,0 +1,277 @@
+---
+icon: 🗄️
+---
+
+# Database
+
+The one page before touching the DB. Covers isolation, entities, migrations, queries, and constraints.
+
+## Multi-tenant isolation
+
+Every query MUST filter by `projectId` or `platformId`. No exceptions.
+
+- For connections with multi-project access, use `ArrayContains([projectId])` on the `projectIds` array column.
+- New endpoints that read/write scoped data get a `securityAccess.project(..., permission)` config — passing `undefined` skips RBAC.
+
+## Entities
+
+Registering a new entity is a two-step chore. TypeORM does NOT auto-discover.
+
+1. Add the class to `getEntities()` in `packages/server/api/src/app/database/database-connection.ts`.
+2. Create a migration (see below) and register it in `getMigrations()` in `postgres-connection.ts`.
+
+Missing step 1 causes silent runtime failures — the entity works locally with schema sync on, then breaks in prod.
+
+Array columns:
+
+```ts
+columnName: {
+ type: String,
+ array: true,
+ nullable: false,
+}
+```
+
+Base columns: import `BaseModelSchema` for `id` / `createdAt` / `updatedAt`.
+
+## Repositories
+
+Use `repoFactory(Entity)()` from `@activepieces/shared`. Do not call `dataSource.getRepository()` directly.
+
+## Queries
+
+- **No N+1.** JOINs / `IN (:...ids)` / batch loads, never per-item lookups inside `Promise.all` or `.map()`.
+- **Cache-shape changes bump the key version.** Anything through `distributedStore` is read by both old and new code during a rolling deploy. New fields arrive `undefined` and pass `Nullable()` validation silently. So `platform_plan:overview:v1:${platformId}` → `:v2:` whenever the shape changes. Old entries need no cleanup **if** the write set `ttlInSeconds`; unset TTLs orphan.
+
+## Migrations — two tracks
+
+Migrations live in two folders. The folder is the source of truth for how the migration runs.
+
+| Track | Folder | Runs | History table | Rollback |
+|---|---|---|---|---|
+| **Blocking** | `packages/server/api/src/app/database/migration/postgres/` | boot lock | `migrations` (TypeORM default) | yes, `breaking` flag |
+| **Background** | `packages/server/api/src/app/database/migration/postgres/background/` | post-listen via BullMQ | `background_migrations` | forward-only |
+
+Tracks are **independent**. Neither waits for the other. Ordering is by timestamp filename within each track only.
+
+### Choosing a track
+
+- **Blocking** — schema shape fast enough to sit at boot: `ADD COLUMN nullable`, `CREATE TABLE`, `NOT VALID` constraints, `ADD CONSTRAINT ... USING INDEX`, `SET NOT NULL` (with a validated CHECK), fast additive DDL.
+- **Background** — anything you don't want at boot: chunked backfills, index reshapes (`CREATE INDEX CONCURRENTLY` + `DROP INDEX CONCURRENTLY` sequences), `VALIDATE CONSTRAINT` on big tables.
+
+Blocking runs under a Redis lock at boot — anything more than seconds blocks every replica from serving. If in doubt, background is the safe default.
+
+**CIC is not automatically background.** A single `CREATE INDEX CONCURRENTLY` on a table where the boot delay is tolerable belongs in the blocking track. Background makes sense when CIC + drops are stacked into a reshape, or the table is huge enough that the boot delay hurts deploys. Either way, always go through `migrationHelpers.createIndexConcurrently` — see below.
+
+### Cross-track dependency
+
+**Any blocking migration that depends on a background backfill MUST call `migrationHelpers.assertBackgroundMigrationComplete({ queryRunner, migration: TheBackfill })` as the first statement of `up()`.** No exceptions — not for `DROP COLUMN`, not for `SET NOT NULL`, not for `USING INDEX`, not for `VALIDATE CONSTRAINT`.
+
+The guard is what triggers boot catchup. Catchup only reacts to the typed `BackgroundMigrationNotCompleteError` the guard throws; a raw Postgres error (nulls hitting `SET NOT NULL`, missing index hitting `USING INDEX`, orphans hitting `VALIDATE CONSTRAINT`) is NOT recognized as a cross-track failure — catchup rethrows it and boot wedges in a restart loop. The guard is the only way for the catchup to know which backfill to run.
+
+The guard also prevents the silently dangerous cases (`DROP COLUMN`, `DELETE FROM`) that Postgres won't error on at all.
+
+Contract DDL and its backfill ship in **different releases**. Same-release attempts fail boot, catchup runs the backfill, retries — this is the intended path.
+
+**Release-notes convention:** when a release ships a background migration whose dependent contract DDL lands in a later release, that earlier release's notes must say something like "self-hosters should let backfill X complete before upgrading further; the app catches up at boot but it may take ~N minutes." Boot catchup handles skip-release correctly, but operators deserve the heads-up so they can plan the upgrade window.
+
+### Interfaces
+
+Blocking:
+```ts
+export class MyMigration1857000000000 implements Migration {
+ name = 'MyMigration1857000000000'
+ breaking = false
+ release = '0.91.0'
+ // transaction defaults to true
+ public async up(q: QueryRunner): Promise<void> { ... }
+ public async down(q: QueryRunner): Promise<void> { ... }
+}
+```
+
+Background:
+```ts
+export class BackfillFooStatus1858000000000 implements BackgroundMigration {
+ name = 'BackfillFooStatus1858000000000'
+ release = '0.91.0'
+ transaction = false as const
+ public async up(q: QueryRunner): Promise<void> { ... }
+ public async down(): Promise<void> {}
+}
+```
+
+`transaction = false as const` — the type is a `false` literal, so `tsc` catches a stray `true`. `CIC` and `VALIDATE CONSTRAINT` refuse to run in a transaction.
+
+### CIC — always via the helper
+
+Every CIC goes through `migrationHelpers.createIndexConcurrently({ ... })`, and every `DROP INDEX CONCURRENTLY` goes through `migrationHelpers.dropIndexConcurrently({ ... })`. Both tracks, no exceptions.
+
+The helper handles the two things a raw `CREATE INDEX CONCURRENTLY` gets wrong:
+
+- **pglite fallback.** pglite rejects `CONCURRENTLY`; the helper runs a plain `CREATE INDEX IF NOT EXISTS` on pglite so local dev works.
+- **Retry safety.** A crashed CIC leaves an `INVALID` index behind. A plain `IF NOT EXISTS` retry sees the name exists and skips — the `INVALID` entry sits forever, unused by the planner. The helper checks `pg_index.indisvalid` and runs `REINDEX INDEX CONCURRENTLY` on an invalid leftover, `CREATE` on a missing one, no-op on a valid one.
+
+Older migrations in `postgres/` use an inline `const concurrently = isPGlite() ? '' : 'CONCURRENTLY'` ternary. Don't write new ones that way — the helper supersedes it. Treat the inline pattern as legacy.
+
+### Index reshapes
+
+Adding a new set of indexes and dropping the olds they replace goes in the **background track** whenever the table is large enough that the boot cost would hurt deploys. The whole reshape sits in one background migration with `transaction = false`, sequencing `CREATE INDEX CONCURRENTLY` and `DROP INDEX CONCURRENTLY` so the table always has coverage.
+
+Two orderings. **Default to All creates then all drops** — mid-batch failure leaves full coverage, recovery is "drop the half-built news and restart", and disk is almost always the cheaper resource than a hot table's coverage. Switch to pair-by-pair only when disk headroom genuinely can't take 2N.
+
+**All creates then all drops** — the default. Peak footprint is 2N indexes. If any CIC fails mid-batch, zero olds have been dropped yet, so the table still has its original coverage — safest rollback story. Use when: the table is hot and you can't afford a transient coverage gap, more than ~3 index pairs are being swapped, or you have the disk for 2N indexes.
+
+```ts
+public async up(q: QueryRunner): Promise<void> {
+ await migrationHelpers.createIndexConcurrently({ queryRunner: q, name: 'idx_new_1', ... })
+ await migrationHelpers.createIndexConcurrently({ queryRunner: q, name: 'idx_new_2', ... })
+ await migrationHelpers.dropIndexConcurrently({ queryRunner: q, name: 'idx_old_1' })
+ await migrationHelpers.dropIndexConcurrently({ queryRunner: q, name: 'idx_old_2' })
+}
+```
+
+**Pair-by-pair** — the disk-constrained variant. Peak footprint is N+1 indexes. Use when: the per-index footprint is big enough that 2N would strain disk, the reshape is only 1-2 pairs, or the pair semantics are independent (new1 fully replaces old1 before new2 is even started). Cost: if a later CIC fails, the earlier olds are already dropped — reduced coverage until the next retry succeeds.
+
+```ts
+public async up(q: QueryRunner): Promise<void> {
+ await migrationHelpers.createIndexConcurrently({ queryRunner: q, name: 'idx_new_1', ... })
+ await migrationHelpers.dropIndexConcurrently({ queryRunner: q, name: 'idx_old_1' })
+ await migrationHelpers.createIndexConcurrently({ queryRunner: q, name: 'idx_new_2', ... })
+ await migrationHelpers.dropIndexConcurrently({ queryRunner: q, name: 'idx_old_2' })
+}
+```
+
+The All-creates-then-all-drops shape can also be done in the blocking track, with the boot-delay tradeoff. The background version gives zero-downtime deploy for the same work.
+
+### Chunking backfills
+
+```ts
+public async up(q: QueryRunner): Promise<void> {
+ while (true) {
+ const rows = await q.query(`
+ WITH updated AS (
+ UPDATE flow_version
+ SET status = jsonb_build_object('kind', state)
+ WHERE id IN (
+ SELECT id FROM flow_version
+ WHERE status IS NULL
+ LIMIT 1000
+ )
+ RETURNING 1
+ )
+ SELECT count(*)::int AS updated_count FROM updated
+ `) as [{ updated_count: number }]
+ if (rows[0].updated_count === 0) break
+ }
+}
+```
+
+Why the CTE wrap: a bare `UPDATE ... RETURNING` has non-portable return shape — PGlite gives you a rows array, node-postgres gives you `[rows, affectedCount]`. Reading `.length` on the node-postgres tuple always yields 2, so the loop never terminates in prod but passes locally. Wrapping in `WITH ... SELECT count(*)` makes the top-level statement a SELECT, which has uniform shape across both drivers. The chunk itself is still idempotent — the `WHERE col IS NULL` skips already-updated rows, so a crash mid-backfill resumes cleanly on retry.
+
+### Constraint recipes
+
+**Unique:**
+```ts
+// background migration
+await migrationHelpers.createIndexConcurrently({
+ queryRunner: q,
+ name: 'idx_foo_unique',
+ table: 'foo',
+ columns: '"col"',
+ unique: true,
+})
+```
+```sql
+-- blocking, next release
+ALTER TABLE foo ADD CONSTRAINT foo_col_unique UNIQUE USING INDEX idx_foo_unique;
+```
+
+**Foreign key:**
+```sql
+-- blocking
+ALTER TABLE foo ADD CONSTRAINT fk_foo FOREIGN KEY (bar_id) REFERENCES bar(id) NOT VALID;
+-- background
+ALTER TABLE foo VALIDATE CONSTRAINT fk_foo;
+```
+
+**CHECK:** same `NOT VALID` → `VALIDATE` pattern as FK.
+
+**`NOT NULL` on existing column** (PG 12+). Three migrations across two releases. The background migration MUST do both the backfill AND the `VALIDATE CONSTRAINT` in one `up()` — splitting them lets Step 3's blocking `SET NOT NULL` boot against a non-validated CHECK, which forces Postgres into a full-table scan under ACCESS EXCLUSIVE. That reintroduces the exact boot stall this whole runner exists to prevent.
+
+Step 1 — blocking, release N:
+```sql
+ALTER TABLE foo ADD CONSTRAINT foo_col_not_null CHECK (col IS NOT NULL) NOT VALID;
+```
+
+Step 2 — background, release N (backfill + validate, atomic from the guard's perspective):
+```ts
+public async up(q: QueryRunner): Promise<void> {
+ while (true) {
+ const rows = await q.query(`
+ WITH updated AS (
+ UPDATE foo SET col = <value>
+ WHERE id IN (SELECT id FROM foo WHERE col IS NULL LIMIT 1000)
+ RETURNING 1
+ )
+ SELECT count(*)::int AS updated_count FROM updated
+ `) as [{ updated_count: number }]
+ if (rows[0].updated_count === 0) break
+ }
+ await q.query(`ALTER TABLE foo VALIDATE CONSTRAINT foo_col_not_null`)
+}
+```
+
+Step 3 — blocking, release N+1 (guard implies both backfill and validate are done, so `SET NOT NULL` is metadata-only):
+```ts
+public async up(q: QueryRunner): Promise<void> {
+ await migrationHelpers.assertBackgroundMigrationComplete({
+ queryRunner: q,
+ migration: BackfillAndValidateFooColNulls, // the single background migration above
+ })
+ await q.query(`ALTER TABLE foo ALTER COLUMN col SET NOT NULL`)
+ await q.query(`ALTER TABLE foo DROP CONSTRAINT foo_col_not_null`)
+}
+```
+
+### Rollback
+
+- Blocking migrations: `down()` required unless `breaking = true`. `check-migration-rollback.ts` enforces the `breaking` flag on destructive DDL.
+- Background migrations: forward-only. `down()` is a no-op body; the rollback tooling skips the `background/` folder entirely. To undo a bad backfill, ship a forward-fix migration.
+
+### Recovery — permanently failing background migrations
+
+A background migration that fails every retry stops the app from booting. The guard refuses the dependent blocking DDL; boot catchup exhausts its 10 attempts and throws with the migration name. Operator options, in order of preference:
+
+1. **Fix the data.** `background_migrations.last_error` names the failing SQL and often points at the problem row. Fix (`UPDATE`, `DELETE`, or correct application code that writes invalid data) and restart the pod. The runner retries automatically.
+2. **Mark the backfill complete manually.** Dangerous — only when the backfill is a no-op for your data (e.g., the backfill fills a column you don't use, or all target rows already have the expected shape, or you plan to drop the column entirely in a later release).
+ ```sql
+ INSERT INTO background_migrations ("name", "executed_at")
+ VALUES ('YourBackfillName1858000000000', NOW())
+ ON CONFLICT ("name") DO UPDATE SET "executed_at" = NOW(), "failed_at" = NULL, "last_error" = NULL;
+ ```
+ Boot proceeds; dependent blocking DDL's guard passes.
+3. **Upgrade to a release with a patch.** If Activepieces ships a corrected backfill, upgrading past it lands the fix.
+
+## Gotchas
+
+- **pglite doesn't support `CONCURRENTLY`.** `migrationHelpers.createIndexConcurrently` / `dropIndexConcurrently` fall back to plain `CREATE INDEX IF NOT EXISTS` / `DROP INDEX IF EXISTS` on pglite. Only affects local dev. Older migrations use an inline `const concurrently = isPGlite() ? '' : 'CONCURRENTLY'` ternary — don't reuse that pattern in new code, the helpers supersede it.
+- **`breaking = true` is the ROLLBACK-safety flag, not the customer-facing "breaking change" label.** Two different concepts. The label is decided per the [PR labels rules](../../../CLAUDE.md#pull-requests); the flag is decided per what the migration's `down()` can undo.
+- **Contract DDL in the same release as its backfill, skip-release upgrades, and fresh installs are all handled by boot catchup.** `runMigrationsWithCatchup` wraps TypeORM's `runMigrations`: when a blocking migration's guard throws `BackgroundMigrationNotCompleteError`, the catchup catches it, runs that one backfill synchronously, and retries. Max 10 catchup attempts (one per distinct dependency), then boot fails with the failing migration name. Normal upgrade pays nothing; skip-release pays a one-time slow boot while prior backfills catch up.
+- **A brand-new hot-path index in the same release as the code that needs it can leave the app on seq scans while background CIC builds.** Only applies when there's *no* prior covering index for the query. Fixes: (a) ship the CIC in a prior release so it's built by the time the code lands (verify via `pendingCount` on `/v1/health/system`), or (b) put the CIC in the blocking track so the index is present when the app starts serving. Reshapes (replacing existing indexes) don't hit this — the old index keeps queries fast while new one builds.
+- **Same-name migration in both folders would run twice.** The two history tables are independent — a rename or folder move without a seed-row migration double-executes on customers that already ran it in the old track.
+- **Background migrations run on API pods only.** Workers don't register system-job handlers. Deployments with zero API pods will never finish backfills; not a supported topology, worth flagging if it comes up.
+
+## Key files
+
+- `packages/server/api/src/app/database/` — connection, migrations, helpers.
+- `packages/server/api/src/app/database/postgres-connection.ts` — `getMigrations()`, `getBackgroundMigrations()`.
+- `packages/server/api/src/app/database/migration.ts` — the `Migration` interface.
+- `packages/server/api/src/app/database/background-migration.ts` — the `BackgroundMigration` interface.
+- `packages/server/api/src/app/database/migration-helpers.ts` — `assertBackgroundMigrationComplete`, `createIndexConcurrently`.
+- `packages/server/api/src/app/database/background-migration-runner.ts` — the BullMQ handler.
+- `tools/scripts/check-migration-rollback.ts` — the CI check.
+
+## Related pages
+
+- [Tables](tables.md), [File Storage](file-storage.md), [Key-Value Store](key-value-store.md), [Audit Logs](audit-logs.md) — domain-specific storage.
+- External: [Database Migrations Playbook](https://www.activepieces.com/docs/handbook/engineering/playbooks/database-migration) — general TypeORM mechanics.
diff --git a/brain/knowledge/data-storage-observability/index.md b/brain/knowledge/data-storage-observability/index.md
index a771bd9f2e7..5b15ba6a155 100644
--- a/brain/knowledge/data-storage-observability/index.md
+++ b/brain/knowledge/data-storage-observability/index.md
@@ -92,6 +92,7 @@ Streams platform/project events to webhook URLs in real time — internal AP flo
## Pages
+- **Database** — the load-bearing page for all backend DB work: isolation, entity registration, migrations (blocking + background), constraint recipes, CIC helper
- **Tables** — Field / Record / Cell and TableWebhooks
- **File Storage** — blobs in S3 or DB, compression, expiry
- **Key-Value Store** — project-scoped state pieces persist across runs
diff --git a/bun.lock b/bun.lock
index f1597b055f1..4b22a7c580a 100644
--- a/bun.lock
+++ b/bun.lock
@@ -167,7 +167,7 @@
},
"packages/core/shared": {
"name": "@activepieces/shared",
- "version": "0.199.0",
+ "version": "0.200.0",
"dependencies": {
"@activepieces/core-execution": "workspace:*",
"@activepieces/core-formula": "workspace:*",
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.json
index c449a2ebee6..5b5ab0e7c1e 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.199.0",
+ "version": "0.200.0",
"type": "commonjs",
"sideEffects": false,
"main": "./dist/src/index.js",
diff --git a/packages/core/shared/src/lib/core/health/index.ts b/packages/core/shared/src/lib/core/health/index.ts
index 111c3eacf8d..e40bb4f9e8f 100644
--- a/packages/core/shared/src/lib/core/health/index.ts
+++ b/packages/core/shared/src/lib/core/health/index.ts
@@ -11,6 +11,19 @@ export const ReleaseHealth = z.object({
}),
})
+export const FailedBackgroundMigration = z.object({
+ name: z.string(),
+ failedAt: z.string(),
+ lastError: z.string(),
+})
+
+export const BackgroundMigrationsHealth = z.object({
+ pendingCount: z.number(),
+ completedCount: z.number(),
+ error: z.string().nullable(),
+ failedMigration: FailedBackgroundMigration.nullable(),
+})
+
export const GetSystemHealthChecksResponse = z.object({
latestVersion: z.string(),
appCpu: z.boolean(),
@@ -20,6 +33,7 @@ export const GetSystemHealthChecksResponse = z.object({
workerRam: z.boolean().nullable(),
database: z.boolean(),
release: ReleaseHealth,
+ backgroundMigrations: BackgroundMigrationsHealth,
})
// Server-measured infra round-trip, so a cross-region benchmark client gets the authoritative
@@ -84,6 +98,8 @@ export const GetDiagnosticsResponse = z.object({
})
export type ReleaseHealth = z.infer<typeof ReleaseHealth>
+export type FailedBackgroundMigration = z.infer<typeof FailedBackgroundMigration>
+export type BackgroundMigrationsHealth = z.infer<typeof BackgroundMigrationsHealth>
export type GetSystemHealthChecksResponse = z.infer<typeof GetSystemHealthChecksResponse>
export type InfraCheck = z.infer<typeof InfraCheck>
export type DeploymentConfig = z.infer<typeof DeploymentConfig>
diff --git a/packages/server/api/src/app/app.ts b/packages/server/api/src/app/app.ts
index a82db4e361c..e7ab40f2502 100644
--- a/packages/server/api/src/app/app.ts
+++ b/packages/server/api/src/app/app.ts
@@ -1,6 +1,6 @@
import { isNil, spreadIfDefined } from '@activepieces/core-utils'
import { PieceMetadata } from '@activepieces/pieces-framework'
-import { aiCostReporter, apVersionUtil, onCallService, UNKNOWN_VERSION, wideEvent } from '@activepieces/server-utils'
+import { aiCostReporter, apDayjs, apVersionUtil, onCallService, UNKNOWN_VERSION, wideEvent } from '@activepieces/server-utils'
import { AddAllowedEmbedOriginsRequestBody, ApEdition, ApEnvironment, AppConnectionWithoutSensitiveData, ApplicationEventName, AuditLogRetentionUpdatedEvent, ConnectionDeletedEvent, ConnectionUpsertedEvent, Flow, FlowActivatedEvent, FlowCreatedEvent, FlowDeactivatedEvent, FlowDeletedEvent, FlowPiecesRevertedEvent, FlowPiecesUpgradedEvent, FlowPublishedEvent, FlowRun, FlowRunFinishedEvent, FlowRunRetriedEvent, FlowRunStartedEvent, FlowUpdatedEvent, Folder, FolderCreatedEvent, FolderDeletedEvent, FolderUpdatedEvent, GitRepoWithoutSensitiveData, ProjectMember, ProjectRelease, ProjectReleaseEvent, ProjectRoleEvent, ProjectWithLimits, SigningKeyEvent, SignUpEvent, Template, UserEmailVerifiedEvent, UserInvitation, UserPasswordResetEvent, UserSignedInEvent, UserWithMetaInformation, VariableWithoutSensitiveData } from '@activepieces/shared'
import replyFrom from '@fastify/reply-from'
import swagger from '@fastify/swagger'
@@ -30,6 +30,7 @@ import { oidcModule } from './core/security/oidc/oidc.module'
import { rateLimitModule } from './core/security/rate-limit'
import { authenticationMiddleware } from './core/security/v2/authn/authentication-middleware'
import { authorizationMiddleware } from './core/security/v2/authz/authorization-middleware'
+import { backgroundMigrationRunner } from './database/background-migration-runner'
import { distributedLock, redisConnections } from './database/redis-connections'
import { agentConversationCreditsHooks } from './ee/agent/agent-conversation-credits'
import { agentEvalModule } from './ee/agent/agent-eval-controller'
@@ -96,7 +97,7 @@ import { system } from './helper/system/system'
import { AppSystemProp } from './helper/system/system-props'
import { SystemJobName } from './helper/system-jobs/common'
import { systemJobHandlers } from './helper/system-jobs/job-handlers'
-import { systemJobsSchedule } from './helper/system-jobs/system-job'
+import { SystemJobBackoff, systemJobsSchedule } from './helper/system-jobs/system-job'
import { systemSnapshot } from './helper/system-snapshot'
import { validateEnvPropsOnStartup } from './helper/system-validator'
import { shutdownTelemetry } from './helper/telemetry.utils'
@@ -318,6 +319,10 @@ export const setupApp = async (app: FastifyInstance): Promise<FastifyInstance> =
},
})
+ systemJobHandlers.registerJobHandler(SystemJobName.RUN_BACKGROUND_MIGRATIONS, async () => {
+ await backgroundMigrationRunner.run({ log: app.log })
+ })
+
app.get(
'/redirect',
async (
@@ -491,6 +496,9 @@ The application started on ${await domainHelper.getPublicApiUrl({ path: '' })},
systemSnapshot.start({ log: app.log })
await migrateQueuesAndRunConsumers(app)
app.log.info('Queues migrated and consumers run')
+ dispatchBackgroundMigrations(app.log).catch(error => {
+ app.log.warn({ error: error instanceof Error ? error.message : String(error) }, '[appPostBoot] Failed to dispatch background migrations job; next pod boot will retry')
+ })
if (environment === ApEnvironment.DEVELOPMENT) {
app.log.warn(
`[WARNING]: The application is running in ${environment} mode.`,
@@ -502,6 +510,24 @@ The application started on ${await domainHelper.getPublicApiUrl({ path: '' })},
void startDevPieceWatcher(app)
}
+async function dispatchBackgroundMigrations(log: FastifyBaseLogger): Promise<void> {
+ await systemJobsSchedule(log).upsertJob({
+ job: {
+ name: SystemJobName.RUN_BACKGROUND_MIGRATIONS,
+ data: {},
+ jobId: SystemJobName.RUN_BACKGROUND_MIGRATIONS,
+ },
+ schedule: {
+ type: 'one-time',
+ date: apDayjs(),
+ },
+ customConfig: {
+ attempts: 10,
+ backoff: { type: SystemJobBackoff.instantBurstThenExponential, delay: 0 },
+ },
+ })
+}
+
// Front-loads the release-read failure signal to boot time. Without this the only alert is
// emitted lazily on the first worker poll (worker-rpc-service.ts), so a mis-packaged app that
// no worker has polled yet looks healthy. A '0.0.0' read fail-closes the dispatch gate and will
diff --git a/packages/server/api/src/app/database/background-migration-runner.ts b/packages/server/api/src/app/database/background-migration-runner.ts
new file mode 100644
index 00000000000..b5e57e7a5a1
--- /dev/null
+++ b/packages/server/api/src/app/database/background-migration-runner.ts
@@ -0,0 +1,230 @@
+import { tryCatch } from '@activepieces/core-utils'
+import { wideEvent } from '@activepieces/server-utils'
+import { FastifyBaseLogger } from 'fastify'
+import { DataSource } from 'typeorm'
+import { BackgroundMigration } from './background-migration'
+import { databaseConnection } from './database-connection'
+import { BackgroundMigrationNotCompleteError } from './migration-helpers'
+import { getBackgroundMigrations } from './postgres-connection'
+import { distributedLock } from './redis-connections'
+
+export const backgroundMigrationRunner = {
+ async ensureTable({ dataSource }: { dataSource?: DataSource } = {}): Promise<void> {
+ const ds = dataSource ?? databaseConnection()
+ await ensureBackgroundMigrationsTable(ds)
+ },
+
+ async run({
+ log,
+ migrations,
+ dataSource,
+ }: {
+ log: FastifyBaseLogger
+ migrations?: (new () => BackgroundMigration)[]
+ dataSource?: DataSource
+ }): Promise<void> {
+ const ds = dataSource ?? databaseConnection()
+ const source = migrations ?? getBackgroundMigrations()
+ await ensureBackgroundMigrationsTable(ds)
+ const completed = await getCompletedNames(ds)
+ const pending = source
+ .map(MigrationClass => new MigrationClass())
+ .filter(instance => !completed.has(instance.name))
+
+ log.info({ migration: { pendingCount: pending.length } }, '[backgroundMigrationRunner] Starting run')
+ wideEvent.set({ migration: { pendingCount: pending.length } })
+
+ for (const migration of pending) {
+ await runOne({ migration, log, dataSource: ds })
+ }
+ },
+
+ async runMigrationsWithCatchup({
+ dataSource,
+ log,
+ }: {
+ dataSource: DataSource
+ log: FastifyBaseLogger
+ }): Promise<void> {
+ await ensureBackgroundMigrationsTable(dataSource)
+ for (let attempt = 1; attempt <= MAX_CATCHUP_ATTEMPTS; attempt++) {
+ const { error } = await tryCatch(async () => dataSource.runMigrations())
+ if (!error) return
+ if (!(error instanceof BackgroundMigrationNotCompleteError)) throw error
+ const name = new error.migration().name
+ log.info({ migration: { name } }, '[runMigrationsWithCatchup] Catching up prior-release backfill before retrying blocking migrations')
+ const { error: catchupError } = await tryCatch(async () =>
+ backgroundMigrationRunner.run({ log, migrations: [error.migration], dataSource }),
+ )
+ if (catchupError) {
+ throw new Error(
+ `Boot catchup for background migration "${name}" failed. See background_migrations.last_error.`,
+ { cause: catchupError },
+ )
+ }
+ }
+ throw new Error(`runMigrationsWithCatchup exceeded ${MAX_CATCHUP_ATTEMPTS} attempts; too many distinct backfill dependencies or a loop`)
+ },
+
+ async getStatus({
+ migrations,
+ dataSource,
+ }: {
+ migrations?: (new () => BackgroundMigration)[]
+ dataSource?: DataSource
+ } = {}): Promise<BackgroundMigrationStatus> {
+ const { data, error } = await tryCatch(async () => {
+ const ds = dataSource ?? databaseConnection()
+ const source = migrations ?? getBackgroundMigrations()
+ await ensureBackgroundMigrationsTable(ds)
+ const completed = await getCompletedNames(ds)
+ const sourceNames = source.map(MigrationClass => new MigrationClass().name)
+ const pendingCount = sourceNames.filter(name => !completed.has(name)).length
+ const failedMigration = await getLatestFailure(ds, sourceNames)
+ return {
+ pendingCount,
+ completedCount: source.length - pendingCount,
+ error: null,
+ failedMigration,
+ }
+ })
+ if (error) {
+ return { pendingCount: 0, completedCount: 0, error: error instanceof Error ? error.message : String(error), failedMigration: null }
+ }
+ return data
+ },
+}
+
+async function runOne({
+ migration,
+ log,
+ dataSource,
+}: {
+ migration: BackgroundMigration
+ log: FastifyBaseLogger
+ dataSource: DataSource
+}): Promise<void> {
+ await distributedLock(log).runExclusive({
+ key: `background_migration:${migration.name}`,
+ timeoutInSeconds: RUN_LOCK_TIMEOUT_SECONDS,
+ fn: async () => {
+ const completed = await getCompletedNames(dataSource)
+ if (completed.has(migration.name)) {
+ log.info({ migration: { name: migration.name } }, '[backgroundMigrationRunner] Migration already completed under another lock holder, skipping')
+ return
+ }
+ log.info({ migration: { name: migration.name } }, '[backgroundMigrationRunner] Running migration')
+ wideEvent.set({ migration: { name: migration.name } })
+ await wideEvent.timed({
+ name: 'backgroundMigration',
+ fn: () => executeMigrationBody({ migration, log, dataSource }),
+ })
+ },
+ })
+}
+
+async function executeMigrationBody({
+ migration,
+ log,
+ dataSource,
+}: {
+ migration: BackgroundMigration
+ log: FastifyBaseLogger
+ dataSource: DataSource
+}): Promise<void> {
+ const queryRunner = dataSource.createQueryRunner()
+ try {
+ try {
+ await migration.up(queryRunner)
+ }
+ finally {
+ await queryRunner.release()
+ }
+ }
+ catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ const { error: recordError } = await tryCatch(async () => dataSource.query(
+ `INSERT INTO "${BACKGROUND_MIGRATIONS_TABLE}" ("name", "failed_at", "last_error") VALUES ($1, NOW(), $2)
+ ON CONFLICT ("name") DO UPDATE SET "failed_at" = NOW(), "last_error" = EXCLUDED."last_error"`,
+ [migration.name, message],
+ ))
+ if (recordError) {
+ log.error({ migration: { name: migration.name }, error: recordError instanceof Error ? recordError.message : String(recordError) }, '[backgroundMigrationRunner] Failed to persist migration failure; original error follows')
+ }
+ log.error({ migration: { name: migration.name }, error: message }, '[backgroundMigrationRunner] Migration failed')
+ throw error
+ }
+
+ await dataSource.query(
+ `INSERT INTO "${BACKGROUND_MIGRATIONS_TABLE}" ("name", "executed_at") VALUES ($1, NOW())
+ ON CONFLICT ("name") DO UPDATE SET "executed_at" = NOW(), "failed_at" = NULL, "last_error" = NULL`,
+ [migration.name],
+ )
+ log.info({ migration: { name: migration.name } }, '[backgroundMigrationRunner] Migration completed')
+}
+
+async function ensureBackgroundMigrationsTable(dataSource: DataSource): Promise<void> {
+ await dataSource.query(
+ `CREATE TABLE IF NOT EXISTS "${BACKGROUND_MIGRATIONS_TABLE}" (
+ "id" BIGSERIAL PRIMARY KEY,
+ "name" TEXT NOT NULL UNIQUE,
+ "executed_at" TIMESTAMPTZ NULL,
+ "failed_at" TIMESTAMPTZ NULL,
+ "last_error" TEXT NULL
+ )`,
+ )
+}
+
+async function getCompletedNames(dataSource: DataSource): Promise<Set<string>> {
+ const rows: unknown = await dataSource.query(
+ `SELECT "name" FROM "${BACKGROUND_MIGRATIONS_TABLE}" WHERE "executed_at" IS NOT NULL`,
+ )
+ const names = new Set<string>()
+ if (!Array.isArray(rows)) return names
+ for (const row of rows) {
+ if (row !== null && typeof row === 'object' && 'name' in row && typeof row.name === 'string') {
+ names.add(row.name)
+ }
+ }
+ return names
+}
+
+async function getLatestFailure(dataSource: DataSource, sourceNames: string[]): Promise<FailedBackgroundMigration | null> {
+ if (sourceNames.length === 0) return null
+ const rows: unknown = await dataSource.query(
+ `SELECT "name", "failed_at", "last_error"
+ FROM "${BACKGROUND_MIGRATIONS_TABLE}"
+ WHERE "executed_at" IS NULL
+ AND "failed_at" IS NOT NULL
+ AND "name" = ANY($1)
+ ORDER BY "failed_at" DESC
+ LIMIT 1`,
+ [sourceNames],
+ )
+ if (!Array.isArray(rows) || rows.length === 0) return null
+ const [row] = rows
+ if (row === null || typeof row !== 'object') return null
+ if (!('name' in row) || typeof row.name !== 'string') return null
+ if (!('failed_at' in row)) return null
+ if (!('last_error' in row) || typeof row.last_error !== 'string') return null
+ const failedAt = row.failed_at instanceof Date ? row.failed_at.toISOString() : String(row.failed_at)
+ return { name: row.name, failedAt, lastError: row.last_error }
+}
+
+const MAX_CATCHUP_ATTEMPTS = 10
+const RUN_LOCK_TIMEOUT_SECONDS = 240
+
+export const BACKGROUND_MIGRATIONS_TABLE = 'background_migrations'
+
+export type FailedBackgroundMigration = {
+ name: string
+ failedAt: string
+ lastError: string
+}
+
+export type BackgroundMigrationStatus = {
+ pendingCount: number
+ completedCount: number
+ error: string | null
+ failedMigration: FailedBackgroundMigration | null
+}
diff --git a/packages/server/api/src/app/database/background-migration.ts b/packages/server/api/src/app/database/background-migration.ts
new file mode 100644
index 00000000000..d1a21487410
--- /dev/null
+++ b/packages/server/api/src/app/database/background-migration.ts
@@ -0,0 +1,7 @@
+import { MigrationInterface } from 'typeorm'
+
+export type BackgroundMigration = MigrationInterface & {
+ name: string
+ release: string
+ transaction: false
+}
diff --git a/packages/server/api/src/app/database/index.ts b/packages/server/api/src/app/database/index.ts
index 9d8d80b1f73..36868b1cdb7 100644
--- a/packages/server/api/src/app/database/index.ts
+++ b/packages/server/api/src/app/database/index.ts
@@ -1,10 +1,13 @@
+import { system } from '../helper/system/system'
+import { backgroundMigrationRunner } from './background-migration-runner'
import { databaseConnection } from './database-connection'
import { databaseSeeds } from './seeds'
export async function initializeDatabase({ runMigrations }: { runMigrations: boolean }): Promise<void> {
- await databaseConnection().initialize()
+ const ds = databaseConnection()
+ await ds.initialize()
if (runMigrations) {
- await databaseConnection().runMigrations()
+ await backgroundMigrationRunner.runMigrationsWithCatchup({ dataSource: ds, log: system.globalLogger() })
}
await databaseSeeds.run()
}
\ No newline at end of file
diff --git a/packages/server/api/src/app/database/migration-helpers.ts b/packages/server/api/src/app/database/migration-helpers.ts
new file mode 100644
index 00000000000..7aca94641c1
--- /dev/null
+++ b/packages/server/api/src/app/database/migration-helpers.ts
@@ -0,0 +1,105 @@
+import { QueryRunner } from 'typeorm'
+import { system } from '../helper/system/system'
+import { AppSystemProp } from '../helper/system/system-props'
+import { BackgroundMigration } from './background-migration'
+import { BACKGROUND_MIGRATIONS_TABLE } from './background-migration-runner'
+import { DatabaseType } from './database-type'
+
+export const migrationHelpers = {
+ assertBackgroundMigrationComplete,
+ createIndexConcurrently,
+ dropIndexConcurrently,
+}
+
+async function assertBackgroundMigrationComplete({
+ queryRunner,
+ migration,
+}: {
+ queryRunner: QueryRunner
+ migration: new () => BackgroundMigration
+}): Promise<void> {
+ const name = new migration().name
+ const rows = await queryRunner.query(
+ `SELECT 1 FROM "${BACKGROUND_MIGRATIONS_TABLE}" WHERE "name" = $1 AND "executed_at" IS NOT NULL`,
+ [name],
+ )
+ if (rows.length === 0) {
+ throw new BackgroundMigrationNotCompleteError(migration)
+ }
+}
+
+async function createIndexConcurrently({
+ queryRunner,
+ name,
+ table,
+ columns,
+ where,
+ unique = false,
+}: {
+ queryRunner: QueryRunner
+ name: string
+ table: string
+ columns: string
+ where?: string
+ unique?: boolean
+}): Promise<void> {
+ const uniqueClause = unique ? 'UNIQUE ' : ''
+ const whereClause = where ? ` WHERE ${where}` : ''
+
+ if (isPGlite()) {
+ await queryRunner.query(
+ `CREATE ${uniqueClause}INDEX IF NOT EXISTS "${name}" ON "${table}" (${columns})${whereClause}`,
+ )
+ return
+ }
+
+ const rows = await queryRunner.query(
+ `SELECT indisvalid FROM pg_index i
+ JOIN pg_class c ON c.oid = i.indexrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE c.relname = $1 AND n.nspname = current_schema()`,
+ [name],
+ )
+ const indisvalid = extractIndisvalid(rows)
+
+ if (indisvalid === true) return
+
+ if (indisvalid === false) {
+ await queryRunner.query(`REINDEX INDEX CONCURRENTLY "${name}"`)
+ return
+ }
+
+ await queryRunner.query(
+ `CREATE ${uniqueClause}INDEX CONCURRENTLY "${name}" ON "${table}" (${columns})${whereClause}`,
+ )
+}
+
+async function dropIndexConcurrently({
+ queryRunner,
+ name,
+}: {
+ queryRunner: QueryRunner
+ name: string
+}): Promise<void> {
+ const concurrently = isPGlite() ? '' : 'CONCURRENTLY'
+ await queryRunner.query(`DROP INDEX ${concurrently} IF EXISTS "${name}"`)
+}
+
+const isPGlite = (): boolean => system.get(AppSystemProp.DB_TYPE) === DatabaseType.PGLITE
+
+function extractIndisvalid(rows: unknown): boolean | undefined {
+ if (!Array.isArray(rows) || rows.length === 0) return undefined
+ const [row] = rows
+ if (row === null || typeof row !== 'object' || !('indisvalid' in row)) return undefined
+ const value = row.indisvalid
+ if (typeof value !== 'boolean') return undefined
+ return value
+}
+
+export class BackgroundMigrationNotCompleteError extends Error {
+ constructor(public readonly migration: new () => BackgroundMigration) {
+ const name = new migration().name
+ super(`Background migration "${name}" has not completed. See background_migrations.last_error for details.`)
+ this.name = 'BackgroundMigrationNotCompleteError'
+ }
+}
diff --git a/packages/server/api/src/app/database/migration/postgres/background/.gitkeep b/packages/server/api/src/app/database/migration/postgres/background/.gitkeep
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/packages/server/api/src/app/database/pglite-connection.ts b/packages/server/api/src/app/database/pglite-connection.ts
index fc625e25326..1f4edd381a0 100644
--- a/packages/server/api/src/app/database/pglite-connection.ts
+++ b/packages/server/api/src/app/database/pglite-connection.ts
@@ -67,7 +67,7 @@ export const createPGliteDataSource = (): DataSource => {
},
},
}).driver,
- migrationsRun: env !== ApEnvironment.TESTING,
+ migrationsRun: false,
migrationsTransactionMode: 'each',
migrations: env !== ApEnvironment.TESTING ? getMigrations() : [],
synchronize: env === ApEnvironment.TESTING,
diff --git a/packages/server/api/src/app/database/postgres-connection.ts b/packages/server/api/src/app/database/postgres-connection.ts
index 03cffcda46a..2a188f75af4 100644
--- a/packages/server/api/src/app/database/postgres-connection.ts
+++ b/packages/server/api/src/app/database/postgres-connection.ts
@@ -24,6 +24,7 @@ import { AddCustomDomain1698077078271 } from '../ee/database/migrations/postgres
import { AddMetadataFieldToFlowTemplates1744780800000 } from '../ee/database/migrations/postgres/1744780800000-AddMetadataFieldToFlowTemplates'
import { system } from '../helper/system/system'
import { AppSystemProp } from '../helper/system/system-props'
+import { BackgroundMigration } from './background-migration'
import { commonProperties } from './database-connection'
import { Migration } from './migration'
import { AddPieceTypeAndPackageTypeToFlowVersion1696245170061 } from './migration/common/1696245170061-add-piece-type-and-package-type-to-flow-version'
@@ -465,6 +466,10 @@ const getSslConfig = (): boolean | TlsOptions => {
return false
}
+export const getBackgroundMigrations = (): (new () => BackgroundMigration)[] => {
+ return []
+}
+
export const getMigrations = (): (new () => Migration)[] => {
const migrations = [
FlowAndFileProjectId1674788714498,
@@ -930,7 +935,7 @@ export const getMigrations = (): (new () => Migration)[] => {
export const createPostgresDataSource = (): DataSource => {
const migrationConfig: MigrationConfig = {
- migrationsRun: true,
+ migrationsRun: false,
migrationsTransactionMode: 'each',
migrations: getMigrations(),
synchronize: false,
diff --git a/packages/server/api/src/app/database/sqlite-connection.ts b/packages/server/api/src/app/database/sqlite-connection.ts
index 42909df9b18..7aed05c0a5f 100644
--- a/packages/server/api/src/app/database/sqlite-connection.ts
+++ b/packages/server/api/src/app/database/sqlite-connection.ts
@@ -371,7 +371,7 @@ const getMigrationConfig = (): MigrationConfig => {
}
return {
- migrationsRun: true,
+ migrationsRun: false,
migrationsTransactionMode: 'each',
migrations: getMigrations(),
}
diff --git a/packages/server/api/src/app/health/health.service.ts b/packages/server/api/src/app/health/health.service.ts
index 293bffdaf74..9058b19adbe 100644
--- a/packages/server/api/src/app/health/health.service.ts
+++ b/packages/server/api/src/app/health/health.service.ts
@@ -1,6 +1,7 @@
import { apVersionUtil, systemUsage, UNKNOWN_VERSION } from '@activepieces/server-utils'
import { ActivepiecesError, ApEdition, apId, AppInstance, DeploymentConfig, ErrorCode, FileLocation, GetDiagnosticsResponse, GetSystemHealthChecksResponse, InfraCheck, ReleaseHealth, tryCatch, unique } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
+import { backgroundMigrationRunner } from '../database/background-migration-runner'
import { databaseConnection } from '../database/database-connection'
import { redisConnections } from '../database/redis-connections'
import { s3Helper } from '../file/s3-helper'
@@ -45,10 +46,11 @@ export const healthStatusService = (log: FastifyBaseLogger) => ({
return buildReleaseHealth(log, workerVersions)
},
getSystemHealthChecks: async (platformId: string): Promise<GetSystemHealthChecksResponse> => {
- const [workers, databaseHealthy, latestVersion] = await Promise.all([
+ const [workers, databaseHealthy, latestVersion, backgroundMigrations] = await Promise.all([
machineService(log).list(platformId),
healthStatusService(log).checkDatabaseHealth(),
apVersionUtil.getLatestRelease(),
+ backgroundMigrationRunner.getStatus(),
])
const hasWorkers = workers.length > 0
const release = buildReleaseHealth(log, workers.map(worker => worker.information.workerProps.version))
@@ -62,6 +64,7 @@ export const healthStatusService = (log: FastifyBaseLogger) => ({
workerRam: hasWorkers ? workers.every(worker => worker.information.totalAvailableRamInBytes >= gigaBytes(WORKER_MIN_RAM_GB)) : null,
database: databaseHealthy,
release,
+ backgroundMigrations,
}
},
collectDeploymentDiagnostics: async (): Promise<DeploymentDiagnostics> => {
diff --git a/packages/server/api/src/app/helper/system-jobs/common.ts b/packages/server/api/src/app/helper/system-jobs/common.ts
index 11daf6cb8e4..3cbf8ccf0a5 100644
--- a/packages/server/api/src/app/helper/system-jobs/common.ts
+++ b/packages/server/api/src/app/helper/system-jobs/common.ts
@@ -16,6 +16,7 @@ export enum SystemJobName {
TOOL_SEARCH_REINDEX = 'tool-search-reindex',
CHAT_STALE_SWEEP = 'chat-stale-sweep',
WAITPOINT_DEADLINE_SWEEP = 'waitpoint-deadline-sweep',
+ RUN_BACKGROUND_MIGRATIONS = 'run-background-migrations',
AUDIT_LOG_RETENTION = 'audit-log-retention',
}
@@ -59,6 +60,7 @@ type SystemJobDataMap = {
[SystemJobName.TOOL_SEARCH_REINDEX]: ToolSearchReindexSystemJobData
[SystemJobName.CHAT_STALE_SWEEP]: Record<string, never>
[SystemJobName.WAITPOINT_DEADLINE_SWEEP]: Record<string, never>
+ [SystemJobName.RUN_BACKGROUND_MIGRATIONS]: Record<string, never>
[SystemJobName.AUDIT_LOG_RETENTION]: Record<string, never>
}
diff --git a/packages/server/api/src/app/helper/system-jobs/job-handlers.ts b/packages/server/api/src/app/helper/system-jobs/job-handlers.ts
index 0af65bbc0c4..6c245fb221c 100644
--- a/packages/server/api/src/app/helper/system-jobs/job-handlers.ts
+++ b/packages/server/api/src/app/helper/system-jobs/job-handlers.ts
@@ -7,13 +7,16 @@ export const systemJobHandlers = {
registerJobHandler<T extends SystemJobName>(name: T, handler: SystemJobHandler<T>): void {
jobHandlers.set(name, handler as SystemJobHandler)
},
+ hasHandler(name: SystemJobName): boolean {
+ return jobHandlers.has(name)
+ },
getJobHandler(name: SystemJobName): SystemJobHandler {
const jobHandler = jobHandlers.get(name)
-
+
if (isNil(jobHandler)) {
throw new Error(`No handler for job ${name}`)
}
-
+
return jobHandler
},
}
\ No newline at end of file
diff --git a/packages/server/api/src/app/helper/system-jobs/system-job.ts b/packages/server/api/src/app/helper/system-jobs/system-job.ts
index 5de92693b7c..b8617a91a2a 100644
--- a/packages/server/api/src/app/helper/system-jobs/system-job.ts
+++ b/packages/server/api/src/app/helper/system-jobs/system-job.ts
@@ -1,6 +1,6 @@
import { isNil, tryCatch } from '@activepieces/core-utils'
import { apDayjs, apDayjsDuration, createLogger, wideEvent } from '@activepieces/server-utils'
-import { Job, JobsOptions, JobState, Queue, Worker } from 'bullmq'
+import { DelayedError, Job, JobsOptions, JobState, Queue, Worker } from 'bullmq'
import { Dayjs } from 'dayjs'
import { FastifyBaseLogger } from 'fastify'
import { redisConnections } from '../../database/redis-connections'
@@ -12,6 +12,9 @@ import { systemJobHandlers } from './job-handlers'
const FIFTEEN_MINUTES = apDayjsDuration(15, 'minute').asMilliseconds()
const ONE_MONTH = apDayjsDuration(1, 'month').asSeconds()
const SYSTEM_JOB_QUEUE = 'system-job-queue'
+const RE_QUEUE_DELAY_MS = apDayjsDuration(1, 'minute').asMilliseconds()
+const RE_QUEUE_MAX_AGE_MS = apDayjsDuration(15, 'minute').asMilliseconds()
+const INSTANT_BURST_THEN_EXPONENTIAL = 'instantBurstThenExponential'
export let systemJobsQueue: Queue<SystemJobData, unknown, SystemJobName>
let systemJobWorker: Worker<SystemJobData, unknown, SystemJobName>
@@ -45,7 +48,17 @@ export const systemJobsSchedule = (log: FastifyBaseLogger): SystemJobSchedule =>
async startWorker(): Promise<void> {
systemJobWorker = new Worker(
SYSTEM_JOB_QUEUE,
- async (job) => {
+ async (job, token) => {
+ if (!systemJobHandlers.hasHandler(job.name)) {
+ const createdAt = Number.isFinite(job.timestamp) ? job.timestamp : Date.now()
+ const ageMs = Date.now() - createdAt
+ if (ageMs > RE_QUEUE_MAX_AGE_MS) {
+ throw new Error(`No handler for system job "${job.name}" after ${Math.round(ageMs / 1000)}s; likely a retired job name`)
+ }
+ log.info({ job: { id: job.id, type: job.name } }, '[systemJob#worker] No handler on this pod; re-queueing (rolling deploy with mixed versions)')
+ await job.moveToDelayed(Date.now() + RE_QUEUE_DELAY_MS, token)
+ throw new DelayedError()
+ }
log.debug({ jobName: job.name }, '[systemJob#worker] Executing job')
const jobLogger = createLogger({
event: 'system-job.execute',
@@ -66,6 +79,9 @@ export const systemJobsSchedule = (log: FastifyBaseLogger): SystemJobSchedule =>
{
connection: await redisConnections.create(),
concurrency: 5,
+ settings: {
+ backoffStrategy: instantBurstThenExponentialBackoff,
+ },
},
)
@@ -153,6 +169,18 @@ async function processSystemJob(job: Job<SystemJobData, unknown, SystemJobName>)
await jobHandler(job.data)
}
+function instantBurstThenExponentialBackoff(attemptsMade: number, type?: string): number {
+ if (type !== INSTANT_BURST_THEN_EXPONENTIAL) {
+ throw new Error(`Unknown system-job backoff type "${type ?? '<unset>'}"; register the strategy or use a built-in type`)
+ }
+ const INSTANT_BURST_SIZE = 5
+ const EXPONENTIAL_BASE_MS = apDayjsDuration(1, 'minute').asMilliseconds()
+ const EXPONENTIAL_CAP_MS = apDayjsDuration(1, 'hour').asMilliseconds()
+ if (attemptsMade <= INSTANT_BURST_SIZE) return 0
+ const exponentialStep = attemptsMade - INSTANT_BURST_SIZE
+ return Math.min(EXPONENTIAL_BASE_MS * 2 ** (exponentialStep - 1), EXPONENTIAL_CAP_MS)
+}
+
async function removeDeprecatedJobs(log: FastifyBaseLogger): Promise<void> {
const deprecatedJobs = [
'trigger-data-cleaner',
@@ -214,3 +242,7 @@ const getJobByNameAndJobId = async (name: string, jobId: string): Promise<Job |
}
return undefined
}
+
+export const SystemJobBackoff = {
+ instantBurstThenExponential: INSTANT_BURST_THEN_EXPONENTIAL,
+} as const
diff --git a/packages/server/api/test/integration/ce/database/background-migration-runner.test.ts b/packages/server/api/test/integration/ce/database/background-migration-runner.test.ts
new file mode 100644
index 00000000000..1aba692ee40
--- /dev/null
+++ b/packages/server/api/test/integration/ce/database/background-migration-runner.test.ts
@@ -0,0 +1,215 @@
+import { FastifyInstance } from 'fastify'
+import { QueryRunner } from 'typeorm'
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import { BackgroundMigration } from '../../../../src/app/database/background-migration'
+import {
+ BACKGROUND_MIGRATIONS_TABLE,
+ backgroundMigrationRunner,
+} from '../../../../src/app/database/background-migration-runner'
+import { databaseConnection } from '../../../../src/app/database/database-connection'
+import { BackgroundMigrationNotCompleteError, migrationHelpers } from '../../../../src/app/database/migration-helpers'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance | null = null
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+describe('backgroundMigrationRunner', () => {
+ it('runs a pending background migration and records it in background_migrations', async () => {
+ const MigrationClass = makeTestMigration({ name: `HappyPath${Date.now()}` })
+ await backgroundMigrationRunner.run({
+ log: app!.log,
+ migrations: [MigrationClass],
+ })
+ const rows = await selectByName(new MigrationClass().name)
+ expect(rows).toHaveLength(1)
+ })
+
+ it('records a failed migration with its error and does not mark it completed', async () => {
+ const MigrationClass = makeTestMigration({
+ name: `Failing${Date.now()}`,
+ up: async () => { throw new Error('boom') },
+ })
+ await expect(
+ backgroundMigrationRunner.run({ log: app!.log, migrations: [MigrationClass] }),
+ ).rejects.toThrow(/boom/)
+ const name = new MigrationClass().name
+ const completed = await selectCompletedByName(name)
+ expect(completed).toHaveLength(0)
+ const status = await backgroundMigrationRunner.getStatus({ migrations: [MigrationClass] })
+ expect(status.failedMigration?.name).toBe(name)
+ expect(status.failedMigration?.lastError).toMatch(/boom/)
+ })
+
+ it('clears failure state when a previously failed migration succeeds on retry', async () => {
+ let shouldFail = true
+ const name = `RetrySucceeds${Date.now()}`
+ const MigrationClass = makeTestMigration({
+ name,
+ up: async () => { if (shouldFail) throw new Error('transient') },
+ })
+ await expect(
+ backgroundMigrationRunner.run({ log: app!.log, migrations: [MigrationClass] }),
+ ).rejects.toThrow(/transient/)
+ shouldFail = false
+ await backgroundMigrationRunner.run({ log: app!.log, migrations: [MigrationClass] })
+ const status = await backgroundMigrationRunner.getStatus({ migrations: [MigrationClass] })
+ expect(status.failedMigration).toBeNull()
+ expect(status.pendingCount).toBe(0)
+ })
+
+ it('skips a migration that has already completed', async () => {
+ let upCalls = 0
+ const MigrationClass = makeTestMigration({
+ name: `Idempotent${Date.now()}`,
+ up: async () => { upCalls++ },
+ })
+ await backgroundMigrationRunner.run({ log: app!.log, migrations: [MigrationClass] })
+ await backgroundMigrationRunner.run({ log: app!.log, migrations: [MigrationClass] })
+ expect(upCalls).toBe(1)
+ })
+
+ it('assertBackgroundMigrationComplete gates a blocking migration until the backfill runs', async () => {
+ const backfill = makeTestMigration({ name: `GateBackfill${Date.now()}` })
+ const contract = async (queryRunner: QueryRunner): Promise<void> => {
+ await migrationHelpers.assertBackgroundMigrationComplete({
+ queryRunner,
+ migration: backfill,
+ })
+ }
+ const preRun = databaseConnection().createQueryRunner()
+ try {
+ await expect(contract(preRun)).rejects.toThrow(/GateBackfill.*has not completed/)
+ }
+ finally {
+ await preRun.release()
+ }
+
+ await backgroundMigrationRunner.run({ log: app!.log, migrations: [backfill] })
+
+ const postRun = databaseConnection().createQueryRunner()
+ try {
+ await expect(contract(postRun)).resolves.toBeUndefined()
+ }
+ finally {
+ await postRun.release()
+ }
+ })
+
+ it('assertBackgroundMigrationComplete rejects a backfill that only failed', async () => {
+ const backfill = makeTestMigration({
+ name: `FailedGate${Date.now()}`,
+ up: async () => { throw new Error('kaboom') },
+ })
+ await expect(
+ backgroundMigrationRunner.run({ log: app!.log, migrations: [backfill] }),
+ ).rejects.toThrow(/kaboom/)
+
+ const queryRunner = databaseConnection().createQueryRunner()
+ try {
+ await expect(migrationHelpers.assertBackgroundMigrationComplete({
+ queryRunner,
+ migration: backfill,
+ })).rejects.toThrow(/FailedGate.*has not completed/)
+ }
+ finally {
+ await queryRunner.release()
+ }
+ })
+
+ it('reports pending count via getStatus', async () => {
+ const done = makeTestMigration({ name: `StatusDone${Date.now()}` })
+ const pending = makeTestMigration({ name: `StatusPending${Date.now()}` })
+ await backgroundMigrationRunner.run({ log: app!.log, migrations: [done] })
+
+ const status = await backgroundMigrationRunner.getStatus({ migrations: [done, pending] })
+ expect(status.pendingCount).toBe(1)
+ expect(status.completedCount).toBeGreaterThanOrEqual(1)
+ })
+
+ it('getStatus returns error-shape instead of throwing on DB failure', async () => {
+ const ds = databaseConnection()
+ const spy = vi.spyOn(ds, 'query').mockRejectedValueOnce(new Error('db down'))
+ const status = await backgroundMigrationRunner.getStatus({ migrations: [], dataSource: ds })
+ expect(status.error).toMatch(/db down/)
+ expect(status.pendingCount).toBe(0)
+ expect(status.completedCount).toBe(0)
+ expect(status.failedMigration).toBeNull()
+ spy.mockRestore()
+ })
+})
+
+describe('runMigrationsWithCatchup', () => {
+ afterEach(() => vi.restoreAllMocks())
+
+ it('runs the backfill when a blocking migration throws BackgroundMigrationNotCompleteError', async () => {
+ const Backfill = makeTestMigration({ name: `CatchupBackfill${Date.now()}` })
+ const ds = databaseConnection()
+ let runMigrationsCalls = 0
+ vi.spyOn(ds, 'runMigrations').mockImplementation(async () => {
+ runMigrationsCalls++
+ if (runMigrationsCalls === 1) throw new BackgroundMigrationNotCompleteError(Backfill)
+ return []
+ })
+
+ await backgroundMigrationRunner.runMigrationsWithCatchup({ dataSource: ds, log: app!.log })
+ expect(runMigrationsCalls).toBe(2)
+ const rows = await selectByName(new Backfill().name)
+ expect(rows).toHaveLength(1)
+ })
+
+ it('rethrows non-NotComplete errors immediately', async () => {
+ const ds = databaseConnection()
+ vi.spyOn(ds, 'runMigrations').mockRejectedValueOnce(new Error('syntax error'))
+ await expect(
+ backgroundMigrationRunner.runMigrationsWithCatchup({ dataSource: ds, log: app!.log }),
+ ).rejects.toThrow(/syntax error/)
+ })
+
+ it('fails fast when the catchup backfill itself throws', async () => {
+ const BrokenBackfill = makeTestMigration({
+ name: `BrokenCatchup${Date.now()}`,
+ up: async () => { throw new Error('backfill bug') },
+ })
+ const ds = databaseConnection()
+ vi.spyOn(ds, 'runMigrations').mockRejectedValue(new BackgroundMigrationNotCompleteError(BrokenBackfill))
+ const promise = backgroundMigrationRunner.runMigrationsWithCatchup({ dataSource: ds, log: app!.log })
+ await expect(promise).rejects.toThrow(/Boot catchup.*BrokenCatchup/)
+ const thrown = await promise.catch(err => err)
+ expect(thrown.cause).toBeInstanceOf(Error)
+ expect(thrown.cause.message).toMatch(/backfill bug/)
+ })
+})
+
+function makeTestMigration({
+ name: migrationName,
+ up: upFn = async () => { /* no-op */ },
+}: {
+ name: string
+ up?: (queryRunner: QueryRunner) => Promise<void>
+}): new () => BackgroundMigration {
+ return class implements BackgroundMigration {
+ name = migrationName
+ release = '0.0.0-test'
+ transaction = false as const
+ public async up(queryRunner: QueryRunner): Promise<void> { await upFn(queryRunner) }
+ public async down(): Promise<void> { /* no-op */ }
+ }
+}
+
+async function selectByName(name: string): Promise<{ name: string }[]> {
+ const rows = await databaseConnection().query(
+ `SELECT "name" FROM "${BACKGROUND_MIGRATIONS_TABLE}" WHERE "executed_at" IS NOT NULL`,
+ ) as { name: string }[]
+ return rows.filter(row => row.name === name)
+}
+
+async function selectCompletedByName(name: string): Promise<{ name: string }[]> {
+ return selectByName(name)
+}
diff --git a/packages/server/api/test/integration/ce/tool-search/tool-search.test.ts b/packages/server/api/test/integration/ce/tool-search/tool-search.test.ts
index d8f752106be..426d5423233 100644
--- a/packages/server/api/test/integration/ce/tool-search/tool-search.test.ts
+++ b/packages/server/api/test/integration/ce/tool-search/tool-search.test.ts
@@ -2,6 +2,7 @@ import { ActionBase, PieceAuth, TriggerBase } from '@activepieces/pieces-framewo
import { apId, PackageType, PieceCategory, PieceType, TriggerStrategy, TriggerTestStrategy } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
+import { initializeDatabase } from '../../../../src/app/database'
import { databaseConnection, resetDatabaseConnection } from '../../../../src/app/database/database-connection'
import { encryptUtils } from '../../../../src/app/helper/encryption'
import { system } from '../../../../src/app/helper/system/system'
@@ -11,10 +12,10 @@ import { toolSearchService } from '../../../../src/app/tool-search/tool-search.s
import { db } from '../../../helpers/db'
import { createMockPieceMetadata } from '../../../helpers/mocks'
-// Boots only the database (migrations run automatically on a POSTGRES DataSource via
-// migrationsRun:true) — deliberately NOT the full server, whose app-event-routing module statically
-// imports individual pieces that vite can't resolve in this test context. The engine only needs the
-// schema + seeded piece_metadata rows; no fastify/HTTP layer is involved.
+// Boots only the database and runs migrations via initializeDatabase (which routes through
+// runMigrationsWithCatchup) — deliberately NOT the full server, whose app-event-routing module
+// statically imports individual pieces that vite can't resolve in this test context. The engine
+// only needs the schema + seeded piece_metadata rows; no fastify/HTTP layer is involved.
const log: FastifyBaseLogger = system.globalLogger()
// A deterministic bag-of-words embedder over a fixed vocabulary, L2-normalized with the real
@@ -110,7 +111,7 @@ async function getIndexRow(pieceName: string, objectName: string): Promise<Index
beforeAll(async () => {
resetDatabaseConnection()
- await databaseConnection().initialize()
+ await initializeDatabase({ runMigrations: true })
}, 300_000)
afterAll(async () => {
diff --git a/packages/server/api/test/unit/app/database/migration-helpers.test.ts b/packages/server/api/test/unit/app/database/migration-helpers.test.ts
new file mode 100644
index 00000000000..95c562361f1
--- /dev/null
+++ b/packages/server/api/test/unit/app/database/migration-helpers.test.ts
@@ -0,0 +1,103 @@
+import { QueryRunner } from 'typeorm'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { BackgroundMigration } from '../../../../src/app/database/background-migration'
+import { DatabaseType } from '../../../../src/app/database/database-type'
+import { migrationHelpers } from '../../../../src/app/database/migration-helpers'
+import { system } from '../../../../src/app/helper/system/system'
+import { AppSystemProp } from '../../../../src/app/helper/system/system-props'
+
+describe('createIndexConcurrently (postgres)', () => {
+ beforeEach(() => {
+ vi.spyOn(system, 'get').mockImplementation((prop) => prop === AppSystemProp.DB_TYPE ? DatabaseType.POSTGRES : undefined)
+ })
+ afterEach(() => vi.restoreAllMocks())
+
+ it('is a no-op when the index already exists and is valid', async () => {
+ const queryRunner = mockQueryRunner([{ indisvalid: true }])
+ await migrationHelpers.createIndexConcurrently({ queryRunner, name: 'idx_foo', table: 'foo', columns: '"bar"' })
+ expect(queryRunner.query).toHaveBeenCalledTimes(1)
+ expect(queryRunner.query).toHaveBeenCalledWith(expect.stringContaining('pg_index'), ['idx_foo'])
+ })
+
+ it('reindexes when an invalid index is present', async () => {
+ const queryRunner = mockQueryRunner([{ indisvalid: false }], [])
+ await migrationHelpers.createIndexConcurrently({ queryRunner, name: 'idx_foo', table: 'foo', columns: '"bar"' })
+ expect(queryRunner.query).toHaveBeenNthCalledWith(2, 'REINDEX INDEX CONCURRENTLY "idx_foo"')
+ })
+
+ it('creates the index when it is missing', async () => {
+ const queryRunner = mockQueryRunner([], [])
+ await migrationHelpers.createIndexConcurrently({ queryRunner, name: 'idx_foo', table: 'foo', columns: '"bar"', where: `"kind" = 'active'` })
+ const secondCall = (queryRunner.query as ReturnType<typeof vi.fn>).mock.calls[1][0]
+ expect(secondCall).toBe(`CREATE INDEX CONCURRENTLY "idx_foo" ON "foo" ("bar") WHERE "kind" = 'active'`)
+ })
+
+ it('supports UNIQUE indexes', async () => {
+ const queryRunner = mockQueryRunner([], [])
+ await migrationHelpers.createIndexConcurrently({ queryRunner, name: 'idx_foo_unique', table: 'foo', columns: '"bar"', unique: true })
+ const secondCall = (queryRunner.query as ReturnType<typeof vi.fn>).mock.calls[1][0]
+ expect(secondCall).toBe(`CREATE UNIQUE INDEX CONCURRENTLY "idx_foo_unique" ON "foo" ("bar")`)
+ })
+})
+
+describe('createIndexConcurrently (pglite)', () => {
+ beforeEach(() => {
+ vi.spyOn(system, 'get').mockImplementation((prop) => prop === AppSystemProp.DB_TYPE ? DatabaseType.PGLITE : undefined)
+ })
+ afterEach(() => vi.restoreAllMocks())
+
+ it('falls back to a plain CREATE INDEX IF NOT EXISTS', async () => {
+ const queryRunner = mockQueryRunner([])
+ await migrationHelpers.createIndexConcurrently({ queryRunner, name: 'idx_foo', table: 'foo', columns: '"bar"' })
+ expect(queryRunner.query).toHaveBeenCalledTimes(1)
+ expect(queryRunner.query).toHaveBeenCalledWith(`CREATE INDEX IF NOT EXISTS "idx_foo" ON "foo" ("bar")`)
+ })
+})
+
+describe('dropIndexConcurrently', () => {
+ afterEach(() => vi.restoreAllMocks())
+
+ it('emits DROP INDEX CONCURRENTLY IF EXISTS on postgres', async () => {
+ vi.spyOn(system, 'get').mockImplementation((prop) => prop === AppSystemProp.DB_TYPE ? DatabaseType.POSTGRES : undefined)
+ const queryRunner = mockQueryRunner([])
+ await migrationHelpers.dropIndexConcurrently({ queryRunner, name: 'idx_foo' })
+ expect(queryRunner.query).toHaveBeenCalledWith(`DROP INDEX CONCURRENTLY IF EXISTS "idx_foo"`)
+ })
+
+ it('omits CONCURRENTLY on pglite', async () => {
+ vi.spyOn(system, 'get').mockImplementation((prop) => prop === AppSystemProp.DB_TYPE ? DatabaseType.PGLITE : undefined)
+ const queryRunner = mockQueryRunner([])
+ await migrationHelpers.dropIndexConcurrently({ queryRunner, name: 'idx_foo' })
+ expect(queryRunner.query).toHaveBeenCalledWith(`DROP INDEX IF EXISTS "idx_foo"`)
+ })
+})
+
+describe('assertBackgroundMigrationComplete', () => {
+ class TestBackfill implements BackgroundMigration {
+ name = 'TestBackfill1234'
+ release = '0.91.0'
+ transaction = false as const
+ public async up(): Promise<void> { /* no-op */ }
+ public async down(): Promise<void> { /* no-op */ }
+ }
+
+ it('resolves when the row is present', async () => {
+ const queryRunner = mockQueryRunner([{}])
+ await expect(
+ migrationHelpers.assertBackgroundMigrationComplete({ queryRunner, migration: TestBackfill }),
+ ).resolves.toBeUndefined()
+ })
+
+ it('throws when the row is absent', async () => {
+ const queryRunner = mockQueryRunner([])
+ await expect(
+ migrationHelpers.assertBackgroundMigrationComplete({ queryRunner, migration: TestBackfill }),
+ ).rejects.toThrow(/TestBackfill1234.*has not completed/)
+ })
+})
+
+function mockQueryRunner(...responses: unknown[]): QueryRunner {
+ const query = vi.fn()
+ responses.forEach(response => query.mockResolvedValueOnce(response))
+ return { query } as unknown as QueryRunner
+}
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index e8e5baf6e34..512b2800cd4 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -2952,6 +2952,9 @@
"Destructive": "Destructive",
"External ID can only contain letters, numbers and underscores": "External ID can only contain letters, numbers and underscores",
"required": "Required",
+ "wholeNumber": "Must be a whole number",
+ "atLeastOne": "Must be at least 1",
+ "atMostTenThousand": "Must be at most 10,000",
"Please connect your account first": "Please connect your account first",
"Others": "Others",
"Powerful Node.js & TypeScript code with npm": "Powerful Node.js & TypeScript code with npm",
diff --git a/packages/web/test/app/routes/platform/infra/health/components/system-health-tab.test.tsx b/packages/web/test/app/routes/platform/infra/health/components/system-health-tab.test.tsx
index 309513bc4dd..84233bab97a 100644
--- a/packages/web/test/app/routes/platform/infra/health/components/system-health-tab.test.tsx
+++ b/packages/web/test/app/routes/platform/infra/health/components/system-health-tab.test.tsx
@@ -142,5 +142,11 @@ function buildHealth(current: string): GetSystemHealthChecksResponse {
current,
workers: { total: 1, versionMismatched: 0, mismatchedVersions: [] },
},
+ backgroundMigrations: {
+ pendingCount: 0,
+ completedCount: 0,
+ error: null,
+ failedMigration: null,
+ },
};
}
diff --git a/tools/scripts/check-migration-rollback.ts b/tools/scripts/check-migration-rollback.ts
index 2dd57cdbac0..a574a39a79d 100644
--- a/tools/scripts/check-migration-rollback.ts
+++ b/tools/scripts/check-migration-rollback.ts
@@ -23,7 +23,9 @@ function getChangedMigrationFiles(): string[] {
return diffOutput
.split('\n')
.filter((file) =>
- MIGRATION_DIRS.some((dir) => file.startsWith(dir)) && file.endsWith('.ts'),
+ MIGRATION_DIRS.some((dir) => file.startsWith(dir))
+ && !file.includes('/background/')
+ && file.endsWith('.ts'),
)
}