@@ -494,9 +494,14 @@ async fn lock_owner_mutation_admission(
494494 mode : OwnerMutationMode ,
495495) -> Result < OwnerMutationAdmission > {
496496 crate :: deletion:: lock_community_deletion_shared ( tx, community) . await ?;
497+ // `FOR NO KEY UPDATE` still serializes with archive (`FOR NO KEY UPDATE`),
498+ // unarchive and deletion admission (`FOR UPDATE`), but not with the
499+ // `FOR KEY SHARE` that every foreign-key child insert takes. A membership
500+ // writer holding a member row or the list lock inserts its kind:13534
501+ // list into `events` last, so `FOR UPDATE` here would deadlock with it.
497502 let target = sqlx:: query (
498503 "SELECT archived_at, deletion_state, deleted_at FROM communities \
499- WHERE id = $1 FOR UPDATE",
504+ WHERE id = $1 FOR NO KEY UPDATE",
500505 )
501506 . bind ( community. as_uuid ( ) )
502507 . fetch_optional ( & mut * * tx)
@@ -1056,9 +1061,12 @@ impl<T> MembershipWrite<T> {
10561061///
10571062/// Call it as the last statement before commit of any transaction that
10581063/// changes `relay_members`, so the list commits or rolls back with the change.
1059- /// The per-community list lock is taken last: every other lock a membership
1060- /// transaction takes comes first, so the final writer reads every committed
1061- /// change and no new lock order appears. `created_at` is at least one second
1064+ /// The per-community list lock is the last explicit lock: every other lock a
1065+ /// membership transaction takes comes first, so the final writer reads every
1066+ /// committed change. The list insert then takes `FOR KEY SHARE` on the
1067+ /// community row through `events.community_id`'s foreign key; owner mutations
1068+ /// lock that row `FOR NO KEY UPDATE`, which doesn't conflict, so no lock cycle
1069+ /// forms. `created_at` is at least one second
10621070/// past every earlier list's, so the id is new and a client replacing by
10631071/// timestamp never keeps an older list from the same second. A burst of
10641072/// changes runs the timestamp ahead of the clock by up to one second per
@@ -2537,6 +2545,156 @@ mod postgres_tests {
25372545 assert_membership_list_matches ( & pool, community, & keys, newest. as_ref ( ) ) . await ;
25382546 }
25392547
2548+ /// Wait until some backend is blocked behind `holder_pid`.
2549+ async fn wait_until_blocked_by ( pool : & PgPool , holder_pid : i32 ) {
2550+ for _ in 0 ..400 {
2551+ let blocked: bool = sqlx:: query_scalar (
2552+ "SELECT EXISTS(SELECT 1 FROM pg_stat_activity \
2553+ WHERE $1 = ANY(pg_blocking_pids(pid)))",
2554+ )
2555+ . bind ( holder_pid)
2556+ . fetch_one ( pool)
2557+ . await
2558+ . expect ( "read blocked backends" ) ;
2559+ if blocked {
2560+ return ;
2561+ }
2562+ tokio:: time:: sleep ( std:: time:: Duration :: from_millis ( 25 ) ) . await ;
2563+ }
2564+ panic ! ( "nothing blocked behind backend {holder_pid}" ) ;
2565+ }
2566+
2567+ /// Run `transfer_ownership` in the background.
2568+ fn spawn_transfer (
2569+ pool : & PgPool ,
2570+ community : CommunityId ,
2571+ new_owner : & str ,
2572+ owner : & str ,
2573+ keys : & nostr:: Keys ,
2574+ ) -> tokio:: task:: JoinHandle < Result < MembershipWrite < TransferResult > > > {
2575+ let ( pool, keys) = ( pool. clone ( ) , keys. clone ( ) ) ;
2576+ let ( new_owner, owner) = ( new_owner. to_owned ( ) , owner. to_owned ( ) ) ;
2577+ tokio:: spawn ( async move {
2578+ transfer_ownership ( & pool, community, & new_owner, & owner, & keys) . await
2579+ } )
2580+ }
2581+
2582+ /// A list repair that holds the list lock while a transfer waits on it
2583+ /// still inserts its list: the transfer's community row lock doesn't
2584+ /// block the insert's foreign-key `FOR KEY SHARE`, so both commit.
2585+ #[ tokio:: test]
2586+ #[ ignore = "requires Postgres" ]
2587+ async fn owner_transfer_and_list_repair_both_commit ( ) {
2588+ let pool = setup_pool ( ) . await ;
2589+ let keys = nostr:: Keys :: generate ( ) ;
2590+ let community = make_test_community ( & pool) . await ;
2591+ let owner = test_pubkey ( ) ;
2592+ let new_owner = test_pubkey ( ) ;
2593+ let _ = bootstrap_owner ( & pool, community, & owner, & keys)
2594+ . await
2595+ . expect ( "bootstrap owner" ) ;
2596+
2597+ let mut repair = crate :: begin_community_write_transaction (
2598+ & pool,
2599+ community,
2600+ observability:: WriterOperation :: Authorization ,
2601+ )
2602+ . await
2603+ . expect ( "begin repair" ) ;
2604+ let repair_pid: i32 = sqlx:: query_scalar ( "SELECT pg_backend_pid()" )
2605+ . fetch_one ( repair. conn ( ) )
2606+ . await
2607+ . expect ( "repair pid" ) ;
2608+ let lock_key = replaceable:: event_replacement_lock_key (
2609+ community,
2610+ buzz_core:: kind:: KIND_NIP43_MEMBERSHIP_LIST as i32 ,
2611+ keys. public_key ( ) . to_bytes ( ) . as_slice ( ) ,
2612+ None ,
2613+ ) ;
2614+ sqlx:: query ( "SELECT pg_advisory_xact_lock($1)" )
2615+ . bind ( lock_key)
2616+ . execute ( repair. conn ( ) )
2617+ . await
2618+ . expect ( "hold list lock" ) ;
2619+
2620+ // The transfer locks the community row, then waits on the list lock.
2621+ let transfer = spawn_transfer ( & pool, community, & new_owner, & owner, & keys) ;
2622+ wait_until_blocked_by ( & pool, repair_pid) . await ;
2623+
2624+ let repaired = tokio:: time:: timeout ( std:: time:: Duration :: from_secs ( 30 ) , async {
2625+ write_nip43_membership_snapshot ( & mut repair, & keys) . await ?;
2626+ repair. commit ( ) . await
2627+ } )
2628+ . await
2629+ . expect ( "repair finishes" ) ;
2630+ repaired. expect ( "repair commits alongside the transfer" ) ;
2631+ let write = tokio:: time:: timeout ( std:: time:: Duration :: from_secs ( 30 ) , transfer)
2632+ . await
2633+ . expect ( "transfer finishes" )
2634+ . expect ( "transfer task" )
2635+ . expect ( "transfer commits alongside the repair" ) ;
2636+ assert ! ( matches!( write. outcome, TransferResult :: Transferred { .. } ) ) ;
2637+ assert_role ( & pool, community, & new_owner, "owner" ) . await ;
2638+ assert_membership_list_matches ( & pool, community, & keys, write. snapshot . as_ref ( ) ) . await ;
2639+ }
2640+
2641+ /// Removing the transferee while a transfer waits on its member row:
2642+ /// the removal's list insert doesn't wait on the transfer's community
2643+ /// row lock, so the removal commits and the transfer then re-adds the
2644+ /// transferee as owner.
2645+ #[ tokio:: test]
2646+ #[ ignore = "requires Postgres" ]
2647+ async fn owner_transfer_and_member_removal_both_commit ( ) {
2648+ let pool = setup_pool ( ) . await ;
2649+ let keys = nostr:: Keys :: generate ( ) ;
2650+ let community = make_test_community ( & pool) . await ;
2651+ let owner = test_pubkey ( ) ;
2652+ let member = test_pubkey ( ) ;
2653+ let _ = bootstrap_owner ( & pool, community, & owner, & keys)
2654+ . await
2655+ . expect ( "bootstrap owner" ) ;
2656+ let _ = add_relay_member ( & pool, community, & member, "member" , None , & keys)
2657+ . await
2658+ . expect ( "add member" ) ;
2659+
2660+ let mut removal = crate :: begin_community_write_transaction (
2661+ & pool,
2662+ community,
2663+ observability:: WriterOperation :: Authorization ,
2664+ )
2665+ . await
2666+ . expect ( "begin removal" ) ;
2667+ let removal_pid: i32 = sqlx:: query_scalar ( "SELECT pg_backend_pid()" )
2668+ . fetch_one ( removal. conn ( ) )
2669+ . await
2670+ . expect ( "removal pid" ) ;
2671+ assert ! ( delete_member_with_acceptances( & mut removal, & member, None )
2672+ . await
2673+ . expect( "delete member" ) ) ;
2674+
2675+ // The transfer locks the community row, then waits on the member row.
2676+ let transfer = spawn_transfer ( & pool, community, & member, & owner, & keys) ;
2677+ wait_until_blocked_by ( & pool, removal_pid) . await ;
2678+
2679+ let removed = tokio:: time:: timeout (
2680+ std:: time:: Duration :: from_secs ( 30 ) ,
2681+ commit_membership_write ( removal, RemoveResult :: Removed , true , & keys) ,
2682+ )
2683+ . await
2684+ . expect ( "removal finishes" )
2685+ . expect ( "removal commits alongside the transfer" ) ;
2686+ assert ! ( removed. snapshot. is_some( ) ) ;
2687+ let write = tokio:: time:: timeout ( std:: time:: Duration :: from_secs ( 30 ) , transfer)
2688+ . await
2689+ . expect ( "transfer finishes" )
2690+ . expect ( "transfer task" )
2691+ . expect ( "transfer commits alongside the removal" ) ;
2692+ assert ! ( matches!( write. outcome, TransferResult :: Transferred { .. } ) ) ;
2693+ assert_role ( & pool, community, & member, "owner" ) . await ;
2694+ assert_role ( & pool, community, & owner, "member" ) . await ;
2695+ assert_membership_list_matches ( & pool, community, & keys, write. snapshot . as_ref ( ) ) . await ;
2696+ }
2697+
25402698 /// Returning to an earlier membership within the same second yields a new
25412699 /// list with a later `created_at`, never the earlier list's id.
25422700 #[ tokio:: test]
0 commit comments