Skip to content

refactor(schema): fan desired-state schema out to one file per table - #8131

Merged
TheSentinel454 merged 4 commits into
mainfrom
elrond/schema-per-table-files
Oct 8, 2026
Merged

TheSentinel454 merged 4 commits into
mainfrom
elrond/schema-per-table-files

Conversation

@TheSentinel454

@TheSentinel454 TheSentinel454 commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Splits the monolithic schema/schema.sql into a declarative, one-file-per-table layout so table definitions can move to SchemaBot, Block's open-source declarative schema-change tool, which reads one CREATE TABLE per file. Its PostgreSQL support and declarative-format limits are documented in docs/postgresql.md.

  • schema/tables/public/<table>.sql: 57 files, each with one CREATE TABLE plus the CREATE INDEX statements for that table. tables/ is the schema directory and public is its namespace, so only table files live under it.
  • Everything SchemaBot's table format cannot apply sits in sibling directories:
    • types/ (10)
    • functions/ (15)
    • partitions/ (2)
    • triggers/ (36, including write-fence attachment)
    • seeds/ (25 operator-global and replica_heartbeat rows)
    • community_write_fence.sql
  • schema/schema.sql is still the entry point, now as a \i manifest in load order: types → functions → tables → partitions → triggers → seeds → fence. CI, scripts, and pgschema apply --file schema/schema.sql callers are unchanged, and each one still runs scripts/reconcile-schema-after-pgschema.sql. The include dirs sit under schema/ because pgschema rejects .. includes.
  • Rust tests that used to read schema.sql now call test_support::desired_state_schema_sql(), which expands the includes into one string.
  • A new layout test checks that every .sql file under schema/ is included exactly once and that table files contain only CREATE TABLE/CREATE INDEX. It also keeps table DDL out of everywhere else: schema.sql may hold only \i lines and CREATE EXTENSION, and outside tables/public/ (including in schema.sql itself) it rejects any statement that creates, alters or drops a table or index, except CREATE TABLE ... PARTITION OF in partitions/. That stops a merge-conflict resolution from pasting DDL back into the manifest.

Equivalence

Checked against origin/main at 1a2ddf9 on a Postgres 17 database:

  • pgschema apply + reconcile, old vs new: identical pg_dump --schema-only output and identical seed rows.
  • Raw psql -f (run from schema/, since psql resolves \i against the working directory), old vs new: identical DDL and seed rows.
  • pgschema plan of the new layout against a database built from the old schema.sql with raw psql: no changes. Against a database built from the old file with pgschema, both the old and the new file give the same plan, which shows existing primary-key churn on events and 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:

  • The moderation_reports (community_id, action_id) foreign key moved from a separate ALTER TABLE into its CREATE TABLE. Postgres generates the same constraint name.
  • The multi-row _operator_global_tables INSERTs are now one INSERT per row, one per seed file.
  • A redundant DROP TRIGGER IF EXISTS trg_events_guard_channel_roster_snapshot is 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:

  • Inline foreign keys. The declarative format doesn't support them. The plan is to enforce those references in the app and then drop the constraints.
  • Relation options. replica_heartbeat uses WITH (vacuum_truncate = false), and non-default relation options are outside the format.
  • Partitioned parents. events and delivery_log are PARTITION BY parents, and changes to them are outside the supported envelope.
  • Enum types. The 10 enum types the table files use are defined in 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.sql seeds only replica_heartbeat. That leaves _operator_global_tables empty after a pgschema apply bootstrap, and the old monolith has the same result. Raw psql loads 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.

  • Old vs new equivalence (above).
  • cargo fmt --check and cargo clippy -p buzz-db --all-targets -D warnings.
  • buzz-db unit tests: 161 passed.
  • Falsification: the layout test fails on an orphaned type file, a trigger added to a table file, and a CREATE INDEX IF NOT EXISTS added to a table file. At d141e50 it also fails on a CREATE TABLE or ALTER TABLE in schema.sql (including one pasted on the CREATE EXTENSION line), an ALTER TABLE, lowercase create table, CREATE INDEX or DROP TABLE in a trigger file, a CREATE UNIQUE INDEX or non-partition table in partitions/, and a DROP INDEX or CREATE UNLOGGED TABLE in a seed file. The clean tree passes.
  • buzz-db Postgres lane (scripts/postgres-test-run.sh -p buzz-db --lib --tests): 446/446 passed at 2c93fd2. At c867a6c, 445/446 passed. The one failure was readiness_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.

Elrond added 2 commits October 6, 2026 16:59
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>
@TheSentinel454
TheSentinel454 marked this pull request as ready for review October 7, 2026 13:39
@TheSentinel454
TheSentinel454 requested a review from a team as a code owner October 7, 2026 13:39

@loganj loganj left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 (or ALTER TABLE ... ADD COLUMN) written directly into schema/schema.sql;
  • a CREATE TABLE (not a partition) in triggers/, 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:

  1. Require that schema.sql contain only comments, \i lines and CREATE EXTENSION.
  2. Outside tables/public/, reject CREATE TABLE unless it is PARTITION OF. Reject ALTER TABLE ... ADD COLUMN and ADD CONSTRAINT everywhere 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.

    1. The moderation_reports (community_id, action_id) foreign key moved from an ALTER TABLE into the CREATE TABLE. Postgres generates the same name.
    2. The multi-row _operator_global_tables INSERTs are now one INSERT per row.
    3. The DROP TRIGGER IF EXISTS was removed.

    The PR description mentions only #3. The other two have no effect, but please mention them in the description.

  • Raw psql (run from schema/), old vs new: the pg_dump --schema-only output is identical. The data is also identical, except for the random replica_heartbeat UUID.

  • pgschema apply + reconcile-schema-after-pgschema.sql with the pinned bin/pgschema, old vs new: the pg_dump output 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 SQL functions reference no tables.
    • No PL/pgSQL %TYPE declarations need a table at create time.
    • Postgres fires triggers in name order.
    • Seeds write only to _operator_global_tables and replica_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.

  • \i and the working directory: I searched .github, scripts, the Dockerfiles, the Justfile, lefthook and the crates. I found no caller that runs psql -f schema/schema.sql from the repo root. All of them use pgschema --file or the Rust expander. The CI path filter schema/** 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_check and _check1, community_deletion_requests_check1, moderation_reports_check and push_leases_check. Reconcile restores only relay_admin_actions_direct_shape.
  • idx_channels_id_live and community_deletion_requests_owner_quota_reservations lose their INCLUDE columns. Those columns become key columns.
  • The column order of the events PK 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 wpfleger96 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🤖 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.rs L1533–1537, L1560–1579: the layout guard matches words, not SQL. It drops -- comments but not /* */ ones, and it scans the inside of quoted strings. So CREATE /* x */ INDEX ... ON channels in a trigger file gets past it, a function error message that says DROP TABLE fails it, and a non-partition table with PARTITION OF inside 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.sql L37–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-completed line.

@TheSentinel454
TheSentinel454 merged commit 7455019 into main Oct 8, 2026
87 of 88 checks passed
@TheSentinel454
TheSentinel454 deleted the elrond/schema-per-table-files branch October 8, 2026 12:47
TheSentinel454 added a commit that referenced this pull request Nov 19, 2026
…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>

This branch was previously deployed

1 inactive deployment
codex-review — d141e501 Deployed Oct 8, 2026 by TheSentinel454 via Run Codex Security Review #7241
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants