PostgreSQL store: the docs do not say that appends can fail under SERIALIZABLE

Open Beginner friendly
#592 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
76/100
Issue type
Documentation
Clarity
Clearly specified
Activity status
Active
Tech stack
postgresql, rust

Research direction

Read the Usage connection options in tellus-persistence-postgres/README.md and the examples in tellus-persistence-postgres/src/lib.rs, then check the append statement and error mapping there. Update the docs to name the supported isolation level and set it in the connection options as suggested; done means the examples and documentation consistently state the behavior under SERIALIZABLE and configure the selected level.

Written by the indexing model from the issue text.

Description

documentation

The README and the crate documentation name no isolation level, and the pool of the Usage section inherits the database's default. Under a default of SERIALIZABLE, e.g. after ALTER DATABASE tellus SET default_transaction_isolation = 'serializable', two appends to different streams at once can fail: one of them gets AppendError::Store with SQLSTATE 40001, although nothing else appended to its stream. Of two appends racing at the head of one stream, the loser gets the same store error instead of AppendError::Conflict.

The append is one statement which reads the stream's head with MAX(seq_no) before it inserts. PostgreSQL can abort one of two such statements when each has read before the other inserted. Whether it does for two different streams depends on where their keys lie in the primary key's index. In the tests below the table is empty, and on an empty index PostgreSQL takes the read's predicate lock on the whole index.

tellus fails the actor on a failed append, whatever the error (spawn.rs 724 to 727). Under the default supervision strategy the actor then stops, and under Restart the command is lost (docs/persistence.md 216).

README.md 152 to 154 states the conflict without a condition: "Appends are a single atomic, conditional statement: an expected next sequence number other than the actual one fails with AppendError::Conflict and leaves the stream untouched, which is tellus's fencing guarantee." The crate documentation says the same (lib.rs 9 to 12). The connection options of the Usage section set only statement_timeout (README.md 33 to 35, lib.rs 28 to 30). The failures of appends to different streams contradict no sentence, since EventStore::append may fail with a store error "if the events cannot be written" (store.rs 42 to 45).

The two tests below are for tellus-persistence-postgres/tests/store.rs and use its COMPOSE, TIMEOUT and database. The tests go after a_stale_writer_at_the_bigint_limit_is_a_conflict, GATE with the other constants and the three helpers in front of store. A trigger holds each insert back until both appends have read their stream's head, so no timing decides the order. The store's pool sets default_transaction_isolation to READ COMMITTED:

/// The key of the advisory lock which holds back every insert into `tellus_events` while a session
/// holds it exclusively.
const GATE: i64 = 4_242;

/// Under a database default of SERIALIZABLE, two appends to different streams at once both
/// succeed on a pool which sets `default_transaction_isolation` to READ COMMITTED, also when each
/// has read its stream's head before the other inserts.
#[tokio::test]
async fn appends_to_two_streams_at_once_succeed_under_a_serializable_database_default() {
    let (store, gate, _container) = serializable_database().await;
    let a = PersistenceId::new("isolation", "a").expect("the segments are valid");
    let b = PersistenceId::new("isolation", "b").expect("the segments are valid");

    let appended = appended_at_once(&store, &gate, [&a, &b]).await;
    assert!(
        matches!(appended, [Ok(()), Ok(())]),
        "two appends to different streams must both succeed, got {appended:?}"
    );
}

/// Under a database default of SERIALIZABLE, two appends at once at the head of one stream are
/// fenced on a pool which sets `default_transaction_isolation` to READ COMMITTED: one succeeds,
/// and the other fails with a conflict.
#[tokio::test]
async fn a_lost_race_is_a_conflict_under_a_serializable_database_default() {
    let (store, gate, _container) = serializable_database().await;
    let id = PersistenceId::new("isolation", "a").expect("the segments are valid");

    let appended = appended_at_once(&store, &gate, [&id, &id]).await;
    assert!(
        matches!(
            appended,
            [Ok(()), Err(AppendError::Conflict)] | [Err(AppendError::Conflict), Ok(())]
        ),
        "of two appends at one head, one must succeed and the other fail with Conflict, got \
         {appended:?}"
    );
}

/// A store over a pool which sets `default_transaction_isolation` to READ COMMITTED, on a database
/// whose default isolation level is SERIALIZABLE, and a pool without that setting. Every insert
/// into `tellus_events` waits while a session holds the advisory lock [GATE].
async fn serializable_database() -> (PostgresStore, PgPool, ContainerAsync<Postgres>) {
    let (pool, container) = database().await;
    PostgresStore::new(pool.clone())
        .migrate()
        .await
        .expect("the migrations run");
    let dbname = COMPOSE.service("postgres").env("POSTGRES_DB");
    sqlx::raw_sql(AssertSqlSafe(format!(
        "ALTER DATABASE {dbname} SET default_transaction_isolation = 'serializable'; \
         CREATE FUNCTION gate() RETURNS trigger LANGUAGE plpgsql AS $$ \
         BEGIN PERFORM pg_advisory_xact_lock_shared({GATE}); RETURN NEW; END $$; \
         CREATE TRIGGER gate BEFORE INSERT ON tellus_events \
         FOR EACH ROW EXECUTE FUNCTION gate();"
    )))
    .execute(&pool)
    .await
    .expect("the database is set up");

    let options = pool
        .connect_options()
        .as_ref()
        .clone()
        .options([("default_transaction_isolation", "read committed")]);
    let store = PgPool::connect_with(options)
        .await
        .map(PostgresStore::new)
        .expect("the pool connects");

    (store, pool, container)
}

