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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
ci(cloud): roll back Cloud without running migrations down (#16987)
Othman Abu Ajamieh931ec1acabcc
diff --git a/.github/workflows/continuous-delivery-rollback.yml b/.github/workflows/continuous-delivery-rollback.ymlindex a9cb72a2ea8..83b536c42ab 100644--- a/.github/workflows/continuous-delivery-rollback.yml+++ b/.github/workflows/continuous-delivery-rollback.yml@@ -4,17 +4,28 @@ on:workflow_dispatch:inputs:rollback_to_image_tag:- description: 'Image tag to roll back TO (e.g. 0.51.0.abc1234.beta)'+ description: 'Image tag to roll back TO, from the previous deploy run (e.g. 0.92.3.abc1234.beta)'required: true+ target:+ description: 'Environment to roll back'+ type: choice+ options:+ - prod+ - stg+ default: prodforce:- description: 'Force rollback even if breaking migrations exist'+ description: 'Roll back even if a breaking migration ran after the target tag'type: booleandefault: false+concurrency:+ group: ${{ inputs.target == 'prod' && 'promote-production' || 'staging-deploy' }}+ cancel-in-progress: false+jobs:rollback:runs-on: ubuntu-latest- environment: production+ environment: ${{ inputs.target == 'prod' && 'production' || 'staging' }}steps:- name: Configure SSHrun: |@@ -33,13 +44,45 @@ jobs:SSH_KEY: ${{ secrets.SSH_PRIVATE_KEY }}SSH_HOST: ${{ secrets.DEV_OPS_HOST }}+ - name: Get current tag+ id: current+ run: |+ OUTPUT=$(ssh ops -t -t 'bash -ic "cd mrsk/${{ inputs.target }} && kamal app version --primary --config-file=config/app.yml 2>&1; exit"' | tr -d '\r')+ CURRENT=$(echo "$OUTPUT" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[a-f0-9]{40}\.beta' | head -1)+ SHA=$(echo "$CURRENT" | cut -d. -f4)+ if [ -z "$SHA" ]; then+ echo "$OUTPUT"+ echo "Could not read the current tag of ${{ inputs.target }}"+ exit 1+ fi+ echo "sha=$SHA" >> $GITHUB_OUTPUT+ echo "Rolling back ${{ inputs.target }} from $CURRENT to ${{ inputs.rollback_to_image_tag }}"++ - uses: actions/checkout@v5+ with:+ ref: ${{ steps.current.outputs.sha }}++ - uses: actions/setup-node@v6+ with:+ node-version: 24++ - uses: oven-sh/setup-bun@v2+ with:+ bun-version: latest++ - name: Install dependencies+ run: bun install --frozen-lockfile++ - name: Build shared and server-utils packages+ run: bunx turbo run build --filter=@activepieces/shared --filter=@activepieces/server-utils+- name: Login to GitHub Container Registryuses: docker/login-action@v4with:registry: ghcr.iousername: ${{ github.actor }}password: ${{ secrets.GITHUB_TOKEN }}-+- name: Extract migration manifest from target imageid: manifestrun: |@@ -49,29 +92,25 @@ jobs:/usr/src/app/packages/server/api/dist/src/migration-manifest.json)echo "json=$MANIFEST" >> $GITHUB_OUTPUT- - name: Rollback DB migrations- run: |- FORCE_FLAG=${{ inputs.force && '"--force"' || '""' }}- MANIFEST='${{ steps.manifest.outputs.json }}'-- printf '%s' "$MANIFEST" | ssh ops 'cat > /tmp/rollback-manifest.json'+ - name: Check for breaking migrations+ id: check+ run: bunx tsx tools/scripts/check-manifest-migrations.ts '${{ steps.manifest.outputs.json }}'- ssh ops -t -t 'bash -ic "$(cat <<'"'"'EOF'"'"'- cd mrsk/prod- MANIFEST=$(cat /tmp/rollback-manifest.json | jq -c '"'"'[.[] | select(. != null)]'"'"')- MANIFEST_ESCAPED="${MANIFEST//\"/\\\"}"- kamal app exec --reuse --config-file=config/app.yml -- node /usr/src/app/packages/server/api/dist/src/rollback.js --manifest "$MANIFEST_ESCAPED"- EOF- )"'-- - name: Redeploy app to target image+ - name: Fail on breaking migrations+ if: steps.check.outputs.has_breaking == 'true' && !inputs.forcerun: |- ssh ops -t -t 'bash -ic "cd mrsk/prod && kamal deploy \- --version ${{ inputs.rollback_to_image_tag }} \- --config-file=config/app.yml --skip-push; exit"'+ echo "Breaking migrations ran after the target tag: ${{ steps.check.outputs.breaking_names }}"+ echo "The old code may not run on this schema. Fix forward, or rerun with force."+ exit 1- name: Redeploy workers to target imagerun: |- ssh ops -t -t 'bash -ic "cd mrsk/prod && kamal deploy \+ ssh ops -t -t 'bash -ic "cd mrsk/${{ inputs.target }} && kamal deploy \--version ${{ inputs.rollback_to_image_tag }} \--config-file=config/worker.yml --skip-push; exit"'++ - name: Redeploy app to target image+ run: |+ ssh ops -t -t 'bash -ic "cd mrsk/${{ inputs.target }} && kamal deploy \+ --version ${{ inputs.rollback_to_image_tag }} \+ --config-file=config/app.yml --skip-push; exit"'diff --git a/brain/knowledge/data-storage-observability/database.md b/brain/knowledge/data-storage-observability/database.mdindex 07d8cf29b2a..473e349d735 100644--- a/brain/knowledge/data-storage-observability/database.md+++ b/brain/knowledge/data-storage-observability/database.md@@ -292,7 +292,7 @@ A background migration that fails every retry stops the app from booting. The gu- **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.-- **A rollback does not stop the paired background migration from running again.** On Cloud, `rollback.js` runs inside a live new-image container (`continuous-delivery-rollback.yml`) and the image switch comes after it. A new-image pod that boots in between re-applies every rolled-back blocking `up()`, then runs any background migration without a completed row, whether `down()` deleted that row or the migration never finished. Whatever it drops is gone under the old image. So a same-release reshape drops only an index whose queries a kept index still serves, and leaves the rest to a later release. `ReshapeFlowRunListIndexesForBarrierChildren` keeps four of the five old `flow_run` list indexes for this reason. Self-hosted rollback stops the app first.+- **A Cloud rollback runs the old image on the new schema; it never runs `down()`.** `continuous-delivery-rollback.yml` only redeploys the target tag (workers first, then the app) and refuses when a `breaking = true` migration ran after that tag, unless forced. So every blocking and background migration must leave a schema the previous release still runs on: whatever a migration drops is gone under the old image. A same-release reshape drops only an index whose queries a kept index still serves, and leaves the rest to a later release; `ReshapeFlowRunListIndexesForBarrierChildren` keeps four of the five old `flow_run` list indexes for this reason. On a revert after a rollback, revert the code and keep the migration: the database keeps the schema either way. Self-hosted rollback (`rollback.js`) still runs `down()` and stops the app first.- **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.- **`check-migrations` and `db-migration` build their database with `src/migrate.ts`, not `typeorm migration:run`.** The CLI runs only the blocking track, so it reports every entity index that a background migration builds as drift. `migrate.ts` runs `runMigrationsWithCatchup` and then the background track, the boot order, through the same `distributedLock` as boot. It ends with `process.exit`: on memory Redis the lock starts redis-memory-server, whose open connection would keep the step from exiting, and the library's killer process stops `redis-server` once the parent is gone.- **A role-level `statement_timeout` on the main app role kills background migrations, and runtime `SET` can't substitute through a pooler.** Managed Postgres (DO, Supabase) caps the app role, which cancels every long `CREATE/DROP/REINDEX CONCURRENTLY` and chunked backfill. The retry loop leaves 0-byte INVALID index artifacts behind that `IF NOT EXISTS` on the next deploy silently skips (that's how `idx_run_project_id_environment_created_status_archived_at` and `idx_todo_run_id` sat on Cloud `flow_run`/`todo` as orphans). Runtime `SET statement_timeout = 0` is unsound on a transaction-mode pooler: the `SET` lands on one backend, the DDL on another that still has the cap, and the `SET` leaks to normal app traffic on the first backend (empirically verified against DO's pool). Fix: dedicated role (`ALTER ROLE ap_migrator SET statement_timeout = 0`) + `AP_POSTGRES_MIGRATION_URL` pointing the runner at a pool for that role. `migrationDatabaseConnection()` resolves this; unset or non-Postgres falls back to the main DS. Full SQL in `docs/install/reference/breaking-changes-unreleased.mdx`.diff --git a/brain/knowledge/flows-execution/flow-runs.md b/brain/knowledge/flows-execution/flow-runs.mdindex b9fc52a2697..6b907d2f524 100644--- a/brain/knowledge/flows-execution/flow-runs.md+++ b/brain/knowledge/flows-execution/flow-runs.md@@ -71,7 +71,7 @@ A Flow Run records one execution of a specific flow version, from trigger to ter- **Barrier children are unlisted, never invisible — and the discriminator is `parentWaitpointId IS NOT NULL`, nothing cheaper.** Children share the parent's flow id, flow version id *and* display name. Of the eight run list/count surfaces, five filter them out and three deliberately keep them: **user-facing and billing surfaces exclude children, ops and load surfaces keep them.** The five are `flowRunService.list` (one edit covering the runs endpoint, the builder's list, the agent tool and the MCP tool), `countByStatus`, `filterFlowRunsAndApplyFilters`, the billing usage report's daily-execution count and `platformAnalyticsReportService`'s `listRuns`. The three that keep counting are `healthMetricsService`, the telemetry daily rollup in `flow-run-module.ts` and the admin platform retry. Two of the five are correctness, not consistency: the shared filter-and-apply helper is the *only* thing stopping a filter-driven bulk retry from being a second door onto the refused mid-graph retry path, and the analytics filter multiplies a user-set per-trigger constant, so counting children makes a flow batching ten items claim eleven times the time saved. Reaching a child by id is the zero-work default (`getOnePopulatedOrThrow` already scopes by project) and `ListFlowRunsRequestQuery.parentWaitpointId` is the opt-back-in, ordered by `dispatchIndex` — a filter on the existing endpoint, not a new one. That listing also requires `dispatchIndex IS NOT NULL`, and the reason is the cursor, not taste: `Paginator` slices its composite cursor at the **first field missing from the decoded cursor object**, so a page ending on a NULL-index child encodes no `dispatchIndex`, emits *no* cursor predicate at all, and returns page 1 again forever. Any ordering added on a nullable column has this failure mode — either exclude the NULLs or do not sort on it. A child with no dispatch index is not a batch (only the webhook header path can make one) and stays reachable by id. `archivedAt` is a separate user-driven axis and is **not** reused for hiding.- **The status-count query plans on `idx_run_project_id_environment_status_created_archived_at`, not the `created`-leading one — but only once the visibility map is healthy.** `EXPLAIN` it on a table whose VM is stale (right after a bulk `UPDATE`) and the planner refuses the index-only scan, falls back to a bitmap heap scan on `idx_run_project_id_environment_created_archived_at`, and you extend the wrong index. `VACUUM ANALYZE` first, then `EXPLAIN`. Appending `parentWaitpointId` as the trailing column keeps the scan index-only and pushes the child exclusion into the Index Cond instead of a post-heap Filter — measured on 1M rows / 50k per project: 42ms and 17.8k buffers → 5.5ms and 4k buffers, `Heap Fetches: 0`. A btree cannot be extended in place, so the migration creates the widened index under a new name **concurrently first** and only then drops the old one; dropping first would leave the hottest table in the product without that index for the length of a concurrent build. The children-listing query needs no new index — the partial `idx_run_parent_waitpoint_id` already covers it. **But the widened index only covers the status-count query, and the runs *list* was left behind.** `flowRunService.list` with no status filter orders by `created DESC` and plans on `idx_run_project_id_environment_created_archived_at`, which has no `parentWaitpointId` — so there the child exclusion is exactly the post-heap Filter this bullet says was eliminated, and every child row created since the newest visible parent is fetched and discarded before the page fills. Cost scales with children ever created, not with page size: right after a wide fan-out the first page walks the whole batch to return ten rows, and the table re-polls it every 15s while anything is non-terminal. **Resolved by making the three `created`-leading list indexes partial on `WHERE "parentWaitpointId" IS NULL`** — the only shape the list asks for, and a child costs nothing to maintain there (see the mostly-NULL bullet above): children are absent from the index entirely, so cost is proportional to page size instead of fan-out size, and a fan-out writes zero entries into them. A normal run is in every one of them, so until the four old list indexes are dropped, each insert and non-HOT update of a normal run maintains eight list indexes instead of five. Measured on 1.02M rows / 200 projects / a 20k-child fan-out as the newest activity: the no-filter list 4.5ms → 0.11ms, flow+status 6.2ms → 0.79ms, `countByStatus` 20.5ms → 1.2ms and the billing daily count 10.7ms → 2.3ms (both now `Index Only Scan`, `Heap Fetches: 0`). Trailing the column instead of a partial predicate was measured too and is the weaker fix — it moves the exclusion into the Index Cond but still walks every child's leaf pages, so it only bought 2-3x where partial buys 40x.- **The status-leading run index must stay NON-partial, and that asymmetry is deliberate.** It is the only index left that can serve the ops aggregates in `healthMetricsService`, which by design count children (see the unlisted-children bullet) and therefore carry no `parentWaitpointId` predicate. Make all four partial and those seven aggregates fall to a `Parallel Seq Scan` on the whole table. The alternative — adding the predicate to `healthMetricsService` — was rejected because it silently reclassifies an ops surface as a user-facing one. So: `created`-leading and `flowId`-leading indexes are partial (list-only), the `status`-leading one is full and keeps `parentWaitpointId` as a trailing column so `countByStatus` stays index-only.-- **The `flow_run` list-index reshape runs in the background track, not at boot.** `AddBarrierChildAttribution` (blocking) only adds the two nullable columns; `ReshapeFlowRunListIndexesForBarrierChildren` (background) builds the five new indexes after the app listens, so a large `flow_run` no longer holds every replica's boot for five concurrent builds. It then drops only `idx_run_project_id_environment_created_archived_at`: with that narrow index present, the planner picks it over the partial `created` index and reads every child again (PGlite, 1M rows and a 20k fan-out: 0.14ms → 3.2ms). Its queries stay covered under the old image, because `idx_run_project_id_environment_created_status_archived_at` has the same leading columns. The other four old indexes stay declared on the entity until a later release drops them, because a new-image pod that boots during a Cloud rollback re-runs the reshape (see the rollback gotcha on the Database page). The new code is fast on the old indexes meanwhile: the list query keeps its index and adds only a `parentWaitpointId IS NULL` filter that matches every row until children exist. **The blocking `down()` restores the old indexes, drops the new ones and deletes the background row before it drops the columns**, because the background track is forward-only and `DROP COLUMN` silently drops all five new indexes with it (each one references `parentWaitpointId`), which would leave `flow_run` with only its primary key. Deleting the row makes a re-upgrade run the reshape again.+- **The `flow_run` list-index reshape runs in the background track, not at boot.** `AddBarrierChildAttribution` (blocking) only adds the two nullable columns; `ReshapeFlowRunListIndexesForBarrierChildren` (background) builds the five new indexes after the app listens, so a large `flow_run` no longer holds every replica's boot for five concurrent builds. It then drops only `idx_run_project_id_environment_created_archived_at`: with that narrow index present, the planner picks it over the partial `created` index and reads every child again (PGlite, 1M rows and a 20k fan-out: 0.14ms → 3.2ms). Its queries stay covered under the old image, because `idx_run_project_id_environment_created_status_archived_at` has the same leading columns. The other four old indexes stay declared on the entity until a later release drops them, because a Cloud rollback runs the old image on the reshaped table (see the rollback gotcha on the Database page). The new code is fast on the old indexes meanwhile: the list query keeps its index and adds only a `parentWaitpointId IS NULL` filter that matches every row until children exist. **The blocking `down()` restores the old indexes, drops the new ones and deletes the background row before it drops the columns**, because the background track is forward-only and `DROP COLUMN` silently drops all five new indexes with it (each one references `parentWaitpointId`), which would leave `flow_run` with only its primary key. Deleting the row makes a re-upgrade run the reshape again.- **A run read must never widen its `flow_version` join, and the paginator is why it costs double.** `queryBuilderForFlowRun` is the single builder behind `list`, `getOne`, `getOnePopulatedOrThrow` *and* `findFlowRunOrThrow`, and the only thing any caller ever reads off the relation is `displayName` — the runs table column and the failed-step dialog. It used to be `leftJoinAndSelect`, which selects all thirteen `flow_version` columns including three `jsonb` ones: `trigger` (the whole flow graph, routinely TOASTed), `backupFiles`, `notes`. The `.addSelect(['"flowVersion"."displayName"'])` sitting beside it was raw SQL, so TypeORM mapped it to nothing — a duplicate column in the SELECT list that read as intent and did no work. Three things compounded it: `Paginator.paginate` uses `getRawAndEntities()` and `mergeAdditionalColumns` copies **every raw key not prefixed `<rootAlias>_` or `ap_cursor_`** onto the entity, so each row carried the graph twice (nested `flowVersion.trigger` *and* flattened `flowVersion_trigger`) — that flattening applies to any paginated list with a join, not just runs; `convertDatesToStrings` in `server.ts` then deep-walks both copies before zod strips them, so the wire payload stayed clean while the DB read, the heap and the per-request CPU did not; and `releaseBarrierWithoutLock` calls `findFlowRunOrThrow` up to 3× per barrier release just to read `status`. The fix is `leftJoin` + `addSelect(['flowVersion.id', 'flowVersion.displayName'])`, and **the PK is load-bearing, not decoration** — `RawSqlResultsToEntityTransformer.group()` keys joined rows by the alias's primary columns, so a partial relation select without the id silently fails to hydrate. Use entity-property notation (`'flowVersion.displayName'`); the quoted raw form is not mapped back onto the relation. Pinned by `list-flow-runs.test.ts`, which asserts on the **service** result, not the HTTP response — zod strips the heavy keys at serialization, so an HTTP-only assertion passes against the wide query too and proves nothing. Measured on 1M runs / 200 projects / 10k flow versions with a ~6.4 KB-on-disk TOASTed trigger, fully warm: a 50-row page went **1.59 MB → 15 KB** returned and 4.63ms → 0.56ms median, and the single-row read behind `findFlowRunOrThrow` 0.63ms → 0.30ms. **`EXPLAIN (ANALYZE, BUFFERS)` cannot measure this and will tell you there is nothing to fix** — it discards output rows, so it never detoasts the wide columns; the before/after execution-buffer difference was 9 pages and the only four-figure number in the plan was *planning* buffers. Time the query with its rows actually materialized (`\timing` + `\o /dev/null`). Two further traps in seeding it: give each project its own flow versions, or a page's lookups collapse into a handful of `Memoize` hits and the join looks free, and fill `trigger` with random text rather than repeated characters, or pglz compresses the payload away.- **Every path that creates a *terminal* run must carry `parentWaitpointId`, not just the paths that execute one.** The barrier releases from a `GROUP BY` over `flow_run.parentWaitpointId`, so a child row that lands terminal without it is invisible: `terminal >= expected` never holds and the parent hangs to the barrier's `timeoutAt`. The `QUOTA_EXCEEDED` admission gate is the trap — `createQuotaExceededRun` writes a finished row straight to `runsMetadataQueue`, bypassing `flowRunService.start`, so it needs **both** `parentWaitpointId` and `dispatchIndex` threaded explicitly at all three call sites (worker RPC `submitPayloads`, sync webhook, manual trigger) — `dispatchIndex` is not in `RUNS_METADATA_UPSERT_KEYS`, so add it there first or the allowlist drops it and the row lands half-attributed. Found while merging the gate into the fan-in branch: neither side was wrong alone. Any future admit-without-executing path inherits the same obligation.### Editions