Skip to content

Commit 3fe9169

Browse files
salman1993claude
andcommitted
chore(db): check that migrations bound their lock wait and stay append-only
A new buzz-db test fails when a relay migration after 0066, or a push gateway migration after 0006, does not start with SET LOCAL lock_timeout. scripts/check-migrations-append-only.sh fails when a .sql file that is already on main is edited, renamed or deleted in either migrations directory. It runs in CI on pull requests, in the pre-push hook and in `just check`. BUZZ_ALLOW_MIGRATION_EDITS=1 or the migration-edit PR label lets a deliberate rewrite through. The prose these checks replace is shortened in docs/database.md and the migrations AGENTS.md files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Salman Mohammed <smohammed@squareup.com>
1 parent a9c63ee commit 3fe9169

8 files changed

Lines changed: 113 additions & 7 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,17 @@ jobs:
187187
run: node --test scripts/ci-selection.test.mjs scripts/ci-required-gates.test.mjs scripts/ci-apt-retry.test.mjs scripts/ci-hermit-retry.test.mjs
188188
- name: File size policy
189189
run: just file-size-check
190+
- name: Merged migrations are append-only
191+
if: github.event_name == 'pull_request'
192+
env:
193+
GH_TOKEN: ${{ github.token }}
194+
PR_NUMBER: ${{ github.event.pull_request.number }}
195+
run: |
196+
# Read labels now, not from the event, so a re-run sees a newly added label.
197+
if gh pr view "$PR_NUMBER" --json labels --jq '.labels[].name' | grep -qx migration-edit; then
198+
export BUZZ_ALLOW_MIGRATION_EDITS=1
199+
fi
200+
just migrations-append-only-check
190201
191202
dead-token-guard:
192203
name: Dead Token Reference Guard

‎Justfile‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ build-release:
9898
cargo build --workspace --release
9999

100100
# Run repo lint, formatting, and repository policy checks
101-
check: fmt-check clippy desktop-check desktop-tauri-fmt-check desktop-tauri-clippy web-check mobile-check security-review-check file-size-check
101+
check: fmt-check clippy desktop-check desktop-tauri-fmt-check desktop-tauri-clippy web-check mobile-check security-review-check file-size-check migrations-append-only-check
102102

103103
# Validate the trusted security-review workflow support and renderer contract.
104104
security-review-check:
@@ -115,6 +115,10 @@ file-size-check:
115115
node web/scripts/check-file-sizes.mjs
116116
node mobile/scripts/check-file-sizes.mjs
117117

118+
# Fail when a migration already on main is edited, renamed or deleted.
119+
migrations-append-only-check:
120+
scripts/check-migrations-append-only.sh
121+
118122
# Format all Rust code
119123
fmt:
120124
cargo fmt --all

‎crates/buzz-db/src/runtime/migration.rs‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2531,6 +2531,53 @@ mod postgres_tests {
25312531
);
25322532
}
25332533

