From 059006f3738a5213af69df0bfb74e242c35981f0 Mon Sep 17 00:00:00 2001 From: michael parsons Date: Tue, 10 Nov 2026 17:42:34 -0800 Subject: [PATCH 1/2] perf(postgres): write a create-only put in one autocommit statement A PutItem whose condition says only that the item must not exist, such as attribute_not_exists(pk), always took the transaction path. For a new item that is four statements: BEGIN, SELECT ... FOR UPDATE, INSERT ... ON CONFLICT DO NOTHING and COMMIT. The PartiQL INSERT statement is also such a put. Every stored item carries its key attributes, so such a condition holds against no item and fails against every item. The key alone decides it. When the put has nothing else to do in a transaction (no secondary or vector index, no stream, no old item to return or to size, and not a slow write), it is now one autocommit INSERT ... ON CONFLICT DO NOTHING: - A row inserted means the item did not exist. - No row means the condition failed. A second statement reads the item for ConditionalCheckFailedException, as the transaction path reports it. That read does not wait for a write in progress on the item; it returns the latest committed item. - If a delete committed between the two statements, the read finds no item and the insert is tried again, up to the existing limit of five inserts for a create race. - After the statement, the put calls fix_up_autocommit, as the unconditional autocommit put does, so a GSI created meanwhile is repaired. extenddb_core::expression::requires_absent_item decides which conditions qualify: attribute_not_exists on a top-level key attribute, through a literal name or a #name; attribute_exists on one under NOT; and AND or OR of such terms when they agree. It is a pure function of the parsed condition, next to removes_only, so another backend can use it too. A #name that does not resolve does not qualify, so its validation error does not change. [storage.postgres] create_only_puts (default true) turns the path off; with false, such puts take the transaction path again. The engine reads it through PostgresEngine::with_create_only_puts, so PostgresConfig does not change. PostgresStorageConfig, which is public, gains the field: a struct literal of it outside this crate needs the field or ..Default::default(), as tests/backup_restore.rs now has. When the item exists, the put is a little slower than before: the insert sends the whole item, and PostgreSQL checks the conflict, where the transaction path stopped at the locking read. Tests: - crates/core: unit tests for requires_absent_item. - tests/create_only_put.rs: absent and present items on a hash table and a hash-and-range table, for each form of the condition (literal name, #name, NOT attribute_exists, AND, OR); a condition on a non-key attribute still overwrites; concurrent create-only puts of one key have one winner, and every loser gets the winner's item; a table with a GSI keeps the transaction path; a delete between the failed insert and the read (forced with a gate trigger and an ACCESS EXCLUSIVE lock) makes the put retry and create the item, on both table shapes, and five such deletes make it give up; with the switch off, a create-only put waits for a row lock again; a micro-benchmark, ignored by default. - tests/gsi_stale_writer.rs: a create-only put that read "no index" and wrote after a GSI build is repaired. - config: create_only_puts defaults to true and accepts a string from an environment override. Co-Authored-By: Claude Opus 5.5 Signed-off-by: michael parsons --- crates/core/src/expression/ast.rs | 136 ++ crates/core/src/expression/mod.rs | 4 +- crates/storage-postgres/src/bootstrapper.rs | 3 +- crates/storage-postgres/src/config.rs | 33 + crates/storage-postgres/src/data/put_item.rs | 108 +- crates/storage-postgres/src/lib.rs | 21 +- .../storage-postgres/tests/backup_restore.rs | 1 + .../storage-postgres/tests/create_only_put.rs | 1107 +++++++++++++++++ .../tests/gsi_stale_writer.rs | 35 +- docs/design/02-high-level-design.md | 1 + docs/manuals/05-admin-guide.md | 1 + 11 files changed, 1425 insertions(+), 25 deletions(-) create mode 100644 crates/storage-postgres/tests/create_only_put.rs 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 2bf8020b5..986d067ad 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -24,7 +24,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 6223d7d52..ddca9a403 100755 --- a/crates/storage-postgres/src/bootstrapper.rs +++ b/crates/storage-postgres/src/bootstrapper.rs @@ -434,7 +434,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..7eb2cda27 100755 --- a/crates/storage-postgres/src/config.rs +++ b/crates/storage-postgres/src/config.rs @@ -25,6 +25,16 @@ 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 it has nothing else to do in + /// a transaction. `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 +43,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 +56,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 +187,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 2fbc3102b..fa78b2cd1 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,22 @@ 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 nothing else to do is the exception: the key alone decides its + // condition (`requires_absent_item`), so one autocommit insert does + // (`insert_absent`). + let no_tx_work = !return_old + && indexes.is_empty() + && vector_metas.is_empty() + && stream.is_none() + && stamp.elapsed() <= super::gsi_build::GRACE_WRITE; + let create_only = self.create_only_puts + && no_tx_work + && condition.is_some_and(|c| requires_absent_item(c, &key_info.key_schema, maps)); + let needs_tx = !no_tx_work || (condition.is_some() && !create_only); if let Some((sk_name, sk_type)) = sk_info(&key_info.key_schema, &key_info.attribute_definitions) @@ -258,6 +266,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) \ @@ -436,6 +449,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) \ @@ -499,6 +517,72 @@ 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, select_sql) = match sk { + Some((sk_col, _)) => ( + format!( + "INSERT INTO {ddb_table} (pk, {sk_col}, item_data) VALUES ($1, $2, $3) \ + ON CONFLICT (pk, {sk_col}) DO NOTHING" + ), + format!("SELECT item_data FROM {ddb_table} WHERE pk = $1 AND {sk_col} = $2"), + ), + None => ( + format!( + "INSERT INTO {ddb_table} (pk, item_data) VALUES ($1, $2) \ + ON CONFLICT (pk) DO NOTHING" + ), + 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!(&insert_sql, pk, sk, item_json, &self.data_pool)?, + None => sqlx::query(&insert_sql) + .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!(&select_sql, pk, sk, &self.data_pool)?, + None => sqlx::query_as(&select_sql) + .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 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 9409b6e44..3e8dedc3d 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -288,6 +288,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 with nothing else to do in a transaction 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. @@ -446,6 +451,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, @@ -494,6 +500,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 @@ -841,6 +855,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 = @@ -881,7 +899,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); engine.serving = Some(Arc::new(registration)); // The startup recovery is a server's; a command reading beside one, diff --git a/crates/storage-postgres/tests/backup_restore.rs b/crates/storage-postgres/tests/backup_restore.rs index 6be91d323..4aeed3154 100644 --- a/crates/storage-postgres/tests/backup_restore.rs +++ b/crates/storage-postgres/tests/backup_restore.rs @@ -5683,6 +5683,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/create_only_put.rs b/crates/storage-postgres/tests/create_only_put.rs new file mode 100644 index 000000000..6e8274dc6 --- /dev/null +++ b/crates/storage-postgres/tests/create_only_put.rs @@ -0,0 +1,1107 @@ +// 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. With nothing else to do in a transaction, the write is one +//! autocommit `INSERT ... ON CONFLICT DO NOTHING`; these tests hold it to the +//! answers of the transaction path. +//! +//! 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. + +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 extenddb_storage_postgres::{PostgresConfig, PostgresEngine}; +use sqlx::postgres::PgPoolOptions; +use sqlx::{Connection, PgConnection, PgPool}; + +const ACCOUNT: &str = "123456789012"; +const REGION: &str = "us-east-1"; +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"; + +struct Scratch { + engine: PostgresEngine, + db: PgPool, + admin: PgPool, + db_name: String, +} + +impl Scratch { + async fn cleanup(self) { + let Scratch { + engine, + db, + admin, + db_name, + } = self; + drop(engine); + db.close().await; + sqlx::query(&format!( + "DROP DATABASE IF EXISTS \"{db_name}\" WITH (FORCE)" + )) + .execute(&admin) + .await + .expect("drop the scratch database"); + admin.close().await; + } +} + +/// The server's base URL, or `None` to skip. With `EXTENDDB_TEST_PG_REQUIRED` +/// set to any value but `0`, a job that must reach a server fails here +/// instead. +fn base_conn() -> Option { + let conn = std::env::var("EXTENDDB_TEST_PG_CONNECTION_STRING").unwrap_or_default(); + if conn.trim().is_empty() { + let required = + std::env::var("EXTENDDB_TEST_PG_REQUIRED").is_ok_and(|v| !v.is_empty() && v != "0"); + assert!( + !required, + "EXTENDDB_TEST_PG_CONNECTION_STRING is not set, and EXTENDDB_TEST_PG_REQUIRED says \ + this job must reach a PostgreSQL server" + ); + return None; + } + Some(conn.trim_end_matches('/').to_owned()) +} + +fn shipped_migrations() -> Vec { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let mut out = Vec::new(); + for dir in ["migrations", "data_migrations"] { + let mut files: Vec<_> = std::fs::read_dir(root.join(dir)) + .expect("read the migrations directory") + .map(|e| e.expect("directory entry").path()) + .filter(|p| p.extension().is_some_and(|e| e == "sql")) + .collect(); + files.sort(); + for f in files { + out.push(std::fs::read_to_string(&f).expect("read a migration file")); + } + } + out +} + +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." + ); +} + +async fn scratch() -> Scratch { + let base = base_conn().expect("caller checks base_conn() first"); + let db_name = format!("eddb_cput_{}", uuid::Uuid::new_v4().simple())[..24].to_owned(); + let admin = PgPoolOptions::new() + .max_connections(1) + .connect(&format!("{base}/postgres")) + .await + .expect("connect to the postgres maintenance database"); + sqlx::query(&format!("CREATE DATABASE \"{db_name}\"")) + .execute(&admin) + .await + .expect("create the scratch database"); + let url = format!("{base}/{db_name}"); + let db = PgPoolOptions::new() + .max_connections(2) + .connect(&url) + .await + .expect("connect to the scratch database"); + // One scratch database stands in for both the catalog and the data database. + for sql in shipped_migrations() { + sqlx::raw_sql(&sql) + .execute(&db) + .await + .expect("apply a shipped migration"); + } + sqlx::query( + "INSERT INTO settings (key, value) VALUES ('control_plane_delay_seconds', '0') \ + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value", + ) + .execute(&db) + .await + .expect("pin the control-plane delay to zero"); + sqlx::query("INSERT INTO accounts (account_id, account_name) VALUES ($1, $2)") + .bind(ACCOUNT) + .bind(format!("acct-{db_name}")) + .execute(&db) + .await + .expect("seed the account row"); + let engine = PostgresEngine::new( + &PostgresConfig { + connection_string: url, + pool_size: 10, + max_item_size_bytes: 400_000, + }, + REGION, + ) + .await + .expect("open a PostgresEngine on the scratch database") + .start_gsi_workers(); + Scratch { + engine, + db, + admin, + db_name, + } +} + +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(&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(&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> { + let c = cond(expr); + s.engine + .put_item(key_info, it, false, 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. +#[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; + } + let pk = format!("k{n}"); + let first = keyed(*range, &pk, "first"); + put_if(&s, key_info, first.clone(), expr, maps) + .await + .unwrap_or_else(|e| panic!("{expr}: first put: {e:?}")); + match put_if(&s, key_info, keyed(*range, &pk, "second"), expr, maps).await { + Err(extenddb_storage::error::StorageError::ConditionFailed(Some(old))) => { + assert_eq!(old, first, "{expr}: the failure names the stored item"); + } + other => { + panic!("{expr}: 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), "{expr} (range: {range}): 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 advisory lock key of the gate. +const GATE: i64 = 0x4372_4f6e; + +/// The key of the item the gate tests race on. +const RACE_PK: &str = "race"; + +/// 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) +} + +/// Wait until `pid` waits for a lock of kind `event`. With `blocker`, wait +/// instead until any backend waits for such a lock that `blocker` holds. Fails +/// after 5 s, so the caller can report what the put did instead. +async fn wait_for_lock_wait( + db: &PgPool, + pid: Option, + blocker: Option, + 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 = $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 Ok(()); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + Err(format!( + "no wait on a {event} lock (pid {pid:?}, blocker {blocker:?})" + )) +} + +/// 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; + sqlx::raw_sql(&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 {data} \ + FOR EACH ROW EXECUTE FUNCTION pass_gate();" + )) + .execute(&s.db) + .await + .expect("install the gate trigger"); + 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"); + (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("SET LOCAL test.bypass_gate = 'on'") + .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(&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).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(&lock_sql).execute(&mut locker); + let open = async { + // The locker queues behind the parked insert; then the gate opens. + wait_for_lock_wait(&s.db, Some(locker_pid), None, "relation").await?; + 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"); + } + 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_for_lock_wait(&s.db, None, Some(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(&sql) + .bind(RACE_PK) + .execute(&mut locker) + .await + .expect("delete the winner"); + sqlx::query("COMMIT") + .execute(&mut locker) + .await + .expect("commit the delete"); + Ok(()) +} + +/// 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); + } + 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_for_lock_wait(&s.db, None, Some(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_for_lock_wait(&s.db, None, Some(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).await; + sqlx::query("BEGIN") + .execute(&mut locker) + .await + .expect("begin the locker"); + sqlx::query(&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. + let on = s.engine.put_item( + &key_info, + item(1, Some("second"), None), + false, + Some(&condition), + &maps, + None, + ); + expect_failure( + tokio::time::timeout(Duration::from_secs(5), on) + .await + .expect("the create-only put does not wait 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_for_lock_wait(&s.db, None, Some(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 2791fbdfb..3a59b87dd 100644 --- a/crates/storage-postgres/tests/gsi_stale_writer.rs +++ b/crates/storage-postgres/tests/gsi_stale_writer.rs @@ -282,10 +282,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; @@ -300,6 +302,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 @@ -317,10 +323,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; @@ -355,15 +370,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/docs/design/02-high-level-design.md b/docs/design/02-high-level-design.md index 92ecd9fc3..e380c8c78 100755 --- a/docs/design/02-high-level-design.md +++ b/docs/design/02-high-level-design.md @@ -394,6 +394,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 nothing else to do in a transaction: no secondary or vector index, no stream, no old item to return or to size, and not a slow write. 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. 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 fe5f402b7..a0393372b 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, when the put has nothing else to do in one: no secondary or vector index, no stream, and no old item to return. `false` keeps such puts on the transaction path. The answers are the same either way | 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. From 16858bdbe950810ba0e75ef629f530f5cdb2822c Mon Sep 17 00:00:00 2001 From: michael parsons Date: Mon, 23 Nov 2026 21:28:30 -0800 Subject: [PATCH 2/2] perf(postgres): an old-item request keeps a create-only put on one statement Changes from the review of 19 Nov. A create-only put that asked for the old item (ReturnValues = ALL_OLD or ReturnConsumedCapacity) took the transaction path. A create-only put that succeeds found no old item, so it has none to return or to size. Such a put now takes the one-statement path too. A table with a secondary index, a vector index or a stream, and a write that is already slow (GRACE_WRITE), keep the transaction path as before. The statement that inserts an item only if its key is absent was built in the transaction path and again in insert_absent. One function, insert_if_absent_sql, now builds it for both. Tests: - tests/common/insert_gate.rs has the gate trigger, the gate session, the outside connection and the lock waits. put_create_race.rs and create_only_put.rs both use it, and their own copies are gone. - create_only_put.rs uses the scratch database of common/stream_disable_fixture.rs in place of its own copy. - The create-only tests also run with return_old set: a put that creates the item returns no old item, a put that finds the item fails with it, and a failed put answers while an outside transaction holds the row lock, which the transaction path does not. Docs: the admin guide row for create_only_puts names the cases that keep the transaction path (an index, a stream, a write over 500 ms) and says when to turn the switch off. The design bullet says the same. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_012kcReu8W93hWBjX8JAwW8P Signed-off-by: michael parsons --- crates/storage-postgres/src/config.rs | 7 +- crates/storage-postgres/src/data/put_item.rs | 62 ++-- crates/storage-postgres/src/lib.rs | 4 +- .../tests/common/insert_gate.rs | 146 ++++++++ .../storage-postgres/tests/create_only_put.rs | 348 +++++------------- .../storage-postgres/tests/put_create_race.rs | 106 +----- docs/design/02-high-level-design.md | 2 +- docs/manuals/05-admin-guide.md | 2 +- 8 files changed, 293 insertions(+), 384 deletions(-) create mode 100644 crates/storage-postgres/tests/common/insert_gate.rs diff --git a/crates/storage-postgres/src/config.rs b/crates/storage-postgres/src/config.rs index 7eb2cda27..acd4f6d62 100755 --- a/crates/storage-postgres/src/config.rs +++ b/crates/storage-postgres/src/config.rs @@ -27,9 +27,10 @@ pub struct PostgresStorageConfig { 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 it has nothing else to do in - /// a transaction. `false` keeps such puts on the transaction path. The - /// answers are the same either way. + /// `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" diff --git a/crates/storage-postgres/src/data/put_item.rs b/crates/storage-postgres/src/data/put_item.rs index fa78b2cd1..abe93f39b 100755 --- a/crates/storage-postgres/src/data/put_item.rs +++ b/crates/storage-postgres/src/data/put_item.rs @@ -92,18 +92,19 @@ impl PostgresEngine { // 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 nothing else to do is the exception: the key alone decides its - // condition (`requires_absent_item`), so one autocommit insert does - // (`insert_absent`). - let no_tx_work = !return_old - && indexes.is_empty() + // 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 - && no_tx_work + && nothing_to_maintain && condition.is_some_and(|c| requires_absent_item(c, &key_info.key_schema, maps)); - let needs_tx = !no_tx_work || (condition.is_some() && !create_only); + 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) @@ -155,10 +156,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!(&insert_sql, pk_text.as_str(), &sk, &item_json, &mut *tx)?; if result.rows_affected() == 1 { @@ -338,10 +336,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(&insert_sql) .bind(pk_text.as_str()) .bind(&item_json) @@ -533,21 +528,12 @@ impl PostgresEngine { sk: Option<(&str, &SortKeyValue)>, item_json: &serde_json::Value, ) -> Result<(), StorageError> { - let (insert_sql, select_sql) = match sk { - Some((sk_col, _)) => ( - format!( - "INSERT INTO {ddb_table} (pk, {sk_col}, item_data) VALUES ($1, $2, $3) \ - ON CONFLICT (pk, {sk_col}) DO NOTHING" - ), - format!("SELECT item_data FROM {ddb_table} WHERE pk = $1 AND {sk_col} = $2"), - ), - None => ( - format!( - "INSERT INTO {ddb_table} (pk, item_data) VALUES ($1, $2) \ - ON CONFLICT (pk) DO NOTHING" - ), - format!("SELECT item_data FROM {ddb_table} WHERE pk = $1"), - ), + 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 { @@ -583,6 +569,22 @@ impl PostgresEngine { } } +/// 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 7212d65b7..fad5eb5da 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -288,8 +288,8 @@ 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 with nothing else to do in a transaction is - /// one autocommit `INSERT ... ON CONFLICT DO NOTHING` + /// 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, 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..5d6deb4c6 --- /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(&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 index 6e8274dc6..14db337ff 100644 --- a/crates/storage-postgres/tests/create_only_put.rs +++ b/crates/storage-postgres/tests/create_only_put.rs @@ -1,15 +1,27 @@ // 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. With nothing else to do in a transaction, the write is one -//! autocommit `INSERT ... ON CONFLICT DO NOTHING`; these tests hold it to the -//! answers of the transaction path. +//! 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; @@ -19,78 +31,17 @@ use extenddb_core::types::{ KeyType, ScalarAttributeType, TableKeyInfo, UpdateTableInput, }; use extenddb_storage::{DataEngine, TableEngine}; -use extenddb_storage_postgres::{PostgresConfig, PostgresEngine}; -use sqlx::postgres::PgPoolOptions; -use sqlx::{Connection, PgConnection, PgPool}; +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 ACCOUNT: &str = "123456789012"; -const REGION: &str = "us-east-1"; 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"; -struct Scratch { - engine: PostgresEngine, - db: PgPool, - admin: PgPool, - db_name: String, -} - -impl Scratch { - async fn cleanup(self) { - let Scratch { - engine, - db, - admin, - db_name, - } = self; - drop(engine); - db.close().await; - sqlx::query(&format!( - "DROP DATABASE IF EXISTS \"{db_name}\" WITH (FORCE)" - )) - .execute(&admin) - .await - .expect("drop the scratch database"); - admin.close().await; - } -} - -/// The server's base URL, or `None` to skip. With `EXTENDDB_TEST_PG_REQUIRED` -/// set to any value but `0`, a job that must reach a server fails here -/// instead. -fn base_conn() -> Option { - let conn = std::env::var("EXTENDDB_TEST_PG_CONNECTION_STRING").unwrap_or_default(); - if conn.trim().is_empty() { - let required = - std::env::var("EXTENDDB_TEST_PG_REQUIRED").is_ok_and(|v| !v.is_empty() && v != "0"); - assert!( - !required, - "EXTENDDB_TEST_PG_CONNECTION_STRING is not set, and EXTENDDB_TEST_PG_REQUIRED says \ - this job must reach a PostgreSQL server" - ); - return None; - } - Some(conn.trim_end_matches('/').to_owned()) -} - -fn shipped_migrations() -> Vec { - let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); - let mut out = Vec::new(); - for dir in ["migrations", "data_migrations"] { - let mut files: Vec<_> = std::fs::read_dir(root.join(dir)) - .expect("read the migrations directory") - .map(|e| e.expect("directory entry").path()) - .filter(|p| p.extension().is_some_and(|e| e == "sql")) - .collect(); - files.sort(); - for f in files { - out.push(std::fs::read_to_string(&f).expect("read a migration file")); - } - } - out -} - fn skip(test: &str) { eprintln!( "SKIP {test}: EXTENDDB_TEST_PG_CONNECTION_STRING is not set, so there is no PostgreSQL \ @@ -98,60 +49,12 @@ fn skip(test: &str) { ); } +/// The scratch database of the shared fixture, with the GSI workers running. async fn scratch() -> Scratch { - let base = base_conn().expect("caller checks base_conn() first"); - let db_name = format!("eddb_cput_{}", uuid::Uuid::new_v4().simple())[..24].to_owned(); - let admin = PgPoolOptions::new() - .max_connections(1) - .connect(&format!("{base}/postgres")) - .await - .expect("connect to the postgres maintenance database"); - sqlx::query(&format!("CREATE DATABASE \"{db_name}\"")) - .execute(&admin) - .await - .expect("create the scratch database"); - let url = format!("{base}/{db_name}"); - let db = PgPoolOptions::new() - .max_connections(2) - .connect(&url) - .await - .expect("connect to the scratch database"); - // One scratch database stands in for both the catalog and the data database. - for sql in shipped_migrations() { - sqlx::raw_sql(&sql) - .execute(&db) - .await - .expect("apply a shipped migration"); - } - sqlx::query( - "INSERT INTO settings (key, value) VALUES ('control_plane_delay_seconds', '0') \ - ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value", - ) - .execute(&db) - .await - .expect("pin the control-plane delay to zero"); - sqlx::query("INSERT INTO accounts (account_id, account_name) VALUES ($1, $2)") - .bind(ACCOUNT) - .bind(format!("acct-{db_name}")) - .execute(&db) - .await - .expect("seed the account row"); - let engine = PostgresEngine::new( - &PostgresConfig { - connection_string: url, - pool_size: 10, - max_item_size_bytes: 400_000, - }, - REGION, - ) - .await - .expect("open a PostgresEngine on the scratch database") - .start_gsi_workers(); + let s = fixture::scratch().await; Scratch { - engine, - db, - admin, - db_name, + engine: s.engine.start_gsi_workers(), + ..s } } @@ -362,10 +265,23 @@ async fn put_if( 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, false, Some(&c), maps, None) + .put_item(key_info, it, return_old, Some(&c), maps, None) .await } @@ -377,7 +293,9 @@ async fn stored(s: &Scratch, key_info: &TableKeyInfo, n: u32) -> Option { } /// 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. +/// 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"; @@ -411,25 +329,30 @@ async fn create_only_put_inserts_when_absent_and_reports_the_item_when_present() if !range && expr.contains("sk") { continue; } - let pk = format!("k{n}"); - let first = keyed(*range, &pk, "first"); - put_if(&s, key_info, first.clone(), expr, maps) - .await - .unwrap_or_else(|e| panic!("{expr}: first put: {e:?}")); - match put_if(&s, key_info, keyed(*range, &pk, "second"), expr, maps).await { - Err(extenddb_storage::error::StorageError::ConditionFailed(Some(old))) => { - assert_eq!(old, first, "{expr}: the failure names the stored item"); - } - other => { - panic!("{expr}: second put: expected ConditionFailed(Some), got {other:?}") + 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"); } - let stored = s - .engine - .get_item(key_info, &key(*range, &pk)) - .await - .expect("get"); - assert_eq!(stored, Some(first), "{expr} (range: {range}): unchanged"); } } s.cleanup().await; @@ -537,59 +460,9 @@ async fn create_only_put_on_an_indexed_table_maintains_the_index() { // 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 advisory lock key of the gate. -const GATE: i64 = 0x4372_4f6e; - /// The key of the item the gate tests race on. const RACE_PK: &str = "race"; -/// 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) -} - -/// Wait until `pid` waits for a lock of kind `event`. With `blocker`, wait -/// instead until any backend waits for such a lock that `blocker` holds. Fails -/// after 5 s, so the caller can report what the put did instead. -async fn wait_for_lock_wait( - db: &PgPool, - pid: Option, - blocker: Option, - 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 = $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 Ok(()); - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - Err(format!( - "no wait on a {event} lock (pid {pid:?}, blocker {blocker:?})" - )) -} - /// The data table of `table`, quoted. async fn data_table(db: &PgPool, table: &str) -> String { let id: String = @@ -612,25 +485,8 @@ async fn gated_table(s: &Scratch, range: bool) -> (TableKeyInfo, String, PgConne (create_hash_table(s).await, HASH_TABLE) }; let data = data_table(&s.db, name).await; - sqlx::raw_sql(&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 {data} \ - FOR EACH ROW EXECUTE FUNCTION pass_gate();" - )) - .execute(&s.db) - .await - .expect("install the gate trigger"); - 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) } @@ -646,7 +502,7 @@ async fn lose_to_a_deleted_winner( rearm: bool, ) -> Result<(), String> { 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"); @@ -663,7 +519,7 @@ async fn lose_to_a_deleted_winner( .expect("insert the winner"); tx.commit().await.expect("commit the winner"); - let (mut locker, locker_pid) = connect(s).await; + let (mut locker, locker_pid) = connect(&s.db).await; sqlx::query("BEGIN") .execute(&mut locker) .await @@ -672,27 +528,15 @@ async fn lose_to_a_deleted_winner( let lock = sqlx::query(&lock_sql).execute(&mut locker); let open = async { // The locker queues behind the parked insert; then the gate opens. - wait_for_lock_wait(&s.db, Some(locker_pid), None, "relation").await?; - 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"); - } + 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_for_lock_wait(&s.db, None, Some(locker_pid), "relation").await?; + 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 { @@ -710,15 +554,6 @@ async fn lose_to_a_deleted_winner( Ok(()) } -/// 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); @@ -737,7 +572,7 @@ async fn deleted_winner_is_retried(test: &str, range: bool) { ); let driver = async { let steps = async { - wait_for_lock_wait(&s.db, None, Some(gate_pid), "advisory").await?; + wait_until_blocked_by(&s.db, gate_pid, "advisory").await?; lose_to_a_deleted_winner(&s, &data, range, &mut gate, "winner", false).await } .await; @@ -802,7 +637,7 @@ async fn a_create_only_put_that_keeps_losing_gives_up_after_five_inserts() { let driver = async { let steps = async { for k in 1..=5 { - wait_for_lock_wait(&s.db, None, Some(gate_pid), "advisory").await?; + 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?; } @@ -851,7 +686,7 @@ async fn the_switch_sends_a_create_only_put_back_to_the_transaction_path() { let data = data_table(&s.db, TABLE).await; // An outside transaction holds the item's row lock. - let (mut locker, locker_pid) = connect(&s).await; + let (mut locker, locker_pid) = connect(&s.db).await; sqlx::query("BEGIN") .execute(&mut locker) .await @@ -871,20 +706,25 @@ async fn the_switch_sends_a_create_only_put_back_to_the_transaction_path() { other => panic!("expected ConditionFailed(Some), got {other:?}"), }; - // On (the default): answered while the lock is still held. - let on = s.engine.put_item( - &key_info, - item(1, Some("second"), None), - false, - Some(&condition), - &maps, - None, - ); - expect_failure( - tokio::time::timeout(Duration::from_secs(5), on) - .await - .expect("the create-only put does not wait for the row lock"), - ); + // 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); @@ -897,7 +737,7 @@ async fn the_switch_sends_a_create_only_put_back_to_the_transaction_path() { None, ); let release = async { - let waited = wait_for_lock_wait(&s.db, None, Some(locker_pid), "transactionid").await; + let waited = wait_until_blocked_by(&s.db, locker_pid, "transactionid").await; sqlx::query("COMMIT") .execute(&mut locker) .await diff --git a/crates/storage-postgres/tests/put_create_race.rs b/crates/storage-postgres/tests/put_create_race.rs index e62d9a508..7a97c22d0 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"; @@ -262,31 +269,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( @@ -414,46 +396,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(&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"); @@ -482,7 +428,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 @@ -494,19 +440,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(&format!("DELETE FROM {table} WHERE pk = 'c'")) .execute(&mut locker) @@ -525,25 +459,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 e380c8c78..d10993047 100755 --- a/docs/design/02-high-level-design.md +++ b/docs/design/02-high-level-design.md @@ -394,7 +394,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 nothing else to do in a transaction: no secondary or vector index, no stream, no old item to return or to size, and not a slow write. 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. +- **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 8b686276d..42985fbb4 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -134,7 +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, when the put has nothing else to do in one: no secondary or vector index, no stream, and no old item to return. `false` keeps such puts on the transaction path. The answers are the same either way | +| `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.