fix(db): fail PR CI on a requires_staging migration without an override (#22628)

## 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:
<justification>`. 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 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-23 14:49:17 -06:00
1 parent 32375d302f
commit 2821af0b52
6 files changed
+101 -34

No files matched your search

+2 -2
View File
@@ -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.
@@ -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: </);
});
test('passes a requires_staging migration with a justified in-file override', async () => {
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/);
});
+5 -2
View File
@@ -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:
@@ -7,7 +7,8 @@
// tsx scripts/migration-compatibility.ts <file.sql>... classify the named files
// tsx scripts/migration-compatibility.ts --check [--base <ref>]
// fail when a migration added since the merge base with <ref>
// (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;
}
@@ -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: <why");
expect(error).toContain("-- paperclip:migration-compat requires_staging: <what");
expect(error).toContain("-- paperclip:migration-compat requires_staging: <why this cannot be split and who accepts the maintenance deploy>");
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: <why");
expect(error).toContain("doc/DATABASE.md");
});
it("lists the lock hazards of a requires_staging migration alongside its breaking changes", () => {
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/)]);
});
});
+33 -20
View File
@@ -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: <why the previous release keeps working and no lock is held long>`;
const REQUIRES_STAGING_OVERRIDE_TEMPLATE = `-- ${MIGRATION_COMPAT_DIRECTIVE} requires_staging: <why this cannot be split and who accepts the maintenance deploy>`;
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: <why the previous release keeps working and no lock is held long>`,
` or, if the previous release cannot run against it:`,
` -- ${MIGRATION_COMPAT_DIRECTIVE} requires_staging: <what has to ship first>`,
" 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}`);
}