2534+
#[test]
2535+
fn new_migrations_start_by_bounding_the_lock_wait() {
2536+
// A DDL statement queued behind a long transaction blocks every query on
2537+
// the table until it gets its lock, so a migration without a lock_timeout
2538+
// can stall the relay fleet during a deploy (docs/database.md rule 6).
2539+
// The versions listed predate the rule. The push gateway's migrations
2540+
// follow the same rules.
2541+
let roots = [
2542+
("migrations", 66),
2543+
("crates/buzz-push-gateway/migrations", 6),
2544+
];
2545+
let repo = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
2546+
let mut missing = Vec::new();
2547+
for (dir, last_exempt) in roots {
2548+
for entry in fs::read_dir(repo.join(dir)).expect("read migrations directory") {
2549+
let path = entry.expect("migrations entry").path();
2550+
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
2551+
continue;
2552+
};
2553+
let Some(version) = name
2554+
.strip_suffix(".sql")
2555+
.and_then(|stem| stem.split('_').next())
2556+
.and_then(|version| version.parse::<u32>().ok())
2557+
else {
2558+
continue;
2559+
};
2560+
if version <= last_exempt {
2561+
continue;
2562+
}
2563+
let sql = fs::read_to_string(&path).expect("read migration");
2564+
let first = split_sql_statements(&sql)
2565+
.first()
2566+
.map(|statement| normalize_sql(statement))
2567+
.unwrap_or_default();
2568+
if !first.starts_with("set local lock_timeout ") {
2569+
missing.push(format!("{dir}/{name}"));
2570+
}
2571+
}
2572+
}
2573+
missing.sort();
2574+
assert!(
2575+
missing.is_empty(),
2576+
"start each migration with `SET LOCAL lock_timeout = '5s';` before any other statement:\n{}",
2577+
missing.join("\n")
2578+
);
2579+
}
2580+
25342581
#[test]
25352582
fn migrations_after_retirement_add_no_triggers_functions_or_foreign_keys() {
25362583
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../migrations");

‎crates/buzz-push-gateway/migrations/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ Read [docs/database.md](../../../docs/database.md) before changing anything
44
here. The existing `push_gateway_*` tables are also duplicated in the relay
55
schema (`migrations/` and `schema/`); until that duplication is removed, a
66
change to them goes there too. The target is for the gateway to own its tables
7-
alone, so put new gateway tables only here. Never edit a merged migration.
7+
alone, so put new gateway tables only here.

‎docs/database.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ apply:
287287

288288
| Location | What goes there |
289289
|---|---|
290-
| `migrations/NNNN_<name>.sql` | The forward migration for existing databases. Use the next free number; rebase and renumber on a collision. Never edit a merged migration: its checksum changes, and relays that run the migrator fail with sqlx `VersionMismatch`. Fix forward in a new migration. |
290+
| `migrations/NNNN_<name>.sql` | The forward migration for existing databases, numbered after the newest on main. Merged migrations are append-only, because relays that already ran one fail with sqlx `VersionMismatch` when its checksum changes. `migration_versions_are_unique` and `just migrations-append-only-check` enforce both. A deliberate rewrite that every deployment has agreed to takes the `migration-edit` PR label. |
291291
| `schema/tables/public/<table>.sql` | The table's final `CREATE TABLE` and its `CREATE INDEX` statements, one table per file. This is the declarative schema source. |
292292
| `schema/schema.sql` | An `\i` line for each new file, after the tables it depends on. |
293293
| `schema/types/`, `schema/sequences/`, `schema/partitions/`, `schema/seeds/` | The matching non-table objects. The layout test permits nothing else here. `schema/` has no `functions/` or `triggers/` directory, and Rule 1 forbids adding one. |
@@ -446,8 +446,9 @@ foreign keys on `events` and `delivery_log`, apply `0104`.
446446

447447
### 6. Bound every lock and statement
448448

449-
- Every migration MUST start with `SET LOCAL lock_timeout`, and SHOULD set
450-
`SET LOCAL statement_timeout` when a statement can scan. A migration that
449+
- Every migration MUST start with `SET LOCAL lock_timeout` (a buzz-db test
450+
enforces it after `0066`), and SHOULD set `SET LOCAL statement_timeout`
451+
when a statement can scan. A migration that
451452
cannot get its lock fails and is retried. It MUST NOT queue behind
452453
traffic on a hot table.
453454
- With `BUZZ_AUTO_MIGRATE` on, migrations are the whole upgrade procedure, so

‎lefthook.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ pre-push:
9898
# The ratchet computes its own merge-base diff, so path filtering here
9999
# would only duplicate policy and create another place for coverage drift.
100100
run: ./scripts/without-git-env.sh just file-size-check
101+
migrations-append-only:
102+
# One git diff against the merge base, so it runs on every push.
103+
run: ./scripts/without-git-env.sh just migrations-append-only-check
101104
rust-tests:
102105
files: git diff --name-only origin/main...HEAD
103106
glob: ["crates/**", "migrations/**", "schema/**", "Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "deny.toml", "scripts/run-tests.sh", "Justfile"]

‎migrations/AGENTS.md‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ Before changing anything in this directory, read
1414
`scripts/reconcile-schema-after-pgschema.sql` where it applies, and, for
1515
existing `push_gateway_*` tables, `crates/buzz-push-gateway/migrations/`.
1616
Do not add new gateway tables here.
17-
- Never edit a merged migration. Fix forward.
1817
- Adding a `community_id` table has its own checklist in that document. A
1918
tenant-owned one is blocked until desired-state bootstraps stop attaching
2019
fence triggers to every `community_id` table.
@@ -23,7 +22,6 @@ Before changing anything in this directory, read
2322
then new code, then backfill, then constraints and cleanup. A contract
2423
migration fails closed if its backfill has not run, and its release notes
2524
name the writer release that upgrades must not skip.
26-
- Bound every lock (`SET LOCAL lock_timeout`).
2725
- Build a missing index inline under the lock and statement budgets, as
2826
`0049` does. Never refuse a table only because it has rows: that crash-loops
2927
every auto-migrating deployment with data, however small.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/env bash
2+
# Fails when a migration that is already on main is edited, renamed or deleted.
3+
#
4+
# sqlx stores each applied migration's checksum. An edited migration makes
5+
# every database that already ran it refuse to start (VersionMismatch), and a
6+
# deleted or renamed one leaves those databases out of step with new ones.
7+
# Fix forward with a new migration instead.
8+
#
9+
# The base is the merge base with origin/main, or the PR base (HEAD^1 of the
10+
# merge commit) in GitHub Actions. CHECK_MIGRATIONS_BASE overrides it.
11+
#
12+
# Escape hatch for a deliberate rewrite, such as a consolidation every
13+
# deployment has agreed to: BUZZ_ALLOW_MIGRATION_EDITS=1 locally, or the
14+
# `migration-edit` label on the PR in CI.
15+
set -euo pipefail
16+
17+
cd "$(git rev-parse --show-toplevel)"
18+
19+
if [[ "${BUZZ_ALLOW_MIGRATION_EDITS:-}" == "1" ]]; then
20+
echo "Migration edits allowed by BUZZ_ALLOW_MIGRATION_EDITS=1."
21+
exit 0
22+
fi
23+
24+
base="${CHECK_MIGRATIONS_BASE:-}"
25+
if [[ -z "$base" ]]; then
26+
if [[ "${GITHUB_ACTIONS:-}" == "true" ]]; then
27+
base="HEAD^1"
28+
elif ! base="$(git merge-base origin/main HEAD)"; then
29+
echo "Could not find the merge base with origin/main. Fetch origin/main or set CHECK_MIGRATIONS_BASE." >&2
30+
exit 2
31+
fi
32+
fi
33+
34+
changed="$(git diff --no-renames --name-status "$base" HEAD -- \
35+
'migrations/*.sql' 'crates/buzz-push-gateway/migrations/*.sql' | grep -v '^A' || true)"
36+
37+
if [[ -n "$changed" ]]; then
38+
echo "These migrations are already on main and must not change:" >&2
39+
echo "$changed" >&2
40+
echo "Revert them and add a new migration that fixes forward. See docs/database.md." >&2
41+
exit 1
42+
fi

0 commit comments

Comments
 (0)