From 4750794ff2985c407220ca737e407c770c247eeb Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 12:36:06 +0100 Subject: [PATCH 1/2] test(database): lock-wait tests share one helper that says why it polls --- apps/auth-service/src/account/tests.rs | 8 ++--- .../src/admin/tests/administrators.rs | 2 +- .../src/admin/tests/invitations.rs | 2 +- apps/auth-service/src/admin/tests/mod.rs | 2 +- .../auth-service/src/admin/tests/mutations.rs | 4 +-- apps/auth-service/src/alerts/tests.rs | 2 +- .../src/clients/tests/deletion.rs | 8 ++--- apps/auth-service/src/clients/tests/mod.rs | 4 +-- .../src/oidc/tests/app_removal.rs | 2 +- .../src/oidc/tests/authorization.rs | 6 ++-- apps/auth-service/src/oidc/tests/mod.rs | 3 +- apps/auth-service/src/oidc/tests/policy.rs | 4 +-- apps/auth-service/src/oidc/tests/tokens.rs | 2 +- .../src/passkey/tests/related_pages.rs | 4 +-- apps/auth-service/src/recovery/tests/undo.rs | 4 +-- .../src/security/tests/sessions.rs | 4 +-- apps/auth-service/src/tests.rs | 11 ------ apps/auth-service/src/web/admin/tests/mod.rs | 2 +- .../src/web/admin/tests/sessions.rs | 4 +-- crates/database/src/connection/mod.rs | 2 ++ crates/database/src/fixtures.rs | 36 ++++++++++++++++--- .../src/repositories/announcements/tests.rs | 20 +++-------- crates/database/src/transaction.rs | 5 ++- docs/dev/testing.md | 5 +-- 24 files changed, 76 insertions(+), 70 deletions(-) diff --git a/apps/auth-service/src/account/tests.rs b/apps/auth-service/src/account/tests.rs index df5314f47..bf801fb19 100644 --- a/apps/auth-service/src/account/tests.rs +++ b/apps/auth-service/src/account/tests.rs @@ -13,7 +13,7 @@ use crate::{ security::{BrowserCookie, CONFIRMATION_MAX_AGE}, tests::{ AUTH_ORIGIN, Browser, Replicas, change, pending_sign_in, registration, sign_out, - until_blocked, unusable_passkey, verified_address, + unusable_passkey, verified_address, }, }; use axum::{ @@ -505,7 +505,7 @@ async fn changes_check_the_administrator_again_after_waiting() { let (result, ()) = tokio::join!( fixture.rename(operator(revoked, Utc::now()), user, passkeys[0]), async { - until_blocked(&mut revocation, 1).await; + revocation.until_blocked(1).await; revocation.commit().await.expect("commit"); } ); @@ -528,7 +528,7 @@ async fn changes_check_the_administrator_again_after_waiting() { let (result, ()) = tokio::join!( fixture.rename(fixture.operator(Duration::zero()), user, passkeys[0]), async { - until_blocked(&mut grant, 1).await; + grant.until_blocked(1).await; grant.commit().await.expect("commit"); } ); @@ -650,7 +650,7 @@ async fn a_confirmation_while_waiting_does_not_count() { .expect("account lock"); let path = passkey::ITEM.replace("{id}", &PasskeyId::new().to_string()); let ((status, body), ()) = tokio::join!(social.call(&routes, Method::DELETE, &path), async { - until_blocked(&mut confirmation, 1).await; + confirmation.until_blocked(1).await; confirmation .sessions() .confirm_passkey(social.session_id, PasskeyId::new(), Utc::now()) diff --git a/apps/auth-service/src/admin/tests/administrators.rs b/apps/auth-service/src/admin/tests/administrators.rs index 547356cde..4eebb3a3d 100644 --- a/apps/auth-service/src/admin/tests/administrators.rs +++ b/apps/auth-service/src/admin/tests/administrators.rs @@ -139,7 +139,7 @@ async fn the_last_active_administrator_stays() { service.disable_user(&cli, a.user_id, reason("Away")), service.revoke_administrator(&cli, b.user_id, reason("Asked by email")), async { - until_blocked(&mut held, 2).await; + held.until_blocked(2).await; held.commit().await.expect("commit"); } ); diff --git a/apps/auth-service/src/admin/tests/invitations.rs b/apps/auth-service/src/admin/tests/invitations.rs index 089490fa3..13241293a 100644 --- a/apps/auth-service/src/admin/tests/invitations.rs +++ b/apps/auth-service/src/admin/tests/invitations.rs @@ -241,7 +241,7 @@ async fn invitation_revocation_waits_for_signup() { let (result, ()) = tokio::join!( service.revoke_invitation(&operator, invitation.id, reason("Asked by email")), async { - until_blocked(&mut signup, 1).await; + signup.until_blocked(1).await; // The signup revokes the browser's session without a deadlock. admin.sign_out(&mut signup).await; signup.commit().await.expect("signup"); diff --git a/apps/auth-service/src/admin/tests/mod.rs b/apps/auth-service/src/admin/tests/mod.rs index 9053135c7..fbc9f9cd8 100644 --- a/apps/auth-service/src/admin/tests/mod.rs +++ b/apps/auth-service/src/admin/tests/mod.rs @@ -3,7 +3,7 @@ use super::*; use crate::security::RequestContext; -use crate::tests::{Browser, Replicas, until_blocked}; +use crate::tests::{Browser, Replicas}; use chrono::{Duration, Utc}; use sourceorigin_common::{ AccountStatus, AuthenticationMethod, Handle, Personal, SessionId, TokenId, UserId, diff --git a/apps/auth-service/src/admin/tests/mutations.rs b/apps/auth-service/src/admin/tests/mutations.rs index 8e48a0f5f..b10dce728 100644 --- a/apps/auth-service/src/admin/tests/mutations.rs +++ b/apps/auth-service/src/admin/tests/mutations.rs @@ -28,7 +28,7 @@ async fn mutations_recheck_the_confirmation_after_waiting() { let (result, ()) = tokio::join!( service.disable_user(&operator, user.user_id, reason), async { - until_blocked(&mut logout, 1).await; + logout.until_blocked(1).await; assert!( operator.confirmation_left() > Duration::zero(), "the mutation waits while its caller is still confirmed" @@ -73,7 +73,7 @@ async fn waiting_mutations_hold_no_caller_locks() { let (result, ()) = tokio::join!( service.disable_user(&operator, user.user_id, reason), async { - until_blocked(&mut switch, 1).await; + switch.until_blocked(1).await; // The switch revokes the caller's session without a deadlock. admin.sign_out(&mut switch).await; switch.commit().await.expect("commit"); diff --git a/apps/auth-service/src/alerts/tests.rs b/apps/auth-service/src/alerts/tests.rs index a272a005a..679305941 100644 --- a/apps/auth-service/src/alerts/tests.rs +++ b/apps/auth-service/src/alerts/tests.rs @@ -157,7 +157,7 @@ async fn concurrent_raises_leave_one_alert() { let database = database.clone(); async move { found(&database, Some(broken(5))).await } }); - crate::tests::until_blocked(&mut first, 1).await; + first.until_blocked(1).await; first.commit().await.expect("commit"); second.await.expect("second raise"); let raised = recorded(&database).await; diff --git a/apps/auth-service/src/clients/tests/deletion.rs b/apps/auth-service/src/clients/tests/deletion.rs index d957d282e..7451d1ef7 100644 --- a/apps/auth-service/src/clients/tests/deletion.rs +++ b/apps/auth-service/src/clients/tests/deletion.rs @@ -176,7 +176,7 @@ async fn deletion_and_refresh_rotation_never_deadlock() { .await .expect("hold the first family"); let deletion = granting.delete(); - until_blocked(&mut holder, 1).await; + holder.until_blocked(1).await; holder .tokens() .redeem_refresh( @@ -225,7 +225,7 @@ async fn deletion_skips_families_granted_while_it_waits() { .await .expect("hold the family"); let deletion = granting.delete(); - until_blocked(&mut holder, 1).await; + holder.until_blocked(1).await; let (token, digest) = granting.grant(fresh).await; let mut rotation = granting.database.begin().await.expect("transaction"); rotation @@ -274,7 +274,7 @@ async fn deletion_and_logout_never_deadlock() { .await .expect("hold the lowest family"); let deletion = granting.delete(); - until_blocked(&mut holder, 1).await; + holder.until_blocked(1).await; let logout = tokio::spawn({ let database = granting.database.clone(); let (user, session) = (granting.user.user_id, granting.user.session_id); @@ -284,7 +284,7 @@ async fn deletion_and_logout_never_deadlock() { tx.commit().await } }); - until_blocked(&mut holder, 2).await; + holder.until_blocked(2).await; holder.commit().await.expect("commit"); deletion.await.expect("task").expect("deletion"); logout.await.expect("task").expect("logout"); diff --git a/apps/auth-service/src/clients/tests/mod.rs b/apps/auth-service/src/clients/tests/mod.rs index 7117c9223..e154ff722 100644 --- a/apps/auth-service/src/clients/tests/mod.rs +++ b/apps/auth-service/src/clients/tests/mod.rs @@ -6,7 +6,7 @@ use super::*; use crate::{ account::{AccountError, AccountService, Owner}, security::Session, - tests::{Browser, Replicas, change, register, registration, replace, until_blocked}, + tests::{Browser, Replicas, change, register, registration, replace}, }; use sourceorigin_common::{AuthenticationMethod, UserId, clients::RedirectUris}; use sourceorigin_repository::Database; @@ -82,7 +82,7 @@ impl Account { .expect("lock") .expect("account"); let (result, ()) = tokio::join!(change(&client), async { - until_blocked(&mut holder, 1).await; + holder.until_blocked(1).await; let session = holder.sessions().find_by_id(stale.session_id).await; let session = session.expect("lookup").expect("session"); let passkey = AuthenticationMethod::Passkey.into(); diff --git a/apps/auth-service/src/oidc/tests/app_removal.rs b/apps/auth-service/src/oidc/tests/app_removal.rs index 633aaca47..03a5509c0 100644 --- a/apps/auth-service/src/oidc/tests/app_removal.rs +++ b/apps/auth-service/src/oidc/tests/app_removal.rs @@ -126,7 +126,7 @@ async fn an_exchange_waits_for_a_removal_and_finds_its_code_expired() { let response = exchanging.exchange(&code, Flow::verifier(), None).await; (response.status(), json(response).await) }); - until_blocked(&mut removal, 1).await; + removal.until_blocked(1).await; removal .oidc() .expire_codes(flow.user_id, &flow.client.id) diff --git a/apps/auth-service/src/oidc/tests/authorization.rs b/apps/auth-service/src/oidc/tests/authorization.rs index 8f5d640b0..6db603166 100644 --- a/apps/auth-service/src/oidc/tests/authorization.rs +++ b/apps/auth-service/src/oidc/tests/authorization.rs @@ -112,9 +112,9 @@ async fn a_failed_redemption_uses_the_code_up_for_one_waiting() { tokio::spawn(async move { flow.exchange(&code, verifier, None).await.status() }) }; let failed = exchange("wrong"); - until_blocked(&mut holder, 1).await; + holder.until_blocked(1).await; let valid = exchange(Flow::verifier()); - until_blocked(&mut holder, 2).await; + holder.until_blocked(2).await; holder.commit().await.expect("commit"); assert_eq!(failed.await.expect("failed"), StatusCode::BAD_REQUEST); @@ -257,7 +257,7 @@ async fn a_consent_whose_session_ended_while_waiting_is_not_saved() { .await; response.status() }); - until_blocked(&mut holder, 1).await; + holder.until_blocked(1).await; let context = RequestContext::TEST.actor(Actor::Anonymous); holder .revoke_sessions( diff --git a/apps/auth-service/src/oidc/tests/mod.rs b/apps/auth-service/src/oidc/tests/mod.rs index e6fe7680f..935fff246 100644 --- a/apps/auth-service/src/oidc/tests/mod.rs +++ b/apps/auth-service/src/oidc/tests/mod.rs @@ -4,8 +4,7 @@ use super::*; use crate::config::TokenDigestKey; use crate::security::RequestContext; use crate::tests::{ - AUTH_ORIGIN, Browser, Replicas, TlsListener, html, json, location, parameter, until_blocked, - verified_address, + AUTH_ORIGIN, Browser, Replicas, TlsListener, html, json, location, parameter, verified_address, }; use crate::{AuthConfig, federation::FederationApplication, web::WebApplication}; use axum::{ diff --git a/apps/auth-service/src/oidc/tests/policy.rs b/apps/auth-service/src/oidc/tests/policy.rs index ffece25d7..ae5fd6267 100644 --- a/apps/auth-service/src/oidc/tests/policy.rs +++ b/apps/auth-service/src/oidc/tests/policy.rs @@ -24,7 +24,7 @@ async fn suspending_an_app_during_an_exchange_issues_nothing() { let exchanging = flow.clone(); let exchange = tokio::spawn(async move { exchanging.exchange(&code, Flow::verifier(), None).await }); - until_blocked(&mut suspension, 1).await; + suspension.until_blocked(1).await; suspension.commit().await.expect("commit"); let response = exchange.await.expect("exchange"); @@ -124,7 +124,7 @@ async fn consent_waits_for_an_owners_change_to_the_app() { .await .status() }); - until_blocked(&mut change, 1).await; + change.until_blocked(1).await; change .oidc() .lock_client(&flow.client.id) diff --git a/apps/auth-service/src/oidc/tests/tokens.rs b/apps/auth-service/src/oidc/tests/tokens.rs index f7c9aa52c..4fbfae24f 100644 --- a/apps/auth-service/src/oidc/tests/tokens.rs +++ b/apps/auth-service/src/oidc/tests/tokens.rs @@ -377,7 +377,7 @@ async fn a_refresh_that_waits_for_an_undo_or_disablement_issues_nothing() { .expect("user"); let refreshing = flow.clone(); let refresh = tokio::spawn(async move { refreshing.refresh(&token).await }); - until_blocked(&mut holder, 1).await; + holder.until_blocked(1).await; if disable { holder .users() diff --git a/apps/auth-service/src/passkey/tests/related_pages.rs b/apps/auth-service/src/passkey/tests/related_pages.rs index ca2a3d741..a57951e90 100644 --- a/apps/auth-service/src/passkey/tests/related_pages.rs +++ b/apps/auth-service/src/passkey/tests/related_pages.rs @@ -3,7 +3,7 @@ use super::*; use crate::{ ClientRegistry, - tests::{change, operator, reason, register, until_blocked}, + tests::{change, operator, reason, register}, }; use sourceorigin_common::{ClientId, clients::RelatedOrigin}; @@ -484,7 +484,7 @@ async fn removing_an_origin_during_a_sign_in_refuses_it() { json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), ); let (finished, ()) = tokio::join!(finish, async { - until_blocked(&mut removal, 1).await; + removal.until_blocked(1).await; removal.commit().await.expect("commit"); }); assert_eq!(finished.status(), StatusCode::BAD_REQUEST); diff --git a/apps/auth-service/src/recovery/tests/undo.rs b/apps/auth-service/src/recovery/tests/undo.rs index fb6bfd2fe..1df2671af 100644 --- a/apps/auth-service/src/recovery/tests/undo.rs +++ b/apps/auth-service/src/recovery/tests/undo.rs @@ -1,7 +1,7 @@ //! Undoing a recovery: who may, what it takes back, and what the pages read of it. use super::*; -use crate::{passkey::VerifiedRecoveryUndo, tests::until_blocked}; +use crate::passkey::VerifiedRecoveryUndo; use sourceorigin_common::events::SignInFailure; /// Undoing a recovery in probation, with a passkey from before it and no @@ -94,7 +94,7 @@ async fn an_undo_and_a_client_deletion_never_deadlock() { let admin = scenario.admin(); async move { admin.undo_recovery(&cli(), user, recovery_reason()).await } }); - until_blocked(&mut holder, 1).await; + holder.until_blocked(1).await; holder .oidc() .delete_client(&client) diff --git a/apps/auth-service/src/security/tests/sessions.rs b/apps/auth-service/src/security/tests/sessions.rs index 3d0164541..4ac679ad2 100644 --- a/apps/auth-service/src/security/tests/sessions.rs +++ b/apps/auth-service/src/security/tests/sessions.rs @@ -1,7 +1,7 @@ //! Session lookup, passkey confirmation age and session locking against logout. use super::*; -use crate::tests::{Browser, Replicas, until_blocked}; +use crate::tests::{Browser, Replicas}; use sourceorigin_crypto::Secret; use sourceorigin_repository::InsertSession; @@ -111,7 +111,7 @@ async fn confirmed_changes_serialize_with_logout() { } }); // The logout waits for the change. - until_blocked(&mut change, 1).await; + change.until_blocked(1).await; change.commit().await.expect("commit change"); assert_eq!(logout.await.expect("logout task").expect("logout"), [id]); let mut change = database.begin().await.expect("change transaction"); diff --git a/apps/auth-service/src/tests.rs b/apps/auth-service/src/tests.rs index 468116f56..4520112dd 100644 --- a/apps/auth-service/src/tests.rs +++ b/apps/auth-service/src/tests.rs @@ -740,17 +740,6 @@ pub(crate) async fn sign_out( .await } -/// Waits until `waiters` other transactions wait for a lock `holder` holds. -pub(crate) async fn until_blocked(holder: &mut DatabaseTransaction<'_>, waiters: i64) { - tokio::time::timeout(std::time::Duration::from_secs(10), async { - while holder.blocked_transactions().await.expect("lock waits") < waiters { - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - }) - .await - .expect("the operation waits for the holder's lock"); -} - /// Issues the refresh grant `family` to `client` from `user_id`'s session /// `session_id`, as a code exchange would, and returns its first refresh token's /// ID and digest. diff --git a/apps/auth-service/src/web/admin/tests/mod.rs b/apps/auth-service/src/web/admin/tests/mod.rs index 46c043790..662039c2f 100644 --- a/apps/auth-service/src/web/admin/tests/mod.rs +++ b/apps/auth-service/src/web/admin/tests/mod.rs @@ -12,7 +12,7 @@ use crate::{ security::{BrowserCookie, RequestContext}, tests::{ AUTH_ORIGIN, Browser, OWN_PAGE, Replicas, cookie, html, location, operator, parameter, - policy, reason, redirect, until_blocked, + policy, reason, redirect, }, }; use axum::{ diff --git a/apps/auth-service/src/web/admin/tests/sessions.rs b/apps/auth-service/src/web/admin/tests/sessions.rs index 4ae105a2f..220e6d8d2 100644 --- a/apps/auth-service/src/web/admin/tests/sessions.rs +++ b/apps/auth-service/src/web/admin/tests/sessions.rs @@ -145,7 +145,7 @@ async fn a_sign_in_racing_a_revocation_never_outlives_it() { let (revoked, ()) = tokio::join!( service.revoke_administrator(&cli, admin.user_id, reason()), async { - until_blocked(&mut redeeming, 1).await; + redeeming.until_blocked(1).await; let expires_at = Utc::now() + chrono::Duration::hours(1); (redeeming.dashboard()) .insert_session(b"in flight", admin.session_id, Utc::now(), expires_at) @@ -178,7 +178,7 @@ async fn a_sign_in_racing_a_revocation_never_outlives_it() { sign_in.hand_off(&owner, &query, proof()), dashboard.visit(&harness.dashboard, code_url.as_str()), async { - until_blocked(&mut revoking, 2).await; + revoking.until_blocked(2).await; revoking.commit().await.expect("commit"); } ); diff --git a/crates/database/src/connection/mod.rs b/crates/database/src/connection/mod.rs index 12df5aace..359e01c80 100644 --- a/crates/database/src/connection/mod.rs +++ b/crates/database/src/connection/mod.rs @@ -424,6 +424,8 @@ impl Database { .await .expect("wait state") { + // wall-clock: PostgreSQL shows a lock wait only in + // `pg_stat_activity`, and signals nothing when one starts. tokio::time::sleep(Duration::from_millis(10)).await; } }) diff --git a/crates/database/src/fixtures.rs b/crates/database/src/fixtures.rs index 233237e39..1fc94ebee 100644 --- a/crates/database/src/fixtures.rs +++ b/crates/database/src/fixtures.rs @@ -2,13 +2,16 @@ //! sessions, delivery channels and an account's event history. This crate's //! tests use them, and so do other crates' tests, behind the `test-util` feature. -use crate::{Database, DatabaseConfig, EventRepository, InsertSession, InsertUser, UserRepository}; +use crate::{ + Database, DatabaseConfig, DatabaseTransaction, EventRepository, InsertSession, InsertUser, + UserRepository, +}; use chrono::{TimeDelta, Utc}; use sourceorigin_common::{ Handle, SessionId, UserId, events::{Browser, DomainEvent, Platform, UserAgentFamily}, }; -use std::net::IpAddr; +use std::{net::IpAddr, time::Duration}; impl Database { /// Opens a pool of up to five connections to `TEST_DATABASE_URL`, with the @@ -24,8 +27,8 @@ impl Database { )] pub async fn test() -> Self { let url = std::env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL"); - let config = DatabaseConfig::new(&url, 5, std::time::Duration::from_secs(5)) - .expect("database configuration"); + let config = + DatabaseConfig::new(&url, 5, Duration::from_secs(5)).expect("database configuration"); let database = Self::connect(config).await.expect("connect"); database.run_migrations().await.expect("migrate"); database @@ -117,6 +120,31 @@ impl EventRepository<'_> { } } +impl DatabaseTransaction<'_> { + /// Waits until `waiters` other transactions wait for a lock this one holds, + /// directly or queued behind another waiter, so a test orders concurrent work + /// on what the database is doing. + /// + /// # Panics + /// + /// Panics if a query fails, or fewer transactions wait within ten seconds. + #[expect( + clippy::expect_used, + reason = "test-only fixture; documented under `# Panics`" + )] + pub async fn until_blocked(&mut self, waiters: i64) { + tokio::time::timeout(Duration::from_secs(10), async { + while self.blocked_transactions().await.expect("lock waits") < waiters { + // wall-clock: PostgreSQL shows a lock wait only in `pg_locks`, and + // signals nothing when one starts. + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the other transactions wait for the holder's lock"); + } +} + /// Declares channels whose deliveries tests insert themselves, so no event causes /// one. Each entry reads `/// Doc comment` then /// `Name = "stored_name": Recipient => Payload;`. Tests run at once on one diff --git a/crates/database/src/repositories/announcements/tests.rs b/crates/database/src/repositories/announcements/tests.rs index f00ae7aa6..792701579 100644 --- a/crates/database/src/repositories/announcements/tests.rs +++ b/crates/database/src/repositories/announcements/tests.rs @@ -326,18 +326,6 @@ async fn purge_as_callers_do(tx: &mut DatabaseTransaction<'_>, user: UserId) { assert!(tx.deletions().purge(user).await.expect("purge")); } -/// Waits until `waiters` transactions wait for `holder`, directly or behind -/// another that does. -async fn until_blocked(holder: &mut DatabaseTransaction<'_>, waiters: i64) { - tokio::time::timeout(std::time::Duration::from_secs(10), async { - while holder.blocked_transactions().await.expect("lock waits") < waiters { - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - }) - .await - .expect("the other transaction waits for the holder's lock"); -} - /// The announcement deliveries queued to `user`. async fn deliveries_to(pool: &PgPool, user: UserId, id: AnnouncementId) -> i64 { sqlx::query_scalar( @@ -384,7 +372,7 @@ async fn sending_and_purging_wait_for_each_other() { purge_as_callers_do(&mut purge, purged).await; let mut sending = DatabaseTransaction::new(pool.begin().await.expect("transaction")); let (sent, ()) = tokio::join!(send_in(&mut sending, everyone, 1), async { - until_blocked(&mut purge, 1).await; + purge.until_blocked(1).await; purge.commit().await.expect("commit"); }); assert!(sent.is_some(), "sent without the purged account"); @@ -422,7 +410,7 @@ async fn sending_and_purging_wait_for_each_other() { purge.commit().await.expect("commit"); }; tokio::join!(purge, async { - until_blocked(&mut sending, 1).await; + sending.until_blocked(1).await; sending.commit().await.expect("commit"); }); assert_eq!(deliveries_to(&pool, purged, chosen).await, 0); @@ -467,7 +455,7 @@ async fn purging_the_last_recipients_at_once_deletes_the_text() { other.commit().await.expect("commit"); }; tokio::join!(other, async { - until_blocked(&mut purge, 1).await; + purge.until_blocked(1).await; purge.commit().await.expect("commit"); }); let announcements = AnnouncementRepository::from_pool(&pool).find(id).await; @@ -503,7 +491,7 @@ async fn a_draft_saved_during_its_accounts_purges_goes_with_them() { }; // Both purges wait: one for the draft, the other behind it. tokio::join!(purge(named[0]), purge(named[1]), async { - until_blocked(&mut drafting, 2).await; + drafting.until_blocked(2).await; drafting.commit().await.expect("commit"); }); let left = AnnouncementRepository::from_pool(&pool).find(id).await; diff --git a/crates/database/src/transaction.rs b/crates/database/src/transaction.rs index c2b43a768..d7e4dd8d3 100644 --- a/crates/database/src/transaction.rs +++ b/crates/database/src/transaction.rs @@ -198,14 +198,13 @@ impl<'a> DatabaseTransaction<'a> { } /// Counts the other transactions waiting for a lock this one holds, directly - /// or queued behind another such waiter, so tests can order concurrent work - /// on what the database is doing rather than on sleeps. + /// or queued behind another such waiter, for [`Self::until_blocked`]. /// /// # Errors /// /// Returns [`DatabaseError`] if the query fails. #[cfg(any(test, feature = "test-util"))] - pub async fn blocked_transactions(&mut self) -> Result { + pub(crate) async fn blocked_transactions(&mut self) -> Result { sqlx::query_scalar!( // `pg_locks` is read afresh by every query; `pg_stat_activity` would // keep the backends this transaction saw first. diff --git a/docs/dev/testing.md b/docs/dev/testing.md index 630ab7c8e..e93ff4b53 100644 --- a/docs/dev/testing.md +++ b/docs/dev/testing.md @@ -80,8 +80,9 @@ throw away, never one that holds real accounts. A TCP URL must include A new database test starts from the fixtures in `crates/database/src/fixtures.rs`. `Database::test()` connects with the limits every connection of the service has. `insert_named` creates an account, `InsertSession::lasting` describes a session, -`known_history` lists an account's events, and `test_channels!` declares channels -whose deliveries a test inserts itself. +`known_history` lists an account's events, `until_blocked` waits until other +transactions queue behind a lock a transaction holds, and `test_channels!` +declares channels whose deliveries a test inserts itself. Another crate's tests get them through the `test-util` feature. A test in `crates/database` that inserts rows with plain SQL connects through `Database::test_pool()` instead, and auth-service's tests use `Replicas`, From 9263ae493671fd76c765586d6ed9b22dd0db32e0 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 15:11:48 +0100 Subject: [PATCH 2/2] test(database): the lock-wait polls agree on where PostgreSQL shows a wait --- crates/database/src/connection/mod.rs | 4 ++-- crates/database/src/fixtures.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/database/src/connection/mod.rs b/crates/database/src/connection/mod.rs index 359e01c80..2f6d1bf67 100644 --- a/crates/database/src/connection/mod.rs +++ b/crates/database/src/connection/mod.rs @@ -424,8 +424,8 @@ impl Database { .await .expect("wait state") { - // wall-clock: PostgreSQL shows a lock wait only in - // `pg_stat_activity`, and signals nothing when one starts. + // wall-clock: PostgreSQL shows lock waits only in its catalog views, + // and signals nothing when one starts. tokio::time::sleep(Duration::from_millis(10)).await; } }) diff --git a/crates/database/src/fixtures.rs b/crates/database/src/fixtures.rs index 1fc94ebee..dba4eb43d 100644 --- a/crates/database/src/fixtures.rs +++ b/crates/database/src/fixtures.rs @@ -135,8 +135,8 @@ impl DatabaseTransaction<'_> { pub async fn until_blocked(&mut self, waiters: i64) { tokio::time::timeout(Duration::from_secs(10), async { while self.blocked_transactions().await.expect("lock waits") < waiters { - // wall-clock: PostgreSQL shows a lock wait only in `pg_locks`, and - // signals nothing when one starts. + // wall-clock: PostgreSQL shows lock waits only in its catalog views, + // and signals nothing when one starts. tokio::time::sleep(Duration::from_millis(10)).await; } })