Skip to content

Commit d835556

Browse files
loganjLarryclaude
committed
Retire the 0032 roster trigger in migration 0076
Every kind:39002 roster writer already checks the roster against canonical channel membership in the application (#8316), and since #8611 no relay requires the 0032 trigger at startup. Migration 0076 drops the trigger and its function, with the lock and statement timeouts from 0049. The desired-state schema and the pgschema reconcile script no longer install them. Relays from this change still store and publish the requested role, so they serve correctly whether or not 0076 has run. Every relay, and every rollback target, must run #8611 or later before 0076 is applied. Tests that compared the trigger with the app check, or that disabled the trigger first, now test the app check alone. A new Postgres test applies 0076 to a database migrated through 0075 and checks that the trigger and function are gone. Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Logan Johnson <[email protected]>
1 parent aed4be8 commit d835556

10 files changed

Lines changed: 106 additions & 597 deletions

File tree

‎crates/buzz-db/src/runtime/migration.rs‎

Lines changed: 15 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -776,10 +776,22 @@ mod postgres_tests {
776776
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
777777
migrations.sort_by_key(|migration| migration.version);
778778

779-
assert_eq!(migrations.len(), 75);
779+
assert_eq!(migrations.len(), 76);
780780
for (index, migration) in migrations.iter().enumerate() {
781781
assert_eq!(migration.version, (index + 1) as i64);
782782
}
783+
let retire_roster_fence = strip_sql_comments(migrations[75].sql.as_str());
784+
for statement in [
785+
"SET LOCAL lock_timeout = '1s';",
786+
"SET LOCAL statement_timeout = '5s';",
787+
"DROP TRIGGER trg_events_guard_channel_roster_snapshot ON events;",
788+
"DROP FUNCTION guard_channel_roster_snapshot();",
789+
] {
790+
assert!(
791+
retire_roster_fence.contains(statement),
792+
"0076 must run {statement}"
793+
);
794+
}
783795
assert!(migrations[70]
784796
.sql
785797
.as_str()
@@ -1331,31 +1343,8 @@ mod postgres_tests {
13311343
assert!(roster_fence.contains("snapshot_members IS DISTINCT FROM canonical_members"));
13321344
assert!(roster_fence.contains("ERRCODE = '23514'"));
13331345

1334-
// Fresh desired-state bootstrap must install the identical executable
1335-
// fence as migration 0032. CI and isolated relay startup use schema.sql
1336-
// without running migrations, so drift reopens rolling-deploy races.
1337-
// The desired state keeps the function and its trigger in separate
1338-
// files, so compare each statement rather than one contiguous span.
1339-
fn extract_span<'a>(sql: &'a str, start: &str, end: &str) -> &'a str {
1340-
let begin = sql.find(start).expect("span start");
1341-
let relative_end = sql[begin..].find(end).expect("span end");
1342-
&sql[begin..begin + relative_end + end.len()]
1343-
}
1344-
for (start, end) in [
1345-
(
1346-
"CREATE OR REPLACE FUNCTION guard_channel_roster_snapshot()",
1347-
"$$ LANGUAGE plpgsql;",
1348-
),
1349-
(
1350-
"CREATE TRIGGER trg_events_guard_channel_roster_snapshot",
1351-
" FOR EACH ROW EXECUTE FUNCTION guard_channel_roster_snapshot();",
1352-
),
1353-
] {
1354-
assert_eq!(
1355-
extract_span(roster_fence, start, end),
1356-
extract_span(&desired_schema, start, end)
1357-
);
1358-
}
1346+
// Migration 0076 retires this fence; the desired state never installs it.
1347+
assert!(!desired_schema.contains("guard_channel_roster_snapshot"));
13591348

13601349
// The single-row heartbeat table is updated continuously. Prevent
13611350
// autovacuum from truncating its heap so standby queries are not

‎crates/buzz-db/src/store/channel_members.rs‎

Lines changed: 67 additions & 310 deletions
Large diffs are not rendered by default.

‎crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,9 @@ async fn apply_pgschema_to_existing_database(pool: &PgPool) {
505505
#[ignore = "requires Postgres"]
506506
async fn migration_schema_0075_adds_invite_columns_without_rewriting_history() {
507507
let (pool, cases) = legacy_fixture().await;
508-
crate::migration::run_migrations(&pool).await.unwrap();
508+
crate::migration::run_migrations_through(&pool, 75)
509+
.await
510+
.unwrap();
509511
assert_eq!(
510512
sqlx::query_scalar::<_, i64>("SELECT max(version) FROM _sqlx_migrations WHERE success")
511513
.fetch_one(&pool)

‎crates/buzz-db/src/store/replaceable.rs‎

Lines changed: 0 additions & 174 deletions
Original file line numberDiff line numberDiff line change
@@ -834,180 +834,6 @@ mod postgres_tests {
834834
drop_scratch_db(&admin, pool, &scratch_name).await;
835835
}
836836

837-
#[tokio::test]
838-
#[ignore = "requires Postgres"]
839-
async fn stale_legacy_roster_cannot_replace_new_locked_snapshot() {
840-
use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp};
841-
842-
let admin = PgPool::connect(&admin_url().await)
843-
.await
844-
.expect("connect admin");
845-
let (setup_pool, scratch_name) = create_scratch_db(&admin, "mixed_roster_writer").await;
846-
let base_url = admin_url().await;
847-
let slash = base_url.rfind('/').expect("database URL has path segment");
848-
let scratch_url = format!("{}/{}", &base_url[..slash], scratch_name);
849-
let pool = PgPoolOptions::new()
850-
.max_connections(1)
851-
.acquire_timeout(Duration::from_secs(1))
852-
.connect(&scratch_url)
853-
.await
854-
.expect("connect one-connection scratch pool");
855-
setup_pool.close().await;
856-
let db = Db::from_pool(pool.clone());
857-
let community_uuid = Uuid::new_v4();
858-
let community = CommunityId::from_uuid(community_uuid);
859-
let channel = Uuid::new_v4();
860-
let relay_keys = Keys::generate();
861-
let owner_keys = Keys::generate();
862-
let owner = owner_keys.public_key().to_bytes();
863-
seed_community_channel(&pool, community_uuid, channel, &owner_keys).await;
864-
865-
// This is the old pod's unlocked capture A. It remains in process memory
866-
// while a role-only canonical mutation advances and the new pod publishes B.
867-
let base = Timestamp::now().as_secs();
868-
let roster = |members: &[(&[u8], &str)], timestamp| {
869-
let tags =
870-
std::iter::once(Tag::parse(["d", channel.to_string().as_str()]).expect("d tag"))
871-
.chain(members.iter().map(|(member, role)| {
872-
Tag::parse(["p", hex::encode(member).as_str(), "", *role]).expect("p tag")
873-
}))
874-
.collect::<Vec<_>>();
875-
EventBuilder::new(Kind::Custom(39002), "")
876-
.tags(tags)
877-
.custom_created_at(Timestamp::from(timestamp))
878-
.sign_with_keys(&relay_keys)
879-
.expect("sign roster")
880-
};
881-
882-
let newcomer = Keys::generate().public_key().to_bytes();
883-
sqlx::query(
884-
"INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) \
885-
VALUES ($1, $2, $3, 'member', $4)",
886-
)
887-
.bind(community_uuid)
888-
.bind(channel)
889-
.bind(newcomer.as_slice())
890-
.bind(owner.as_slice())
891-
.execute(&pool)
892-
.await
893-
.expect("seed member before legacy capture");
894-
let stale_a = roster(
895-
&[(owner.as_slice(), "owner"), (newcomer.as_slice(), "member")],
896-
base + 2,
897-
);
898-
899-
sqlx::query(
900-
"UPDATE channel_members SET role = 'admin' \
901-
WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3",
902-
)
903-
.bind(community_uuid)
904-
.bind(channel)
905-
.bind(newcomer.as_slice())
906-
.execute(&pool)
907-
.await
908-
.expect("commit newer canonical role");
909-
910-
let relay_pubkey = relay_keys.public_key().to_bytes();
911-
let mut snapshot = db
912-
.lock_member_snapshot(community, channel, &relay_pubkey)
913-
.await
914-
.expect("new writer captures locked roster B");
915-
let fresh_b = roster(
916-
&[(owner.as_slice(), "owner"), (newcomer.as_slice(), "admin")],
917-
base + 1,
918-
);
919-
assert!(
920-
snapshot
921-
.replace_member_event(&fresh_b)
922-
.await
923-
.expect("new writer publishes B")
924-
.1
925-
);
926-
snapshot
927-
.release()
928-
.await
929-
.expect("commit B and release locks");
930-
931-
// Reproduce the old binary on one connection: replacement key ->
932-
// old-head UPDATE -> raw INSERT. Do not use the app API, whose guard
933-
// rejects before the retained trigger can exercise this legacy fence.
934-
// A size-one pool and bounded attempt also catch self-deadlock.
935-
let error = tokio::time::timeout(Duration::from_secs(3), async {
936-
let mut tx = pool.begin().await.expect("begin legacy replacement");
937-
let relay_pubkey = relay_keys.public_key().to_bytes();
938-
sqlx::query("SELECT pg_advisory_xact_lock($1)")
939-
.bind(crate::store::replaceable::event_replacement_lock_key(
940-
community,
941-
39002,
942-
&relay_pubkey,
943-
Some(channel.as_bytes().as_slice()),
944-
))
945-
.execute(&mut *tx)
946-
.await
947-
.expect("legacy replacement key");
948-
let deleted = sqlx::query(
949-
"UPDATE events SET deleted_at = NOW() \
950-
WHERE community_id=$1 AND kind=39002 AND pubkey=$2 \
951-
AND channel_id=$3 AND deleted_at IS NULL",
952-
)
953-
.bind(community_uuid)
954-
.bind(relay_pubkey.as_slice())
955-
.bind(channel)
956-
.execute(&mut *tx)
957-
.await
958-
.expect("legacy soft-delete of current head");
959-
assert_eq!(deleted.rows_affected(), 1, "legacy path must delete the live head");
960-
let result = sqlx::query(
961-
"INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag) \
962-
VALUES ($1, $2, $3, $4, 39002, $5, $6, $7, NOW(), $8, $9)",
963-
)
964-
.bind(community_uuid)
965-
.bind(stale_a.id.as_bytes().as_slice())
966-
.bind(relay_pubkey.as_slice())
967-
.bind(chrono::DateTime::from_timestamp(stale_a.created_at.as_secs() as i64, 0).expect("timestamp"))
968-
.bind(serde_json::to_value(&stale_a.tags).expect("tags"))
969-
.bind(&stale_a.content)
970-
.bind(stale_a.sig.serialize().as_slice())
971-
.bind(channel)
972-
.bind(channel.to_string())
973-
.execute(&mut *tx)
974-
.await;
975-
tx.rollback().await.expect("restore live head after legacy attempt");
976-
result
977-
})
978-
.await
979-
.expect("legacy replacement must not deadlock")
980-
.expect_err("stale captured roster A must be rejected");
981-
assert!(
982-
matches!(error, sqlx::Error::Database(ref db_error)
983-
if db_error.code().as_deref() == Some("23514")
984-
&& db_error.message() == "kind 39002 roster does not match canonical channel membership"),
985-
"expected trigger roster fence check violation, got {error:?}"
986-
);
987-
988-
let live_ids: Vec<Vec<u8>> = sqlx::query_scalar(
989-
"SELECT id FROM events WHERE community_id=$1 AND channel_id=$2 \
990-
AND kind=39002 AND pubkey=$3 AND deleted_at IS NULL",
991-
)
992-
.bind(community_uuid)
993-
.bind(channel)
994-
.bind(relay_pubkey.as_slice())
995-
.fetch_all(&pool)
996-
.await
997-
.expect("load live roster heads");
998-
assert_eq!(live_ids, vec![fresh_b.id.as_bytes().to_vec()]);
999-
let stale_rows: i64 =
1000-
sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id=$1 AND id=$2")
1001-
.bind(community_uuid)
1002-
.bind(stale_a.id.as_bytes().as_slice())
1003-
.fetch_one(&pool)
1004-
.await
1005-
.expect("count rejected stale roster");
1006-
assert_eq!(stale_rows, 0, "stale roster insert must roll back");
1007-
1008-
drop_scratch_db(&admin, pool, &scratch_name).await;
1009-
}
1010-
1011837
#[tokio::test]
1012838
#[ignore = "requires Postgres"]
1013839
async fn nip_rs_replacement_hard_deletes_payload_and_watermark_rejects_replay() {

‎crates/buzz-relay/src/handlers/side_effects.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1325,7 +1325,7 @@ async fn store_group_members_event(
13251325
// relay's moderation-DM key participates in the {relay, recipient} DM used
13261326
// for moderation notices) MUST retain the relay's own `p` tag. nostr's
13271327
// default `build_with_ctx` strips any `p` tag matching the signer, which
1328-
// would drop the relay from the snapshot and fail migration 0032's roster
1328+
// would drop the relay from the snapshot and fail the roster
13291329
// fence against the canonical two-member DM. `allow_self_tagging` keeps the
13301330
// snapshot faithful to `channel_members`.
13311331
let event = EventBuilder::new(Kind::Custom(KIND_NIP29_GROUP_MEMBERS as u16), "")
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
-- Every kind:39002 roster writer checks the roster against canonical channel
2+
-- membership in the application (validate_channel_roster_snapshot, from
3+
-- #8316), and since #8611 no relay requires this trigger at startup. Retire
4+
-- the trigger that repeats that check: it compares roster labels with the
5+
-- stored role exactly, so it would refuse rosters that show the computed
6+
-- `member`/`bot` label. Every relay and rollback target must run #8611 or
7+
-- later before this migration runs; older relays refuse to start without the
8+
-- trigger. Published migrations remain checksum-frozen.
9+
--
10+
-- DROP TRIGGER takes ACCESS EXCLUSIVE on each partition of events in turn,
11+
-- and keeps each lock while it waits for the next. While the locks are queued
12+
-- or held, event reads and writes both block.
13+
-- lock_timeout bounds each lock wait and statement_timeout bounds each whole
14+
-- statement, as in 0049. Either timeout rolls the migration back with no
15+
-- change, and it can be retried.
16+
SET LOCAL lock_timeout = '1s';
17+
SET LOCAL statement_timeout = '5s';
18+
19+
DROP TRIGGER trg_events_guard_channel_roster_snapshot ON events;
20+
DROP FUNCTION guard_channel_roster_snapshot();

‎schema/functions/guard_channel_roster_snapshot.sql‎

Lines changed: 0 additions & 72 deletions
This file was deleted.

‎schema/schema.sql‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,6 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto;
6464

6565
-- functions
6666
\i functions/channels_community_id_immutable.sql
67-
\i functions/guard_channel_roster_snapshot.sql
6867
\i functions/events_created_at_floor_guard.sql
6968
\i functions/prevent_community_deletion_request_retargeting.sql
7069
\i functions/prevent_community_deletion_approval_removal.sql

‎schema/triggers/events.sql‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
CREATE TRIGGER trg_events_guard_channel_roster_snapshot
2-
BEFORE INSERT ON events
3-
FOR EACH ROW EXECUTE FUNCTION guard_channel_roster_snapshot();
4-
51
-- INSERT OR UPDATE OF: an UPDATE can move a previously exempt row into the
62
-- guarded set (channel_id NULL -> NOT NULL) or move a channel row's
73
-- created_at below the fence, so both mutation paths re-run the guard on the

0 commit comments

Comments
 (0)