diff --git a/crates/core/src/expression/ast.rs b/crates/core/src/expression/ast.rs index 3ec2d3aef..91f8aeb8a 100755 --- a/crates/core/src/expression/ast.rs +++ b/crates/core/src/expression/ast.rs @@ -3,6 +3,9 @@ //! Expression AST types for condition and update expressions. +use super::resolver::{ExpressionMaps, resolve_name_ref}; +use crate::types::KeySchemaElement; + /// A single element in a document path. #[derive(Debug, Clone, PartialEq)] pub enum PathElement { @@ -104,6 +107,62 @@ pub fn removes_only(actions: &[UpdateAction]) -> bool { !actions.is_empty() && actions.iter().all(UpdateAction::removes_only) } +/// Whether `condition` holds exactly when the item does not exist. +/// +/// Every stored item carries its key attributes. So `attribute_not_exists` on +/// a key attribute holds against no item and fails against every item, +/// whatever else the item holds, and `attribute_exists` on one is its +/// opposite. `AND`, `OR` and `NOT` of such terms keep that property when their +/// operands agree, for example `attribute_not_exists(pk) AND +/// attribute_not_exists(sk)` or `NOT attribute_exists(pk)`. A backend can +/// decide such a condition by whether the key is taken, without reading the +/// item. A `#name` that does not resolve answers false, so that the request +/// takes the path that reports the validation error. +#[must_use] +pub fn requires_absent_item( + condition: &Expr, + key_schema: &[KeySchemaElement], + maps: &ExpressionMaps, +) -> bool { + holds_when_absent(condition, key_schema, maps) == Some(true) +} + +/// `Some(true)` when `condition` holds exactly when the item does not exist, +/// `Some(false)` when it holds exactly when the item exists, and `None` when +/// the key alone does not decide it. +fn holds_when_absent( + condition: &Expr, + key_schema: &[KeySchemaElement], + maps: &ExpressionMaps, +) -> Option { + match condition { + Expr::And(a, b) | Expr::Or(a, b) => { + let a = holds_when_absent(a, key_schema, maps)?; + (holds_when_absent(b, key_schema, maps)? == a).then_some(a) + } + Expr::Not(e) => holds_when_absent(e, key_schema, maps).map(|absent| !absent), + Expr::Function { name, args } => { + let absent = match name.as_str() { + "attribute_not_exists" => true, + "attribute_exists" => false, + _ => return None, + }; + let [Expr::Path(path)] = args.as_slice() else { + return None; + }; + let [PathElement::Attribute(attr)] = path.as_slice() else { + return None; + }; + let attr = resolve_name_ref(attr, maps).ok()?; + key_schema + .iter() + .any(|k| k.attribute_name == attr.as_ref()) + .then_some(absent) + } + _ => None, + } +} + #[cfg(test)] mod tests { use super::removes_only; @@ -132,3 +191,80 @@ mod tests { assert!(!removes_only(&actions("DELETE s :v ADD n :w"))); } } + +#[cfg(test)] +mod requires_absent_item_tests { + use super::requires_absent_item; + use crate::expression::parser::parse_condition; + use crate::expression::resolver::ExpressionMaps; + use crate::expression::tokenizer::tokenize; + use crate::types::{KeySchemaElement, KeyType}; + + fn check(expr: &str, names: &[(&str, &str)]) -> bool { + let schema = [ + KeySchemaElement { + attribute_name: "pk".to_owned(), + key_type: KeyType::Hash, + }, + KeySchemaElement { + attribute_name: "sk".to_owned(), + key_type: KeyType::Range, + }, + ]; + let cond = parse_condition(&tokenize(expr).expect("tokens")).expect("condition"); + let mut maps = ExpressionMaps::default(); + for (k, v) in names { + maps.names.insert((*k).to_owned(), (*v).to_owned()); + } + requires_absent_item(&cond, &schema, &maps) + } + + #[test] + fn terms_on_key_attributes_that_agree_require_an_absent_item() { + assert!(check("attribute_not_exists(pk)", &[])); + assert!(check("attribute_not_exists(sk)", &[])); + assert!(check("attribute_not_exists(#k)", &[("k", "pk")])); + assert!(check( + "attribute_not_exists(pk) AND attribute_not_exists(sk)", + &[] + )); + assert!(check( + "attribute_not_exists(pk) OR attribute_not_exists(sk)", + &[] + )); + assert!(check("NOT attribute_exists(pk)", &[])); + assert!(check( + "(NOT attribute_exists(pk)) AND (attribute_not_exists(sk))", + &[] + )); + assert!(check( + "NOT (attribute_exists(pk) OR attribute_exists(sk))", + &[] + )); + } + + #[test] + fn other_conditions_do_not() { + assert!(!check("attribute_exists(pk)", &[])); + assert!(!check("NOT attribute_not_exists(pk)", &[])); + assert!(!check("attribute_not_exists(other)", &[])); + assert!(!check("attribute_not_exists(#k)", &[("k", "other")])); + assert!(!check("attribute_not_exists(#missing)", &[])); + assert!(!check("attribute_not_exists(pk.x)", &[])); + assert!(!check("attribute_not_exists(pk[0])", &[])); + assert!(!check( + "attribute_not_exists(pk) AND attribute_not_exists(other)", + &[] + )); + assert!(!check( + "attribute_not_exists(pk) AND attribute_exists(sk)", + &[] + )); + assert!(!check( + "attribute_not_exists(pk) OR attribute_exists(sk)", + &[] + )); + assert!(!check("attribute_type(pk, :t)", &[])); + assert!(!check("pk = :v", &[])); + } +} diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 4e68df885..6c24055b8 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -29,7 +29,9 @@ mod tokenizer; mod update_evaluator; mod update_parser; -pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only}; +pub use ast::{ + ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only, requires_absent_item, +}; pub use evaluator::evaluate_condition; pub use key_condition::{ KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands, diff --git a/crates/storage-postgres/src/bootstrapper.rs b/crates/storage-postgres/src/bootstrapper.rs index 163234d29..41dd06d25 100755 --- a/crates/storage-postgres/src/bootstrapper.rs +++ b/crates/storage-postgres/src/bootstrapper.rs @@ -438,7 +438,8 @@ impl Bootstrapper for PostgresBootstrapper { r#"[storage.postgres] connection_string = "{}" # pool_size = 20 # Max connections for data operations (default 20, min 10) -# catalog_pool_size = # Max connections for management/catalog ops (defaults to pool_size, min 10)"#, +# catalog_pool_size = # Max connections for management/catalog ops (defaults to pool_size, min 10) +# create_only_puts = true # A PutItem with only attribute_not_exists on the key is one INSERT, no transaction"#, self.catalog_connection_url() ) } diff --git a/crates/storage-postgres/src/config.rs b/crates/storage-postgres/src/config.rs index 7162b5daa..acd4f6d62 100755 --- a/crates/storage-postgres/src/config.rs +++ b/crates/storage-postgres/src/config.rs @@ -25,6 +25,17 @@ pub struct PostgresStorageConfig { deserialize_with = "extenddb_storage::config::string_coerce::opt_u32" )] pub catalog_pool_size: Option, + /// Write a `PutItem` whose condition only says that the item must not + /// exist (`attribute_not_exists` on a key attribute) as one autocommit + /// `INSERT ... ON CONFLICT DO NOTHING`, when the table has no index and no + /// stream to maintain and the write is not already slow. `false` keeps + /// such puts on the transaction path. The answers are the same either + /// way. + #[serde( + default = "default_create_only_puts", + deserialize_with = "extenddb_storage::config::string_coerce::bool" + )] + pub create_only_puts: bool, } impl Default for PostgresStorageConfig { @@ -33,6 +44,7 @@ impl Default for PostgresStorageConfig { connection_string: default_connection_string(), pool_size: default_pool_size(), catalog_pool_size: None, + create_only_puts: default_create_only_puts(), } } } @@ -45,6 +57,10 @@ fn default_pool_size() -> u32 { 20 } +fn default_create_only_puts() -> bool { + true +} + /// Parsed components of a `PostgreSQL` connection string. pub struct ConnParts { pub user: String, @@ -172,6 +188,24 @@ catalog_pool_size = 10"#, assert_eq!(cfg.pool_size, 25); assert_eq!(cfg.catalog_pool_size, Some(10)); } + + /// `create_only_puts` is on when omitted, and an environment override + /// (`EXTENDDB__STORAGE__POSTGRES__CREATE_ONLY_PUTS=false`) arrives as a + /// string. + #[test] + fn create_only_puts_defaults_on_and_accepts_both_forms() { + let conn = r#"connection_string = "postgresql://u:p@localhost:5432/db""#; + for (extra, expected) in [ + ("", true), + ("create_only_puts = false", false), + ("create_only_puts = \"false\"", false), + ("create_only_puts = \"true\"", true), + ] { + let cfg: PostgresStorageConfig = + toml::from_str(&format!("{conn}\n{extra}")).expect("the config must deserialize"); + assert_eq!(cfg.create_only_puts, expected, "{extra:?}"); + } + } } #[cfg(test)] diff --git a/crates/storage-postgres/src/data/put_item.rs b/crates/storage-postgres/src/data/put_item.rs index e43f8f75e..3332a8f24 100755 --- a/crates/storage-postgres/src/data/put_item.rs +++ b/crates/storage-postgres/src/data/put_item.rs @@ -3,11 +3,13 @@ //! `put_item` and `get_item` implementations for the `PostgreSQL` backend. -use extenddb_core::expression::{Expr, ExpressionMaps}; +use extenddb_core::expression::{Expr, ExpressionMaps, requires_absent_item}; use extenddb_core::types::{Item, TableKeyInfo}; use extenddb_storage::StreamCapture; use extenddb_storage::error::StorageError; -use extenddb_storage::util::{composite_pk_to_text, parse_sk, pk_to_text, sk_column, sk_info}; +use extenddb_storage::util::{ + SortKeyValue, composite_pk_to_text, parse_sk, pk_to_text, sk_column, sk_info, +}; use super::gsi_build::fix_up_stale_write; use super::index::{enqueue_async_indexes, fetch_write_path_indexes, sync_indexes}; @@ -86,16 +88,23 @@ impl PostgresEngine { self.index_propagation_delay().await }; - // When there's a condition, return_old, indexes, or stream capture, we need a transaction - // A write that is already slow takes the transaction path even with no - // index to maintain, so that a repair for a GSI created meanwhile commits - // with the write (`gsi_build::fix_up_stale_write`) instead of after it. - let needs_tx = condition.is_some() - || return_old - || !indexes.is_empty() - || !vector_metas.is_empty() - || stream.is_some() - || stamp.elapsed() > super::gsi_build::GRACE_WRITE; + // A write takes a transaction when it has a condition, an old item to + // return, an index or a stream to maintain, or is already slow: a repair + // for a GSI created meanwhile then commits with the write + // (`gsi_build::fix_up_stale_write`) instead of after it. A create-only + // put with no index or stream to maintain is the exception: the key + // alone decides its condition (`requires_absent_item`), so one + // autocommit insert does (`insert_absent`). `return_old` does not keep + // it in a transaction, because a create-only put that succeeds found no + // old item. + let nothing_to_maintain = indexes.is_empty() + && vector_metas.is_empty() + && stream.is_none() + && stamp.elapsed() <= super::gsi_build::GRACE_WRITE; + let create_only = self.create_only_puts + && nothing_to_maintain + && condition.is_some_and(|c| requires_absent_item(c, &key_info.key_schema, maps)); + let needs_tx = !create_only && (condition.is_some() || return_old || !nothing_to_maintain); if let Some((sk_name, sk_type)) = sk_info(&key_info.key_schema, &key_info.attribute_definitions) @@ -157,10 +166,7 @@ impl PostgresEngine { } Err(e) => return Err(e), } - let insert_sql = format!( - "INSERT INTO {ddb_table} (pk, {sk_col}, item_data) VALUES ($1, $2, $3) \ - ON CONFLICT (pk, {sk_col}) DO NOTHING" - ); + let insert_sql = insert_if_absent_sql(&ddb_table, Some(sk_col)); let result = bind_sk_execute!( sqlx::AssertSqlSafe(insert_sql), pk_text.as_str(), @@ -278,6 +284,11 @@ impl PostgresEngine { } else { Ok(None) } + } else if create_only { + self.insert_absent(&ddb_table, &pk_text, Some((sk_col, &sk)), &item_json) + .await?; + self.fix_up_autocommit(stamp, key_info, &item).await; + Ok(None) } else { let upsert_sql = format!( "INSERT INTO {ddb_table} (pk, {sk_col}, item_data) VALUES ($1, $2, $3) \ @@ -347,10 +358,7 @@ impl PostgresEngine { } Err(e) => return Err(e), } - let insert_sql = format!( - "INSERT INTO {ddb_table} (pk, item_data) VALUES ($1, $2) \ - ON CONFLICT (pk) DO NOTHING" - ); + let insert_sql = insert_if_absent_sql(&ddb_table, None); let result = sqlx::query(sqlx::AssertSqlSafe(insert_sql)) .bind(pk_text.as_str()) .bind(&item_json) @@ -458,6 +466,11 @@ impl PostgresEngine { } else { Ok(None) } + } else if create_only { + self.insert_absent(&ddb_table, &pk_text, None, &item_json) + .await?; + self.fix_up_autocommit(stamp, key_info, &item).await; + Ok(None) } else { let upsert_sql = format!( "INSERT INTO {ddb_table} (pk, item_data) VALUES ($1, $2) \ @@ -525,6 +538,90 @@ impl PostgresEngine { /// bound as `UpdateItem`. const MAX_CREATE_RACE_ATTEMPTS: u32 = 5; +impl PostgresEngine { + /// A create-only put without a transaction: one `INSERT ... ON CONFLICT DO + /// NOTHING` of the item, keyed on `pk` and, on a table with a sort key, on + /// `sk` (its column and value). A row inserted means the item did not + /// exist. No row means the item exists, so the condition fails, and a read + /// fetches the item that blocked the insert, which the transaction path also + /// reports. If a delete committed between the two statements, the read finds + /// no item and the insert is tried again, up to `MAX_CREATE_RACE_ATTEMPTS` + /// inserts. + async fn insert_absent( + &self, + ddb_table: &str, + pk: &str, + sk: Option<(&str, &SortKeyValue)>, + item_json: &serde_json::Value, + ) -> Result<(), StorageError> { + let insert_sql = insert_if_absent_sql(ddb_table, sk.map(|(sk_col, _)| sk_col)); + let select_sql = match sk { + Some((sk_col, _)) => { + format!("SELECT item_data FROM {ddb_table} WHERE pk = $1 AND {sk_col} = $2") + } + None => format!("SELECT item_data FROM {ddb_table} WHERE pk = $1"), + }; + let mut attempt: u32 = 0; + loop { + super::gsi_build::pause_before_autocommit_statement().await; + let inserted = match sk { + Some((_, sk)) => bind_sk_execute!( + sqlx::AssertSqlSafe(insert_sql.as_str()), + pk, + sk, + item_json, + &self.data_pool + )?, + None => sqlx::query(sqlx::AssertSqlSafe(insert_sql.as_str())) + .bind(pk) + .bind(item_json) + .execute(&self.data_pool) + .await + .map_err(|e| StorageError::Internal(e.to_string()))?, + }; + if inserted.rows_affected() == 1 { + return Ok(()); + } + let existing: Option<(serde_json::Value,)> = match sk { + Some((_, sk)) => bind_sk_fetch_optional!( + sqlx::AssertSqlSafe(select_sql.as_str()), + pk, + sk, + &self.data_pool + )?, + None => sqlx::query_as(sqlx::AssertSqlSafe(select_sql.as_str())) + .bind(pk) + .fetch_optional(&self.data_pool) + .await + .map_err(|e| StorageError::Internal(e.to_string()))?, + }; + if let Some((v,)) = existing { + return Err(StorageError::ConditionFailed(Some(json_to_item(v)?))); + } + attempt += 1; + if attempt >= MAX_CREATE_RACE_ATTEMPTS { + return Err(create_race_exhausted(attempt)); + } + } + } +} + +/// The statement that inserts an item only if its key is not in the table: on +/// `pk` and, with `sk_col`, on the sort key column too. It inserts no row when +/// the key exists. The transaction path and `insert_absent` both use it. +fn insert_if_absent_sql(ddb_table: &str, sk_col: Option<&str>) -> String { + match sk_col { + Some(sk_col) => format!( + "INSERT INTO {ddb_table} (pk, {sk_col}, item_data) VALUES ($1, $2, $3) \ + ON CONFLICT (pk, {sk_col}) DO NOTHING" + ), + None => format!( + "INSERT INTO {ddb_table} (pk, item_data) VALUES ($1, $2) \ + ON CONFLICT (pk) DO NOTHING" + ), + } +} + /// The error after `MAX_CREATE_RACE_ATTEMPTS` lost create races. Like the one /// `UpdateItem` returns, it is an internal error (HTTP 500). fn create_race_exhausted(attempt: u32) -> StorageError { diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index 234e07a98..38adb70ac 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -302,6 +302,11 @@ pub struct PostgresEngine { /// the search path exists, so this backend still refuses vector operations /// over the wire; the flag is what that decision will read. pub(crate) vector_capable: bool, + /// Whether a create-only put on a table with no index and no stream to + /// maintain is one autocommit `INSERT ... ON CONFLICT DO NOTHING` + /// (`storage.postgres.create_only_puts`, on by default). Off, such a put + /// takes the transaction path, as every conditional put did before. + pub(crate) create_only_puts: bool, /// The serving registration a server holds for its life, so `migrate /// --yes` refuses while it serves, and takes again after the database /// ended its session. `None` outside a server. @@ -488,6 +493,7 @@ impl PostgresEngine { initial_gsi_delay, )), vector_capable, + create_only_puts: true, serving: None, snapshot_open_slots: Arc::new(tokio::sync::Semaphore::new(snapshot_slot_count( pool_size, @@ -536,6 +542,14 @@ impl PostgresEngine { } } + /// Turn the create-only put path on or off + /// (`storage.postgres.create_only_puts`). It is on unless this turns it off. + #[must_use] + pub fn with_create_only_puts(mut self, enabled: bool) -> Self { + self.create_only_puts = enabled; + self + } + pub fn start_gsi_workers(mut self) -> Self { self.gsi_queue = Some(gsi_queue::GsiQueue::spawn(self.data_pool.clone())); self @@ -883,6 +897,10 @@ fn server_components_factory( Box> + Send>, > { let connection_string = config.connection_config().to_string(); + let create_only_puts = config + .as_any() + .downcast_ref::() + .is_none_or(|c| c.create_only_puts); // Both pools admit the jobs the instance may run at once (the rule is // `pool_size_for_jobs`'s). let job_floor = @@ -938,7 +956,8 @@ fn server_components_factory( .map_err(|e| BackendError::ConnectionFailed { backend: "postgres".to_string(), details: e.to_string(), - })?; + })? + .with_create_only_puts(create_only_puts); drop(data_connection); engine.serving = Some(Arc::new(registration)); diff --git a/crates/storage-postgres/tests/backup_restore.rs b/crates/storage-postgres/tests/backup_restore.rs index 706458491..fa17ad8f7 100644 --- a/crates/storage-postgres/tests/backup_restore.rs +++ b/crates/storage-postgres/tests/backup_restore.rs @@ -5855,6 +5855,7 @@ mod catalog_index { connection_string: s.catalog_url.clone(), pool_size: 10, catalog_pool_size: Some(10), + ..Default::default() }; let open = |beside_server: bool| { let mut options = ServerComponentsOptions::default(); diff --git a/crates/storage-postgres/tests/common/insert_gate.rs b/crates/storage-postgres/tests/common/insert_gate.rs new file mode 100644 index 000000000..a3e668435 --- /dev/null +++ b/crates/storage-postgres/tests/common/insert_gate.rs @@ -0,0 +1,146 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +#![allow(dead_code)] + +//! The insert gate and the lock waits that the create-race tests share +//! (`put_create_race.rs` and `create_only_put.rs`). +//! +//! A `BEFORE INSERT` trigger makes every insert into a data table pass an +//! advisory lock, the gate. A test session holds the gate, so a put's insert +//! parks there while the test commits a competing item. When the test opens +//! the gate, the insert goes on and loses to that item. +//! +//! Each function takes the pool of the test's scratch database. A session +//! outside the pool comes from `connect`, which uses the pool's own connection +//! options. + +use std::time::Duration; + +use sqlx::{Connection, PgConnection, PgPool}; + +/// The advisory lock key of the gate. Advisory locks belong to one database, +/// and each test has its own scratch database, so one key serves every test. +pub const GATE: i64 = 0x5075_7452; + +/// The statement that lets the inserts of its transaction pass the gate +/// without waiting. +pub const BYPASS_GATE: &str = "SET LOCAL test.bypass_gate = 'on'"; + +/// Open a connection to the database of `db`, outside the pool. Returns it and +/// its backend pid. +pub async fn connect(db: &PgPool) -> (PgConnection, i32) { + let mut conn = PgConnection::connect_with(&db.connect_options()) + .await + .expect("connect to the scratch database"); + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut conn) + .await + .expect("read the backend pid"); + (conn, pid) +} + +/// Make every insert into `table` pass the gate first, unless its transaction +/// ran `BYPASS_GATE`. Passing takes the gate shared and releases it, so an +/// insert parks while a session holds the gate exclusively. +pub async fn install_gate(db: &PgPool, table: &str) { + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( + "CREATE FUNCTION pass_gate() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN \ + IF current_setting('test.bypass_gate', true) = 'on' THEN RETURN NEW; END IF; \ + PERFORM pg_advisory_lock_shared({GATE}); \ + PERFORM pg_advisory_unlock_shared({GATE}); \ + RETURN NEW; \ + END $$; \ + CREATE TRIGGER pass_gate BEFORE INSERT ON {table} \ + FOR EACH ROW EXECUTE FUNCTION pass_gate();" + ))) + .execute(db) + .await + .expect("install the gate trigger"); +} + +/// Open a session that holds the gate exclusively: the gate is closed. Returns +/// the session and its backend pid. +pub async fn close_gate(db: &PgPool) -> (PgConnection, i32) { + let (mut gate, gate_pid) = connect(db).await; + sqlx::query("SELECT pg_advisory_lock($1)") + .bind(GATE) + .execute(&mut gate) + .await + .expect("close the gate"); + (gate, gate_pid) +} + +/// Open the gate, so that the parked insert goes on. With `rearm`, close it +/// again behind that insert, so the put's next insert parks too. +pub async fn open_gate(gate: &mut PgConnection, rearm: bool) { + sqlx::query("SELECT pg_advisory_unlock($1)") + .bind(GATE) + .execute(&mut *gate) + .await + .expect("open the gate"); + if rearm { + // Granted only after the parked insert has passed the gate. + sqlx::query("SELECT pg_advisory_lock($1)") + .bind(GATE) + .execute(&mut *gate) + .await + .expect("close the gate again"); + } +} + +/// Release every advisory lock `gate` holds. A driver that stops early calls +/// this, so that a parked insert goes on and the put can report its result. +pub async fn open_gate_fully(gate: &mut PgConnection) { + sqlx::query("SELECT pg_advisory_unlock_all()") + .execute(gate) + .await + .expect("open the gate"); +} + +/// Wait until a backend waits for a lock of kind `event` (`transactionid`, +/// `advisory` or `relation`) that the backend `blocker` holds. Fails after +/// 5 s, so the caller can report what the put did instead. +pub async fn wait_until_blocked_by(db: &PgPool, blocker: i32, event: &str) -> Result<(), String> { + if lock_wait(db, None, Some(blocker), event).await { + return Ok(()); + } + Err(format!( + "no backend waited on the {event} lock of backend {blocker}" + )) +} + +/// Wait until the backend `pid` waits for a lock of kind `event`. Fails after +/// 5 s, like `wait_until_blocked_by`. +pub async fn wait_until_waiting(db: &PgPool, pid: i32, event: &str) -> Result<(), String> { + if lock_wait(db, Some(pid), None, event).await { + return Ok(()); + } + Err(format!("backend {pid} did not wait on a {event} lock")) +} + +/// Poll `pg_stat_activity` for up to 5 s for a wait on a lock of kind `event`: +/// by the backend `pid` when it is given, and on a lock that `blocker` holds +/// when that is given. +async fn lock_wait(db: &PgPool, pid: Option, blocker: Option, event: &str) -> bool { + for _ in 0..500 { + let waiting: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_stat_activity \ + WHERE datname = current_database() AND wait_event_type = 'Lock' \ + AND wait_event = $3 \ + AND ($1::int IS NULL OR pid = $1) \ + AND ($2::int IS NULL OR $2 = ANY(pg_blocking_pids(pid)))", + ) + .bind(pid) + .bind(blocker) + .bind(event) + .fetch_one(db) + .await + .expect("read pg_stat_activity"); + if waiting > 0 { + return true; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + false +} diff --git a/crates/storage-postgres/tests/create_only_put.rs b/crates/storage-postgres/tests/create_only_put.rs new file mode 100644 index 000000000..29e58c9fb --- /dev/null +++ b/crates/storage-postgres/tests/create_only_put.rs @@ -0,0 +1,947 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! Create-only puts: a `PutItem` whose condition is `attribute_not_exists` on a +//! key attribute. On a table with no index and no stream to maintain, the write +//! is one autocommit `INSERT ... ON CONFLICT DO NOTHING`; these tests hold it to +//! the answers of the transaction path. +//! +//! The scratch database is the one of `common/stream_disable_fixture.rs`, and +//! the insert gate is the one of `common/insert_gate.rs`, which +//! `put_create_race.rs` uses too. +//! +//! Requires `EXTENDDB_TEST_PG_CONNECTION_STRING`, a base URL with no database +//! component (for example `postgresql://postgres@127.0.0.1:5432`), pointing at a +//! server whose role may create and drop databases. Without it every test here +//! reports a skip and passes, the same convention the wire suites use. + +// The scratch database of the stream disable tests. The fixture also exports +// the stream types for those tests, and this file uses none of them. +#[allow(unused_imports)] +#[path = "common/stream_disable_fixture.rs"] +mod fixture; +#[path = "common/insert_gate.rs"] +mod insert_gate; + +use std::collections::{BTreeMap, BTreeSet}; +use std::time::Duration; + +use extenddb_core::expression::ExpressionMaps; +use extenddb_core::types::{ + AttributeDefinition, AttributeValue, BillingMode, CreateTableInput, Item, KeySchemaElement, + KeyType, ScalarAttributeType, TableKeyInfo, UpdateTableInput, +}; +use extenddb_storage::{DataEngine, TableEngine}; +use fixture::{ACCOUNT, Scratch, base_conn}; +use insert_gate::{ + BYPASS_GATE, close_gate, connect, install_gate, open_gate, open_gate_fully, + wait_until_blocked_by, wait_until_waiting, +}; +use sqlx::{PgConnection, PgPool}; + +const TABLE: &str = "t_create_only"; +/// A table keyed on `pk` alone; the put has a separate statement for it. +const HASH_TABLE: &str = "t_create_only_hash"; + +fn skip(test: &str) { + eprintln!( + "SKIP {test}: EXTENDDB_TEST_PG_CONNECTION_STRING is not set, so there is no PostgreSQL \ + to build a scratch catalog in." + ); +} + +/// The scratch database of the shared fixture, with the GSI workers running. +async fn scratch() -> Scratch { + let s = fixture::scratch().await; + Scratch { + engine: s.engine.start_gsi_workers(), + ..s + } +} + +async fn create_table(s: &Scratch) -> TableKeyInfo { + s.engine + .create_table( + ACCOUNT, + CreateTableInput { + table_name: TABLE.to_owned(), + key_schema: vec![ + KeySchemaElement { + attribute_name: "pk".to_owned(), + key_type: KeyType::Hash, + }, + KeySchemaElement { + attribute_name: "sk".to_owned(), + key_type: KeyType::Range, + }, + ], + attribute_definitions: vec![ + AttributeDefinition { + attribute_name: "pk".to_owned(), + attribute_type: ScalarAttributeType::S, + }, + AttributeDefinition { + attribute_name: "sk".to_owned(), + attribute_type: ScalarAttributeType::N, + }, + ], + billing_mode: Some(BillingMode::PayPerRequest), + ..Default::default() + }, + ) + .await + .expect("create the table"); + s.engine + .table_key_info(ACCOUNT, TABLE) + .await + .expect("read the key info") +} + +/// A table keyed on `pk` (S) alone. +async fn create_hash_table(s: &Scratch) -> TableKeyInfo { + s.engine + .create_table( + ACCOUNT, + CreateTableInput { + table_name: HASH_TABLE.to_owned(), + key_schema: vec![KeySchemaElement { + attribute_name: "pk".to_owned(), + key_type: KeyType::Hash, + }], + attribute_definitions: vec![AttributeDefinition { + attribute_name: "pk".to_owned(), + attribute_type: ScalarAttributeType::S, + }], + billing_mode: Some(BillingMode::PayPerRequest), + ..Default::default() + }, + ) + .await + .expect("create the hash table"); + s.engine + .table_key_info(ACCOUNT, HASH_TABLE) + .await + .expect("read the key info") +} + +/// An item keyed on `pk` and, on the range table, on `sk` 1, with `v` as its +/// value. +fn keyed(range: bool, pk: &str, v: &str) -> Item { + let mut it = key(range, pk); + it.insert("v".to_owned(), AttributeValue::S(v.to_owned())); + it +} + +/// The key of `keyed(range, pk, _)`. +fn key(range: bool, pk: &str) -> Item { + let mut it = BTreeMap::from([("pk".to_owned(), AttributeValue::S(pk.to_owned()))]); + if range { + it.insert("sk".to_owned(), AttributeValue::N("1".to_owned())); + } + it +} + +/// Add GSI `gidx` keyed on `g` (S) and, when `range`, `r` (N). +async fn add_gsi(s: &Scratch, range: bool) { + let mut defs = vec![serde_json::json!({"AttributeName": "g", "AttributeType": "S"})]; + let mut schema = vec![serde_json::json!({"AttributeName": "g", "KeyType": "HASH"})]; + if range { + defs.push(serde_json::json!({"AttributeName": "r", "AttributeType": "N"})); + schema.push(serde_json::json!({"AttributeName": "r", "KeyType": "RANGE"})); + } + let input: UpdateTableInput = serde_json::from_value(serde_json::json!({ + "TableName": TABLE, + "AttributeDefinitions": defs, + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gidx", + "KeySchema": schema, + "Projection": {"ProjectionType": "ALL"}, + }}], + })) + .expect("build the UpdateTable input"); + s.engine + .update_table(ACCOUNT, input) + .await + .expect("add the GSI"); +} + +fn item(n: u32, g: Option<&str>, r: Option) -> Item { + let mut it = BTreeMap::from([ + ("pk".to_owned(), AttributeValue::S(format!("p{}", n % 5))), + ("sk".to_owned(), AttributeValue::N(n.to_string())), + ]); + if let Some(g) = g { + it.insert("g".to_owned(), AttributeValue::S(g.to_owned())); + } + if let Some(r) = r { + it.insert("r".to_owned(), AttributeValue::N(r.to_string())); + } + it +} + +async fn put(s: &Scratch, key_info: &TableKeyInfo, it: Item) { + s.engine + .put_item(key_info, it, false, None, &ExpressionMaps::default(), None) + .await + .expect("put"); +} + +async fn ids(db: &PgPool) -> (String, String, String) { + sqlx::query_as( + "SELECT t.table_id, i.index_id, i.index_status FROM tables t \ + JOIN indexes i ON i.table_id = t.table_id \ + WHERE t.table_name = $1 AND i.index_name = 'gidx'", + ) + .bind(TABLE) + .fetch_one(db) + .await + .expect("look up the ids") +} + +/// `(base_pk, base_sk, g, item_data)` for every row of the index: the key +/// columns and the projected item, so a row with the right key but a stale +/// projection shows up as a difference. +async fn index_rows(db: &PgPool, index_id: &str) -> BTreeSet<(String, String, String, String)> { + let rows: Vec<(String, String, String, String)> = sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT base_pk, base_sk_n::text, pk, item_data::text FROM \"_ddb_{index_id}\"" + ))) + .fetch_all(db) + .await + .expect("read the index table"); + rows.into_iter().collect() +} + +/// `(pk, sk, g, item_data)` for every base item carrying `g`; the GSIs in this +/// file project ALL, so the index row's item is the base item. +async fn expected_rows(db: &PgPool, table_id: &str) -> BTreeSet<(String, String, String, String)> { + let rows: Vec<(String, String, String, String)> = sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT pk, sk_n::text, item_data->'g'->>'S', item_data::text FROM \"_ddb_{table_id}\" \ + WHERE item_data ? 'g'" + ))) + .fetch_all(db) + .await + .expect("read the base table"); + rows.into_iter().collect() +} + +/// Wait for the GSI to become ACTIVE. `UpdateTable` publishes it before returning +/// unless the build hit a transient failure, in which case the recovery worker +/// (not running in these tests) would; a short wait tells the two apart. +async fn wait_active(db: &PgPool) -> String { + let mut status = String::new(); + for _ in 0..100 { + status = ids(db).await.2; + if status == "ACTIVE" { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + status +} + +async fn wait_queue_empty(db: &PgPool) { + for _ in 0..500 { + let n: i64 = sqlx::query_scalar("SELECT count(*) FROM gsi_pending") + .fetch_one(db) + .await + .expect("count pending rows"); + if n == 0 { + return; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("the propagation queue did not drain"); +} + +fn cond(expr: &str) -> extenddb_core::expression::Expr { + extenddb_core::expression::parse_condition( + &extenddb_core::expression::tokenize(expr).expect("tokenize"), + ) + .expect("parse") +} + +async fn put_if( + s: &Scratch, + key_info: &TableKeyInfo, + it: Item, + expr: &str, + maps: &ExpressionMaps, +) -> Result, extenddb_storage::error::StorageError> { + put_if_old(s, key_info, it, expr, maps, false).await +} + +/// `put_if` that also asks for the old item when `return_old` is set, as a +/// request with `ReturnValues = ALL_OLD` or `ReturnConsumedCapacity` does. +async fn put_if_old( + s: &Scratch, + key_info: &TableKeyInfo, + it: Item, + expr: &str, + maps: &ExpressionMaps, + return_old: bool, +) -> Result, extenddb_storage::error::StorageError> { + let c = cond(expr); + s.engine + .put_item(key_info, it, return_old, Some(&c), maps, None) + .await +} + +async fn stored(s: &Scratch, key_info: &TableKeyInfo, n: u32) -> Option { + s.engine + .get_item(key_info, &item(n, None, None)) + .await + .expect("get") +} + +/// On a table keyed on `pk` and `sk` and on one keyed on `pk` alone, which have +/// their own statements, for each form of the condition, without and with a +/// request for the old item. A put that creates the item has no old item to +/// return. +#[tokio::test] +async fn create_only_put_inserts_when_absent_and_reports_the_item_when_present() { + let test = "create_only_put_inserts_when_absent_and_reports_the_item_when_present"; + if base_conn().is_none() { + return skip(test); + } + let s = scratch().await; + let maps = ExpressionMaps::default(); + let mut named = ExpressionMaps::default(); + named.names.insert("k".to_owned(), "pk".to_owned()); + let forms = [ + ("attribute_not_exists(pk)", &maps), + ("attribute_not_exists(#k)", &named), + ("NOT attribute_exists(pk)", &maps), + ("attribute_not_exists(sk)", &maps), + ( + "attribute_not_exists(pk) AND attribute_not_exists(sk)", + &maps, + ), + ( + "attribute_not_exists(pk) OR attribute_not_exists(sk)", + &maps, + ), + ]; + let tables = [ + (create_table(&s).await, true), + (create_hash_table(&s).await, false), + ]; + for (key_info, range) in &tables { + for (n, (expr, maps)) in forms.iter().enumerate() { + if !range && expr.contains("sk") { + continue; + } + for return_old in [false, true] { + let what = format!("{expr} (range: {range}, return_old: {return_old})"); + let pk = format!("k{n}-{return_old}"); + let first = keyed(*range, &pk, "first"); + let created = put_if_old(&s, key_info, first.clone(), expr, maps, return_old) + .await + .unwrap_or_else(|e| panic!("{what}: first put: {e:?}")); + assert_eq!(created, None, "{what}: a created item has no old item"); + let second = keyed(*range, &pk, "second"); + match put_if_old(&s, key_info, second, expr, maps, return_old).await { + Err(extenddb_storage::error::StorageError::ConditionFailed(Some(old))) => { + assert_eq!(old, first, "{what}: the failure names the stored item"); + } + other => { + panic!("{what}: second put: expected ConditionFailed(Some), got {other:?}") + } + } + let stored = s + .engine + .get_item(key_info, &key(*range, &pk)) + .await + .expect("get"); + assert_eq!(stored, Some(first), "{what}: unchanged"); + } + } + } + s.cleanup().await; +} + +/// `attribute_not_exists` on a non-key attribute is not create-only: an +/// existing item without the attribute passes and is overwritten. +#[tokio::test] +async fn not_exists_on_a_non_key_attribute_still_overwrites() { + let test = "not_exists_on_a_non_key_attribute_still_overwrites"; + if base_conn().is_none() { + return skip(test); + } + let s = scratch().await; + let key_info = create_table(&s).await; + let maps = ExpressionMaps::default(); + put(&s, &key_info, item(1, None, None)).await; + let next = item(1, Some("g"), None); + put_if( + &s, + &key_info, + next.clone(), + "attribute_not_exists(g)", + &maps, + ) + .await + .expect("passes: the stored item has no g"); + assert_eq!(stored(&s, &key_info, 1).await, Some(next)); + s.cleanup().await; +} + +/// Concurrent create-only puts of one key: exactly one wins, and every loser +/// reports the winner's item. +#[tokio::test] +async fn concurrent_create_only_puts_have_one_winner() { + let test = "concurrent_create_only_puts_have_one_winner"; + if base_conn().is_none() { + return skip(test); + } + let s = scratch().await; + let key_info = create_table(&s).await; + let maps = ExpressionMaps::default(); + for round in 0..20u32 { + let n = 100 + round; + let attempts = (0..8u32).map(|w| { + let it = item(n, Some(&format!("w{w}")), None); + put_if(&s, &key_info, it, "attribute_not_exists(pk)", &maps) + }); + let results = futures::future::join_all(attempts).await; + let winners = results.iter().filter(|r| r.is_ok()).count(); + assert_eq!(winners, 1, "round {round}: {results:?}"); + let winner = stored(&s, &key_info, n).await.expect("the winner's item"); + for r in &results { + match r { + Ok(_) => {} + Err(extenddb_storage::error::StorageError::ConditionFailed(Some(old))) => { + assert_eq!(old, &winner, "round {round}"); + } + Err(e) => panic!("round {round}: {e:?}"), + } + } + } + s.cleanup().await; +} + +/// On a table with a GSI the put keeps the transaction path, and the index +/// gets its row. +#[tokio::test] +async fn create_only_put_on_an_indexed_table_maintains_the_index() { + let test = "create_only_put_on_an_indexed_table_maintains_the_index"; + if base_conn().is_none() { + return skip(test); + } + let s = scratch().await; + let key_info = create_table(&s).await; + add_gsi(&s, false).await; + assert_eq!(wait_active(&s.db).await, "ACTIVE"); + let maps = ExpressionMaps::default(); + for n in 0..10 { + put_if( + &s, + &key_info, + item(n, Some("g"), None), + "attribute_not_exists(pk)", + &maps, + ) + .await + .expect("create"); + } + wait_queue_empty(&s.db).await; + let (table_id, index_id, _) = ids(&s.db).await; + assert_eq!( + index_rows(&s.db, &index_id).await, + expected_rows(&s.db, &table_id).await + ); + s.cleanup().await; +} + +// The tests below take the arm where the item is gone again when the put reads +// it after a lost insert. A BEFORE INSERT trigger parks the put's insert on an +// advisory lock, the gate, while an outside transaction commits a winner. A +// second session, the locker, then asks for the table's ACCESS EXCLUSIVE lock, +// which queues behind the parked insert. When the gate opens, the insert loses +// to the committed winner at once and ends. The locker takes the table, and the +// put's read, a plain SELECT that no row lock would delay, queues behind it. The +// locker deletes the winner and commits, so the read finds no item. + +/// The key of the item the gate tests race on. +const RACE_PK: &str = "race"; + +/// The data table of `table`, quoted. +async fn data_table(db: &PgPool, table: &str) -> String { + let id: String = + sqlx::query_scalar("SELECT table_id FROM tables WHERE account_id = $1 AND table_name = $2") + .bind(ACCOUNT) + .bind(table) + .fetch_one(db) + .await + .expect("look up the table id"); + format!("\"_ddb_{id}\"") +} + +/// A table of the given shape, its data table, and the session that holds the +/// gate, closed. Every insert into the table passes the gate first, unless its +/// transaction sets `test.bypass_gate`. +async fn gated_table(s: &Scratch, range: bool) -> (TableKeyInfo, String, PgConnection, i32) { + let (key_info, name) = if range { + (create_table(s).await, TABLE) + } else { + (create_hash_table(s).await, HASH_TABLE) + }; + let data = data_table(&s.db, name).await; + install_gate(&s.db, &data).await; + let (gate, gate_pid) = close_gate(&s.db).await; + (key_info, data, gate, gate_pid) +} + +/// With the put's insert parked at the gate, commit a winner `v`, and delete +/// it between the put's lost insert and its read. With `rearm`, the gate closes +/// again behind the insert, so the put's next insert parks too. +async fn lose_to_a_deleted_winner( + s: &Scratch, + data: &str, + range: bool, + gate: &mut PgConnection, + v: &str, + rearm: bool, +) -> Result<(), String> { + let mut tx = s.db.begin().await.expect("begin the winner"); + sqlx::query(BYPASS_GATE) + .execute(&mut *tx) + .await + .expect("bypass the gate"); + let sql = if range { + format!("INSERT INTO {data} (pk, sk_n, item_data) VALUES ($1, 1, $2)") + } else { + format!("INSERT INTO {data} (pk, item_data) VALUES ($1, $2)") + }; + sqlx::query(sqlx::AssertSqlSafe(sql)) + .bind(RACE_PK) + .bind(serde_json::to_value(keyed(range, RACE_PK, v)).expect("serialize the winner")) + .execute(&mut *tx) + .await + .expect("insert the winner"); + tx.commit().await.expect("commit the winner"); + + let (mut locker, locker_pid) = connect(&s.db).await; + sqlx::query("BEGIN") + .execute(&mut locker) + .await + .expect("begin the locker"); + let lock_sql = format!("LOCK TABLE {data} IN ACCESS EXCLUSIVE MODE"); + let lock = sqlx::query(sqlx::AssertSqlSafe(lock_sql)).execute(&mut locker); + let open = async { + // The locker queues behind the parked insert; then the gate opens. + wait_until_waiting(&s.db, locker_pid, "relation").await?; + open_gate(gate, rearm).await; + Ok::<(), String>(()) + }; + let (lock_result, gate) = tokio::join!(lock, open); + gate?; + lock_result.expect("lock the table"); + // The put's read waits for the locker. + wait_until_blocked_by(&s.db, locker_pid, "relation").await?; + let sql = if range { + format!("DELETE FROM {data} WHERE pk = $1 AND sk_n = 1") + } else { + format!("DELETE FROM {data} WHERE pk = $1") + }; + sqlx::query(sqlx::AssertSqlSafe(sql)) + .bind(RACE_PK) + .execute(&mut locker) + .await + .expect("delete the winner"); + sqlx::query("COMMIT") + .execute(&mut locker) + .await + .expect("commit the delete"); + Ok(()) +} + +async fn deleted_winner_is_retried(test: &str, range: bool) { + if base_conn().is_none() { + return skip(test); + } + let s = scratch().await; + let (key_info, data, mut gate, gate_pid) = gated_table(&s, range).await; + let maps = ExpressionMaps::default(); + let create_only = cond("attribute_not_exists(pk)"); + let put = s.engine.put_item( + &key_info, + keyed(range, RACE_PK, "loser"), + false, + Some(&create_only), + &maps, + None, + ); + let driver = async { + let steps = async { + wait_until_blocked_by(&s.db, gate_pid, "advisory").await?; + lose_to_a_deleted_winner(&s, &data, range, &mut gate, "winner", false).await + } + .await; + open_gate_fully(&mut gate).await; + steps + }; + let (result, steps) = + tokio::time::timeout(Duration::from_secs(30), async { tokio::join!(put, driver) }) + .await + .expect("the put finished"); + if let Err(e) = steps { + panic!("{e}; the put returned {result:?}"); + } + assert_eq!(result.expect("the retried insert succeeds"), None); + let stored = s + .engine + .get_item(&key_info, &key(range, RACE_PK)) + .await + .expect("get"); + assert_eq!(stored, Some(keyed(range, RACE_PK, "loser"))); + s.cleanup().await; +} + +#[tokio::test] +async fn a_create_only_put_whose_blocking_item_is_deleted_creates_the_item() { + deleted_winner_is_retried( + "a_create_only_put_whose_blocking_item_is_deleted_creates_the_item", + false, + ) + .await; +} + +#[tokio::test] +async fn a_create_only_put_whose_blocking_item_is_deleted_creates_the_item_on_a_range_table() { + deleted_winner_is_retried( + "a_create_only_put_whose_blocking_item_is_deleted_creates_the_item_on_a_range_table", + true, + ) + .await; +} + +/// Five lost inserts in a row, each to an item deleted before the read: the +/// put gives up, as on the transaction path, and writes nothing. +#[tokio::test] +async fn a_create_only_put_that_keeps_losing_gives_up_after_five_inserts() { + let test = "a_create_only_put_that_keeps_losing_gives_up_after_five_inserts"; + if base_conn().is_none() { + return skip(test); + } + let s = scratch().await; + let (key_info, data, mut gate, gate_pid) = gated_table(&s, true).await; + let maps = ExpressionMaps::default(); + let create_only = cond("attribute_not_exists(pk)"); + let put = s.engine.put_item( + &key_info, + keyed(true, RACE_PK, "loser"), + false, + Some(&create_only), + &maps, + None, + ); + let driver = async { + let steps = async { + for k in 1..=5 { + wait_until_blocked_by(&s.db, gate_pid, "advisory").await?; + lose_to_a_deleted_winner(&s, &data, true, &mut gate, &format!("w{k}"), k < 5) + .await?; + } + Ok::<(), String>(()) + } + .await; + open_gate_fully(&mut gate).await; + steps + }; + let (result, steps) = + tokio::time::timeout(Duration::from_secs(30), async { tokio::join!(put, driver) }) + .await + .expect("the put finished"); + if let Err(e) = steps { + panic!("{e}; the put returned {result:?}"); + } + match result { + Err(extenddb_storage::error::StorageError::Internal(m)) => { + assert!(m.contains("after 5 attempts"), "{m}"); + } + other => panic!("expected Internal after 5 inserts, got {other:?}"), + } + let stored = s + .engine + .get_item(&key_info, &key(true, RACE_PK)) + .await + .expect("get"); + assert_eq!(stored, None, "the put that gave up wrote nothing"); + s.cleanup().await; +} + +/// The read after a lost insert does not wait for a write in progress on the +/// item, as the transaction path's locking read does; with +/// `create_only_puts` off, the put takes that path again. +#[tokio::test] +async fn the_switch_sends_a_create_only_put_back_to_the_transaction_path() { + let test = "the_switch_sends_a_create_only_put_back_to_the_transaction_path"; + if base_conn().is_none() { + return skip(test); + } + let s = scratch().await; + let key_info = create_table(&s).await; + let maps = ExpressionMaps::default(); + let first = item(1, Some("first"), None); + put(&s, &key_info, first.clone()).await; + let data = data_table(&s.db, TABLE).await; + + // An outside transaction holds the item's row lock. + let (mut locker, locker_pid) = connect(&s.db).await; + sqlx::query("BEGIN") + .execute(&mut locker) + .await + .expect("begin the locker"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "SELECT item_data FROM {data} WHERE pk = 'p1' AND sk_n = 1 FOR UPDATE" + ))) + .execute(&mut locker) + .await + .expect("lock the item"); + + let condition = cond("attribute_not_exists(pk)"); + let expect_failure = |r: Result, extenddb_storage::error::StorageError>| match r { + Err(extenddb_storage::error::StorageError::ConditionFailed(Some(old))) => { + assert_eq!(old, first); + } + other => panic!("expected ConditionFailed(Some), got {other:?}"), + }; + + // On (the default): answered while the lock is still held, also when the + // request asks for the old item. + for return_old in [false, true] { + let on = s.engine.put_item( + &key_info, + item(1, Some("second"), None), + return_old, + Some(&condition), + &maps, + None, + ); + expect_failure( + tokio::time::timeout(Duration::from_secs(5), on) + .await + .unwrap_or_else(|_| { + panic!("the create-only put (return_old: {return_old}) waited for the row lock") + }), + ); + } + + // Off: the locking read waits for the outside transaction. + let off_engine = s.engine.clone().with_create_only_puts(false); + let off = off_engine.put_item( + &key_info, + item(1, Some("second"), None), + false, + Some(&condition), + &maps, + None, + ); + let release = async { + let waited = wait_until_blocked_by(&s.db, locker_pid, "transactionid").await; + sqlx::query("COMMIT") + .execute(&mut locker) + .await + .expect("commit the locker"); + waited + }; + let (result, waited) = tokio::join!(off, release); + waited.unwrap_or_else(|e| panic!("{e}: the put did not wait for the row lock")); + expect_failure(result); + s.cleanup().await; +} + +/// One measured shape of the micro-benchmark below. +struct Shape { + name: &'static str, + condition: Option<&'static str>, + /// Put on keys that exist, so the condition fails. + existing: bool, +} + +const BENCH_SHAPES: [Shape; 5] = [ + Shape { + name: "create-only, new item", + condition: Some("attribute_not_exists(pk)"), + existing: false, + }, + Shape { + name: "same answer, transaction path, new item", + condition: Some("attribute_not_exists(pk) AND attribute_not_exists(zz)"), + existing: false, + }, + Shape { + name: "create-only, item exists", + condition: Some("attribute_not_exists(pk)"), + existing: true, + }, + Shape { + name: "same answer, transaction path, item exists", + condition: Some("attribute_not_exists(pk) AND attribute_not_exists(zz)"), + existing: true, + }, + Shape { + name: "unconditional, new item (reference)", + condition: None, + existing: false, + }, +]; + +/// Micro-benchmark of the create-only put against the transaction path. +/// +/// `attribute_not_exists(pk) AND attribute_not_exists(zz)` gives the same +/// answer as `attribute_not_exists(pk)` (every stored item has `pk`), but its +/// second term is not on a key attribute, so it keeps the transaction path. The +/// two conditions therefore measure the two paths in one binary, on one +/// database. Shapes run interleaved, round after round, so drift on the host +/// affects them alike. +/// +/// Ignored by default: numbers from a local server are only meaningful +/// relative to each other on the same machine, so this runs by hand around a +/// change, never in CI: +/// +/// ```text +/// EXTENDDB_TEST_PG_CONNECTION_STRING=postgresql://postgres:pg@127.0.0.1:5432 \ +/// cargo test --release -p extenddb-storage-postgres --test create_only_put -- \ +/// --ignored --test-threads=1 --nocapture bench_ +/// ``` +/// +/// Reported for each shape: the latency of one put at a time (p50, p90, p99), +/// and the throughput with `IN_FLIGHT` puts in flight. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "micro-benchmark; run by hand with --ignored"] +async fn bench_create_only_put_against_the_transaction_path() { + const ROUNDS: u32 = 5; + const SERIAL_PUTS: u32 = 400; + const IN_FLIGHT: u32 = 8; + const PARALLEL_PUTS: u32 = 2_000; + const EXISTING: u32 = 1_000; + + let test = "bench_create_only_put_against_the_transaction_path"; + if base_conn().is_none() { + return skip(test); + } + let s = scratch().await; + let key_info = create_table(&s).await; + let maps = ExpressionMaps::default(); + let conditions: Vec> = BENCH_SHAPES + .iter() + .map(|shape| shape.condition.map(cond)) + .collect(); + + // Keys that exist, for the shapes whose condition fails. + let value = "x".repeat(200); + let value = value.as_str(); + let existing_item = |n: u32| keyed(true, &format!("exists-{n}"), value); + for n in 0..EXISTING { + put(&s, &key_info, existing_item(n)).await; + } + let mut next_key = 0u64; + let mut fresh_item = move || { + next_key += 1; + keyed(true, &format!("new-{next_key}"), value) + }; + + let mut latencies: Vec> = vec![Vec::new(); BENCH_SHAPES.len()]; + let mut throughputs: Vec> = vec![Vec::new(); BENCH_SHAPES.len()]; + for _ in 0..ROUNDS { + for (i, shape) in BENCH_SHAPES.iter().enumerate() { + let condition = conditions[i].as_ref(); + let pick = |fresh: &mut dyn FnMut() -> Item, n: u32| { + if shape.existing { + existing_item(n % EXISTING) + } else { + fresh() + } + }; + let check = |r: Result, extenddb_storage::error::StorageError>| match ( + shape.existing, + r, + ) { + (false, Ok(_)) + | (true, Err(extenddb_storage::error::StorageError::ConditionFailed(Some(_)))) => {} + (_, other) => panic!("{}: unexpected answer {other:?}", shape.name), + }; + + for n in 0..SERIAL_PUTS { + let it = pick(&mut fresh_item, n); + let start = std::time::Instant::now(); + let r = s + .engine + .put_item(&key_info, it, false, condition, &maps, None) + .await; + latencies[i].push(start.elapsed().as_micros()); + check(r); + } + + let items: Vec = (0..PARALLEL_PUTS) + .map(|n| pick(&mut fresh_item, n)) + .collect(); + let mut chunks: Vec> = (0..IN_FLIGHT).map(|_| Vec::new()).collect(); + for (n, it) in items.into_iter().enumerate() { + chunks[n % IN_FLIGHT as usize].push(it); + } + let start = std::time::Instant::now(); + let workers = chunks.into_iter().map(|chunk| { + let s = &s; + let key_info = &key_info; + let maps = &maps; + async move { + for it in chunk { + check( + s.engine + .put_item(key_info, it, false, condition, maps, None) + .await, + ); + } + } + }); + futures::future::join_all(workers).await; + throughputs[i].push(f64::from(PARALLEL_PUTS) / start.elapsed().as_secs_f64()); + } + } + + print_report( + ROUNDS, + SERIAL_PUTS, + PARALLEL_PUTS, + IN_FLIGHT, + latencies, + throughputs, + ); + s.cleanup().await; +} + +/// Print the micro-benchmark's table: per shape, the latency percentiles of +/// the puts made one at a time, and the median throughput of the rounds. +fn print_report( + rounds: u32, + serial: u32, + parallel: u32, + in_flight: u32, + mut latencies: Vec>, + mut throughputs: Vec>, +) { + println!( + "\n{rounds} rounds; {serial} puts one at a time and {parallel} with {in_flight} in \ + flight, per shape and round\n" + ); + println!( + "{:<44} {:>8} {:>8} {:>8} {:>16}", + "shape", "p50 us", "p90 us", "p99 us", "puts/s (median)" + ); + for (i, shape) in BENCH_SHAPES.iter().enumerate() { + let lat = &mut latencies[i]; + lat.sort_unstable(); + let pick = |q: usize| lat[(lat.len() - 1) * q / 100]; + let tput = &mut throughputs[i]; + tput.sort_by(f64::total_cmp); + println!( + "{:<44} {:>8} {:>8} {:>8} {:>16.0}", + shape.name, + pick(50), + pick(90), + pick(99), + tput[tput.len() / 2] + ); + } +} diff --git a/crates/storage-postgres/tests/gsi_stale_writer.rs b/crates/storage-postgres/tests/gsi_stale_writer.rs index 8907e7159..a29ea0c09 100644 --- a/crates/storage-postgres/tests/gsi_stale_writer.rs +++ b/crates/storage-postgres/tests/gsi_stale_writer.rs @@ -284,10 +284,12 @@ async fn expected_rows(db: &PgPool, table_id: &str) -> BTreeSet<(String, String, rows.into_iter().collect() } -/// Three writes that read "no index", then write after the GSI is ACTIVE: a new -/// item, an overwrite that changes the index key, and a delete. Paused at `at`; -/// with `conditional` the last two carry a condition, which puts them on the -/// transaction path whatever the pause. +/// Four writes that read "no index", then write after the GSI is ACTIVE: a new +/// item, an overwrite that changes the index key, a delete, and a create-only +/// put of a new item (`attribute_not_exists(pk)`). Paused at `at`; with +/// `conditional` the overwrite and the delete carry a condition, which puts them +/// on the transaction path whatever the pause. The create-only put writes +/// without a transaction when it is not slow, like the unconditional put. async fn drive(at: PauseWrites, conditional: bool) { let s = scratch().await; let key_info = create_table(&s).await; @@ -302,6 +304,10 @@ async fn drive(at: PauseWrites, conditional: bool) { &extenddb_core::expression::tokenize("attribute_exists(pk)").expect("tokenize"), ) .expect("parse"); + let create_only = extenddb_core::expression::parse_condition( + &extenddb_core::expression::tokenize("attribute_not_exists(pk)").expect("tokenize"), + ) + .expect("parse"); let writes = async { let a = s .engine @@ -319,10 +325,19 @@ async fn drive(at: PauseWrites, conditional: bool) { let c = s .engine .delete_item(&ki, &key2, false, conditional.then_some(&cond), &maps, None); - let (a, b, c) = tokio::join!(a, b, c); + let create = s.engine.put_item( + &ki, + item(101, Some("late create"), None), + false, + Some(&create_only), + &maps, + None, + ); + let (a, b, c, create) = tokio::join!(a, b, c, create); a.expect("late put"); b.expect("late overwrite"); c.expect("late delete"); + create.expect("late create-only put"); }; let build = async { tokio::time::sleep(Duration::from_millis(200)).await; @@ -357,15 +372,15 @@ async fn writes_that_missed_a_new_gsi_are_repaired() { // One test for the three paths, run in sequence, because the pause is // process-wide. // - // Unconditional writes on a table with no index write without a transaction. - // Paused between that decision and the statement, they stay on that path: the - // statement lands after the backfill, and the repair runs after the statement, - // on its own (`fix_up_autocommit`). + // Unconditional writes and create-only puts on a table with no index write + // without a transaction. Paused between that decision and the statement, they + // stay on that path: the statement lands after the backfill, and the repair + // runs after the statement, on its own (`fix_up_autocommit`). drive(PauseWrites::BeforeAutocommitStatement, false).await; // Paused after the catalog read instead, the same writes are already slow // when the decision is made and move to the transaction path, where the // repair commits with the write (`fix_up_stale_write`). drive(PauseWrites::AfterIndexRead, false).await; - // Conditional writes take a transaction regardless. + // Other conditional writes take a transaction regardless. drive(PauseWrites::AfterIndexRead, true).await; } diff --git a/crates/storage-postgres/tests/key_ring_rows.rs b/crates/storage-postgres/tests/key_ring_rows.rs index c5d4a5533..fd779ac2a 100644 --- a/crates/storage-postgres/tests/key_ring_rows.rs +++ b/crates/storage-postgres/tests/key_ring_rows.rs @@ -413,6 +413,7 @@ async fn a_server_starts_on_a_switched_catalog_with_its_kek() { connection_string: s.catalog_url(), pool_size: 10, catalog_pool_size: None, + ..Default::default() }; let start = |key_source: KeySource| { let mut options = extenddb_storage::server_components::ServerComponentsOptions::default(); diff --git a/crates/storage-postgres/tests/put_create_race.rs b/crates/storage-postgres/tests/put_create_race.rs index b77b4f4b2..938d9a8cb 100644 --- a/crates/storage-postgres/tests/put_create_race.rs +++ b/crates/storage-postgres/tests/put_create_race.rs @@ -21,6 +21,9 @@ //! server whose role may create and drop databases. Without it every test here //! reports a skip and passes, the same convention the wire suites use. +#[path = "common/insert_gate.rs"] +mod insert_gate; + use std::collections::BTreeMap; use std::time::Duration; @@ -33,8 +36,12 @@ use extenddb_core::types::{ use extenddb_storage::error::StorageError; use extenddb_storage::{DataEngine, StreamCapture, TableEngine, TransactWriteOp}; use extenddb_storage_postgres::{PostgresConfig, PostgresEngine}; +use insert_gate::{ + BYPASS_GATE, close_gate, connect, install_gate, open_gate, open_gate_fully, + wait_until_blocked_by, +}; use sqlx::postgres::PgPoolOptions; -use sqlx::{Connection, PgConnection, PgPool, Postgres, Transaction}; +use sqlx::{PgConnection, PgPool, Postgres, Transaction}; const ACCOUNT: &str = "123456789012"; const REGION: &str = "us-east-1"; @@ -264,31 +271,6 @@ async fn create_in_flight( (creator, pid) } -/// Wait until a backend waits for a lock of kind `event` (`transactionid` or -/// `advisory`) that the backend `blocker` holds. Fails after 5 s, so the caller -/// can report what the put did instead. -async fn wait_until_blocked_by(db: &PgPool, blocker: i32, event: &str) -> Result<(), String> { - for _ in 0..500 { - let waiting: i64 = sqlx::query_scalar( - "SELECT count(*) FROM pg_stat_activity \ - WHERE datname = current_database() AND wait_event_type = 'Lock' \ - AND wait_event = $2 AND $1 = ANY(pg_blocking_pids(pid))", - ) - .bind(blocker) - .bind(event) - .fetch_one(db) - .await - .expect("read pg_stat_activity"); - if waiting > 0 { - return Ok(()); - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - Err(format!( - "no backend waited on the {event} lock of backend {blocker}" - )) -} - /// Run `put` (ReturnValues ALL_OLD) while the winner's create is in flight, /// commit the create once the put waits on it, and return the put's result. async fn put_after_winner( @@ -416,46 +398,10 @@ async fn a_lost_create_race_fails_a_condition_the_winner_breaks() { // not make an insert wait. The put's locking re-read then waits on the locker, // which deletes the winner and commits, so the re-read returns no row. -/// The advisory lock key of the gate. -const GATE: i64 = 0x5075_7452; - -/// Open a connection to the scratch database outside its pools. Returns it and -/// its backend pid. -async fn connect(s: &Scratch) -> (PgConnection, i32) { - let base = base_conn().expect("caller checks base_conn() first"); - let mut conn = PgConnection::connect(&format!("{base}/{}", s.db_name)) - .await - .expect("connect to the scratch database"); - let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") - .fetch_one(&mut conn) - .await - .expect("read the backend pid"); - (conn, pid) -} - -/// Make every insert into `table` pass the gate first, unless its transaction -/// sets `test.bypass_gate`. Passing takes the gate shared and releases it, so -/// an insert parks while a session holds the gate exclusively. -async fn install_gate(s: &Scratch, table: &str) { - sqlx::raw_sql(sqlx::AssertSqlSafe(format!( - "CREATE FUNCTION pass_gate() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN \ - IF current_setting('test.bypass_gate', true) = 'on' THEN RETURN NEW; END IF; \ - PERFORM pg_advisory_lock_shared({GATE}); \ - PERFORM pg_advisory_unlock_shared({GATE}); \ - RETURN NEW; \ - END $$; \ - CREATE TRIGGER pass_gate BEFORE INSERT ON {table} \ - FOR EACH ROW EXECUTE FUNCTION pass_gate();" - ))) - .execute(&s.db) - .await - .expect("install the gate trigger"); -} - /// Commit the item with `v` as its value, past the gate. async fn commit_winner(s: &Scratch, table: &str, range: bool, v: &str) { let mut tx = s.db.begin().await.expect("begin the winner"); - sqlx::query("SET LOCAL test.bypass_gate = 'on'") + sqlx::query(BYPASS_GATE) .execute(&mut *tx) .await .expect("bypass the gate"); @@ -484,7 +430,7 @@ async fn lose_to_a_vanishing_winner( rearm: bool, ) -> Result<(), String> { commit_winner(s, table, range, v).await; - let (mut locker, locker_pid) = connect(s).await; + let (mut locker, locker_pid) = connect(&s.db).await; sqlx::query("BEGIN") .execute(&mut locker) .await @@ -496,19 +442,7 @@ async fn lose_to_a_vanishing_winner( .await .expect("lock the winner"); assert!(locked.is_some(), "the locker holds the committed winner"); - sqlx::query("SELECT pg_advisory_unlock($1)") - .bind(GATE) - .execute(&mut *gate) - .await - .expect("open the gate"); - if rearm { - // Granted only after the parked insert has passed the gate. - sqlx::query("SELECT pg_advisory_lock($1)") - .bind(GATE) - .execute(&mut *gate) - .await - .expect("close the gate again"); - } + open_gate(gate, rearm).await; wait_until_blocked_by(&s.db, locker_pid, "transactionid").await?; sqlx::query(sqlx::AssertSqlSafe(format!( "DELETE FROM {table} WHERE pk = 'c'" @@ -529,25 +463,11 @@ async fn lose_to_a_vanishing_winner( async fn gated_table(s: &Scratch, range: bool) -> (TableKeyInfo, String, PgConnection, i32) { let key_info = table(s, range).await; let data = data_table(&s.db).await; - install_gate(s, &data).await; - let (mut gate, gate_pid) = connect(s).await; - sqlx::query("SELECT pg_advisory_lock($1)") - .bind(GATE) - .execute(&mut gate) - .await - .expect("close the gate"); + install_gate(&s.db, &data).await; + let (gate, gate_pid) = close_gate(&s.db).await; (key_info, data, gate, gate_pid) } -/// Release every advisory lock `gate` holds. A driver that stops early calls -/// this, so that a parked insert goes on and the put can report its result. -async fn open_gate_fully(gate: &mut PgConnection) { - sqlx::query("SELECT pg_advisory_unlock_all()") - .execute(gate) - .await - .expect("open the gate"); -} - async fn deleted_winner_is_retried(test: &str, range: bool) { if base_conn().is_none() { return skip(test); diff --git a/docs/design/02-high-level-design.md b/docs/design/02-high-level-design.md index d05555be0..9e79c0320 100755 --- a/docs/design/02-high-level-design.md +++ b/docs/design/02-high-level-design.md @@ -396,6 +396,7 @@ Read-modify-write operations (UpdateItem, PutItem with conditions, DeleteItem wi - **Serialization:** Concurrent updates to the same item are serialized by PostgreSQL's row lock, not by any in-memory mutex. - **No TOCTOU races:** Another request cannot modify the item between the condition check and the write. - **Missing items:** A missing item has no row to lock, so `INSERT ... ON CONFLICT DO NOTHING` decides which writer creates it. A PutItem or UpdateItem that loses re-reads the winner `FOR UPDATE`, checks its condition against it, and writes after it. If the winner was deleted in the meantime, it retries the insert, up to 5 inserts in total. +- **Create-only puts:** A PutItem whose condition only says that the item must not exist (`attribute_not_exists` on a key attribute, `NOT attribute_exists` on one, or an AND or OR of such terms; `extenddb_core::expression::requires_absent_item`) needs no lock when it has no secondary or vector index and no stream to maintain, and is not a slow write (one that has taken more than 500 ms when it starts to write). `ReturnValues = ALL_OLD` and `ReturnConsumedCapacity` do not change this, because a create-only put that succeeds found no old item. It is one autocommit `INSERT ... ON CONFLICT DO NOTHING`. A row inserted means the item did not exist. No row means the condition failed, and an autocommit read fetches the item for the `ConditionalCheckFailedException`. If that read finds no item, a delete committed between the two statements, and the put retries the insert, up to 5 inserts in total. Unlike the locking read, the read does not wait for a write in progress on the item: the put answers with the latest committed item. `[storage.postgres] create_only_puts = false` keeps these puts on the transaction path; a put that finds the item sends the whole item before it learns that the condition failed, so a workload where most of these puts find the item is faster with the switch off. There is no in-memory locking (no `Mutex`, `RwLock`, or similar) on the data path. All contention is managed by PostgreSQL. diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index 214040065..0be7e7cfc 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -134,6 +134,7 @@ ExtendDB owns the collections, tables and indexes of its catalog and data databa | `connection_string` | `postgresql://extenddb:extenddb-local-dev@localhost:5432/extenddb_catalog` | Catalog database connection string | | `pool_size` | `20` | Maximum concurrent database connections (minimum: 10) | | `catalog_pool_size` | (= `pool_size`) | Maximum connections for management/authz pool (minimum: 10) | +| `create_only_puts` | `true` | Write a `PutItem` whose condition only says that the item must not exist (`attribute_not_exists` on a key attribute) as one `INSERT ... ON CONFLICT DO NOTHING`, without a transaction. A put on a table with a secondary index, a vector index or a stream keeps the transaction path, and so does a put that has already taken more than 500 milliseconds when it starts to write. `false` keeps all such puts on the transaction path. The answers are the same either way. Set it to `false` for a workload where most of these puts find that the item exists: such a put sends the whole item before it learns that the condition failed, and it is slower than on the transaction path | Backup and restore jobs are bounded per server process by `[backup] max_concurrent_jobs` (default 4, below), not per account; a request that finds every slot held waits up to 30 s for one and is then refused with `LimitExceededException`. The server raises `pool_size` and `catalog_pool_size` to at least `2 * max_concurrent_jobs + 10` and logs the raise with both numbers, so every job the bound admits has a connection. Each running restore holds one connection from this pool for its whole copy, plus one dedicated connection outside the pool for its claim.