From 4e8f836576c457c2fd51a1a0072240fd7d95aecf Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Tue, 17 Nov 2026 13:44:33 -0500 Subject: [PATCH] buzz-db: drop the community_deletion_lock_key and profile_name_fields functions (contract) (#9598) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Phase 2 of retiring the two remaining plain SQL functions. Phase 1 moved their work into the relay: - #9396 builds the community deletion lock key in Rust (`deletion::community_deletion_lock_key`, locked with `hashtextextended($1, 0)`). - #9397 reads profile names with inline SQL (`PROFILE_NAME_FIELDS` in `buzz-search`). No relay at or after #9397's merge (`279a31da`) calls either function. This PR drops them: - **Migration 0093** runs `DROP FUNCTION community_deletion_lock_key(UUID)` and `DROP FUNCTION profile_name_fields(TEXT)` under a 5s `lock_timeout`, with no `IF EXISTS` and no `CASCADE`. If anything still depends on a function, the migration fails instead. Migrations 0029 and 0064 stay frozen. No database function calls either one any more: 0090 dropped the fence functions, which were the only SQL callers of the lock key. - **Desired state:** removes both `schema/functions/` files and their `schema.sql` includes. Both boot paths stay catalog-equivalent (`admin_schema_parity_between_desired_state_and_migrations`). - **Tests:** - New `migration_0093_drops_plain_sql_functions`. It migrates to 0092, checks that both functions exist and that serving and deletion catalog validation pass, then runs 0093 and checks that both functions are gone and that validation still passes. This covers new code on either side of the drop. - The migration listing test pins 0093's statements and that it has no `CASCADE`. - `desired_state_catalog_has_no_universal_fence_and_still_boots` now asserts that both functions are absent. - Replaces the Rust-vs-SQL lock key parity test with `community_deletion_lock_key_bytes_are_fixed`, a unit test that maps fixed UUIDs (nil, max, and one with hex letters) to their exact keys. Older replicas and the repair-script key in `docs/database.md` build the same string, so a changed prefix or UUID format must fail a test. - Removes two relay test-schema wrappers (`bridge.rs`, `ingest.rs`) that forwarded `community_deletion_lock_key` to `public`. Writers no longer call it, and the wrapper's `CREATE FUNCTION` would fail once the function is gone. - **Docs:** `docs/trigger-retirement-deployment.md` gets a `0093` section with the required stop. ## Deploy gate **Required stop:** any relay build at or after `279a31da` (#9397's merge, which follows #9396). `relay-v0.3.0` does not contain it. A relay older than that which still serves after 0093 fails every write and deletion that takes the community deletion lock, with `42883 community_deletion_lock_key(uuid) does not exist`, and its profile name search fails with `42883 profile_name_fields(text) does not exist`. 0093 takes no table locks and needs no cleanup. Migration number: #8696 and #9398 also propose `0093`. Whichever lands second renumbers. ## Review-Proven Rules - **RPR #2 (every path):** I checked every reference on `main` and at the stop build `279a31da`. At both, only test code reads either function: no boot, readiness, catalog or runtime query depends on them. Serving and deletion catalog validation pass before and after 0093, in the new test. - **RPR #3 (falsifiable):** removing the `profile_name_fields` drop from 0093 turns `migration_0093_drops_plain_sql_functions` red. - **RPR #3 (lock key bytes):** a changed prefix, `.simple()` UUID formatting, or uppercase formatting each turns `community_deletion_lock_key_bytes_are_fixed` red. ## What got simpler Two database functions, their desired-state files, a cross-language parity test and two test-only SQL wrappers are gone. After this PR, the only functions left in `schema/functions/` are trigger functions. ## Validation Blox gate at `95ac71c8`: - `cargo fmt --all --check`, and `cargo clippy -p buzz-db -p buzz-relay --all-targets -D warnings`. - `buzz-db --lib` unit tests: 216/216, including the migration listing test. - `buzz-db` Postgres tests (`migration::`, `deletion::`, `nip_fi_binding::` postgres_tests): 130/130. These include `migration_0093_drops_plain_sql_functions`, `admin_schema_parity_between_desired_state_and_migrations` and `deletion_surface_parity_between_migration_0029_and_schema_sql`. - `buzz-search` `profile_names*` Postgres tests: 4/4, on a fully migrated database where `profile_name_fields` no longer exists. - The two relay tests whose test-schema wrapper this PR removes: 2/2. - Must-fail check: with the `profile_name_fields` drop removed from 0093, `migration_0093_drops_plain_sql_functions` fails. Second Blox gate at `e1b5513a` (the lock key vector test): - `cargo fmt --all --check`, and `cargo clippy -p buzz-db --all-targets -D warnings`. - `buzz-db --lib` unit tests: 217/217. - Must-fail checks: a changed prefix, `.simple()` and uppercase UUID formatting each fail `community_deletion_lock_key_bytes_are_fixed`. The first gate run found that `deletion_surface_parity_between_migration_0029_and_schema_sql` still expected `community_deletion_lock_key` in `schema.sql`. The second commit fixes that. 🤖 Generated with [Claude Code](https://claude.com/claude-code) buzz-review-completed --------- Signed-off-by: Luke Tornquist Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 --- crates/buzz-db/src/runtime/migration.rs | 74 +++++++++++++++++-- crates/buzz-db/src/store/deletion.rs | 57 +++++++------- crates/buzz-relay/src/api/bridge.rs | 9 +-- crates/buzz-relay/src/handlers/ingest.rs | 4 +- docs/trigger-retirement-deployment.md | 22 ++++++ migrations/0093_drop_plain_sql_functions.sql | 8 ++ .../functions/community_deletion_lock_key.sql | 4 - schema/functions/profile_name_fields.sql | 24 ------ schema/schema.sql | 2 - 9 files changed, 131 insertions(+), 73 deletions(-) create mode 100644 migrations/0093_drop_plain_sql_functions.sql delete mode 100644 schema/functions/community_deletion_lock_key.sql delete mode 100644 schema/functions/profile_name_fields.sql diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 2a3d4782df..ef6240b088 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -1033,6 +1033,22 @@ mod postgres_tests { < retire_nip_rs.find("DROP TRIGGER").unwrap(), "0091 must bound its ACCESS EXCLUSIVE lock on events before the first DROP" ); + // The relay builds the deletion lock key in Rust and reads profile + // names inline, so 0093 drops both plain SQL functions. 0029 and 0064 + // stay frozen. + assert_eq!(migrations[92].version, 93); + let retire_functions = strip_sql_comments(migrations[92].sql.as_str()); + for statement in [ + "SET LOCAL lock_timeout = '5s';", + "DROP FUNCTION community_deletion_lock_key(UUID);", + "DROP FUNCTION profile_name_fields(TEXT);", + ] { + assert!( + retire_functions.contains(statement), + "0093 must run {statement}" + ); + } + assert!(!retire_functions.contains("CASCADE")); assert_eq!(migrations[55].version, 56); assert!(migrations[55] .sql @@ -1517,7 +1533,6 @@ mod postgres_tests { ] { assert!(retirement.contains(&format!("DROP FUNCTION {signature};"))); } - assert!(!retirement.contains("DROP FUNCTION community_deletion_lock_key")); assert!(!retirement.contains("DROP FUNCTION enforce_community_tombstone")); assert!(deletion.contains("community tombstones are permanent")); assert!(deletion.contains("SET LOCAL lock_timeout = '5s'")); @@ -2556,6 +2571,7 @@ mod postgres_tests { "assert_community_write_allowed", "enforce_community_write_fence", "attach_community_write_fence", + "community_deletion_lock_key", ] .contains(&function.as_str()) { @@ -3963,14 +3979,13 @@ mod postgres_tests { .await .expect("count retired functions"); assert_eq!(fence_functions, 0); - let retained: (bool, bool) = sqlx::query_as( - "SELECT to_regprocedure('community_deletion_lock_key(uuid)') IS NOT NULL, \ - EXISTS(SELECT 1 FROM pg_trigger WHERE tgname = 'communities_deletion_tombstone')", + let tombstone: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM pg_trigger WHERE tgname = 'communities_deletion_tombstone')", ) .fetch_one(&pool) .await - .expect("read retained guards"); - assert_eq!(retained, (true, true)); + .expect("read retained guard"); + assert!(tombstone); store .validate_serving_catalog() .await @@ -3981,6 +3996,53 @@ mod postgres_tests { .expect("deletion catalog must accept post-retirement catalog"); } + /// 0093 drops both plain SQL functions, and the relay boots on either + /// side of it: rolling deploys run new code before and after the drop. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn migration_0093_drops_plain_sql_functions() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + let retirement = MIGRATOR + .iter() + .find(|m| m.description == "drop plain sql functions") + .expect("function retirement migration is embedded") + .version; + async fn present(pool: &PgPool) -> (bool, bool) { + sqlx::query_as( + "SELECT to_regprocedure('community_deletion_lock_key(uuid)') IS NOT NULL, \ + to_regprocedure('profile_name_fields(text)') IS NOT NULL", + ) + .fetch_one(pool) + .await + .expect("look up plain SQL functions") + } + let store = crate::deletion::DeletionStore::new(pool.clone()); + MIGRATOR + .run_to(retirement - 1, &pool) + .await + .expect("apply pre-retirement migrations"); + assert_eq!(present(&pool).await, (true, true)); + store + .validate_serving_catalog() + .await + .expect("new code must boot before the drop"); + store + .validate_catalog() + .await + .expect("deletion must accept the catalog before the drop"); + run_migrations(&pool).await.expect("apply all migrations"); + assert_eq!(present(&pool).await, (false, false)); + store + .validate_serving_catalog() + .await + .expect("new code must boot after the drop"); + store + .validate_catalog() + .await + .expect("deletion must accept the catalog after the drop"); + } + /// Verify migration 0044 applies cleanly against a DB that has rows in /// the NIP-FI 0041+0042 tables. The immutability guards (no_delete, /// no_truncate) are enforced via triggers; DROP TABLE bypasses them and diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index e3f244a0ba..3645edb9eb 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -48,10 +48,9 @@ pub const SCHEMA_DESTRUCTION_LOCK_KEY: i64 = 0x62757a7a64656c31; /// `hashtextextended($1, 0)`. /// /// Deletion takes the lock exclusively and community writers take it shared. -/// The bytes must equal the SQL function -/// `community_deletion_lock_key(uuid)` (`'buzz-community-deletion:' || -/// target::text`) for as long as any relay or database function still uses -/// it, or deletion and writers stop excluding each other. +/// The bytes are permanent: operator repair scripts build the same key +/// (`docs/database.md`), and a replica holding an older key during a rolling +/// deploy would stop excluding deletion. pub fn community_deletion_lock_key(community: CommunityId) -> String { format!("buzz-community-deletion:{}", community.as_uuid()) } @@ -4099,6 +4098,28 @@ fn bound_text(input: &str, max: usize) -> String { mod tests { use super::*; + /// The key bytes are permanent: older replicas and operator repair + /// scripts build the same string, so any change splits the lock. + #[test] + fn community_deletion_lock_key_bytes_are_fixed() { + for (id, key) in [ + ( + Uuid::nil(), + "buzz-community-deletion:00000000-0000-0000-0000-000000000000", + ), + ( + Uuid::max(), + "buzz-community-deletion:ffffffff-ffff-ffff-ffff-ffffffffffff", + ), + ( + Uuid::from_u128(0x0123_4567_89ab_cdef_fedc_ba98_7654_3210), + "buzz-community-deletion:01234567-89ab-cdef-fedc-ba9876543210", + ), + ] { + assert_eq!(community_deletion_lock_key(CommunityId::from_uuid(id)), key); + } + } + /// Every table an approval may gain is one this release purges and /// verifies, and every pending table may be gained after approval. #[test] @@ -4771,14 +4792,15 @@ mod postgres_tests { .await .expect("lookup retired function"); assert!(!retired_function); - let retained: (bool, bool) = sqlx::query_as( + let retired: (bool, bool, bool) = sqlx::query_as( "SELECT to_regprocedure('community_deletion_lock_key(uuid)') IS NOT NULL, \ + to_regprocedure('profile_name_fields(text)') IS NOT NULL, \ EXISTS(SELECT 1 FROM pg_trigger WHERE tgname = 'communities_deletion_tombstone')", ) .fetch_one(&db.pool) .await - .expect("lookup retained guards"); - assert_eq!(retained, (true, true)); + .expect("lookup retired functions and retained guard"); + assert_eq!(retired, (false, false, true)); } #[tokio::test] @@ -4921,27 +4943,6 @@ DROP FUNCTION community_deletion_lock_key(UUID); } } - /// Mixed-version fleets lock through both the Rust key and the SQL - /// function until the function is dropped; they must name the same lock. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn community_deletion_lock_key_matches_the_sql_function() { - let (db, _) = store().await; - let mut communities = vec![Uuid::nil(), Uuid::max()]; - communities.extend((0..64).map(|_| Uuid::new_v4())); - for id in communities { - let community = CommunityId::from_uuid(id); - let (rust_lock, sql_lock): (i64, i64) = - sqlx::query_as("SELECT hashtextextended($1, 0), community_deletion_lock_key($2)") - .bind(community_deletion_lock_key(community)) - .bind(id) - .fetch_one(&db.pool) - .await - .expect("hash lock keys"); - assert_eq!(rust_lock, sql_lock, "lock key drifted for {id}"); - } - } - #[tokio::test] #[ignore = "requires Postgres"] async fn migration_schema_single_table_guards_are_optional_for_serving_and_deletion() { diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 31cae9b12b..7429c411c3 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -11169,9 +11169,8 @@ pub(crate) mod postgres_tests { .expect("local Postgres and Redis"); // A schema whose `users` table can be taken away after the link, // so only the owner-to-agent lookup fails at revoke time. It - // carries `communities` and the deletion lock key so writes pass - // community write admission, and `events` for the member list - // each membership change writes. + // carries `communities` so writes pass community write admission, + // and `events` for the member list each membership change writes. let db_url = crate::test_support::database_url(); let schema = format!("late_owner_{}", uuid::Uuid::new_v4().simple()); sqlx::raw_sql(sqlx::AssertSqlSafe(format!( @@ -11183,9 +11182,7 @@ pub(crate) mod postgres_tests { CREATE TABLE {schema}.join_policy_acceptances \ (LIKE public.join_policy_acceptances INCLUDING ALL); \ CREATE TABLE {schema}.communities (LIKE public.communities INCLUDING ALL); \ - CREATE TABLE {schema}.events (LIKE public.events INCLUDING ALL); \ - CREATE FUNCTION {schema}.community_deletion_lock_key(target UUID) RETURNS BIGINT \ - LANGUAGE SQL IMMUTABLE STRICT AS 'SELECT public.community_deletion_lock_key(target)';" + CREATE TABLE {schema}.events (LIKE public.events INCLUDING ALL);" ))) .execute(state.db.pool()) .await diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 99ac76628b..2f2ce7257c 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -8328,9 +8328,7 @@ mod postgres_tests { CREATE TABLE {schema}.users (LIKE public.users INCLUDING ALL); \ CREATE TABLE {schema}.relay_invites (LIKE public.relay_invites INCLUDING ALL); \ CREATE TABLE {schema}.community_bans (LIKE public.community_bans INCLUDING ALL); \ - CREATE TABLE {schema}.communities (LIKE public.communities INCLUDING ALL); \ - CREATE FUNCTION {schema}.community_deletion_lock_key(target UUID) RETURNS BIGINT \ - LANGUAGE SQL IMMUTABLE STRICT AS 'SELECT public.community_deletion_lock_key(target)';" + CREATE TABLE {schema}.communities (LIKE public.communities INCLUDING ALL);" ))) .execute(&admin) .await diff --git a/docs/trigger-retirement-deployment.md b/docs/trigger-retirement-deployment.md index 60bcaab127..c3162f0080 100644 --- a/docs/trigger-retirement-deployment.md +++ b/docs/trigger-retirement-deployment.md @@ -70,3 +70,25 @@ With it on, the stop build refuses a database that has migrations it does not know (`VersionMissing`) and does not start. With it off, the stop build serves, but its startup check finds the floor trigger gone and keeps the replica fence closed, so cursor reads go to the writer. + +## Plain SQL functions (`0093`) + +`0093_drop_plain_sql_functions.sql` drops two functions whose work the relay +now does in application code: + +| Function | Application replacement | +| --- | --- | +| `community_deletion_lock_key(uuid)` | the Rust-built lock key, [#9396](https://github.com/block/buzz/pull/9396) | +| `profile_name_fields(text)` | inline profile-name SQL, [#9397](https://github.com/block/buzz/pull/9397) | + +**A relay build at or after commit `279a31da` (the merge of +[#9397](https://github.com/block/buzz/pull/9397), which follows #9396) and +before `0093` is a required stop.** No tagged relay release contains it: +`relay-v0.3.0` does not, so a deployment on a tagged release must move to a +stop build first. Follow the same procedure as above. An older relay that +still serves after `0093` fails every write and deletion that takes the community deletion lock, with +`42883 community_deletion_lock_key(uuid) does not exist`, and its profile name +search fails with `42883 profile_name_fields(text) does not exist`. + +`0093` takes no table locks. It needs no cleanup, and a rollback to a stop +build needs auto-migration off, as above. diff --git a/migrations/0093_drop_plain_sql_functions.sql b/migrations/0093_drop_plain_sql_functions.sql new file mode 100644 index 0000000000..b87a8a01ed --- /dev/null +++ b/migrations/0093_drop_plain_sql_functions.sql @@ -0,0 +1,8 @@ +SET LOCAL lock_timeout = '5s'; + +-- The relay builds the community deletion lock key in Rust (#9396) and reads +-- profile names with inline SQL (#9397). No supported relay calls either +-- function. Migrations 0029 and 0064 stay frozen. Neither drop uses CASCADE: +-- if anything still depends on a function, the migration fails instead. +DROP FUNCTION community_deletion_lock_key(UUID); +DROP FUNCTION profile_name_fields(TEXT); diff --git a/schema/functions/community_deletion_lock_key.sql b/schema/functions/community_deletion_lock_key.sql deleted file mode 100644 index 8864ede390..0000000000 --- a/schema/functions/community_deletion_lock_key.sql +++ /dev/null @@ -1,4 +0,0 @@ -CREATE FUNCTION community_deletion_lock_key(target UUID) RETURNS BIGINT -LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE AS $$ - SELECT hashtextextended('buzz-community-deletion:' || target::text, 0) -$$; diff --git a/schema/functions/profile_name_fields.sql b/schema/functions/profile_name_fields.sql deleted file mode 100644 index 5a4b6cd43f..0000000000 --- a/schema/functions/profile_name_fields.sql +++ /dev/null @@ -1,24 +0,0 @@ --- Profile name search reads `name` and `display_name` from stored kind:0 --- content. Content is any text the signer chose, and some valid JSON cannot --- become jsonb (for example `\u0000`, a lone surrogate, a huge number or very --- deep nesting). Such content has no searchable names; it must never make the --- whole search query fail. Only string values count as names. -CREATE FUNCTION profile_name_fields(content TEXT, OUT name TEXT, OUT display_name TEXT) -LANGUAGE plpgsql IMMUTABLE STRICT AS $$ -DECLARE - doc JSONB; -BEGIN - doc := content::jsonb; - IF jsonb_typeof(doc) = 'object' THEN - IF jsonb_typeof(doc -> 'name') = 'string' THEN - name := doc ->> 'name'; - END IF; - IF jsonb_typeof(doc -> 'display_name') = 'string' THEN - display_name := doc ->> 'display_name'; - END IF; - END IF; -EXCEPTION WHEN OTHERS THEN - name := NULL; - display_name := NULL; -END -$$; diff --git a/schema/schema.sql b/schema/schema.sql index 2c8ddeb16d..4c60a0537a 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -67,9 +67,7 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; \i functions/prevent_community_deletion_request_retargeting.sql \i functions/prevent_community_deletion_approval_removal.sql \i functions/protect_community_deletion_manifest_keys.sql -\i functions/community_deletion_lock_key.sql \i functions/enforce_community_tombstone.sql -\i functions/profile_name_fields.sql -- tables \i tables/public/communities.sql