Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,17 @@ jobs:
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
- name: File size policy
run: just file-size-check
- name: Merged migrations are append-only
if: github.event_name == 'pull_request'
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
# Read labels now, not from the event, so a re-run sees a newly added label.
if gh pr view "$PR_NUMBER" --json labels --jq '.labels[].name' | grep -qx migration-edit; then
export BUZZ_ALLOW_MIGRATION_EDITS=1
fi
just migrations-append-only-check

dead-token-guard:
name: Dead Token Reference Guard
Expand Down
6 changes: 5 additions & 1 deletion Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ build-release:
cargo build --workspace --release

# Run repo lint, formatting, and repository policy checks
check: fmt-check clippy desktop-check desktop-tauri-fmt-check desktop-tauri-clippy web-check mobile-check security-review-check file-size-check
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

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

# Fail when a migration already on main is edited, renamed or deleted.
migrations-append-only-check:
scripts/check-migrations-append-only.sh

# Format all Rust code
fmt:
cargo fmt --all
Expand Down
47 changes: 47 additions & 0 deletions crates/buzz-db/src/runtime/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2704,6 +2704,53 @@ mod postgres_tests {
);
}

#[test]
fn new_migrations_start_by_bounding_the_lock_wait() {
// A DDL statement queued behind a long transaction blocks every query on
// the table until it gets its lock, so a migration without a lock_timeout
// can stall the relay fleet during a deploy (docs/database.md rule 6).
// The versions listed predate the rule. The push gateway's migrations
// follow the same rules.
let roots = [
("migrations", 66),
("crates/buzz-push-gateway/migrations", 6),
];
let repo = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let mut missing = Vec::new();
for (dir, last_exempt) in roots {
for entry in fs::read_dir(repo.join(dir)).expect("read migrations directory") {
let path = entry.expect("migrations entry").path();
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
continue;
};
let Some(version) = name
.strip_suffix(".sql")
.and_then(|stem| stem.split('_').next())
.and_then(|version| version.parse::<u32>().ok())
else {
continue;
};
if version <= last_exempt {
continue;
}
let sql = fs::read_to_string(&path).expect("read migration");
let first = split_sql_statements(&sql)
.first()
.map(|statement| normalize_sql(statement))
.unwrap_or_default();
if !first.starts_with("set local lock_timeout ") {
missing.push(format!("{dir}/{name}"));
}
}
}
missing.sort();
assert!(
missing.is_empty(),
"start each migration with `SET LOCAL lock_timeout = '5s';` before any other statement:\n{}",
missing.join("\n")
);
}

#[test]
fn migrations_after_retirement_add_no_triggers_functions_or_foreign_keys() {
let violations: Vec<String> = migrations_after(LAST_SCHEMA_OBJECT_RETIREMENT_MIGRATION)
Expand Down
2 changes: 1 addition & 1 deletion crates/buzz-push-gateway/migrations/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ Read [docs/database.md](../../../docs/database.md) before changing anything
here. The existing `push_gateway_*` tables are also duplicated in the relay
schema (`migrations/` and `schema/`); until that duplication is removed, a
change to them goes there too. The target is for the gateway to own its tables
alone, so put new gateway tables only here. Never edit a merged migration.
alone, so put new gateway tables only here.
7 changes: 4 additions & 3 deletions docs/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ apply:

| Location | What goes there |
|---|---|
| `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. |
| `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. `just migrations-append-only-check` enforces this. A deliberate rewrite that every deployment has agreed to takes the `migration-edit` PR label. |
| `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. |
| `schema/schema.sql` | An `\i` line for each new file, after the tables it depends on. |
| `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. |
Expand Down Expand Up @@ -471,8 +471,9 @@ foreign keys on `events` and `delivery_log`, apply `0104`.

### 6. Bound every lock and statement

- Every migration MUST start with `SET LOCAL lock_timeout`, and SHOULD set
`SET LOCAL statement_timeout` when a statement can scan. A migration that
- Every migration MUST start with `SET LOCAL lock_timeout` (a buzz-db test
enforces it after `0066`), and SHOULD set `SET LOCAL statement_timeout`
when a statement can scan. A migration that
cannot get its lock fails and is retried. It MUST NOT queue behind
traffic on a hot table.
- With `BUZZ_AUTO_MIGRATE` on, migrations are the whole upgrade procedure, so
Expand Down
3 changes: 3 additions & 0 deletions lefthook.yml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ pre-push:
# The ratchet computes its own merge-base diff, so path filtering here
# would only duplicate policy and create another place for coverage drift.
run: ./scripts/without-git-env.sh just file-size-check
migrations-append-only:
# One git diff against the merge base, so it runs on every push.
run: ./scripts/without-git-env.sh just migrations-append-only-check
rust-tests:
files: git diff --name-only origin/main...HEAD
glob: ["crates/**", "migrations/**", "schema/**", "Cargo.toml", "Cargo.lock", "rust-toolchain.toml", "deny.toml", "scripts/run-tests.sh", "Justfile"]
Expand Down
2 changes: 0 additions & 2 deletions migrations/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ Before changing anything in this directory, read
`scripts/reconcile-schema-after-pgschema.sql` where it applies, and, for
existing `push_gateway_*` tables, `crates/buzz-push-gateway/migrations/`.
Do not add new gateway tables here.
- Never edit a merged migration. Fix forward.
- Adding a `community_id` table has its own checklist in that document. A
tenant-owned one is blocked until desired-state bootstraps stop attaching
fence triggers to every `community_id` table.
Expand All @@ -24,7 +23,6 @@ Before changing anything in this directory, read
then new code, then backfill, then constraints and cleanup. A contract
migration fails closed if its backfill has not run, and its release notes
name the writer release that upgrades must not skip.
- Bound every lock (`SET LOCAL lock_timeout`).
- Build a missing index inline under the lock and statement budgets, as
`0049` does. Never refuse a table only because it has rows: that crash-loops
every auto-migrating deployment with data, however small.
42 changes: 42 additions & 0 deletions scripts/check-migrations-append-only.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
# Fails when a migration that is already on main is edited, renamed or deleted.
#
# sqlx stores each applied migration's checksum. An edited migration makes
# every database that already ran it refuse to start (VersionMismatch), and a
# deleted or renamed one leaves those databases out of step with new ones.
# Fix forward with a new migration instead.
#
# The base is the merge base with origin/main, or the PR base (HEAD^1 of the
# merge commit) in GitHub Actions. CHECK_MIGRATIONS_BASE overrides it.
#
# Escape hatch for a deliberate rewrite, such as a consolidation every
# deployment has agreed to: BUZZ_ALLOW_MIGRATION_EDITS=1 locally, or the
# `migration-edit` label on the PR in CI.
set -euo pipefail

cd "$(git rev-parse --show-toplevel)"

if [[ "${BUZZ_ALLOW_MIGRATION_EDITS:-}" == "1" ]]; then
echo "Migration edits allowed by BUZZ_ALLOW_MIGRATION_EDITS=1."
exit 0
fi

base="${CHECK_MIGRATIONS_BASE:-}"
if [[ -z "$base" ]]; then
if [[ "${GITHUB_ACTIONS:-}" == "true" ]]; then
base="HEAD^1"
elif ! base="$(git merge-base origin/main HEAD)"; then
echo "Could not find the merge base with origin/main. Fetch origin/main or set CHECK_MIGRATIONS_BASE." >&2
exit 2
fi
fi

changed="$(git diff --no-renames --name-status "$base" HEAD -- \
'migrations/*.sql' 'crates/buzz-push-gateway/migrations/*.sql' | grep -v '^A' || true)"
Comment on lines +34 to +35

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Propagate failures from the migration diff

When CHECK_MIGRATIONS_BASE names an unavailable revision, the || true suppresses the failure of the entire pipeline, not just grep's no-match status. Reproducing with CHECK_MIGRATIONS_BASE=refs/heads/nonexistent-review-base bash scripts/check-migrations-append-only.sh prints fatal: bad revision but exits 0. This makes the append-only gate report success without checking any migrations. Capture the Git output separately and propagate its failure before filtering added files.

AGENTS.md reference: AGENTS.md:L232-L236

Useful? React with 👍 / 👎.


if [[ -n "$changed" ]]; then
echo "These migrations are already on main and must not change:" >&2
echo "$changed" >&2
echo "Revert them and add a new migration that fixes forward. See docs/database.md." >&2
exit 1
fi
Loading