Lines
100 %
Functions
Branches
//! `DeleteTransaction` on the tag lock protocol under forced interleavings.
use super::lock_protocol::link_raw_tag;
use super::*;
use crate::command::CmdError;
use crate::db::DBError;
use crate::error::ServerError;
use sqlx::Connection;
fn delete(
fx: &Fixture,
tx_id: Uuid,
) -> impl std::future::Future<Output = Result<Option<CmdResult>, CmdError>> {
DeleteTransaction::new()
.user_id(fx.user.id)
.transaction_id(tx_id)
.run()
}
async fn tag_rows_named(pool: &PgPool, name: &str) -> anyhow::Result<Vec<String>> {
let mut values: Vec<String> =
sqlx::query_scalar("SELECT tag_value FROM tags WHERE tag_name = $1")
.bind(name)
.fetch_all(pool)
.await?;
values.sort();
Ok(values)
/// A padded `cat= x` linked to the transaction merges into `cat=x`, the lower
/// id. A third connection holds the padded row: the trim job queues on it,
/// then the delete. Released, the trim job moves the link the delete wants,
/// while the delete waits for the padded row: without the key locks the two
/// meet in a deadlock.
#[local_db_sqlx_test]
async fn delete_and_the_trim_job_do_not_deadlock(pool: PgPool) -> anyhow::Result<()> {
let fx = fixture().await?;
let tx_id = fx.create_tx(None).await?;
let other = fx.create_tx(None).await?;
let mut ids = [Uuid::new_v4(), Uuid::new_v4()];
ids.sort();
let [survivor, loser] = ids;
for (id, value) in [(survivor, "x"), (loser, " x")] {
sqlx::query("INSERT INTO tags (id, tag_name, tag_value) VALUES ($1, 'cat', $2)")
.bind(id)
.bind(value)
.execute(&pool)
for (owner, tag_id) in [(other, survivor), (tx_id, loser)] {
sqlx::query_file!(
"sql/insert/transaction_tags/transaction_tag.sql",
owner,
tag_id
)
let mut blocker_conn = fx.user.get_connection().await?;
let mut blocker = blocker_conn.begin().await?;
sqlx::query_file!("sql/select/tags/lock_by_id.sql", loser)
.fetch_one(&mut *blocker)
let mut trim_conn = fx.user.get_connection().await?;
let trim = crate::fleet::run_tenant_jobs(&mut trim_conn);
let deleted = async {
wait_for_blocked(&fx, 1).await?;
delete(&fx, tx_id).await.map_err(anyhow::Error::from)
};
let release = release_after(wait_for_blocked(&fx, 2), blocker);
let (trimmed, deleted, released) = tokio::join!(trim, deleted, release);
released?;
assert_no_deadlock(&trimmed);
assert_no_deadlock(&deleted);
trimmed?;
deleted?;
assert_eq!(fx.transaction_count(tx_id).await?, 0);
assert_eq!(fx.tx_tags(other).await?, vec![pair("cat", "x")]);
assert_eq!(tag_rows_named(&pool, "cat").await?, vec!["x"]);
/// The delete and an edit of another transaction both want the shared `a`,
/// held by a third connection; both finish, and `a` survives for the edit.
async fn delete_and_an_edit_sharing_a_tag_do_not_deadlock(pool: PgPool) -> anyhow::Result<()> {
let (deleted, edited) = (fx.create_tx(None).await?, fx.create_tx(None).await?);
UpdateTransaction::new()
.transaction_id(deleted)
.tags(tag_map(&[("a", "1"), ("z", "9")]))
let mut conn = fx.user.get_connection().await?;
let mut holder = conn.begin().await?;
hold_key(&mut holder, "a", "1").await?;
let delete = delete(&fx, deleted);
let edit = UpdateTransaction::new()
.transaction_id(edited)
.tags(tag_map(&[("a", "1")]))
.run();
let release = release_after(wait_for_blocked(&fx, 2), holder);
let (d, e, r) = tokio::join!(delete, edit, release);
r?;
assert_no_deadlock(&d);
assert_no_deadlock(&e);
d?;
e?;
assert_eq!(fx.transaction_count(deleted).await?, 0);
assert_eq!(fx.tx_tags(edited).await?, vec![pair("a", "1")]);
assert_eq!(tag_rows_named(&pool, "a").await?, vec!["1"]);
assert!(tag_rows_named(&pool, "z").await?.is_empty());
/// The linked tag is renamed while the delete waits for its key: the retry
/// locks the new key and drops the renamed row with the transaction.
async fn a_rename_before_the_lock_retries_the_delete(pool: PgPool) -> anyhow::Result<()> {
let linked = link_raw_tag(&pool, tx_id, "cat", "k0").await?;
let mut renamer = conn.begin().await?;
hold_key(&mut renamer, "cat", "k0").await?;
rename(&mut renamer, linked, "k1").await?;
let steer = release_after(wait_for_key_waiter(&fx, "cat", "k0"), renamer);
let (deleted, steered) = tokio::join!(delete(&fx, tx_id), steer);
steered?;
assert!(tag_rows_named(&pool, "cat").await?.is_empty());
/// Every attempt finds its linked tag renamed: after the last one the delete
/// fails and deletes nothing.
async fn three_renames_fail_the_delete_without_deleting(pool: PgPool) -> anyhow::Result<()> {
let tx_id = fx.create_tx(Some("kept")).await?;
let splits = fx.split_ids(tx_id).await?;
let mut conns = Vec::new();
for _ in 0..3 {
conns.push(fx.user.get_connection().await?);
let mut holders = Vec::new();
for ((conn, held), next) in conns
.iter_mut()
.zip(["k0", "k1", "k2"])
.zip(["k1", "k2", "k3"])
{
hold_key(&mut holder, "cat", held).await?;
holders.push((holder, held, next));
let steer = rename_in_turn(&fx, "cat", linked, holders);
assert!(
matches!(
deleted,
Err(CmdError::Server(ServerError::DB(DBError::WriteConflict)))
),
"{deleted:?}"
);
assert_eq!(fx.transaction_count(tx_id).await?, 1);
assert_eq!(fx.split_ids(tx_id).await?, splits);
assert_eq!(
fx.tx_tags(tx_id).await?,
vec![pair("cat", "k3"), pair("note", "kept")]