Lines
91.03 %
Functions
97.83 %
Branches
100 %
//! Lock waits that tests force and observe, so a test cannot pass without the
//! contention it claims to exercise.
use super::Fixture;
use sqlx::types::Uuid;
use sqlx::{PgConnection, Postgres, Transaction};
/// The advisory key of `sql/select/tags/lock_key.sql`, as a SQL expression.
macro_rules! key_hash {
() => {
"hashtextextended(length($1::text)::text || ':' || $1 || $2::text, 0)"
};
}
/// Every wait gives up after `POLLS * POLL_PAUSE` (30 s) and fails the test.
const POLLS: usize = 1500;
const POLL_PAUSE: std::time::Duration = std::time::Duration::from_millis(20);
/// Polls until at least `count` backends of this database wait on a lock.
pub(in crate::command) async fn wait_for_blocked(fx: &Fixture, count: i64) -> anyhow::Result<()> {
let mut conn = fx.user.get_connection().await?;
wait_for_blocked_on(&mut conn, count).await
/// Same, polling on an already held connection, for tests whose commands
/// leave no pooled connection free to poll with. Inside a transaction
/// `pg_stat_activity` is a frozen snapshot that misses backends connecting
/// later, so each poll clears it.
pub(in crate::command) async fn wait_for_blocked_on(
conn: &mut PgConnection,
count: i64,
) -> anyhow::Result<()> {
for _ in 0..POLLS {
sqlx::query("SELECT pg_stat_clear_snapshot()")
.execute(&mut *conn)
.await?;
let waiting: i64 = sqlx::query_scalar(
"SELECT count(*) FROM pg_stat_activity
WHERE datname = current_database() AND wait_event_type = 'Lock'",
)
.fetch_one(&mut *conn)
if waiting >= count {
return Ok(());
tokio::time::sleep(POLL_PAUSE).await;
anyhow::bail!("fewer than {count} backends ever waited on a lock")
/// Polls until a backend waits for the advisory lock of `(name, value)`.
pub(in crate::command) async fn wait_for_key_waiter(
fx: &Fixture,
name: &str,
value: &str,
let query = concat!(
"SELECT count(*) FROM pg_locks
WHERE locktype = 'advisory' AND NOT granted
AND database = (SELECT oid FROM pg_database WHERE datname = current_database())
AND ((classid::bigint << 32) | objid::bigint) = ",
key_hash!()
);
let waiting: i64 = sqlx::query_scalar(query)
.bind(name)
.bind(value)
if waiting > 0 {
anyhow::bail!("nobody ever waited for the key ({name}, {value})")
/// Take the advisory lock of `(name, value)` until `conn`'s transaction ends.
pub(in crate::command) async fn hold_key(
sqlx::query_file!("sql/select/tags/lock_key.sql", name, value)
.fetch_one(conn)
Ok(())
/// Whether no other transaction holds the advisory lock of `(name, value)`.
pub(in crate::command) async fn key_is_free(
) -> anyhow::Result<bool> {
let free: bool = sqlx::query_scalar(concat!("SELECT pg_try_advisory_lock(", key_hash!(), ")"))
if free {
sqlx::query(concat!("SELECT pg_advisory_unlock(", key_hash!(), ")"))
Ok(free)
/// Await `waited`, then commit `holder` whatever it returned: a wait that
/// fails must not leave the holder's locks blocking the commands under test,
/// since dropping a transaction only queues its rollback.
pub(in crate::command) async fn release_after<T>(
waited: impl Future<Output = anyhow::Result<T>>,
holder: Transaction<'_, Postgres>,
) -> anyhow::Result<T> {
let waited = waited.await;
holder.commit().await?;
waited
/// Set the stored value of the tag row `id`.
pub(in crate::command) async fn rename(
id: Uuid,
sqlx::query("UPDATE tags SET tag_value = $2 WHERE id = $1")
.bind(id)
.execute(conn)
/// Each `(holder, held, next)` in turn: once a backend waits for the held
/// key `(name, held)`, rename the tag row `id` to `next` and commit. A failed
/// wait rolls back this and every later holder before failing.
pub(in crate::command) async fn rename_in_turn(
holders: Vec<(Transaction<'_, Postgres>, &str, &str)>,
let mut pending = holders.into_iter();
while let Some((mut holder, held, next)) = pending.next() {
let renamed = async {
wait_for_key_waiter(fx, name, held).await?;
rename(&mut holder, id, next).await
.await;
if let Err(err) = renamed {
holder.rollback().await?;
for (rest, _, _) in pending {
rest.rollback().await?;
return Err(err);
/// Keeps the cycle holder from running its own deadlock check, so the command
/// under test is always the one that detects the cycle.
///
/// Only a superuser may set `deadlock_timeout`; the suites run as one in the
/// xtask private cluster.
async fn defer_deadlock_check(conn: &mut PgConnection) -> anyhow::Result<()> {
sqlx::query("SET LOCAL deadlock_timeout = '1min'")
.await
.map_err(|err| {
anyhow::anyhow!(
"setting deadlock_timeout needs a superuser; run the tests in the xtask \
private cluster (`cargo run -p xtask -- postgres -- cargo nextest run ...`): {err}"
})?;
/// Abort the command under test with a deadlock once: when it waits on
/// `stall`'s lock, run `during`; then `cycle` waits for the key `(name,
/// value)` the command holds, and `stall` is released, so the command meets
/// `cycle`. Both holders end on every path.
pub(in crate::command) async fn steer_deadlock(
stall: Transaction<'_, Postgres>,
mut cycle: Transaction<'_, Postgres>,
(name, value): (&str, &str),
during: impl Future<Output = anyhow::Result<()>>,
let started = async {
defer_deadlock_check(&mut cycle).await?;
wait_for_blocked(fx, 1).await?;
during.await
if let Err(err) = started {
stall.rollback().await?;
cycle.rollback().await?;
let waiter = async {
let held = hold_key(&mut cycle, name, value).await;
cycle.commit().await?;
held
let stalled = async {
wait_for_key_waiter(fx, name, value).await?;
anyhow::Ok(())
let (w, r) = tokio::join!(waiter, release_after(stalled, stall));
w?;
r