Files
PaperClipAI/packages/db/scripts/migration-compatibility.ts
T
DottaandClaude Opus 5.5 2821af0b52 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>
2026-11-23 14:49:17 -06:00

135 lines
6.2 KiB
TypeScript

// Reports whether migrations can be applied while the previous release is
// still running. See "Migration compatibility with the running release" in
// doc/DATABASE.md.
//
// tsx scripts/migration-compatibility.ts summary of every migration
// tsx scripts/migration-compatibility.ts --json per-migration results as JSON
// 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` or `requires_staging`
// without an override
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
checkNewMigrationCompatibility,
classifyMigrationSequence,
parseNonTransactionalMigrations,
summarizeMigrationCompatibility,
type MigrationCompatInput,
} from "../src/migration-compatibility.js";
const migrationsDir = fileURLToPath(new URL("../src/migrations", import.meta.url));
const executorPath = fileURLToPath(new URL("../src/client.ts", import.meta.url));
function journalFiles(): string[] {
const journal = JSON.parse(readFileSync(path.join(migrationsDir, "meta", "_journal.json"), "utf8")) as {
entries: { idx: number; tag: string }[];
};
// Apply order: journal idx, then file name (the journal repeats an idx).
return [...journal.entries]
.sort((left, right) => left.idx - right.idx || left.tag.localeCompare(right.tag))
.map((entry) => `${entry.tag}.sql`);
}
function read(file: string): MigrationCompatInput {
return { fileName: path.basename(file), sql: readFileSync(file, "utf8") };
}
function git(args: string[]): string | null {
try {
return execFileSync("git", args, { cwd: migrationsDir, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
} catch {
return null;
}
}
/** Journal migrations split by whether the merge base has them, or null without git history. */
function migrationsAddedSince(requestedBase: string | null): { base: string; prior: string[]; files: string[] } | null {
for (const ref of requestedBase ? [requestedBase] : ["origin/master", "master"]) {
const base = git(["merge-base", "HEAD", ref])?.trim();
if (!base) continue;
// ls-tree lists the current directory (the migrations folder) of the base.
const listed = git(["ls-tree", "--name-only", base]);
if (!listed?.includes(".sql")) continue;
const existing = new Set(listed.split("\n"));
const journal = journalFiles();
return { base, prior: journal.filter((file) => existing.has(file)), files: journal.filter((file) => !existing.has(file)) };
}
return null;
}
function check(requestedBase: string | null): number {
const added = migrationsAddedSince(requestedBase);
if (!added) {
// A source archive or shallow clone has no base to compare with. The pull
// request policy job runs the same guard with full history.
console.log("migration compatibility: no merge base available, skipped.");
return requestedBase ? 2 : 0;
}
const nonTransactionalMigrations = parseNonTransactionalMigrations(readFileSync(executorPath, "utf8"));
if (!nonTransactionalMigrations) {
console.error("error: MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS was not found in packages/db/src/client.ts.");
return 1;
}
const result = checkNewMigrationCompatibility(added.files.map((file) => read(path.join(migrationsDir, file))), {
priorMigrationSql: added.prior.map((file) => read(path.join(migrationsDir, file)).sql),
nonTransactionalMigrations,
});
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 blocked.`);
}
return result.passed ? 0 : 1;
}
function main(): number {
const args = process.argv.slice(2);
const flag = (name: string) => args.includes(name);
const baseIndex = args.indexOf("--base");
const base = baseIndex === -1 ? null : args[baseIndex + 1] ?? null;
if (flag("--check")) return check(base);
const named = args.filter((arg, index) => !arg.startsWith("--") && (baseIndex === -1 || index !== baseIndex + 1));
const journal = journalFiles().map((file) => read(path.join(migrationsDir, file)));
// A named file is judged after the journal migrations that precede it, or
// after the whole journal when it is not in the journal yet.
const results = named.length === 0
? classifyMigrationSequence(journal.map((input) => input.sql)).map((result, index) => ({ fileName: journal[index].fileName, ...result }))
: named.map(read).map((input) => {
const position = journal.findIndex((entry) => entry.fileName === input.fileName);
const prior = (position === -1 ? journal : journal.slice(0, position)).map((entry) => entry.sql);
return { fileName: input.fileName, ...classifyMigrationSequence([input.sql], prior)[0] };
});
if (flag("--json")) {
console.log(JSON.stringify(results, null, 2));
return 0;
}
if (named.length > 0) {
for (const result of results) {
console.log(`${result.fileName}: ${result.compatibility}${result.override ? " (override)" : ""}`);
for (const reason of result.reasons) {
const where = reason.statements.length ? ` [statement ${reason.statements.join(", ")}]` : "";
console.log(` ${reason.compatibility} ${reason.code}${where}: ${reason.message}`);
}
}
return 0;
}
const summary = summarizeMigrationCompatibility(results);
const percent = (count: number) => `${((count / Math.max(summary.total, 1)) * 100).toFixed(1)}%`;
console.log(`${summary.total} migrations, ${summary.overrides} with an override`);
for (const [compatibility, count] of Object.entries(summary.byCompatibility)) {
console.log(` ${compatibility.padEnd(18)} ${String(count).padStart(4)} ${percent(count)}`);
}
console.log("Migrations per blocking reason:");
for (const reason of summary.blockingReasons) {
console.log(` ${String(reason.migrations).padStart(4)} ${reason.compatibility.padEnd(16)} ${reason.code}`);
}
return 0;
}
process.exitCode = main();