Skip to content

buzz-db: drop the remaining relay foreign keys - #9740

Merged
TheSentinel454 merged 7 commits into
mainfrom
elrond/buzz-729-relay-fk-drops
Nov 19, 2026
Merged

TheSentinel454 merged 7 commits into
mainfrom
elrond/buzz-729-relay-fk-drops

Conversation

@TheSentinel454

@TheSentinel454 TheSentinel454 commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Contract step of the foreign-key retirement (docs/database.md Rule 2 and "Retiring a trigger, function, or foreign key"). Three migrations drop the 59 relay foreign keys left on main. After this PR, neither the desired state nor a migrated database has a foreign key.

Migration Drops Lock set
0102_drop_tenant_reference_fks.sql 25 keys between tenant tables 25 tables, no communities
0103_drop_community_fks.sql 32 community_id keys on unpartitioned tables 32 tables, then communities
0104_drop_event_table_community_fks.sql community_id keys on events and delivery_log, with the clone on every partition both parents and all partitions, then communities

The first commit also fixes one remaining dependence on a cascade. The account cleanup in user deletion deleted a member's join-policy acceptances in an earlier batch than the member row. An acceptance written while the member delete waited on the row lock was removed only by ON DELETE CASCADE. It now deletes those acceptances in the membership transaction, as delete_member_with_acceptances already does. Without the fix the run fails closed ("supported rows remain; rerun to resume"). User deletion has no production users yet, so the fix ships in this PR instead of its own release before the drop.

Phase and order

Locks

A lock probe on PostgreSQL 17 shows that ALTER TABLE ... DROP CONSTRAINT on a foreign key takes ACCESS EXCLUSIVE on the child and on the referenced table. On events it also takes ACCESS EXCLUSIVE on every partition. So each migration:

  • sets lock_timeout = '300ms' and statement_timeout = '800ms';
  • takes every lock it needs in one LOCK TABLE ... IN ACCESS EXCLUSIVE MODE, children first and communities last;
  • then drops the constraints, which only change the catalog.

The budgets end a blocked attempt before the 1s deadlock_timeout. A lock cycle with a relay query then fails this transaction, not the relay query. A failed attempt rolls back and can be retried. With auto-migration, the relay fails to start and retries on restart.

Deployments that apply schema out of band should apply each file in its own transaction. pgschema cannot drop a foreign key from a partitioned table, so deployments that bring an existing database up to date with pgschema apply 0104 first (docs/database.md). 0104 locks every events partition, so on a busy deployment apply it separately and retry it until it succeeds.

Community hard delete

With the community foreign keys gone, nothing in the database stops DELETE FROM communities. Production code never hard-deletes a community: deletion purges the children and tombstones the row. The existing source test every_production_single_table_guard_writer_preserves_its_invariants (crates/buzz-db/tests/observability_source.rs) already fails on any production DELETE FROM communities. It takes about 2.4s in CI.

