From 2821af0b5248db2d597defab708999fc5ade5641 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:49:17 -0600 Subject: [PATCH] fix(db): fail PR CI on a requires_staging migration without an override (#22628) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip Cloud deploys a new release while the previous release still serves the same database > - Core classifies every new migration as `online_compatible`, `requires_staging`, or `unknown`, and the pull-request guard checks the migrations a PR adds > - The guard fails an `unknown` migration without an override, but it only prints a notice for a `requires_staging` migration > - A `requires_staging` release is refused by every stack that serves two releases at once, so continuous deploy stalls until somebody runs a maintenance deploy > - This pull request makes the guard fail a `requires_staging` migration unless the file carries a justified `requires_staging` override > - The benefit is that a migration that forces a maintenance window cannot merge by accident. The author must split it or accept the maintenance deploy in writing. ## Linked Issues or Issue Description Refs #20913 (the classifier and the guard). Refs #22513 (the migration that stalled deploys). **What existing behavior does this improve?** The pull-request migration guard in `packages/db/src/migration-compatibility.ts` and `.github/scripts/check-pr-migration-order.mjs`. **Current behavior** A new migration classified `requires_staging` passes the guard with a `::notice`. Nothing stops it from merging. Stacks that deploy with overlap then refuse the release. **Proposed behavior** A new `requires_staging` migration fails the guard unless the file starts with `-- paperclip:migration-compat requires_staging: `. The error lists the reasons and tells the author to split the migration into expand and contract steps, or to add the override and accept a maintenance deploy. A justified override passes with a notice that says the release ships with a maintenance deploy. **Reason and benefit** On 2026-11-22 a `requires_staging` migration merged. Continuous deploy to the overlap-deploy staging stacks stalled for about 4.5 hours, and a manual maintenance deploy took 38 stacks offline for a median of about 2.5 minutes each. An explicit decision in the migration file makes this cost visible at review time. **Breaking changes** None for existing migrations. The guard judges only the migrations that a PR adds. A PR that adds a `requires_staging` migration must now add the override or split the migration. ## What Changed - `checkNewMigrationCompatibility` returns an error for a `requires_staging` migration without an override. The error lists the `requires_staging` and `unknown` reasons and the two ways forward. - A `requires_staging` migration with a valid override passes with a notice. It reuses the existing in-file directive and its minimum justification length. There is no new mechanism. - `doc/DATABASE.md` ("Migration compatibility with the running release") says that `requires_staging` fails the PR and when to use the override. - Doc comments in the CI script and the `--check` CLI usage now name both blocking classes. The CLI success line says "none blocked". - Red/green tests in `packages/db/src/migration-compatibility.test.ts` and `.github/scripts/tests/check-pr-migration-order.test.mjs`: `requires_staging` without an override fails, with a justified override passes, with an empty justification fails, and `online_compatible` passes. ## Verification - Red: with the old guard, the new tests failed (vitest: 3 failed of 116; node test: 3 failed of 14). - Green: `cd packages/db && pnpm exec vitest run src/migration-compatibility.test.ts` passes 116 of 116. - Green: `node --test .github/scripts/tests/check-pr-migration-order.test.mjs` passes 14 of 14. - `pnpm --filter @paperclipai/db typecheck` passes, including `check:migrations`. - `pnpm verify` exits 2 because a global CI input changed (`.github/scripts/check-pr-migration-order.mjs`). Required CI supplies the broad coverage. ## Risks - Low risk. The change affects only the PR guard for new migrations. Deployers and the cloud migrator manifest do not change. - An open PR that adds a `requires_staging` migration fails the guard after it rebases. The error says how to fix it. - Note: migration `0500_funny_malcolm_colcord.sql` from #22513 already has a justified `requires_staging` override. This guard passes it with a notice. To stop such a migration at review time, a further policy is necessary, for example a required reviewer for the override. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (Anthropic, model ID `claude-opus-5-5`), in Claude Code with tool use (shell, file edits) and extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .github/scripts/check-pr-migration-order.mjs | 4 +- .../tests/check-pr-migration-order.test.mjs | 31 +++++++++-- doc/DATABASE.md | 7 ++- .../db/scripts/migration-compatibility.ts | 5 +- .../db/src/migration-compatibility.test.ts | 35 ++++++++++-- packages/db/src/migration-compatibility.ts | 53 ++++++++++++------- 6 files changed, 101 insertions(+), 34 deletions(-) diff --git a/.github/scripts/check-pr-migration-order.mjs b/.github/scripts/check-pr-migration-order.mjs index d3130c31c5f..ad54fc335f4 100644 --- a/.github/scripts/check-pr-migration-order.mjs +++ b/.github/scripts/check-pr-migration-order.mjs @@ -68,8 +68,8 @@ export function checkMigrationOrder(baseMigrationFiles, prMigrationFiles) { /** * Judges whether the migrations a PR adds can be applied while the previous - * release is still running. `unknown` without an in-file override fails; - * `requires_staging` only produces a notice. + * release is still running. `unknown` or `requires_staging` without an + * in-file override fails. */ export async function checkMigrationCompatibility(migrations, { priorMigrationSql, executorSource } = {}) { // Type-stripped by Node: the policy job runs before dependencies are installed. diff --git a/.github/scripts/tests/check-pr-migration-order.test.mjs b/.github/scripts/tests/check-pr-migration-order.test.mjs index f169a20de6f..d0eca52c1b1 100644 --- a/.github/scripts/tests/check-pr-migration-order.test.mjs +++ b/.github/scripts/tests/check-pr-migration-order.test.mjs @@ -76,14 +76,36 @@ test('fails an override that has no justification', async () => { assert.match(result.errors[0], /needs a justification/); }); -test('reports requires_staging as a notice without failing', async () => { +test('fails a requires_staging migration without an override', async () => { const result = await checkMigrationCompatibility([ { fileName: migration('0233_drop'), sql: 'ALTER TABLE "issues" DROP COLUMN "note";' }, ]); + assert.equal(result.passed, false); + assert.equal(result.errors.length, 1); + assert.match(result.errors[0], /0233_drop\.sql: requires_staging/); + assert.match(result.errors[0], /drop_column/); + assert.match(result.errors[0], /expand and contract migrations/); + assert.match(result.errors[0], /-- paperclip:migration-compat requires_staging: { + const result = await checkMigrationCompatibility([{ + fileName: migration('0233_drop'), + sql: '-- paperclip:migration-compat requires_staging: note is unused and ops accepts a maintenance deploy\nALTER TABLE "issues" DROP COLUMN "note";', + }]); + assert.equal(result.passed, true); assert.deepEqual(result.errors, []); - assert.match(result.notices[0], /0233_drop\.sql: requires_staging/); + assert.match(result.notices[0], /0233_drop\.sql: requires_staging by override/); +}); + +test('passes an online_compatible migration without a notice', async () => { + const result = await checkMigrationCompatibility([ + { fileName: migration('0233_add'), sql: 'ALTER TABLE "issues" ADD COLUMN "note" text;' }, + ]); + + assert.deepEqual(result, { passed: true, errors: [], notices: [] }); }); test('passes when a PR adds no migrations', async () => { @@ -119,6 +141,7 @@ test('treats CREATE TABLE IF NOT EXISTS as new only when the target branch never priorMigrationSql: ['CREATE TABLE "widgets" ("id" uuid, "title" text);'], }); - assert.deepEqual(fresh.notices, []); - assert.match(existing.notices[0], /0231_widgets\.sql: requires_staging/); + assert.equal(fresh.passed, true); + assert.equal(existing.passed, false); + assert.match(existing.errors[0], /0231_widgets\.sql: requires_staging/); }); diff --git a/doc/DATABASE.md b/doc/DATABASE.md index e37932a4a89..ecb92a12e1c 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -287,7 +287,7 @@ because a failed run starts again from the first statement. The pull-request guard fails a new `CONCURRENTLY` migration that is not in that list. **The rule for a new migration.** A pull request fails when a migration it adds -is `unknown`. Rewrite the migration, split it into expand and contract +is `unknown` or `requires_staging`. Rewrite the migration, split it into expand and contract migrations, or, when you have verified the migration yourself, state the class in the first lines of the migration file: @@ -301,7 +301,10 @@ override is read only from the migration file, so it is reviewed with the SQL and travels with it. A contract migration (for example the `DROP COLUMN` that follows an expand release) always classifies as `requires_staging`; mark it `online_compatible` this way once no running release uses the column. -`requires_staging` does not fail the pull request yet; it prints a notice. +Cloud stacks that serve two releases at once refuse a `requires_staging` +release, so it ships only through a maintenance deploy. Prefer splitting it +into expand and contract migrations; add the `requires_staging` override only +when the maintenance deploy is accepted. Check a migration locally: diff --git a/packages/db/scripts/migration-compatibility.ts b/packages/db/scripts/migration-compatibility.ts index 56dcc3281cf..c1303197793 100644 --- a/packages/db/scripts/migration-compatibility.ts +++ b/packages/db/scripts/migration-compatibility.ts @@ -7,7 +7,8 @@ // tsx scripts/migration-compatibility.ts ... classify the named files // tsx scripts/migration-compatibility.ts --check [--base ] // fail when a migration added since the merge base with -// (default origin/master, then master) is `unknown` without an override +// (default origin/master, then master) is `unknown` or `requires_staging` +// without an override import { execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; import path from "node:path"; @@ -80,7 +81,7 @@ function check(requestedBase: string | null): number { for (const notice of result.notices) console.log(`notice: ${notice}`); for (const error of result.errors) console.error(`error: ${error}`); if (result.passed) { - console.log(`migration compatibility: ${added.files.length} new migration(s) since ${added.base.slice(0, 12)}, none unclassified.`); + console.log(`migration compatibility: ${added.files.length} new migration(s) since ${added.base.slice(0, 12)}, none blocked.`); } return result.passed ? 0 : 1; } diff --git a/packages/db/src/migration-compatibility.test.ts b/packages/db/src/migration-compatibility.test.ts index 68a38e15586..676ad48748b 100644 --- a/packages/db/src/migration-compatibility.test.ts +++ b/packages/db/src/migration-compatibility.test.ts @@ -284,7 +284,7 @@ describe("checkNewMigrationCompatibility", () => { expect(error).toContain("CREATE INDEX CONCURRENTLY"); expect(error).toContain("expand migration now and a contract migration in a later release"); expect(error).toContain("-- paperclip:migration-compat online_compatible: "); expect(error).toContain("doc/DATABASE.md"); }); @@ -320,10 +320,37 @@ describe("checkNewMigrationCompatibility", () => { .toEqual([expect.stringContaining("0505_again.sql")]); }); - it("does not fail requires_staging, and prints a notice instead", () => { - const result = checkNewMigrationCompatibility([staged]); + it("fails a requires_staging migration without an override and tells the author what to do", () => { + const result = checkNewMigrationCompatibility([additive, staged]); + expect(result.passed).toBe(false); + expect(result.notices).toEqual([]); + expect(result.errors).toHaveLength(1); + const [error] = result.errors; + expect(error).toContain("0502_staged.sql: requires_staging"); + expect(error).toContain("drop_column (statement 1)"); + expect(error).toContain("maintenance deploy"); + expect(error).toContain("backward-compatible expand and contract migrations"); + expect(error).toContain("-- paperclip:migration-compat requires_staging: { + const mixed = { fileName: "0506_mixed.sql", sql: `DROP INDEX "issues_a_idx";${BP}UPDATE "issues" SET a = 'x';${BP}DELETE FROM "issues" WHERE a IS NULL;` }; + const [error] = checkNewMigrationCompatibility([mixed]).errors; + expect(error).toContain("delete_rows (statement 3)"); + expect(error).toContain("lock_hazard_data_backfill (statement 2)"); + }); + + it("passes a requires_staging migration that carries a justified override, with a notice", () => { + const result = checkNewMigrationCompatibility([{ ...staged, sql: `-- paperclip:migration-compat requires_staging: the column rename cannot be split and ops accepts a maintenance deploy\n${staged.sql}` }]); expect(result).toMatchObject({ passed: true, errors: [] }); - expect(result.notices).toEqual([expect.stringMatching(/0502_staged\.sql: requires_staging[\s\S]*drop_column \(statement 1\)[\s\S]*does not fail the check yet/)]); + expect(result.notices).toEqual([expect.stringMatching(/0502_staged\.sql: requires_staging by override, so it ships with a maintenance deploy: the column rename/)]); + }); + + it("fails a requires_staging override without a justification", () => { + const result = checkNewMigrationCompatibility([{ ...staged, sql: `-- paperclip:migration-compat requires_staging:\n${staged.sql}` }]); + expect(result.passed).toBe(false); + expect(result.errors).toEqual([expect.stringMatching(/0502_staged\.sql: .*needs a justification/)]); }); }); diff --git a/packages/db/src/migration-compatibility.ts b/packages/db/src/migration-compatibility.ts index 20c461bcf3c..9e58aae5463 100644 --- a/packages/db/src/migration-compatibility.ts +++ b/packages/db/src/migration-compatibility.ts @@ -583,6 +583,20 @@ function describeReasons(result: MigrationCompatResult, compatibility: Migration .map((reason) => ` - ${reason.code}${reason.statements.length ? ` (statement ${reason.statements.join(", ")})` : ""}: ${reason.message}`); } +const ONLINE_COMPATIBLE_OVERRIDE_TEMPLATE = `-- ${MIGRATION_COMPAT_DIRECTIVE} online_compatible: `; +const REQUIRES_STAGING_OVERRIDE_TEMPLATE = `-- ${MIGRATION_COMPAT_DIRECTIVE} requires_staging: `; + +function formatBlocker(fileName: string, result: MigrationCompatResult, summary: string, remedies: readonly string[]): string { + return [ + `${fileName}: ${summary}`, + ...describeReasons(result, "requires_staging"), + ...describeReasons(result, "unknown"), + " Do one of the following:", + ...remedies.map((remedy, index) => ` ${index + 1}. ${remedy}`), + " See \"Migration compatibility with the running release\" in doc/DATABASE.md.", + ].join("\n"); +} + export type MigrationCompatGuardOptions = { /** * SQL of every migration that applies before the new ones. Without it, @@ -599,8 +613,7 @@ export type MigrationCompatGuardOptions = { /** * The pull-request guard for migrations a change adds, in apply order. - * `unknown` without a valid override fails. `requires_staging` passes with a - * notice until deployers enforce staging. + * `unknown` or `requires_staging` without a valid override fails. */ export function checkNewMigrationCompatibility( migrations: readonly MigrationCompatInput[], @@ -625,25 +638,25 @@ export function checkNewMigrationCompatibility( if (result.overrideError) { errors.push(`${fileName}: ${result.overrideError}`); } else if (result.compatibility === "unknown") { - errors.push([ - `${fileName}: cannot tell whether this migration is safe to apply while the previous release is still running.`, - ...describeReasons(result, "unknown"), - " Do one of the following:", - " 1. Rewrite it so every statement is recognized as compatible, for example CREATE INDEX CONCURRENTLY,", - " ADD CONSTRAINT ... NOT VALID, or a nullable column or constant default.", - " 2. Split it into an expand migration now and a contract migration in a later release.", - " 3. If you have verified it yourself, make these the first lines of the file:", - ` -- ${MIGRATION_COMPAT_DIRECTIVE} online_compatible: `, - ` or, if the previous release cannot run against it:`, - ` -- ${MIGRATION_COMPAT_DIRECTIVE} requires_staging: `, - " See \"Migration compatibility with the running release\" in doc/DATABASE.md.", - ].join("\n")); + errors.push(formatBlocker(fileName, result, "cannot tell whether this migration is safe to apply while the previous release is still running.", [ + "Rewrite it so every statement is recognized as compatible, for example CREATE INDEX CONCURRENTLY,\n ADD CONSTRAINT ... NOT VALID, or a nullable column or constant default.", + "Split it into an expand migration now and a contract migration in a later release.", + [ + "If you have verified it yourself, make these the first lines of the file:", + ` ${ONLINE_COMPATIBLE_OVERRIDE_TEMPLATE}`, + " or, if the previous release cannot run against it and a maintenance deploy is acceptable:", + ` ${REQUIRES_STAGING_OVERRIDE_TEMPLATE}`, + ].join("\n"), + ])); } else if (result.compatibility === "requires_staging") { - notices.push([ - `${fileName}: requires_staging. The previous release cannot keep running against this migration, so a deployer that may not pause will hold it back.`, - ...(result.override ? [` - override: ${result.override.justification}`] : describeReasons(result, "requires_staging")), - " This does not fail the check yet. Prefer an expand migration now and the contract migration in a later release.", - ].join("\n")); + if (result.override) { + notices.push(`${fileName}: requires_staging by override, so it ships with a maintenance deploy: ${result.override.justification}`); + } else { + errors.push(formatBlocker(fileName, result, "requires_staging. The previous release cannot keep running against this migration, so every deployer that serves two releases at once refuses it and the release needs a maintenance deploy.", [ + "Split it into backward-compatible expand and contract migrations: ship the expand migration\n (new tables, nullable columns, NOT VALID constraints, CONCURRENTLY indexes) and the code that\n uses it now, and the contract migration (drops, renames, NOT NULL) in a later release.", + `If a maintenance deploy is acceptable, make this the first line of the file:\n ${REQUIRES_STAGING_OVERRIDE_TEMPLATE}`, + ])); + } } else if (result.override) { notices.push(`${fileName}: online_compatible by override (classifier said ${result.classified}): ${result.override.justification}`); }