Fail CI on new triggers, functions, rules and foreign keys (#9812)

## Summary

Migrations up to `0104` dropped every trigger, function and foreign key.
`docs/database.md` Rules 1 and 2 forbid adding them back, but nothing
enforced that. This PR adds the guard.

- **Migration lint.**
`migrations_after_retirement_add_no_triggers_functions_or_foreign_keys`
scans each migration numbered after `0104`. It fails on `CREATE [OR
REPLACE] FUNCTION | PROCEDURE | TRIGGER | RULE`, `CREATE CONSTRAINT
TRIGGER`, `CREATE EVENT TRIGGER`, `REFERENCES` and `FOREIGN KEY`,
outside `--` comments. The error names the file and line, for example
`migrations/0105_probe.sql:2: CREATE OR REPLACE FUNCTION`. Nested `/*
*/` comments are skipped. Quoted identifiers and string values are data,
except a string passed to `EXECUTE` or `format(`. Each dollar-quoted
body is scanned as SQL up to its closing delimiter, so DDL run through
`EXECUTE` in a `DO` block is caught, and an apostrophe inside `$$...$$`
cannot hide the rest of the file. It runs in the infra-free `buzz-db
--lib` unit lane.
- **Schema file check.**
`desired_state_schema_layout_is_complete_and_schemabot_shaped` allows
`schema/` files only under `tables/public/`, `types/`, `partitions/` and
`seeds/`, and runs the same scan on every file. A `functions/` or
`triggers/` file, or an inline `REFERENCES` in a table file, fails it.
- **Catalog check.**
`admin_schema_parity_between_desired_state_and_migrations` now asserts
that both bootstrap paths (pgschema + reconcile, and all migrations)
have zero non-internal triggers, event triggers, `public` functions and
procedures, rules and foreign keys. Extension members (pgcrypto) are
excluded. No allowlist is needed: main with all 104 migrations applied
has none of these objects.

Main now has `0105`, which passes the lint. Open PRs that add a
migration only need to renumber to `0106` or later. The two open ones
(https://github.com/block/buzz/pull/9621 and
https://github.com/block/buzz/pull/9690) add no forbidden object.

### What got simpler

- The parity test's per-table trigger comparisons (`events`,
`event_mentions`, and the five tables `0096` unguarded) and its separate
foreign-key check are replaced by one zero-object assertion.
- The scoped-key lint no longer parses foreign keys. None may exist, so
checking that they lead with `community_id` is dead logic.
- `schema/schema.sql` drops its empty `-- functions` and `-- triggers`
sections. Its header and `docs/database.md` stop describing `functions/`
and `triggers/` directories that no longer exist, and the doc's
"remaining triggers stay as a backstop" text now says they are gone.

### Checklist (`docs/database.md`)

- [x] Phase: none. Test and docs change only. No migration and no
runtime code.
- [x] No trigger, function, procedure, rule or foreign key is added.
- [x] No migration mutates rows.
- [x] Rule 4 locations: no schema change. `schema/schema.sql` changes
only comments.

### Related issue

None found.

### Testing

Run on a Linux workstation with PostgreSQL 17 at `b7254f90`, before the
review fixes. CI passed with the first review fixes at `0fed6b1b`.
`9749e618` adds dollar-quote, nested `EXECUTE $tag$` and `$1` cases to
`schema_object_lint_reports_each_construct_with_its_line`, and CI checks
it.

- `cargo fmt --check` and `cargo clippy -p buzz-db --all-targets -D
warnings`: pass.
- `cargo test -p buzz-db --lib` and `cargo nextest run -p buzz-db
--lib`: 223 passed.
- `scripts/postgres-test-run.sh` for
`admin_schema_parity_between_desired_state_and_migrations`,
`migrated_catalog_retires_universal_fences_but_keeps_deletion_guards`
and `pgschema_reapply_keeps_runtime_partitions`: 3 passed.
- Proof the lint can fail: a temporary `migrations/0105_probe.sql` with
a function and a `REFERENCES` column fails the lint with
`migrations/0105_probe.sql:2: CREATE OR REPLACE FUNCTION` and
`migrations/0105_probe.sql:3: REFERENCES`.
- Proof the catalog check can fail: a temporary `0105` that creates
`probe()` fails the parity test with `the migrations leave a trigger,
function, rule or foreign key`, `left: ["function probe()"]`.
- The catalog on main at `9c0bcd62`, with all 104 migrations applied
through psql, has no triggers, functions, foreign keys, rules or event
triggers.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Luke Tornquist
2026-11-20 15:56:50 -05:00
committed by GitHub
parent bc0b552894
commit af8287d961
3 changed files with 383 additions and 120 deletions

View File

@@ -18,7 +18,7 @@ PostgreSQL stores data. The application owns behavior.
| Schema source of truth | Two parallel sources: ordered sqlx migrations in `migrations/` and the desired-state manifest in `schema/` | The declarative desired state in `schema/tables/public/` is the source of truth. Deployments that apply schema out of band plan each change from it, with the tool of their choice. `migrations/` stays, because auto-migration stays supported (next row). Each app owns its own migrations and declarative schema: the relay's copies of the push gateway's tables are debt to remove (Rule 4). |
| Who applies DDL | Startup migrations when `BUZZ_AUTO_MIGRATE` is on (binary default off, Helm chart default on), `buzz-admin migrate`, the push gateway's pre-upgrade Helm Job, and partition creation at relay startup and on a schedule | Both modes stay supported. Deployments at scale, including Block's hosted deployment, apply schema changes out of band through a reviewed workflow before deploying, and their serving relay runs no DDL. Smaller and self-hosted deployments MAY keep auto-migration on. Still open: how the two modes share one schema source, how auto-migration orders a release whose expand, backfill, and contract steps arrive in one upgrade, and how an operator recovers after a contract migration fails at boot (Rule 5). Monthly partition creation is planned to move out of the relay. Changes to partitioned tables (`events`, `delivery_log`) are outside the out-of-band envelope (Rule 6): attaching a partition to a live parent and building an index on a partitioned parent need their own reviewed procedure. |
| Integrity between tables | None in the database (migrations `0102`-`0104` dropped the last foreign keys) | None in the database. The owning application transaction checks references and performs deletes explicitly. |
| Guards and follow-up writes | Triggers and PL/pgSQL functions (`schema/functions/`, `schema/triggers/`) | None in the database. Guards run in the owning writer's transaction; follow-up work is recorded in the same transaction and processed as durable, retryable application work. |
| Guards and follow-up writes | None in the database. Earlier migrations dropped the last triggers and functions | None in the database. Guards run in the owning writer's transaction; follow-up work is recorded in the same transaction and processed as durable, retryable application work. |
| Data repair | Some historical repair embedded in migrations | Backfill definitions in application code, run by the durable framework in [data-backfills.md](data-backfills.md). |
| Rollout | Effectively schema and code together | Expand, then deploy, then backfill, then contract. Each step is applied and verified on its own. |
@@ -47,10 +47,9 @@ adds to them moves away from the target.
unbounded, in one transaction, while holding locks, with no checkpoint, pause,
or recovery. The backfill framework exists to provide those properties.
The move to declarative, out-of-band schema changes is in progress. Until it
finishes, any remaining trigger or function stays in place as a backstop. Each
is removed on its own, after its application replacement has shipped and been
verified. None is removed early, and no new one is added.
The move to declarative, out-of-band schema changes is in progress. The last
triggers, functions, and foreign keys are already dropped. Rules 1 and 2 keep
new ones out, and CI enforces both.
## Rules for changes now
@@ -75,6 +74,17 @@ transaction that owns the write:
Dropping or narrowing an existing trigger or function is welcome. Follow the
retirement sequence below.
**Enforcement.** `migrations_after_retirement_add_no_triggers_functions_or_foreign_keys`
in `crates/buzz-db/src/runtime/migration.rs` fails CI when a migration numbered
after `0104` contains `CREATE FUNCTION`, `CREATE PROCEDURE`, `CREATE TRIGGER`,
`CREATE RULE` (each with or without `OR REPLACE`), `CREATE CONSTRAINT TRIGGER`,
`CREATE EVENT TRIGGER`, `REFERENCES`, or `FOREIGN KEY`. It names the file and
line. Comments, quoted identifiers, and string values are skipped; a string
passed to `EXECUTE` or `format(` is checked as SQL. The desired-state layout
test applies the same check to every file under `schema/`.
`admin_schema_parity_between_desired_state_and_migrations` asserts that both
bootstrap paths leave no trigger, function, rule, or foreign key.
**No exception for the community write fence.** Migration 0090 dropped the
universal fence triggers and their helper functions; a new table MUST NOT bring
a fence trigger back. Writers of a new tenant-owned table MUST be
@@ -124,7 +134,7 @@ Then, all in the same PR:
- [ ] Every writer of the table goes through community admission
(`begin_community_write_transaction` or another constructor that returns
`AdmittedTx`). Nothing writes the table outside it.
- [ ] No fence trigger in the migration or under `schema/triggers/`.
- [ ] No fence trigger in the migration.
- [ ] The table in `EXPECTED_SCOPED_TABLES` (`crates/buzz-db/src/store/deletion.rs`).
- [ ] The table in `PURGE_SCOPED_TABLES` in the same file, ordered child
before parent. A table missing here keeps its rows after the purge, and
@@ -280,7 +290,7 @@ apply:
| `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. |
| `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/partitions/`, `schema/seeds/` | The matching non-table objects. The layout test permits nothing else here. Rule 1 forbids any addition to `functions/` and `triggers/`. |
| `schema/types/`, `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. |
| `scripts/reconcile-schema-after-pgschema.sql` | Idempotent convergence, plus a live assertion, for anything `pgschema` does not preserve: seed rows, some storage parameters, partition attachment, and the shapes listed in AGENTS.md *Common Gotchas* #7. |
| `crates/buzz-push-gateway/migrations/`, `crates/buzz-push-gateway/schema/`, **and** the relay copies | The six `push_gateway_*` tables have two homes. The gateway applies its own migration history to its own database, through a pre-install/pre-upgrade Helm Job ([push-gateway-deployment.md](push-gateway-deployment.md)). `crates/buzz-push-gateway/schema/tables/public/` holds the gateway's declarative end state, one table per file; its parity test fails when it drifts from the gateway migrations. The relay schema also defines them: `migrations/` (`0015`, `0043`, `0045`, `0060`), `schema/tables/public/push_gateway_*.sql`, and `schema/seeds/push_gateway_*.sql`. Until the duplication is removed, a gateway schema change goes in both, as relay `0060` mirrors gateway `0006`. Every rule here applies to both. The target is for the gateway to own its tables alone, in its own migrations and declarative schema; do not add new gateway tables to the relay schema. |