Checklist (docs/database.md)

  • Phase: contract; prior and next steps above.
  • No trigger, function, procedure, rule, or foreign key is added.
  • No migration mutates rows. No backfill.
  • Contract dependency: on writers, not data. The required stop is named above. A row check cannot prove a writer release, so the migrations do not check rows.
  • Every Rule 4 location: migrations/, schema/tables/public/ (42 files), and docs. No schema/ manifest, seed or reconcile change is needed. pgschema cannot drop a foreign key from a partitioned table (it drops the parent's key, then fails on each partition's copy), so the test launchers run the new scripts/drop-partitioned-foreign-keys.sql (0104's drop, with 0104's locks and budgets) before apply: scripts/start-relay-for-tests.sh, which reuses its database, and the populated-upgrade test. docs/database.md now tells desired-state deployments to apply the dropping migration first. The push gateway is unaffected (its last key was dropped in push-gateway: drop the delegation → installation foreign key #9610).
  • Catalog parity: admin_schema_parity_between_desired_state_and_migrations now asserts zero foreign keys on both paths. Constraint names match on both paths (catalog dump on PostgreSQL 17).
  • The deployed relay works against the new schema. No code catches SQLSTATE 23503 or relies on a cascade (re-audited against main for parent deletes and child writes added since the inventory).
  • Lock and statement timeouts: above. No index is built.

What got simpler

  • 59 database objects removed. The schema is now plain tables, indexes and checks, which out-of-band apply needs.
  • Comments that hedged on "while the foreign key exists" now describe one behavior.
  • Two test helpers that dropped or rewrote foreign keys before a test (drop_foreign_keys_between, retire_foreign_key_delete_actions) are deleted, with their 33 calls.

Tests

The approval/request digest binding now rests on the app-side joins only. approval_boundary_blocks_claim_until_exact_inventory_is_approved tampers with each digest before the claim (claim refused) and after it (heartbeat and execution token fail closed, the lease is unchanged, and both work again once restored).

The review fixes were gated at 81fb046c: fmt (fixed in the next commit, then rechecked at 57aeabf9), clippy, the 220 unit tests, the approval and upgrade Postgres tests, the parity test, and the helper SQL. The full results below are from ec34cc2e, before the review fixes.

  • cargo fmt --check and cargo clippy -p buzz-db --all-targets -D warnings: pass.
  • cargo test -p buzz-db --lib: 220 passed.
  • Full buzz-db Postgres lane (scripts/postgres-test-run.sh -p buzz-db --lib --tests): 859 of 860 passed. The failure is media_reference_full_query_plans (statement timeout). Its fixture builds its own tables with no foreign keys, and it fails the same way on main (7e7ec731) on the same workstation, so it is not caused by this PR.
  • Mutants (each failed as expected):
    • remove one drop from 0103 → admin_schema_parity_between_desired_state_and_migrations fails ("migrations leave a foreign key");
    • keep a REFERENCES in schema/tables/public/events.sql → the same test fails ("desired state has a foreign key");
    • remove the new acceptance delete → membership_delete_removes_acceptance_recorded_after_acceptance_batch fails.

buzz-review-completed

🤖 Generated with Claude Code

TheSentinel454 and others added 5 commits November 19, 2026 15:07
The account cleanup deletes a member's join-policy acceptances in one
batch and the relay_members row in a later transaction. An acceptance
whose writer commits while the member delete waits on the row lock
stays behind. Today the foreign key's ON DELETE CASCADE removes it.
Without the foreign key, the run would stop with "supported rows
remain; rerun to resume" and need a second pass.

docs/database.md Rule 2 requires the parent's transaction to delete its
dependent rows. Delete the member's acceptances in the membership
transaction, under the member row lock, as
delete_member_with_acceptances already does. The new Postgres test
drops the foreign key first, so the cascade cannot hide a missing
delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Contract step of the foreign-key retirement (docs/database.md Rule 2).
The app-side checks and explicit deletes shipped in #9399, #9404 and
#9608. Three migrations drop the 59 foreign keys left on main:

- 0102: the 25 keys between tenant tables;
- 0103: the 32 community_id keys on unpartitioned tables;
- 0104: the community_id keys on events and delivery_log, with the
  clone on every partition.

Each drop takes ACCESS EXCLUSIVE on the child and the referenced table
(PostgreSQL 17 lock probe). Each migration takes all of its locks in one
LOCK TABLE, children first, with lock_timeout 300ms and
statement_timeout 800ms, so it fails before the 1s deadlock_timeout
instead of a relay query.

schema/tables/public drops every REFERENCES and FOREIGN KEY clause. The
desired-state and migrated parity test now asserts zero foreign keys on
both paths, and the 0029 drift test ignores the dropped clauses. Stale
"while the foreign key exists" comments are updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Tests no longer need to drop foreign keys first: the schema has none.
Delete drop_foreign_keys_between and retire_foreign_key_delete_actions,
and their calls. The deletion approval test now checks that a tampered
digest on either side grants no claim, since no key binds them.

pgschema cannot drop a foreign key from a partitioned table: it drops
the parent's constraint, then each partition's copy, which is already
gone. scripts/drop-partitioned-foreign-keys.sql drops the two keys
first. start-relay-for-tests.sh (which reuses its database) and the
populated-upgrade test run it before apply.

The 0102 header names the required stop as #9608 or later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Normalize both sides with without_foreign_keys, and drop the loop over
one invariant (clippy::single_element_loop).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
@TheSentinel454
TheSentinel454 marked this pull request as ready for review November 19, 2026 20:35
@github-actions github-actions Bot added the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 19, 2026
@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

🔐 Codex Security Review

Note: This is an automated, security-focused review generated by Codex.
Use it as a supplement to human review; false positives are possible.

Scope

  • Exact PR diff: 7e7ec731cd6d756ac487245643449b19fb836bd3...57aeabf919442044b36b40e7ddbd5e9d9d88b568
  • Model: gpt-6.1-sol

💡 Click "edited" above to see earlier reviews for this PR.


Review Summary

Overall Risk: NONE

No concrete security, correctness, or reliability regressions found in the authorized PR range.

Findings

No concrete security, correctness, or reliability findings were identified.

Notes

  • Review used read-only source and history inspection. Builds and tests were not executed.

Generated by Codex Security Review |
Requested by: @TheSentinel454 |
Workflow run

- drop-partitioned-foreign-keys.sql takes 0104's locks in one statement
  within 0104's budgets, and says it is for the test launchers only.
- docs/database.md: desired-state deployments apply the dropping
  migration before pgschema, which cannot drop a trigger or foreign key
  from a partitioned table.
- The approval boundary test now also tampers with each digest after the
  claim, and checks that heartbeat and the execution token fail closed
  without changing the lease, then work again once the digest is restored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
@github-actions github-actions Bot removed the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 19, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
@github-actions github-actions Bot added the codex-security-review-current The posted Codex security review matches its recorded range. label Nov 19, 2026

@joahg joahg 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.

🤖 Checked 0102-0104: they are DDL-only DROP CONSTRAINTs (no row changes, no data loss), the lock sets are taken children-first under 300ms/800ms budgets, and the parity test now asserts zero foreign keys on both the migrated and desired-state paths. I traced each former CASCADE/SET NULL key to an explicit delete or guard on main (workflow children in workflow/deletion.rs, personal_read_frontiers before accounts, join_policy_acceptances in both removal paths and the new user-deletion fix, owned-agent links refused rather than nulled in profile_batches/plan.rs, product_feedback and manifest keys in the purge), and the tests that used to retire cascades now run with none. PostgreSQL CI is green. Remaining risk is operational, not a blocker: locking 25 busy tables (and every events partition in 0104) within 300ms can fail repeatedly under load, so watch the first rollout for relay restart loops, and the documented 'no rollback below #9608' stop is the only protection against an older build.

@TheSentinel454
TheSentinel454 merged commit 729cb10 into main Nov 19, 2026
92 checks passed
@TheSentinel454
TheSentinel454 deleted the elrond/buzz-729-relay-fk-drops branch November 19, 2026 22:51
TheSentinel454 added a commit that referenced this pull request Nov 19, 2026
#9740 dropped the subscriptions foreign keys. Final user removal no
longer fails on a retained row, so the profile cleanup guard blocks
nothing real. Remove it with its test and doc paragraph. The retiring
table test now seeds stragglers without lifting a constraint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
morgmart added a commit that referenced this pull request Nov 20, 2026
…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

This branch was successfully deployed

1 active deployment
codex-review — 57aeabf9 Deployed Nov 19, 2026 by TheSentinel454 via Run Codex Security Review #16478
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex-security-review-current The posted Codex security review matches its recorded range.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants