Lines
97.73 %
Functions
85.71 %
Branches
100 %
//! Edits on the tag lock protocol under forced interleavings.
use super::*;
use crate::command::CmdError;
use crate::db::DBError;
use crate::error::ServerError;
use sqlx::Connection;
/// Insert the tag row `(name, value)` verbatim and link it to `tx_id`.
pub(super) async fn link_raw_tag(
pool: &PgPool,
tx_id: Uuid,
name: &str,
value: &str,
) -> anyhow::Result<Uuid> {
let id = Uuid::new_v4();
sqlx::query("INSERT INTO tags (id, tag_name, tag_value) VALUES ($1, $2, $3)")
.bind(id)
.bind(name)
.bind(value)
.execute(pool)
.await?;
sqlx::query_file!("sql/insert/transaction_tags/transaction_tag.sql", tx_id, id)
Ok(id)
}
fn edit_tags(
fx: &Fixture,
tags: &[(&str, &str)],
) -> impl std::future::Future<Output = Result<Option<CmdResult>, CmdError>> {
UpdateTransaction::new()
.user_id(fx.user.id)
.transaction_id(tx_id)
.tags(tag_map(tags))
.run()
/// Two edits of transactions linked to a padded stored tag both write its
/// normalized key; the first queues on the padded row, the second on its key.
#[local_db_sqlx_test]
async fn padded_stored_key_and_normalized_destination_do_not_deadlock(
pool: PgPool,
) -> anyhow::Result<()> {
let fx = fixture().await?;
let (first, second) = (fx.create_tx(None).await?, fx.create_tx(None).await?);
let padded = link_raw_tag(&pool, first, "cat", " x").await?;
sqlx::query_file!(
"sql/insert/transaction_tags/transaction_tag.sql",
second,
padded
)
.execute(&pool)
let mut conn = fx.user.get_connection().await?;
let mut blocker = conn.begin().await?;
sqlx::query_file!("sql/select/tags/lock_by_id.sql", padded)
.fetch_one(&mut *blocker)
let wanted = [("cat", "x"), ("zone", "z")];
let release = async {
let waited = wait_for_blocked(&fx, 2).await;
blocker.commit().await?;
waited
};
let (a, b, r) = tokio::join!(
edit_tags(&fx, first, &wanted),
edit_tags(&fx, second, &wanted),
release
);
r?;
a?;
b?;
for tx_id in [first, second] {
assert_eq!(
fx.tx_tags(tx_id).await?,
vec![pair("cat", " x"), pair("zone", "z")]
/// A linked tag is renamed while the edit waits for its key: the attempt sees
/// `KeyChanged`, and the retry runs in a fresh DB transaction, since the
/// first attempt's key locks are gone while the retry waits.
async fn a_rename_before_the_lock_retries_in_a_fresh_transaction(
let tx_id = fx.create_tx(None).await?;
let linked = link_raw_tag(&pool, tx_id, "cat", "k0").await?;
let mut first_conn = fx.user.get_connection().await?;
let mut renamer = first_conn.begin().await?;
hold_key(&mut renamer, "cat", "k0").await?;
rename(&mut renamer, linked, "k1").await?;
let mut second_conn = fx.user.get_connection().await?;
let mut holder = second_conn.begin().await?;
hold_key(&mut holder, "cat", "k1").await?;
let edit = edit_tags(&fx, tx_id, &[("zone", "z")]);
let steer = async {
let renamed = release_after(wait_for_key_waiter(&fx, "cat", "k0"), renamer).await;
let retry_waits = async {
renamed?;
wait_for_key_waiter(&fx, "cat", "k1").await?;
anyhow::Ok(key_is_free(&fx, "cat", "k0").await? && key_is_free(&fx, "zone", "z").await?)
release_after(retry_waits, holder).await
let (edited, steered) = tokio::join!(edit, steer);
assert!(steered?, "the retry still held the first attempt's locks");
edited?;
assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("zone", "z")]);
/// Every attempt finds its linked tag renamed: after the last one the edit
/// fails and writes nothing.
async fn three_renames_fail_the_edit_without_writing(pool: PgPool) -> anyhow::Result<()> {
let tx_id = fx.create_tx(Some("kept")).await?;
let before = 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"])
{
let mut holder = conn.begin().await?;
hold_key(&mut holder, "cat", held).await?;
holders.push((holder, held, next));
let new_date = Utc.with_ymd_and_hms(2001, 2, 3, 4, 5, 6).single();
let new_date = new_date.ok_or_else(|| anyhow::anyhow!("date"))?;
let edit = UpdateTransaction::new()
.tags(tag_map(&[("zone", "z")]))
.post_date(new_date)
.splits(fx.splits(tx_id, 7))
.note("changed".to_string())
.run();
let steer = rename_in_turn(&fx, "cat", linked, holders);
steered?;
assert!(
matches!(
edited,
Err(CmdError::Server(ServerError::DB(DBError::WriteConflict)))
),
"{edited:?}"
vec![pair("cat", "k3"), pair("note", "kept")]
assert_eq!(fx.split_ids(tx_id).await?, before);
assert_eq!(fx.tag_rows_with_value("z").await?, 0);
let row = sqlx::query_file!("sql/select/transactions/by_id.sql", tx_id)
.fetch_one(&mut *conn)
assert_ne!(row.post_date, new_date);