1
//! The script tag write-back on the tag lock protocol: its retries, under
2
//! forced interleavings.
3

            
4
use super::lock_protocol::link_raw_tag;
5
use super::lock_protocol_create::GROCERIES_SCRIPT_WASM;
6
use super::*;
7
use crate::db::DBError;
8
use crate::error::ServerError;
9
use crate::script::{TransactionState, load_transaction_state};
10
use crate::script_tags::write_one;
11
use scripting::ScriptExecutor;
12
use sqlx::Connection;
13

            
14
4
async fn loaded(fx: &Fixture, tx_id: Uuid) -> anyhow::Result<TransactionState> {
15
4
    load_transaction_state(fx.user.id, tx_id)
16
4
        .await?
17
        .ok_or_else(|| anyhow::anyhow!("not loaded"))
18
4
}
19

            
20
/// `state` with the transaction tags `tags` created by scripts.
21
3
fn with_created(mut state: TransactionState, tags: &[(&str, &str)]) -> TransactionState {
22
3
    for (name, value) in tags {
23
4
        let created = tag(name, value);
24
4
        state.created_tags.insert(created.id);
25
4
        state.transaction_tags.push(created);
26
    }
27
3
    state
28
3
}
29

            
30
2
async fn lock_split_row(conn: &mut sqlx::PgConnection, split: Uuid) -> anyhow::Result<()> {
31
2
    sqlx::query("SELECT id FROM splits WHERE id = $1 FOR UPDATE")
32
2
        .bind(split)
33
2
        .fetch_one(conn)
34
2
        .await?;
35
2
    Ok(())
36
2
}
37

            
38
/// The splits the scripts tagged, in the order the write-back writes them.
39
1
fn tagged_splits(state: &TransactionState) -> Vec<Uuid> {
40
1
    state
41
1
        .split_tags
42
1
        .iter()
43
2
        .filter(|(_, tag)| state.created_tags.contains(&tag.id))
44
2
        .map(|(split, _)| *split)
45
        .collect()
46
1
}
47

            
48
/// The write-back holds its tag keys and stalls on the first tagged split; a
49
/// holder of the second split then waits for a key. Released, the write-back
50
/// meets the holder and is aborted with a deadlock, then retries in a fresh
51
/// transaction from the scripts' output. The script is deleted while the
52
/// first attempt stalls, so a retry that reran scripts would lose its tags.
53
#[local_db_sqlx_test]
54
async fn write_back_retries_a_deadlock_without_rerunning_scripts(
55
    pool: PgPool,
56
) -> anyhow::Result<()> {
57
    let fx = fixture().await?;
58
    let tx_id = fx.create_tx(Some("groceries")).await?;
59
    let script = fx
60
        .user
61
        .create_script(GROCERIES_SCRIPT_WASM.to_vec(), None)
62
        .await?;
63
    let report = loaded(&fx, tx_id).await?.run_scripts(
64
        &ScriptExecutor::try_new()?,
65
        &[(script, GROCERIES_SCRIPT_WASM.to_vec())],
66
    )?;
67
    anyhow::ensure!(report.failures.is_empty(), "{:?}", report.failures);
68
    let state = report.state;
69
    let [first, second] = tagged_splits(&state)[..] else {
70
        anyhow::bail!("the script tags both splits");
71
    };
72
    let mut stall_conn = fx.user.get_connection().await?;
73
    let mut stall = stall_conn.begin().await?;
74
    lock_split_row(&mut stall, first).await?;
75
    let mut cycle_conn = fx.user.get_connection().await?;
76
    let mut cycle = cycle_conn.begin().await?;
77
    lock_split_row(&mut cycle, second).await?;
78

            
79
    let write_back = write_one(fx.user, tx_id, &state);
80
1
    let steer = steer_deadlock(&fx, stall, cycle, ("category", "groceries"), async {
81
1
        fx.user.delete_script(script).await?;
82
1
        Ok(())
83
1
    });
84
    let (written, steered) = tokio::join!(write_back, steer);
85
    steered?;
86
    written?;
87

            
88
    assert!(fx.user.list_scripts().await?.is_empty());
89
    for split in [first, second] {
90
        assert_eq!(fx.split_tag_values(split).await?, vec!["groceries"]);
91
    }
92
}
93

            
94
/// The write-back and an edit of another transaction write the same two
95
/// keys; a third connection holds the later one while both queue.
96
#[local_db_sqlx_test]
97
async fn write_back_and_an_edit_sharing_tags_do_not_deadlock(pool: PgPool) -> anyhow::Result<()> {
98
    let fx = fixture().await?;
99
    let (scripted, edited) = (fx.create_tx(None).await?, fx.create_tx(None).await?);
100
    let state = with_created(loaded(&fx, scripted).await?, &[("a", "1"), ("z", "9")]);
101
    let mut conn = fx.user.get_connection().await?;
102
    let mut holder = conn.begin().await?;
103
    hold_key(&mut holder, "z", "9").await?;
104

            
105
    let write_back = write_one(fx.user, scripted, &state);
106
    let edit = UpdateTransaction::new()
107
        .user_id(fx.user.id)
108
        .transaction_id(edited)
109
        .tags(tag_map(&[("a", "1"), ("z", "9")]))
110
        .run();
111
    let release = release_after(wait_for_blocked(&fx, 2), holder);
112
    let (w, e, r) = tokio::join!(write_back, edit, release);
113
    r?;
114
    assert_no_deadlock(&w);
115
    assert_no_deadlock(&e);
116
    w?;
117
    e?;
118
    for tx_id in [scripted, edited] {
119
        assert_eq!(
120
            fx.tx_tags(tx_id).await?,
121
            vec![pair("a", "1"), pair("z", "9")]
122
        );
123
    }
124
}
125

            
126
/// A linked tag renamed while the write-back waits for its key is a
127
/// transient `KeyChanged`; the retry then sees the changed revision and
128
/// refuses, writing nothing.
129
#[local_db_sqlx_test]
130
async fn a_rename_before_the_lock_retries_and_refuses_as_stale(pool: PgPool) -> anyhow::Result<()> {
131
    let fx = fixture().await?;
132
    let tx_id = fx.create_tx(None).await?;
133
    let linked = link_raw_tag(&pool, tx_id, "cat", "k0").await?;
134
    let state = with_created(loaded(&fx, tx_id).await?, &[("zone", "z")]);
135
    let mut conn = fx.user.get_connection().await?;
136
    let mut renamer = conn.begin().await?;
137
    hold_key(&mut renamer, "cat", "k0").await?;
138
    rename(&mut renamer, linked, "k1").await?;
139

            
140
    let steer = release_after(wait_for_key_waiter(&fx, "cat", "k0"), renamer);
141
    let (written, steered) = tokio::join!(write_one(fx.user, tx_id, &state), steer);
142
    steered?;
143
    match written {
144
        Err(ServerError::Script(message)) => assert_eq!(message, crate::logical::STALE_REVISION),
145
        other => anyhow::bail!("the write-back must be refused as stale: {other:?}"),
146
    }
147
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("cat", "k1")]);
148
    assert_eq!(fx.tag_rows_with_value("z").await?, 0);
149
}
150

            
151
/// Every attempt finds its linked tag renamed: after the last one the
152
/// write-back fails with a write conflict and writes nothing.
153
#[local_db_sqlx_test]
154
async fn three_renames_fail_the_write_back_without_writing(pool: PgPool) -> anyhow::Result<()> {
155
    let fx = fixture().await?;
156
    let tx_id = fx.create_tx(None).await?;
157
    let linked = link_raw_tag(&pool, tx_id, "cat", "k0").await?;
158
    let state = with_created(loaded(&fx, tx_id).await?, &[("zone", "z")]);
159
    let mut conns = Vec::new();
160
    for _ in 0..3 {
161
        conns.push(fx.user.get_connection().await?);
162
    }
163
    let mut holders = Vec::new();
164
    for ((conn, held), next) in conns
165
        .iter_mut()
166
        .zip(["k0", "k1", "k2"])
167
        .zip(["k1", "k2", "k3"])
168
    {
169
        let mut holder = conn.begin().await?;
170
        hold_key(&mut holder, "cat", held).await?;
171
        holders.push((holder, held, next));
172
    }
173

            
174
    let steer = rename_in_turn(&fx, "cat", linked, holders);
175
    let (written, steered) = tokio::join!(write_one(fx.user, tx_id, &state), steer);
176
    steered?;
177
    assert!(
178
        matches!(written, Err(ServerError::DB(DBError::WriteConflict))),
179
        "{written:?}"
180
    );
181
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("cat", "k3")]);
182
    assert_eq!(fx.tag_rows_with_value("z").await?, 0);
183
}