Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 69 additions & 7 deletions crates/buzz-db/src/runtime/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -890,7 +890,7 @@ mod postgres_tests {
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
migrations.sort_by_key(|migration| migration.version);

assert_eq!(migrations.len(), 92);
assert_eq!(migrations.len(), 93);
assert_eq!(migrations[89].version, 90);
assert!(migrations[89]
.sql
Expand Down Expand Up @@ -1028,6 +1028,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
Expand Down Expand Up @@ -1512,7 +1528,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'"));
Expand Down Expand Up @@ -2551,6 +2566,7 @@ mod postgres_tests {
"assert_community_write_allowed",
"enforce_community_write_fence",
"attach_community_write_fence",
"community_deletion_lock_key",
]
.contains(&function.as_str())
{
Expand Down Expand Up @@ -3956,14 +3972,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
Expand All @@ -3974,6 +3989,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
Expand Down
57 changes: 29 additions & 28 deletions crates/buzz-db/src/store/deletion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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() {
Expand Down
9 changes: 3 additions & 6 deletions crates/buzz-relay/src/api/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand All @@ -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
Expand Down
4 changes: 1 addition & 3 deletions crates/buzz-relay/src/handlers/ingest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions docs/trigger-retirement-deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
8 changes: 8 additions & 0 deletions migrations/0093_drop_plain_sql_functions.sql
Original file line number Diff line number Diff line change
@@ -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);
4 changes: 0 additions & 4 deletions schema/functions/community_deletion_lock_key.sql

This file was deleted.

24 changes: 0 additions & 24 deletions schema/functions/profile_name_fields.sql

This file was deleted.

2 changes: 0 additions & 2 deletions schema/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading