Repository navigation
push-gateway: drop the delegation → installation foreign key - #9610
Conversation
🔐 Codex Security Review
Review SummaryOverall Risk: NONE
FindingsNo concrete security, correctness, or reliability findings were identified. Notes
Generated by Codex Security Review | |
f99448b to
9cb4c0c
Compare
9cb4c0c to
dcbccbe
Compare
Rebased off #9610 onto main, which ends at 0094, so the drop is 0095. A build between #9363 and #9615 is not a valid 0094 stop, so the shared stop must also satisfy 0094's rule, not only come before it. Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Luke Tornquist <tornquist@squareup.com>
## What The push gateway reaper deletes expired delegations and then expired installations in two statements. A delegation writer (`upsert_delegation`) that holds the installation lock can commit a new child between them. With the foreign key, the installation delete then fails, and the reap transaction rolls back. This PR locks the expired installations with `FOR UPDATE` first, as every authority mutation does. It then deletes their delegations and the installations by id. A writer that was holding the lock commits first, and the delete sees its child. A later writer finds the parent gone and is rejected. No schema change. This is the code half of #9610. The gateway image with this change must run everywhere before the delegation foreign key is dropped. ## Tests Blox at `20b66f8f`: fmt, clippy, and the push-gateway PostgreSQL tests (15/15) pass. - `reaper_deletes_delegation_committed_while_it_waits`: a writer holds the installation lock and inserts a child. The reaper starts and waits. The writer commits. The reaper deletes both rows. - `delegation_for_missing_installation_is_rejected`: `upsert_delegation` for an unknown installation returns `Rejected` and writes nothing. ## What got simpler The reaper now uses the same lock order as every other authority write. The child delete no longer needs a correlated subquery. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
dcbccbe to
bfab773
Compare
wpfleger96
left a comment
There was a problem hiding this comment.
🤖 Automated review at bfab7738: changes requested.
Blocking: relay migration number collision. #9398 merged into main and owns migrations/0096_drop_single_table_guards.sql. This PR adds migrations/0096_drop_push_gateway_delegation_fk.sql, so main would end up with two version-96 migrations. The migration-count test in crates/buzz-db/src/runtime/migration.rs also conflicts, because main already asserts 96 migrations. GitHub reports the branch as conflicting. Rebase onto main, rename the relay migration to 0097_drop_push_gateway_delegation_fk.sql, and update the test to expect 97 migrations with migrations[96].version == 97.
No other findings. The gateway migration's constraint name matches the default Postgres name for the inline REFERENCES in gateway migration 0001 and relay migration 0015. The relay copy uses IF EXISTS, and the hand-built test schema and declarative schema both drop the reference.
bfab773 to
33f7df9
Compare
wpfleger96
left a comment
There was a problem hiding this comment.
🤖 Automated review at 33f7df90: no blocking findings.
The migration number collision from the earlier review is fixed. The relay migration is now 0098, main ends at 0097, and the count test expects 98 migrations.
What was checked:
- Constraint name. Gateway
0001and relay0015both declare the reference inline without a name, so Postgres names itpush_gateway_delegations_installation_id_fkey, which is what both drops use. Both bound the lock withlock_timeout = '5s'. - The app holds the reference without the FK.
upsert_delegationlocks the installationFOR UPDATEbefore it writes a delegation.create_installationandreap_expiredlock the parent installations before deleting their delegations and then the installations. #9627, which added the reaper lock, is on main. - Running it. Fresh gateway and relay installs and populated upgrades from the base reach versions 8 and 98 with no delegation FK and no row changes. Both drops fail cleanly at about 5 seconds under a held writer lock and succeed on retry. Nine deterministically ordered races between the real reaper and
upsert_delegation(writer first with an expired delegation, writer first with a renewal, reaper first) left no orphaned delegation. The gateway andbuzz-dbPostgres suites pass.
Non-blocking suggestion: migrations/0098_drop_push_gateway_delegation_fk.sql tolerates a missing constraint but not a missing table, because ALTER TABLE has no IF EXISTS. Relay migration 0015 and the desired-state schema both create the table, so no supported upgrade hits this. If a relay database without the legacy table should be able to migrate, use ALTER TABLE IF EXISTS.
Rollout: as the description says, every gateway and rollback target must run #9627 (44cdd9fe) or later before gateway migration 0008 runs. The Helm chart runs migrations before it replaces replicas, so shipping #9627 and this PR in one rollout does not satisfy that.
The gateway already checks this reference in its own transactions: upsert_delegation locks the installation FOR UPDATE and rejects a missing or revoked one, the reaper locks expired installations before it deletes them and their delegations (#9627), and delivery rejects a delegation whose installation is gone. Gateway migration 0008 drops the constraint. Relay migration 0101 drops the relay's legacy copy (docs/database.md Rule 4); no relay code reads or writes these tables. Required stop: every gateway must run #9627 or later before this ships. Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Luke Tornquist <tornquist@squareup.com>
33f7df9 to
ba8a96b
Compare
wpfleger96
left a comment
There was a problem hiding this comment.
🤖 Automated review at ba8a96b0: no blocking findings.
Since the last review at 33f7df90, the only change is the rebase that renames the relay migration to 0101. Its SQL is unchanged. Main still ends at 0100, and the count test expects 101 migrations with migrations[100].version == 101.
What was checked:
- Numbering. Gateway
0008follows0007. Relay0101follows main's0100. - The drops. Both name the default constraint
push_gateway_delegations_installation_id_fkeyfrom the inlineREFERENCESin gateway0001and relay0015, and both setlock_timeout = '5s'first. The declarative schema and the hand-built test schema drop the reference too, and the relay parity test now coverspush_gateway_delegations. - Rule 5 ordering. #9627 (
44cdd9fe), which makes the reaper lock installations before deleting them, is on the base. The application checks listed in the description are the ones the gateway runs. - CI is green at this head, including the PostgreSQL suite that runs the new
migrated_schema_has_no_foreign_keystest and the relay parity test.
Non-blocking suggestion: the required stop (every gateway and rollback target on #9627 or later before gateway 0008 runs) is written only in the migration comment and this description. docs/database.md asks release notes to name the stop, and the changelog is generated from commit subjects. The relay records its required stops in deploy/charts/buzz/README.md, and the gateway chart README already lists upgrade prerequisites. A short "Required stop before gateway migration 0008" note in deploy/charts/buzz-push-gateway/README.md would put it where operators look. If an operator skips it, the cost is low: an orphaned delegation is rejected by authorize_delivery, so the only effect is a dead row.
wpfleger96
left a comment
There was a problem hiding this comment.
🤖 Approving at ba8a96b0. No blocking findings.
- Both drops name the default inline-FK constraint from gateway
0001and relay0015, and both bound the lock withlock_timeout. Numbering follows main (gateway0008, relay0101). - Every delete of an installation (
create_installation,reap_expired) locks itFOR UPDATEand deletes its delegations first.upsert_delegationtakes the same lock and rejects a missing or revoked installation, andauthorize_deliveryrejects a delegation whose installation is gone. The gateway's readiness check doesn't depend on the constraint. - The one rollout risk is the stated stop: the gateway's pre-upgrade Helm job runs
0008while old pods are still serving, so every running and rollback gateway needs #9627. If one is missed, the cost is an orphaned delegation that delivery rejects and the reaper removes when it expires. No wrong delivery and no data loss.
Gateway 0007 added installations.platform and 0008 dropped the delegation -> installation foreign key (#9610). Mirror both in schema/: add the platform column and drop the inline REFERENCES, so the desired state no longer brings the FK back. List the gateway schema/ directory under docs/database.md Rule 4. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
…c-spec-mobile * origin/main: push-gateway: drop the delegation → installation foreign key (#9610) Match desktop unread cues on mobile channel rows (#9715) feat(mobile): refresh Huddle speaking styles and iOS controls (#9716) feat(cli): add raw query and publish escape-hatch commands (#9653) fix(mobile): only say "Community changed" when the community changed (#9156) chore: require relay owner review for the relay and db crates (#9728) fix(mobile): align Huddle cards and preserve conversation navigation (#9713) Match mobile mention chips to desktop styling (#9706) feat(relay): push mentions to people outside a listed channel (#9623) fix(db): undo migration 0097 (#9710) Signed-off-by: Will Pfleger <wpfleger@block.xyz>
…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>
…ead-dot * origin/main: (34 commits) Fix media deletion’s community ownership and share agent discovery (#9670) buzz-db: drop the remaining relay foreign keys (#9740) perf(mobile): hash upload payloads in bounded worker chunks (#9747) feat(read-state): sync mark read, channel mark unread and thread follows (#9501) Fix shared stars and mutes in mobile and CLI (#9684) fix(mobile): keep active iOS Huddles connected while locked (#9682) fix(mobile): hash upload payloads off the UI isolate (#9736) perf(relay): serve named-only channel access from the access caches (#9735) fix(mobile): stop notification extension sending cookies to Builderlab (#9741) Remove personal workflow data and missed event copies (#9675) fix(relay): rename target log field to target_pubkey (#9739) feat(push-gateway): declarative desired-state schema, one file per table (#8328) test(cli): keep the raw refusal exit test independent of BUZZ_* env (#9733) docs(nip-pm): define pinned messages (#9712) push-gateway: drop the delegation → installation foreign key (#9610) Match desktop unread cues on mobile channel rows (#9715) feat(mobile): refresh Huddle speaking styles and iOS controls (#9716) feat(cli): add raw query and publish escape-hatch commands (#9653) fix(mobile): only say "Community changed" when the community changed (#9156) chore: require relay owner review for the relay and db crates (#9728) ... Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> # Conflicts: # mobile/lib/features/activity/activity_page.dart # mobile/lib/features/channels/channel_unread.dart
Summary
Retire the last foreign key in the push gateway schema:
push_gateway_delegations.installation_id → push_gateway_installations(id). This followsdocs/database.mdRule 2 and the relay FK retirement work (#9399, #9404).schema/tables/public/push_gateway_delegations.sqlloses the inlineREFERENCES.Required stop
Every gateway and rollback target must run #9627 (
44cdd9fe) or later before this merges and deploys. #9627 makes the reaper lock expired installations before it deletes their delegations. Without the FK, an older reaper can leave an orphaned delegation. This is step 2 of the Rule 5 retirement sequence; #9627 is step 1.Why the app already enforces the reference
upsert_delegation(only delegation insert)FOR UPDATEin the same transaction; rejects a missing or revoked one.create_installation(replaces expired installations)FOR UPDATE, deletes their delegations, then the installations.reap_expiredFOR UPDATE, deletes their delegations, then the installations (#9627).authorize_deliveryRejected.revoke_delegationrevoke_installation,rotate_endpoint,advance_assertion_counterThe relay never reads or writes the
push_gateway_*tables (the gateway requires its own database), so dropping the relay copy changes no relay behavior.Tests
The gateway tests run against the migrated schema, which no longer has the FK, so they prove the app check.
migrated_schema_has_no_foreign_keys(new): the gateway schema has no foreign keys after migrations. It fails if gateway migration 0008 is removed.delegation_for_missing_installation_is_rejectedandreaper_deletes_delegation_committed_while_it_waits(from push-gateway: lock expired installations before reaping #9627) now run without the FK.reaper_retains_revocation_tombstones_until_authority_expiry: its hand-built schema drops the FK too.push_gateway_delegationsjoins the constraint parity check inadmin_schema_parity_between_desired_state_and_migrations, and the migration count test covers 0101.Validation
Blox at
33f7df90(before the rename to 0101; CI covers the rebased head):cargo fmt --check, clippy (buzz-push-gateway,buzz-db, all targets), gateway unit tests,buzz-dbmigration unit tests: pass.scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests: 16/16 pass.buzz-dbPostgres tests for migrations, parity, push, floor retirement and retained guards: 56/56 pass, includingadmin_schema_parity_between_desired_state_and_migrations.migrated_schema_has_no_foreign_keysfails (1 foreign key vs 0).Coordination
What got simpler
One fewer database object. Every gateway reference check now lives in one place: the gateway's own transactions.
buzz-review-completed
🤖 Generated with Claude Code