mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 05:47:10 +01:00
## 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>
170 lines
6.3 KiB
JavaScript
170 lines
6.3 KiB
JavaScript
#!/usr/bin/env node
|
|
import { execFileSync } from 'node:child_process';
|
|
import { existsSync, readFileSync } from 'node:fs';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
const MIGRATIONS_DIRECTORY = 'packages/db/src/migrations/';
|
|
const MIGRATION_FILE_PATTERN = /^packages\/db\/src\/migrations\/(\d{4})_[^/]+\.sql$/;
|
|
|
|
function parseMigration(file) {
|
|
const match = file.match(MIGRATION_FILE_PATTERN);
|
|
return match ? { file, number: Number.parseInt(match[1], 10) } : null;
|
|
}
|
|
|
|
function formatMigrationNumber(number) {
|
|
return String(number).padStart(4, '0');
|
|
}
|
|
|
|
export function checkMigrationOrder(baseMigrationFiles, prMigrationFiles) {
|
|
const invalidFiles = [...baseMigrationFiles, ...prMigrationFiles]
|
|
.filter((file) => !parseMigration(file));
|
|
|
|
if (invalidFiles.length > 0) {
|
|
return {
|
|
passed: false,
|
|
message: [
|
|
'Migration SQL files must start with a 4-digit number:',
|
|
...invalidFiles.map((file) => `- ${file}`),
|
|
].join('\n'),
|
|
};
|
|
}
|
|
|
|
if (prMigrationFiles.length === 0) {
|
|
return { passed: true, message: 'No new migrations in this PR.' };
|
|
}
|
|
|
|
const baseMigrations = baseMigrationFiles.map(parseMigration);
|
|
const prMigrations = prMigrationFiles.map(parseMigration);
|
|
const latestBaseMigration = baseMigrations.reduce(
|
|
(latest, migration) => migration.number > latest.number ? migration : latest,
|
|
{ file: '(none)', number: -1 },
|
|
);
|
|
const outOfOrder = prMigrations.filter(
|
|
(migration) => migration.number <= latestBaseMigration.number,
|
|
);
|
|
|
|
if (outOfOrder.length === 0) {
|
|
return {
|
|
passed: true,
|
|
message: `All new migrations follow ${latestBaseMigration.file}.`,
|
|
};
|
|
}
|
|
|
|
const nextNumber = formatMigrationNumber(latestBaseMigration.number + 1);
|
|
return {
|
|
passed: false,
|
|
message: [
|
|
`The target branch already contains migrations through ${latestBaseMigration.file}.`,
|
|
'This PR adds migration numbers that would be inserted into or collide with that history:',
|
|
...outOfOrder.map((migration) => `- ${migration.file}`),
|
|
'',
|
|
`Update from the target branch, then renumber this PR's migrations starting at ${nextNumber}`,
|
|
'in their intended order. Keep each SQL filename, matching meta snapshot, and',
|
|
'packages/db/src/migrations/meta/_journal.json entry aligned, then push again.',
|
|
'Migration numbers are append-only and cannot reuse a number already present on the target branch.',
|
|
].join('\n'),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Judges whether the migrations a PR adds can be applied while the previous
|
|
* 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.
|
|
const { checkNewMigrationCompatibility, parseNonTransactionalMigrations } = await import(
|
|
new URL('../../packages/db/src/migration-compatibility.ts', import.meta.url).href
|
|
);
|
|
// `executorSource` is the text of packages/db/src/client.ts. It names the
|
|
// migrations that run outside a transaction, which CONCURRENTLY needs.
|
|
const nonTransactionalMigrations = executorSource === undefined
|
|
? undefined
|
|
: parseNonTransactionalMigrations(executorSource);
|
|
if (nonTransactionalMigrations === null) {
|
|
return {
|
|
passed: false,
|
|
errors: ['MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS was not found in packages/db/src/client.ts, so CONCURRENTLY migrations cannot be checked.'],
|
|
notices: [],
|
|
};
|
|
}
|
|
const { passed, errors, notices } = checkNewMigrationCompatibility(migrations, {
|
|
priorMigrationSql,
|
|
nonTransactionalMigrations,
|
|
});
|
|
return { passed, errors, notices };
|
|
}
|
|
|
|
function gitPaths(args) {
|
|
return execFileSync('git', args, { encoding: 'utf8' })
|
|
.split('\0')
|
|
.filter(Boolean);
|
|
}
|
|
|
|
function escapeWorkflowCommand(message) {
|
|
return message
|
|
.replaceAll('%', '%25')
|
|
.replaceAll('\r', '%0D')
|
|
.replaceAll('\n', '%0A');
|
|
}
|
|
|
|
async function main() {
|
|
const [baseSha, headSha] = process.argv.slice(2);
|
|
const shaPattern = /^[0-9a-f]{40}$/i;
|
|
if (!shaPattern.test(baseSha ?? '') || !shaPattern.test(headSha ?? '')) {
|
|
console.error('Usage: check-pr-migration-order.mjs <40-character base SHA> <40-character head SHA>');
|
|
process.exit(2);
|
|
}
|
|
|
|
const baseMigrationFiles = gitPaths([
|
|
'ls-tree', '-r', '--name-only', '-z', baseSha, '--', MIGRATIONS_DIRECTORY,
|
|
]).filter((file) => file.endsWith('.sql'));
|
|
const prMigrationFiles = gitPaths([
|
|
'diff', '--name-only', '--diff-filter=A', '-z', `${baseSha}...${headSha}`, '--',
|
|
MIGRATIONS_DIRECTORY,
|
|
]).filter((file) => file.endsWith('.sql'));
|
|
const result = checkMigrationOrder(baseMigrationFiles, prMigrationFiles);
|
|
|
|
if (!result.passed) {
|
|
console.error(
|
|
`::error title=Migration numbers must follow the target branch::${escapeWorkflowCommand(result.message)}`,
|
|
);
|
|
console.error(result.message);
|
|
process.exit(1);
|
|
}
|
|
console.log(result.message);
|
|
|
|
if (prMigrationFiles.length === 0) return;
|
|
// The checkout is the merge of the PR into the target branch, so it holds
|
|
// the target branch's migrations and the migrator source.
|
|
const root = fileURLToPath(new URL('../../', import.meta.url));
|
|
const compatibility = await checkMigrationCompatibility(
|
|
[...prMigrationFiles].sort().map((file) => ({
|
|
fileName: file,
|
|
sql: execFileSync('git', ['show', `${headSha}:${file}`], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }),
|
|
})),
|
|
{
|
|
priorMigrationSql: [...baseMigrationFiles].sort()
|
|
.filter((file) => existsSync(`${root}${file}`))
|
|
.map((file) => readFileSync(`${root}${file}`, 'utf8')),
|
|
executorSource: readFileSync(`${root}packages/db/src/client.ts`, 'utf8'),
|
|
},
|
|
);
|
|
for (const notice of compatibility.notices) {
|
|
console.log(`::notice title=Migration compatibility::${escapeWorkflowCommand(notice)}`);
|
|
console.log(notice);
|
|
}
|
|
for (const error of compatibility.errors) {
|
|
console.error(
|
|
`::error title=Migration is not classified as safe under the running release::${escapeWorkflowCommand(error)}`,
|
|
);
|
|
console.error(error);
|
|
}
|
|
if (!compatibility.passed) process.exit(1);
|
|
console.log('Every new migration is classified for application under the running release.');
|
|
}
|
|
|
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
await main();
|
|
}
|