/// Appends one event to each of the two streams at once, both expecting an empty stream. Both
/// appends have read their stream's head before either inserts: the gate opens only once both wait
/// behind it.
async fn appended_at_once(
    store: &PostgresStore,
    gate: &PgPool,
    ids: [&PersistenceId; 2],
) -> [Result<(), AppendError<Error>>; 2] {
    let mut closed = gate.acquire().await.expect("a connection is acquired");
    sqlx::query("SELECT pg_advisory_lock($1)")
        .bind(GATE)
        .execute(&mut *closed)
        .await
        .expect("the gate closes");
    let event = EncodedEvent {
        manifest: "isolation".into(),
        schema_version: SchemaVersion::new(1),
        payload: vec![1],
    };

    let opening = async {
        timeout(TIMEOUT, async {
            while waiting_behind_the_gate(gate).await < 2 {
                sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("both appends must wait behind the gate");
        sqlx::query("SELECT pg_advisory_unlock($1)")
            .bind(GATE)
            .execute(&mut *closed)
            .await
            .expect("the gate opens");
    };
    let (first, second, ()) = tokio::join!(
        store.append(ids[0], SeqNo::ZERO, vec![event.clone()]),
        store.append(ids[1], SeqNo::ZERO, vec![event]),
        opening,
    );
    [first, second]
}

async fn waiting_behind_the_gate(pool: &PgPool) -> i64 {
    sqlx::query_scalar::<_, i64>(
        "SELECT count(*) FROM pg_locks \
         WHERE locktype = 'advisory' AND objid = $1 AND NOT granted",
    )
    .bind(GATE)
    .fetch_one(pool)
    .await
    .expect("the locks are read")
}

They also need sqlx::AssertSqlSafe and tokio::time::sleep among the imports. With the .options(...) call removed, the store's pool inherits the database default, as the pool of the Usage section does. Both tests then fail in 10 of 10 runs of cargo test -p tellus-persistence-postgres --test store under_a_serializable_database_default, each time with 40001. One run, with the note:, failures: and error: lines left out:

running 2 tests
test appends_to_two_streams_at_once_succeed_under_a_serializable_database_default ... FAILED
test a_lost_race_is_a_conflict_under_a_serializable_database_default ... FAILED

---- appends_to_two_streams_at_once_succeed_under_a_serializable_database_default stdout ----

thread 'appends_to_two_streams_at_once_succeed_under_a_serializable_database_default' (18960955) panicked at tellus-persistence-postgres/tests/store.rs:146:5:
two appends to different streams must both succeed, got [Ok(()), Err(Store(Sqlx(Database(PgDatabaseError { severity: Error, code: "40001", message: "could not serialize access due to read/write dependencies among transactions", detail: Some("Reason code: Canceled on identification as a pivot, during commit attempt."), hint: Some("The transaction might succeed if retried."), position: None, where: None, schema: None, table: None, column: None, data_type: None, constraint: None, file: Some("predicate.c"), line: Some(4652), routine: Some("PreCommit_CheckForSerializationFailure") }))))]

---- a_lost_race_is_a_conflict_under_a_serializable_database_default stdout ----

thread 'a_lost_race_is_a_conflict_under_a_serializable_database_default' (18960954) panicked at tellus-persistence-postgres/tests/store.rs:161:5:
of two appends at one head, one must succeed and the other fail with Conflict, got [Ok(()), Err(Store(Sqlx(Database(PgDatabaseError { severity: Error, code: "40001", message: "could not serialize access due to read/write dependencies among transactions", detail: Some("Reason code: Canceled on identification as a pivot, during write."), hint: Some("The transaction might succeed if retried."), position: None, where: None, schema: None, table: None, column: None, data_type: None, constraint: None, file: Some("predicate.c"), line: Some(4593), routine: Some("OnConflict_CheckForSerializationFailure") }))))]

test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured; 16 filtered out; finished in 1.16s

As written, both pass in 10 of 10 runs, and so they do in 10 of 10 with repeatable read in place of read committed.

The statement and its error mapping are in lib.rs 157 to 182. It runs at the session's default isolation level, and every error but a unique violation becomes AppendError::Store.

Suggestion: name the isolation level the store relies on in the README and the crate documentation: READ COMMITTED, PostgreSQL's default, or REPEATABLE READ, not SERIALIZABLE. Set it in the connection options of the Usage section, of the example in lib.rs and of the crate's three examples, e.g. .options([("statement_timeout", "3s"), ("default_transaction_isolation", "read committed")]). A startup option takes precedence over the database default, which the two tests pin.

Dominant language
Rust
Stars
37
Forks
1
Avg merge
4h 56m
Merged PRs (30d)
219

Getting set up

  • Ships a Dockerfile or Docker Compose file
  • No pull request template
  • No contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from tellus-rs/tellus

All issues in tellus-rs/tellus

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.