Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
ci: catch migration-number collisions with the latest main before merge (MUL-9832) (#11178)
Jiayuan Zhang4ceffd536603
diff --git a/.github/workflows/migration-numbers.yml b/.github/workflows/migration-numbers.ymlnew file mode 100644index 0000000000..525031fc77--- /dev/null+++ b/.github/workflows/migration-numbers.yml@@ -0,0 +1,131 @@+name: Migration numbers++# A PR's CI checks migration numbers only against the main it was pushed onto.+# When main later gains a migration with the same number, nothing conflicts+# textually and the PR stays green; merging it turns main red (MUL-9832).+# Pull requests get the check as usual; every push that adds migrations to+# main re-checks all open PRs and posts the result as a commit status on each+# PR head, so a stale green turns red before anyone merges it.+on:+ pull_request:+ branches: [main]+ paths:+ - "server/migrations/**"+ - "scripts/check-migration-numbers.mjs"+ - ".github/workflows/migration-numbers.yml"+ push:+ branches: [main]+ paths:+ - "server/migrations/**"+ workflow_dispatch:++# A newer main supersedes an older sweep: it re-checks every open PR anyway.+concurrency:+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || 'open-prs' }}+ cancel-in-progress: true++permissions:+ contents: read++jobs:+ pull-request:+ if: ${{ github.event_name == 'pull_request' }}+ runs-on: ubuntu-latest+ steps:+ - name: Checkout+ uses: actions/checkout@v6+ with:+ fetch-depth: 0+ filter: blob:none++ - name: Check against the latest main+ env:+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ run: node scripts/check-migration-numbers.mjs --base origin/main --head "$HEAD_SHA"++ open-prs:+ if: ${{ github.event_name != 'pull_request' }}+ runs-on: ubuntu-latest+ permissions:+ contents: read+ pull-requests: read+ statuses: write+ steps:+ # Runs main's script only. PR heads are read as git trees, never+ # checked out or executed, so the write token never meets PR code.+ - name: Checkout+ uses: actions/checkout@v6+ with:+ ref: main+ fetch-depth: 0+ filter: blob:none++ - name: Fetch open PR heads+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ gh pr list --repo "$GITHUB_REPOSITORY" --base main --state open --limit 2000 \+ --json number --jq '.[].number' > "$RUNNER_TEMP/prs.txt"+ echo "$(wc -l < "$RUNNER_TEMP/prs.txt") open PRs"+ sed 's|.*|+refs/pull/&/head:refs/remotes/pull/&|' "$RUNNER_TEMP/prs.txt" \+ | git fetch --no-tags --filter=blob:none --stdin origin++ - name: Post migration-number status on PR heads+ env:+ GH_TOKEN: ${{ github.token }}+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}+ run: |+ base=$(git rev-parse origin/main)+ context="Migration numbers vs latest main"+ passed=0+ failed=0+ posted=0+ errors=0+ while read -r number; do+ head=$(git rev-parse "refs/remotes/pull/$number")+ # Most PRs touch no migrations; skip them before starting node.+ # --name-only compares tree entries; --quiet would download blobs.+ [ -n "$(git diff --name-only --no-renames "$base...$head" -- server/migrations/)" ] || continue++ code=0+ result=$(node scripts/check-migration-numbers.mjs --base origin/main --head "$head" --json) || code=$?+ case "$code" in+ 0) state=success ;;+ 1) state=failure ;;+ *) echo "::warning::PR #$number: migration check could not run"; continue ;;+ esac+ [ "$(jq '.added | length' <<<"$result")" -gt 0 ] || continue++ description=$(jq -r '.summary' <<<"$result")+ description=${description:0:140}+ if [ "$state" = failure ]; then+ failed=$((failed + 1))+ echo "PR #$number: renumber $(jq -r '[.collisions[] | "\(.stem) to \(.suggestedNumber)"] | join(", ")' <<<"$result")"+ else+ passed=$((passed + 1))+ fi++ # Every migration that lands re-runs this sweep, while GitHub+ # rate-limits status writes and caps them at 1000 per commit and+ # context. Write only when the state or text changes, and never a+ # first success: the pull-request job already reports that.+ current=$(gh api "repos/$GITHUB_REPOSITORY/commits/$head/status" \+ --jq ".statuses[] | select(.context == \"$context\") | [.state, .description] | @tsv") || current=""+ [ "$current" = "$state"$'\t'"$description" ] && continue+ [ -z "$current" ] && [ "$state" = success ] && continue++ if gh api --silent "repos/$GITHUB_REPOSITORY/statuses/$head" \+ -f state="$state" \+ -f context="$context" \+ -f description="$description" \+ -f target_url="$RUN_URL"; then+ posted=$((posted + 1))+ else+ errors=$((errors + 1))+ echo "::warning::PR #$number: could not post the migration-number status"+ fi+ sleep 1+ done < "$RUNNER_TEMP/prs.txt"+ echo "Checked against main@${base:0:9}: $passed PR(s) clear, $failed PR(s) need a renumber; posted $posted status change(s), $errors failed" \+ | tee -a "$GITHUB_STEP_SUMMARY"+ [ "$errors" -eq 0 ]diff --git a/AGENTS.md b/AGENTS.mdindex 6a19dcabcd..31f6366053 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -80,6 +80,7 @@ Installed desktop clients may talk to newer backends. Preserve response compatib- Every migration-created index, including indexes on new tables, uses `CREATE [UNIQUE] INDEX CONCURRENTLY`. Each concurrent index build gets its own single-statement migration file; the runner executes files outside an explicit transaction.- Register every concurrent index build in `server/cmd/migrate/main.go` so an interrupted build's INVALID index is dropped before retry: up-direction builds in `concurrentIndexCleanups`, down-direction rebuilds in `concurrentDownIndexCleanups` (version → index name).- Before pushing a migration, rebase onto the latest `origin/main`, number it as the current highest prefix plus one, and run `go test ./cmd/migrate ./internal/migrations` from `server/`.+- A PR's green CI covers only the main it ran against; main can take the same number later without a textual conflict. Right before merging a PR that adds migrations, run `git fetch origin main` and `node scripts/check-migration-numbers.mjs --head <PR head>`. A failing check, or a failing `Migration numbers vs latest main` status on the PR, means renumber first, never merge as is.- Conditionally skipped migrations are still recorded in `schema_migrations`. Later DDL touching conditional objects must be idempotent (`IF EXISTS` / `IF NOT EXISTS`); document recovery if the missing object would break runtime behavior.## Row Lock Orderdiff --git a/scripts/check-migration-numbers.mjs b/scripts/check-migration-numbers.mjsnew file mode 100644index 0000000000..bf14ed11b1--- /dev/null+++ b/scripts/check-migration-numbers.mjs@@ -0,0 +1,146 @@+#!/usr/bin/env node+// Fails when a branch adds a migration whose numeric prefix is already taken+// on the base branch, or by another migration the same branch adds.+//+// TestMigrationNumericPrefixesAreUnique checks the same rule, but a PR's CI+// runs it only against the main of the moment it was pushed. When main later+// gains a migration with the same number there is no textual conflict, the+// PR stays green, and merging it turns main red (MUL-9832). So run this+// against a freshly fetched main right before merging. The migration-numbers+// workflow also re-runs it for every open PR whenever main gains a migration+// and posts the result as a commit status on each PR head.+//+// The check models the merge result: the base's migrations, minus the ones+// the branch deleted since it forked, plus the ones it added.+//+// Usage:+// git fetch origin main+// node scripts/check-migration-numbers.mjs [--base origin/main] [--head HEAD] [--json]+//+// Exit codes: 0 no collision, 1 collision, 2 the check could not run.++import { execFileSync } from "node:child_process";+import { pathToFileURL } from "node:url";++const MIGRATIONS_DIR = "server/migrations";+// Mirrors firstUniqueMigrationNumber in migrations_lint_test.go: earlier+// numbers carry historical duplicates.+const FIRST_UNIQUE_MIGRATION_NUMBER = 129;++export function migrationNumber(stem) {+ const match = /^(\d+)_/.exec(stem);+ return match ? Number(match[1]) : null;+}++// Each argument is the list of migration stems (file names without+// `.up.sql`) present at that commit.+export function findMigrationCollisions({ base, head, mergeBase }) {+ const headStems = new Set(head);+ const mergeBaseStems = new Set(mergeBase);+ const added = [...headStems].filter((stem) => !mergeBaseStems.has(stem)).sort();+ const addedStems = new Set(added);+ const deleted = new Set([...mergeBaseStems].filter((stem) => !headStems.has(stem)));+ const merged = new Set([...base.filter((stem) => !deleted.has(stem)), ...added]);++ const stemsByNumber = new Map();+ for (const stem of merged) {+ const number = migrationNumber(stem);+ if (number === null) continue;+ stemsByNumber.set(number, [...(stemsByNumber.get(number) ?? []), stem]);+ }++ const collisions = [];+ for (const stem of added) {+ const number = migrationNumber(stem);+ if (number === null || number < FIRST_UNIQUE_MIGRATION_NUMBER) continue;+ const others = stemsByNumber.get(number).filter((other) => other !== stem);+ if (others.length === 0) continue;+ collisions.push({+ stem,+ number,+ conflictsWith: others.sort().map((other) => ({ stem: other, addedByHead: addedStems.has(other) })),+ });+ }++ let next = Math.max(0, ...stemsByNumber.keys());+ for (const collision of collisions) collision.suggestedNumber = ++next;++ return { added, collisions };+}++export function checkRefs({ base, head, cwd }) {+ const git = (...args) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });+ const stemsAt = (ref) =>+ git("ls-tree", "--name-only", ref, "--", `${MIGRATIONS_DIR}/`)+ .split("\n")+ .filter((path) => path.endsWith(".up.sql"))+ .map((path) => path.slice(MIGRATIONS_DIR.length + 1, -".up.sql".length));+ const mergeBase = git("merge-base", base, head).trim();+ return findMigrationCollisions({ base: stemsAt(base), head: stemsAt(head), mergeBase: stemsAt(mergeBase) });+}++// Leaves out the suggested number on purpose: it moves with every migration+// main gains, and the open-PR sweep reposts a status only when this text+// changes.+export function summarize(collisions, baseLabel) {+ if (collisions.length === 0) return `Migration numbers are free on ${baseLabel}`;+ const numbers = [...new Set(collisions.map((collision) => collision.number))];+ const verb = numbers.length === 1 ? "is" : "are";+ return `Migration ${numbers.join(", ")} ${verb} already taken; renumber above the highest on ${baseLabel}`;+}++function main(argv) {+ const base = readFlag(argv, "--base") ?? "origin/main";+ const head = readFlag(argv, "--head") ?? "HEAD";+ const json = argv.includes("--json");++ let result;+ try {+ result = checkRefs({ base, head });+ } catch (error) {+ console.error(`Could not compare migrations between ${base} and ${head}: ${error.stderr?.trim() || error.message}`);+ return 2;+ }+ const { added, collisions } = result;++ if (json) {+ console.log(JSON.stringify({ base, head, added, collisions, summary: summarize(collisions, base) }));+ return collisions.length === 0 ? 0 : 1;+ }++ if (added.length === 0) {+ console.log(`No migrations added against ${base}.`);+ return 0;+ }+ if (collisions.length === 0) {+ console.log(`${added.length} added migration(s) have numbers that are free on ${base}.`);+ return 0;+ }++ for (const { stem, number, conflictsWith, suggestedNumber } of collisions) {+ const owners = conflictsWith+ .map((other) => (other.addedByHead ? `${other.stem} (also added here)` : other.stem))+ .join(", ");+ const message = `${stem} uses migration number ${number}, already taken by ${owners}; renumber it to ${suggestedNumber}`;+ console.log(process.env.GITHUB_ACTIONS ? `::error file=${MIGRATIONS_DIR}/${stem}.up.sql::${message}` : ` ${message}`);+ }+ console.error(+ [+ "",+ `${collisions.length} migration number(s) collide with ${base}.`,+ "Rename both the .up.sql and .down.sql files (and any references to the",+ "version, such as concurrent index cleanups in server/cmd/migrate/main.go),",+ "then fetch main again and rerun this check before merging.",+ ].join("\n"),+ );+ return 1;+}++function readFlag(argv, name) {+ const i = argv.indexOf(name);+ return i !== -1 && argv[i + 1] ? argv[i + 1] : undefined;+}++if (import.meta.url === pathToFileURL(process.argv[1]).href) {+ process.exit(main(process.argv.slice(2)));+}diff --git a/scripts/check-migration-numbers.test.mjs b/scripts/check-migration-numbers.test.mjsnew file mode 100644index 0000000000..2f7072096e--- /dev/null+++ b/scripts/check-migration-numbers.test.mjs@@ -0,0 +1,126 @@+import assert from "node:assert/strict";+import { execFileSync, spawnSync } from "node:child_process";+import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import test from "node:test";++import { findMigrationCollisions, summarize } from "./check-migration-numbers.mjs";++const script = fileURLToPath(new URL("./check-migration-numbers.mjs", import.meta.url));++test("a number main took after the branch forked collides", () => {+ const { added, collisions } = findMigrationCollisions({+ mergeBase: ["718_a"],+ base: ["718_a", "719_main", "720_main", "721_main"],+ head: ["718_a", "719_branch"],+ });+ assert.deepEqual(added, ["719_branch"]);+ assert.deepEqual(collisions, [+ {+ stem: "719_branch",+ number: 719,+ conflictsWith: [{ stem: "719_main", addedByHead: false }],+ suggestedNumber: 722,+ },+ ]);+ assert.equal(summarize(collisions, "origin/main"), "Migration 719 is already taken; renumber above the highest on origin/main");+});++test("a branch that renumbered past main is clear", () => {+ const { added, collisions } = findMigrationCollisions({+ mergeBase: ["718_a"],+ base: ["718_a", "719_main"],+ head: ["718_a", "720_branch"],+ });+ assert.deepEqual(added, ["720_branch"]);+ assert.deepEqual(collisions, []);+});++test("two migrations the branch adds with one number both collide", () => {+ const { collisions } = findMigrationCollisions({+ mergeBase: ["718_a"],+ base: ["718_a"],+ head: ["718_a", "719_x", "719_y"],+ });+ assert.deepEqual(+ collisions.map(({ stem, suggestedNumber }) => [stem, suggestedNumber]),+ [["719_x", 720], ["719_y", 721]],+ );+ assert.equal(collisions[0].conflictsWith[0].addedByHead, true);+ assert.equal(summarize(collisions, "main"), "Migration 719 is already taken; renumber above the highest on main");+});++test("renaming a migration within its own number is not a collision", () => {+ const { collisions } = findMigrationCollisions({+ mergeBase: ["718_a", "719_old_name"],+ base: ["718_a", "719_old_name"],+ head: ["718_a", "719_new_name"],+ });+ assert.deepEqual(collisions, []);+});++test("historical duplicate numbers below 129 are ignored", () => {+ const { collisions } = findMigrationCollisions({+ mergeBase: [],+ base: ["100_main"],+ head: ["100_branch"],+ });+ assert.deepEqual(collisions, []);+});++test("the CLI catches a collision the branch's own base never had", (t) => {+ const dir = mkdtempSync(join(tmpdir(), "migration-numbers-"));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const env = {+ ...process.env,+ GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null",+ GIT_AUTHOR_NAME: "CI test", GIT_AUTHOR_EMAIL: "[email protected]",+ GIT_COMMITTER_NAME: "CI test", GIT_COMMITTER_EMAIL: "[email protected]",+ };+ delete env.GITHUB_ACTIONS;+ const git = (...args) => execFileSync("git", args, { cwd: dir, env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });+ const migrations = join(dir, "server", "migrations");+ const addMigration = (stem) => {+ writeFileSync(join(migrations, `${stem}.up.sql`), `-- ${stem}\n`);+ writeFileSync(join(migrations, `${stem}.down.sql`), `-- ${stem}\n`);+ };+ const run = (...args) => spawnSync("node", [script, ...args], { cwd: dir, env, encoding: "utf8" });++ mkdirSync(migrations, { recursive: true });+ git("init", "-b", "main");+ addMigration("718_existing");+ git("add", ".");+ git("commit", "-m", "base");++ git("checkout", "-b", "feature");+ addMigration("719_feature");+ git("add", ".");+ git("commit", "-m", "feature migration");+ assert.equal(run("--base", "main").status, 0, "clear while main has not moved");++ git("checkout", "main");+ addMigration("719_other");+ addMigration("720_other");+ git("add", ".");+ git("commit", "-m", "another PR lands first");+ assert.equal(spawnSync("git", ["merge-tree", "--write-tree", "main", "feature"], { cwd: dir, env }).status, 0,+ "no textual conflict, so nothing else stops the merge");++ git("checkout", "feature");+ const stale = run("--base", "main");+ assert.equal(stale.status, 1);+ assert.match(stale.stdout, /719_feature uses migration number 719, already taken by 719_other; renumber it to 721/);++ for (const direction of ["up", "down"]) {+ renameSync(join(migrations, `719_feature.${direction}.sql`), join(migrations, `721_feature.${direction}.sql`));+ }+ git("add", "-A");+ git("commit", "-m", "renumber");+ const fixed = run("--base", "main", "--json");+ assert.equal(fixed.status, 0);+ assert.deepEqual(JSON.parse(fixed.stdout).added, ["721_feature"]);++ assert.equal(run("--base", "missing-ref").status, 2);+});