Repository navigation
refactor(schema): fan desired-state schema out to one file per table - #8131
Conversation
schema/schema.sql becomes an ordered \i manifest. Each table now lives in schema/tables/public/<table>.sql with only its CREATE TABLE and CREATE INDEX statements, the shape SchemaBot applies; schema/tables is the SchemaBot schema directory and public its namespace. Types, functions, partitions, triggers (including write-fence attachment), seed rows, and the fence bootstrap move to sibling directories that SchemaBot never reads. The fan-out is a pure re-layout: pgschema and raw psql bootstraps from the old and new layouts produce identical pg_dump --schema-only output and seed rows. The deferred moderation_reports -> moderation_actions foreign key is declared inline, and a no-op DROP TRIGGER IF EXISTS on a fresh database is dropped. Tests that read schema.sql as one script use a test helper that expands the includes, and a new layout test pins that every schema/ file is included exactly once and table files stay SchemaBot-shaped. Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
…NOT EXISTS/CONCURRENTLY indexes in layout test Addresses review P2-1..P2-4 on #8131. Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
loganj
left a comment
There was a problem hiding this comment.
Review of head c867a6c8. Logan asked me to review this PR and to put the layout-test gap first.
Fix before merge: the layout test does not check where tables are declared
desired_state_schema_layout_is_complete_and_schemabot_shaped checks only the files under tables/public/. It does not check schema.sql itself or the other include directories. So these changes pass the test, and SchemaBot never sees the table:
- a
CREATE TABLE(orALTER TABLE ... ADD COLUMN) written directly intoschema/schema.sql; - a
CREATE TABLE(not a partition) intriggers/,seeds/,functions/or another sibling directory.
This is likely to happen soon. Today 7 open PRs edit schema/schema.sql: #8154, #8151, #8143, #8138, #7899, #7713 and #7679. After this PR merges, each one will conflict. The easiest way to resolve the conflict is to paste the new SQL back into the manifest. Postgres and pgschema accept that, CI is green, and the table drifts out of the layout without a warning.
Suggested fix, in the same test:
- Require that
schema.sqlcontain only comments,\ilines andCREATE EXTENSION. - Outside
tables/public/, rejectCREATE TABLEunless it isPARTITION OF. RejectALTER TABLE ... ADD COLUMNandADD CONSTRAINTeverywhere except where the layout allows them.
What I verified (local Postgres 17, compared with merge-base 1a2ddf9e)
-
Statement-level comparison of old and new: only 3 differences.
- The
moderation_reports(community_id, action_id)foreign key moved from anALTER TABLEinto theCREATE TABLE. Postgres generates the same name. - The multi-row
_operator_global_tablesINSERTs are now one INSERT per row. - The
DROP TRIGGER IF EXISTSwas removed.
The PR description mentions only #3. The other two have no effect, but please mention them in the description.
- The
-
Raw
psql(run fromschema/), old vs new: thepg_dump --schema-onlyoutput is identical. The data is also identical, except for the randomreplica_heartbeatUUID. -
pgschema apply+reconcile-schema-after-pgschema.sqlwith the pinnedbin/pgschema, old vs new: thepg_dumpoutput is identical.
Chesterton's fence checks (no problem found)
-
The removed
DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshot: it had a reason. The old roster-fence test cut one contiguous text span, from the function to the trigger. It required that span to equal migration 0032 exactly, and 0032 needs the DROP because it runs on databases that already exist. Now the test compares the function and the trigger separately, so the DROP is not needed. On a fresh database it never did anything. -
The new load order (functions before tables, seeds after triggers):
- The only two
LANGUAGE SQLfunctions reference no tables. - No PL/pgSQL
%TYPEdeclarations need a table at create time. - Postgres fires triggers in name order.
- Seeds write only to
_operator_global_tablesandreplica_heartbeat. Neither table has a trigger or the fence. - Triggers on a partitioned parent reach its partitions in either order.
The identical dumps confirm this.
- The only two
-
\iand the working directory: I searched.github,scripts, the Dockerfiles, the Justfile, lefthook and the crates. I found no caller that runspsql -f schema/schema.sqlfrom the repo root. All of them usepgschema --fileor the Rust expander. The CI path filterschema/**covers the new files.
Minor
- The new roster-fence comparison ends the function span at the first
$$ LANGUAGE plpgsql;. Both sides use that terminator, so drift is still detected. The test is weaker than before, and that is acceptable.
Older problem (main has it too; not caused by this PR)
The database built by pgschema apply + reconcile is different from the raw psql build:
- These multi-column CHECKs are missing:
community_deletion_checkpoints_checkand_check1,community_deletion_requests_check1,moderation_reports_checkandpush_leases_check. Reconcile restores onlyrelay_admin_actions_direct_shape. idx_channels_id_liveandcommunity_deletion_requests_owner_quota_reservationslose theirINCLUDEcolumns. Those columns become key columns.- The column order of the
eventsPK changes. The description already mentions this.
So CI does not enforce those CHECKs. This matters for the SchemaBot plan, because a declarative tool can lose constraints in the same way. I suggest a separate issue.
…dirs The layout test only checked files under schema/tables/public/, so table DDL pasted into schema/schema.sql (an easy merge-conflict resolution) or a table declared in a sibling directory still built and passed CI. Restrict schema.sql to \i includes and CREATE EXTENSION, and outside tables/public/ reject ALTER TABLE and any CREATE TABLE other than PARTITION OF in partitions/. Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
…iles Outside tables/public/, reject CREATE [UNIQUE] INDEX and ALTER/DROP of tables and indexes, not just ALTER TABLE. Run the statement check over schema.sql too, so a one-line paste after CREATE EXTENSION is caught. Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
wpfleger96
left a comment
There was a problem hiding this comment.
🤖 Thanks, Luke. Nothing here blocks.
I expanded the 146 includes and compared them with the old schema.sql one statement at a time, ignoring comments and whitespace. The only differences are the three listed in the description: the moderation_reports foreign key now sits in its CREATE TABLE (and moderation_actions now loads first), each of the 25 _operator_global_tables rows is its own INSERT with the same content and order, and the no-op DROP TRIGGER IF EXISTS is gone. Nothing was dropped or duplicated. The new order is safe: types load before everything, the two SQL-language functions use only built-ins, the PL/pgSQL functions only touch tables at run time, and every foreign-key target and partition parent exists before it's referenced. Every pgschema apply caller still passes the entry-point path and runs the reconcile script, and every Rust reader of the old file now goes through desired_state_schema_sql(). The drift checks against migrations compare the same content, except that the roster check no longer compares the removed DROP.
On Postgres 17.10 with the repo's pgschema 1.7.4, base and head give the same pg_dump --schema-only through both pgschema apply + reconcile and raw psql run from schema/. Table rows match except the generated replica_heartbeat.epoch UUID. A head pgschema plan against a raw-loaded base is empty, and against a pgschema-loaded base it gives the same 18 events primary-key operations that the base file gives, so that churn was already there. scripts/postgres-test-setup.sh works at head, and scripts/start-isolated-test-relay.sh reaches ready. Removing an include, and adding a CREATE INDEX to a trigger file, each make the layout test fail. I also saw the _operator_global_tables gap you described: pgschema + reconcile leaves it empty on both base and head.
Optional
migration.rsL1533–1537, L1560–1579: the layout guard matches words, not SQL. It drops--comments but not/* */ones, and it scans the inside of quoted strings. SoCREATE /* x */ INDEX ... ON channelsin a trigger file gets past it, a function error message that saysDROP TABLEfails it, and a non-partition table withPARTITION OFinside a string default slips through the partition exception. The current schema is fine either way. Skipping comments and string literals before matching would close this, or the test doc could say it guards the repo's usual SQL spelling rather than every valid form.schema.sqlL37–38 still says "Every table below cites the conformance surface it implements". Those citations now live in the table files.- The description has no
buzz-review-completedline.
…ble (#8328) ## Summary Gives the push gateway a declarative desired-state schema in the same layout the relay uses since #8131: a `\i` manifest plus one file per table, the shape SchemaBot reads. - `crates/buzz-push-gateway/schema/schema.sql`: an ordered `\i` manifest and nothing else. - `crates/buzz-push-gateway/schema/tables/public/<table>.sql`: the end state of migrations `0001`–`0008` for all six gateway tables. That includes `0007`'s `installations.platform` column and `0008`'s dropped delegation → installation foreign key (#9610), so the delegation table declares no `REFERENCES`. Each file holds only its `CREATE TABLE` and plain `CREATE [UNIQUE] INDEX` statements. - `src/postgres.rs`: the six table names are now one `GATEWAY_TABLES` constant shared by readiness and the runtime-role GRANT, instead of two hand-copied lists. - `src/postgres/desired_schema_postgres_tests.rs` adds two tests: - `desired_state_schema_layout_is_complete_and_schemabot_shaped` (no infra needed). It checks that the manifest includes every file exactly once and holds only `\i` lines, that each table file creates exactly one table, and that indexes use a plain `CREATE INDEX` on that table. - `desired_state_schema_matches_migrations` (PostgreSQL lane). It builds one probe database from `schema.sql` through the real `bin/pgschema apply` and another through `GATEWAY_MIGRATOR`. It then requires the two `public` catalogs to match: table set, columns from `pg_attribute` (full type with typmod via `format_type`, default, nullability, identity, generation, collation), table options (persistence, RLS flags, `reloptions`), constraints (`pg_get_constraintdef`) and index shapes (`pg_get_indexdef` + `indoption`). Neither probe may hold functions, non-internal triggers, policies, views, sequences or user types, and the declared table set must equal `GATEWAY_TABLES`. It compares the whole `public` catalog, not a list of tables, so a future migration that changes `public` tables, columns, table options, constraints or indexes without a matching `schema/` change fails CI. It doesn't cover data-only migrations or objects outside `public` (other schemas, roles, database settings). Probe databases are created from `template0` and dropped even when an assertion, `pgschema` or setup fails; the original failure is re-raised unchanged. Connection details, including the password, come from the resolved `PgConnectOptions`, so percent-encoded credentials, `?password=` and Unix-socket URLs reach `pgschema` the way SQLx sees them. `pgschema` 1.7.4 builds an unquoted keyword DSN, so a password or socket path with whitespace, a quote, `=` or a backslash isn't supported (noted in the test). ## Not changed The gateway still migrates itself at startup: bootstrap guard, then SQLx migrations, then runtime-role grants. The guard and grants are operational steps, not desired-state DDL, so they stay in code. No `schemabot.yaml` is added: SchemaBot isn't configured for the relay or the gateway yet, so the yaml for both waits until that server-side setup exists. The manifest header notes that the relay's post-pgschema reconcile step (root `AGENTS.md` gotcha #7) doesn't apply, because the gateway schema has no seed DML or storage parameters. SchemaBot compatibility is not proven here. The parity test shows the files are equivalent under `pgschema`. Since #9610 the gateway schema has no foreign keys, so the earlier inline-FK caveat is gone. `docs/database.md` Rule 4 now lists the gateway `schema/` directory as a schema location. ## What got simpler To read the gateway's schema today you have to replay eight migrations: two CHECK rewrites, two dropped UNIQUE constraints, a dropped column, an added column and a dropped foreign key. After this PR it's one declarative file per table, in the same convention as the relay. There is no new runtime path and no new abstraction, and the duplicated table list in `postgres.rs` collapses to one constant. ## Testing At `c4336392` (rebased on main after #9610; mirrors gateway `0007`/`0008`; reads the `pgschema` password from a copy with a URL-safe host and username, so a `PGHOST` or default-search socket no longer panics and a `/role` username no longer drops the password): - `cargo fmt --all -- --check` and `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings`: pass. - `cargo test -p buzz-push-gateway --lib desired_schema`: pass, including `resolved_password_reads_through_a_socket_host_and_slash_username`. Removing the username normalization makes that test fail. - `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 17/17 passed, including `desired_state_schema_matches_migrations`. At `df3ff104` (password from resolved connect options), same workstation: - fmt, clippy (`-D warnings`, with and without `personal-dev-app-attest`): pass. `cargo nextest run -p buzz-push-gateway`: 80/80, and 82/82 with the feature. `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 13/13. - `?password=`: with `PGPASSWORD` unset, `postgres://<role>:wrong@localhost/postgres?password=<encoded p@ss:w/rd#x>` passes the parity test, so `pgschema` gets the query-parameter password that SQLx uses. A wrong `?password=` is rejected (`28P01`). - The CHECK-bound falsification still fails with `constraint parity mismatch`. Every run leaves 0 probe databases. At `f937924a` (probe cleanup and connection-URL follow-up), on a Linux workstation against PostgreSQL 16 with the repo's pinned `bin/pgschema`: - `cargo fmt --all -- --check`, plus `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings` with and without `--features personal-dev-app-attest`: pass. - `cargo nextest run -p buzz-push-gateway`: 60/60 passed, and 62/62 with `personal-dev-app-attest`. `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 12/12 passed. - Probe cleanup: with a CHECK bound changed (2048→4096), the previous test code fails and leaves both `push_gateway_{desired,migrated}_*` databases behind. The new code fails with the same `constraint parity mismatch` panic and leaves none. A table file that makes `pgschema apply` fail (`no_such_column`) also reports `pgschema apply failed: ... column "no_such_column" does not exist` and leaves none. - Connection URLs: the parity test passes as a role whose password is `p@ss:w/rd#%x`, given percent-encoded in the URL with `PGPASSWORD` unset. It also passes over `postgres://<user>@%2Fvar%2Frun%2Fpostgresql:5432/postgres` (Unix socket, peer auth). Earlier, at `ee2745cb78`: - `scripts/postgres-test-packages.sh` discovers `buzz-push-gateway`. The parity test lives under a `*_postgres_tests` module so the `postgres-ci` nextest filter selects it. - `cargo fmt --all -- --check` and `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings` both pass. - `cargo nextest run -p buzz-push-gateway`: 60/60 passed, including the layout test. - `scripts/postgres-test-run.sh -p buzz-push-gateway`: 12/12 passed, including `desired_state_schema_matches_migrations`. - Falsification checks: - Dropping the partial predicate from `push_gateway_installations_active_token` makes the parity test fail with an index-shape mismatch. - Adding an unmirrored `0007` migration (`ADD COLUMN probe TEXT`) makes the parity test fail with a column mismatch. Mirroring the column in the table file makes it pass again. - Putting `CREATE TABLE` DDL in `schema.sql` makes the layout test fail. - A `0007` adding `probe VARCHAR(64)` mirrored as `VARCHAR(128)` fails with a column mismatch (typmod); mirroring it exactly passes. - An unmirrored `0007` `ALTER COLUMN expires_at TYPE TIMESTAMP` fails with a column mismatch. - An unmirrored `0007` `ENABLE ROW LEVEL SECURITY` fails with a table-option mismatch. - A `0007` creating a function and trigger fails the "only tables and indexes" check. Known gap: `sqlx::migrate!` doesn't notice a *new* migration file on an incremental build. The crate has no `build.rs` `rerun-if-changed`, and neither does any other crate in the workspace. For the `0007` check above I touched `src/postgres.rs` to force the macro to re-expand. Clean CI builds aren't affected. buzz-review-completed --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Splits the monolithic
schema/schema.sqlinto a declarative, one-file-per-table layout so table definitions can move to SchemaBot, Block's open-source declarative schema-change tool, which reads oneCREATE TABLEper file. Its PostgreSQL support and declarative-format limits are documented indocs/postgresql.md.schema/tables/public/<table>.sql: 57 files, each with oneCREATE TABLEplus theCREATE INDEXstatements for that table.tables/is the schema directory andpublicis its namespace, so only table files live under it.types/(10)functions/(15)partitions/(2)triggers/(36, including write-fence attachment)seeds/(25 operator-global andreplica_heartbeatrows)community_write_fence.sqlschema/schema.sqlis still the entry point, now as a\imanifest in load order: types → functions → tables → partitions → triggers → seeds → fence. CI, scripts, andpgschema apply --file schema/schema.sqlcallers are unchanged, and each one still runsscripts/reconcile-schema-after-pgschema.sql. The include dirs sit underschema/becausepgschemarejects..includes.schema.sqlnow calltest_support::desired_state_schema_sql(), which expands the includes into one string..sqlfile underschema/is included exactly once and that table files contain onlyCREATE TABLE/CREATE INDEX. It also keeps table DDL out of everywhere else:schema.sqlmay hold only\ilines andCREATE EXTENSION, and outsidetables/public/(including inschema.sqlitself) it rejects any statement that creates, alters or drops a table or index, exceptCREATE TABLE ... PARTITION OFinpartitions/. That stops a merge-conflict resolution from pasting DDL back into the manifest.Equivalence
Checked against
origin/mainat 1a2ddf9 on a Postgres 17 database:pgschema apply+ reconcile, old vs new: identicalpg_dump --schema-onlyoutput and identical seed rows.psql -f(run fromschema/, sincepsqlresolves\iagainst the working directory), old vs new: identical DDL and seed rows.pgschema planof the new layout against a database built from the oldschema.sqlwith rawpsql: no changes. Against a database built from the old file withpgschema, both the old and the new file give the same plan, which shows existing primary-key churn oneventsand its partitions. That churn is not new in this PR.Statement by statement, the expanded manifest differs from the old file in three places, none of which changes the resulting database:
moderation_reports(community_id, action_id)foreign key moved from a separateALTER TABLEinto itsCREATE TABLE. Postgres generates the same constraint name._operator_global_tablesINSERTs are now one INSERT per row, one per seed file.DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshotis removed. It did nothing on a fresh database.Known follow-up
These shapes in
tables/public/still need work before SchemaBot can manage the tables:replica_heartbeatusesWITH (vacuum_truncate = false), and non-default relation options are outside the format.eventsanddelivery_logarePARTITION BYparents, and changes to them are outside the supported envelope.types/, outside the tables directory. It is still unverified whether SchemaBot's planner resolves column types it doesn't declare.None of these change in this PR.
Also found, and present before this PR:
scripts/reconcile-schema-after-pgschema.sqlseeds onlyreplica_heartbeat. That leaves_operator_global_tablesempty after apgschema applybootstrap, and the old monolith has the same result. Rawpsqlloads all 25 registrations. This is listed here as identified debt, not fixed.What got simpler
A 2,100-line file becomes one file per object kind, so a table's full definition is in one place. Nothing new runs at runtime: the manifest replaces the monolith one-for-one, and the layout test keeps future additions in the same shape.
Testing
All run on Blox at c867a6c unless noted. At 54f90cd (layout-test tightening, test-only): fmt, clippy, buzz-db unit tests (161 passed) and the Postgres lane (446/446 passed) all pass. At d141e50 (test-only follow-up): fmt, clippy and buzz-db unit tests pass.
cargo fmt --checkandcargo clippy -p buzz-db --all-targets -D warnings.buzz-dbunit tests: 161 passed.CREATE INDEX IF NOT EXISTSadded to a table file. At d141e50 it also fails on aCREATE TABLEorALTER TABLEinschema.sql(including one pasted on theCREATE EXTENSIONline), anALTER TABLE, lowercasecreate table,CREATE INDEXorDROP TABLEin a trigger file, aCREATE UNIQUE INDEXor non-partition table inpartitions/, and aDROP INDEXorCREATE UNLOGGED TABLEin a seed file. The clean tree passes.buzz-dbPostgres lane (scripts/postgres-test-run.sh -p buzz-db --lib --tests): 446/446 passed at 2c93fd2. At c867a6c, 445/446 passed. The one failure wasreadiness_check_cancellation_balances_waiter_and_inflight_connection, a pool-cancellation timing test that doesn't touch the schema; it passed 3 of 3 runs when re-run on its own.