diff --git a/crates/app/src/cmd_settings.rs b/crates/app/src/cmd_settings.rs index 3fc483dd1..4d8447201 100755 --- a/crates/app/src/cmd_settings.rs +++ b/crates/app/src/cmd_settings.rs @@ -23,7 +23,7 @@ use extenddb_config::{self as config, MASK}; // Re-use validation constants from the ops layer. use extenddb_server::management::ops_settings::{ - KNOWN_KEYS, READONLY_KEYS, server_setting_default, + KNOWN_KEYS, READONLY_KEYS, server_setting_default, writable_key_validator, }; #[derive(Args)] @@ -180,13 +180,32 @@ async fn get(store: &dyn SettingsStore, key: &str, show_secret: bool) -> anyhow: } async fn set(store: &dyn SettingsStore, key: &str, value: &str) -> anyhow::Result<()> { + validate(key, value)?; + + // Write under the canonical name so the deprecated alias updates the row the read + // path consults, rather than adding a second one that is silently ignored. + let key = extenddb_core::settings_keys::canonical_key(key); + store + .set_setting(key, value) + .await + .map_err(|e| anyhow::anyhow!("Failed to set setting: {e:?}"))?; + + tracing::warn!( + target: "extenddb::audit::settings", + "settings-set: key={key}, value={value}", + ); + println!("{key} = {value}"); + Ok(()) +} + +/// Refuse a read-only or unknown key, or a value its validator rejects, with +/// the same lookup the management API uses. +fn validate(key: &str, value: &str) -> anyhow::Result<()> { if READONLY_KEYS.contains(&key) { anyhow::bail!("Setting '{key}' is read-only and cannot be changed via this command."); } - // Validate against known keys. - let known = KNOWN_KEYS.iter().find(|(k, _)| *k == key); - if let Some((_, validator)) = known { + if let Some(validator) = writable_key_validator(key) { validator(value) .map_err(|reason| anyhow::anyhow!("Invalid value for '{key}': {reason}"))?; } else { @@ -200,20 +219,6 @@ async fn set(store: &dyn SettingsStore, key: &str, value: &str) -> anyhow::Resul .join(", ") ); } - - // Write under the canonical name so the deprecated alias updates the row the read - // path consults, rather than adding a second one that is silently ignored. - let key = extenddb_core::settings_keys::canonical_key(key); - store - .set_setting(key, value) - .await - .map_err(|e| anyhow::anyhow!("Failed to set setting: {e:?}"))?; - - tracing::warn!( - target: "extenddb::audit::settings", - "settings-set: key={key}, value={value}", - ); - println!("{key} = {value}"); Ok(()) } @@ -452,4 +457,23 @@ mod tests { ); } } + + #[test] + fn a_table_gsi_phase_hold_is_writable_from_the_cli() { + // The admin guide lists `gsi_creating_phase_delay_ms:` among the + // settings managed with `extenddb settings set`. + validate("gsi_creating_phase_delay_ms:orders", "1000").expect("a valid hold"); + validate("gsi_creating_phase_delay_ms:orders", "0").expect("zero clears it"); + let err = + validate("gsi_creating_phase_delay_ms:orders", "60001").expect_err("above the bound"); + assert!( + err.to_string() + .starts_with("Invalid value for 'gsi_creating_phase_delay_ms:orders'"), + "{err}" + ); + let err = validate("gsi_creating_phase_delay_ms:ab", "1000") + .expect_err("a table name the service would refuse"); + assert!(err.to_string().starts_with("Unknown setting"), "{err}"); + assert!(!config::should_redact("gsi_creating_phase_delay_ms:orders")); + } } diff --git a/crates/core/src/settings_keys.rs b/crates/core/src/settings_keys.rs index 45652baf2..89b1a86a8 100644 --- a/crates/core/src/settings_keys.rs +++ b/crates/core/src/settings_keys.rs @@ -100,6 +100,28 @@ pub const VECTOR_INDEX_MIN_CREATING_MS: &str = "vector_index_min_creating_ms"; /// Unset, nothing waits and no branch is taken. pub const VECTOR_ALLOCATION_PHASE_DELAY_MS: &str = "vector_allocation_phase_delay_ms"; +/// Test-only hold on the two `CREATING` phases of a GSI that `UpdateTable` adds. +/// +/// Keys take the form `gsi_creating_phase_delay_ms:` (see +/// [`gsi_creating_phase_delay_key`]) and the value is milliseconds. While it is +/// set for a table, a GSI added to that table waits that long after its catalog +/// row commits and before its backfill starts (`Backfilling: false`), then that +/// long again after the backfill has started (`Backfilling: true`). The phases +/// come from the build itself; the hold only lengthens them. On a test-sized +/// table both phases otherwise last milliseconds, so a client polling +/// DescribeTable could not observe them, and the measured Query and Scan refusals +/// for each phase could not be tested at the wire. +/// +/// Scoped to one table so a test that sets it does not slow the GSI builds of the +/// tests running beside it. Unset or zero, nothing waits. +pub const GSI_CREATING_PHASE_DELAY_MS: &str = "gsi_creating_phase_delay_ms"; + +/// The settings key holding [`GSI_CREATING_PHASE_DELAY_MS`] for one table. +#[must_use] +pub fn gsi_creating_phase_delay_key(table_name: &str) -> String { + format!("{GSI_CREATING_PHASE_DELAY_MS}:{table_name}") +} + /// The accounts whose SearchVectors requests accept the extended /// `SearchConditionExpression` grammar: `all` (the default when the row is /// absent or empty), `off`, or a comma-separated list of 12-digit account diff --git a/crates/core/src/types/table.rs b/crates/core/src/types/table.rs index 1fd5bcaae..7100bbc76 100755 --- a/crates/core/src/types/table.rs +++ b/crates/core/src/types/table.rs @@ -292,6 +292,21 @@ pub struct GsiDescription { pub projection: Projection, #[serde(rename = "IndexStatus")] pub index_status: String, + /// Whether a GSI added by `UpdateTable` is still being populated. + /// + /// The same three states, in the same order, as + /// [`VectorIndexDescription::backfilling`], whose comment carries the + /// vector measurement. Measured for a GSI on 2026-10-26 (us-east-1): `false` + /// while the index is `CREATING` and its backfill has not started, `true` + /// while it runs, absent once the index is `ACTIVE`. ExtendDB reports the + /// member only for a GSI that `UpdateTable` added, and `None` serialises as + /// an absent member. + #[serde( + rename = "Backfilling", + skip_serializing_if = "Option::is_none", + default + )] + pub backfilling: Option, #[serde( rename = "ProvisionedThroughput", skip_serializing_if = "Option::is_none" @@ -751,7 +766,9 @@ pub const VECTOR_INDEX_SCAN_NOT_SUPPORTED: &str = "Scan operation not supported /// Prefix of the Scan refusal while a vector index is still backfilling; /// continues with the index name. The service reuses the GSI wording even -/// though the index is a vector index. Measured 2026-08-20. +/// though the index is a vector index. Measured 2026-08-20. A GSI that +/// `UpdateTable` is backfilling refuses both Query and Scan with this sentence +/// (measured 2026-10-26). pub const VECTOR_INDEX_BACKFILLING_SCAN_PREFIX: &str = "Cannot read from backfilling global secondary index: "; diff --git a/crates/engine/src/backup/tests.rs b/crates/engine/src/backup/tests.rs index 80c6f8949..0f06879ac 100644 --- a/crates/engine/src/backup/tests.rs +++ b/crates/engine/src/backup/tests.rs @@ -4160,6 +4160,7 @@ fn described(request: &RestoreRequest) -> TableDescription { key_schema: g.key_schema.clone(), projection: g.projection.clone(), index_status: "ACTIVE".to_owned(), + backfilling: None, provisioned_throughput: Some(ProvisionedThroughputDescription { read_capacity_units: 9, write_capacity_units: 9, @@ -12016,6 +12017,7 @@ fn music_table() -> TableDescription { non_key_attributes: None, }, index_status: "ACTIVE".to_owned(), + backfilling: None, provisioned_throughput: Some(ProvisionedThroughputDescription { read_capacity_units: 1, write_capacity_units: 1, diff --git a/crates/engine/src/partiql/authorize.rs b/crates/engine/src/partiql/authorize.rs index 7354f1cfd..1c062cb55 100644 --- a/crates/engine/src/partiql/authorize.rs +++ b/crates/engine/src/partiql/authorize.rs @@ -244,12 +244,12 @@ async fn each_disjunct( /// The key schema of what `stmt` reads or writes: the index's for a read of /// an index, the table's otherwise. `None` when the table is missing, when -/// the index is missing or a vector index, so that the condition keys read -/// from the key are absent. +/// the index is missing, a vector index or a GSI whose backfill has started, +/// so that the condition keys read from the key are absent. /// /// # Errors /// -/// A failed read of the index other than a missing index. +/// A failed read of the index other than a missing or backfilling index. async fn target_schema( ctx: &OperationContext, stmt: &Statement, @@ -279,6 +279,7 @@ async fn target_schema( { Ok(info) => Ok(Some(info.key_schema)), Err(StorageError::IndexNotFound(_)) => Ok(None), + Err(e) if extenddb_storage::gsi_backfill::is_backfilling_refusal(&e) => Ok(None), Err(e) => Err(storage_err_to_dynamo(e)), } } diff --git a/crates/engine/src/partiql/batch.rs b/crates/engine/src/partiql/batch.rs index b41c62b2f..a4f135141 100644 --- a/crates/engine/src/partiql/batch.rs +++ b/crates/engine/src/partiql/batch.rs @@ -381,6 +381,11 @@ async fn check_read( "The table does not have the specified index".to_owned(), )); } + // A GSI whose backfill has started is refused per statement + // too, with the sentence `ExecuteStatement` gets. + Err(e) if extenddb_storage::gsi_backfill::is_backfilling_refusal(&e) => { + return untranslated(storage_err_to_dynamo(e)); + } Err(e) => return Err(storage_err_to_dynamo(e)), } } diff --git a/crates/engine/src/update_table_tests.rs b/crates/engine/src/update_table_tests.rs index 0670fe366..95552e602 100644 --- a/crates/engine/src/update_table_tests.rs +++ b/crates/engine/src/update_table_tests.rs @@ -100,6 +100,7 @@ fn projected_total_counts_kept_indexes_and_created_ones() { key_schema: Vec::new(), projection: include(30), index_status: "ACTIVE".to_owned(), + backfilling: None, provisioned_throughput: None, index_size_bytes: 0, item_count: 0, @@ -112,6 +113,7 @@ fn projected_total_counts_kept_indexes_and_created_ones() { key_schema: Vec::new(), projection: include(50), index_status: "ACTIVE".to_owned(), + backfilling: None, provisioned_throughput: None, index_size_bytes: 0, item_count: 0, diff --git a/crates/engine/src/warm_throughput.rs b/crates/engine/src/warm_throughput.rs index 6434be79c..8356eba68 100644 --- a/crates/engine/src/warm_throughput.rs +++ b/crates/engine/src/warm_throughput.rs @@ -226,6 +226,7 @@ mod tests { projection_type: ProjectionType::All, non_key_attributes: None, }, + backfilling: None, index_status: "ACTIVE".to_owned(), provisioned_throughput: Some(ProvisionedThroughputDescription::default()), index_size_bytes: 0, diff --git a/crates/server/src/management/ops_settings.rs b/crates/server/src/management/ops_settings.rs index f5f0940dd..d3d93fdb7 100755 --- a/crates/server/src/management/ops_settings.rs +++ b/crates/server/src/management/ops_settings.rs @@ -115,10 +115,12 @@ fn validate_unknown_commit_test_gate(value: &str) -> Result<(), &'static str> { } } -#[cfg(feature = "mongodb-test-hooks")] +/// The table name of a `:` key, when the name is one the +/// service would accept for a table: 3 to 255 characters from `a-z`, `A-Z`, +/// `0-9`, `.`, `_` and `-`. fn table_scoped_gate_table_name<'a>(key: &'a str, prefix: &str) -> Option<&'a str> { let table_name = key.strip_prefix(prefix)?.strip_prefix(':')?; - let valid = !table_name.is_empty() + let valid = (3..=255).contains(&table_name.len()) && table_name .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')); @@ -137,6 +139,16 @@ fn is_table_scoped_unknown_commit_gate_key(key: &str) -> bool { .is_some() } +/// `gsi_creating_phase_delay_ms:`, with a name the service would +/// accept for a table. +fn is_gsi_creating_phase_delay_key(key: &str) -> bool { + table_scoped_gate_table_name( + key, + extenddb_core::settings_keys::GSI_CREATING_PHASE_DELAY_MS, + ) + .is_some() +} + fn validate_bool(value: &str) -> Result<(), &'static str> { match value { "true" | "false" => Ok(()), @@ -160,6 +172,26 @@ fn validate_index_propagation_delay_ms(value: &str) -> Result<(), &'static str> } } +/// The validator for a writable key: one of [`KNOWN_KEYS`], or a table's +/// `gsi_creating_phase_delay_ms:` hold. The management API and +/// `extenddb settings set` both look keys up here, so they accept the same +/// keys. +#[must_use] +pub fn writable_key_validator(key: &str) -> Option { + KNOWN_KEYS + .iter() + .find(|(k, _)| *k == key) + .map(|(_, validator)| *validator) + // A test lever for the same reason as the vector ones above: the two + // CREATING phases of a GSI build last milliseconds on a test-sized table, + // so the measured refusal for each cannot be observed from a client unless + // a test can lengthen them. Scoped to one table; same bound and validator. + .or_else(|| { + is_gsi_creating_phase_delay_key(key) + .then_some(validate_backfill_batch_delay_ms as Validator) + }) +} + /// Set a runtime setting with validation. /// /// Validates the key and value, then delegates the write to the @@ -179,10 +211,7 @@ pub async fn set_setting( return Err(OpError::Validation(format!("Setting '{key}' is read-only"))); } - let known = KNOWN_KEYS - .iter() - .find(|(k, _)| *k == key) - .map(|(_, validator)| *validator); + let known = writable_key_validator(key); #[cfg(feature = "mongodb-test-hooks")] let known = known .or_else(|| { @@ -225,6 +254,33 @@ pub async fn set_setting( Ok(()) } +#[cfg(test)] +mod tests { + use super::is_gsi_creating_phase_delay_key; + + #[test] + fn a_gsi_phase_hold_is_writable_for_one_valid_table_name() { + assert!(is_gsi_creating_phase_delay_key( + "gsi_creating_phase_delay_ms:orders-2026.v1_x" + )); + assert!(!is_gsi_creating_phase_delay_key( + "gsi_creating_phase_delay_ms" + )); + assert!(!is_gsi_creating_phase_delay_key( + "gsi_creating_phase_delay_ms:" + )); + assert!(!is_gsi_creating_phase_delay_key( + "gsi_creating_phase_delay_ms:ab" + )); + assert!(!is_gsi_creating_phase_delay_key( + "gsi_creating_phase_delay_ms:has space" + )); + assert!(!is_gsi_creating_phase_delay_key( + "gsi_creating_phase_delay_msx:orders" + )); + } +} + #[cfg(all(test, feature = "search-inequality-filters"))] #[path = "ops_settings_search_tests.rs"] mod search_tests; diff --git a/crates/storage-cassandra/src/create_table.rs b/crates/storage-cassandra/src/create_table.rs index 64d8f4d27..9d7bf2cde 100644 --- a/crates/storage-cassandra/src/create_table.rs +++ b/crates/storage-cassandra/src/create_table.rs @@ -596,6 +596,7 @@ impl CassandraEngine { key_schema: g.key_schema.clone(), projection: g.projection.clone(), index_status: "ACTIVE".to_owned(), + backfilling: None, provisioned_throughput: Some(ProvisionedThroughputDescription { read_capacity_units: g .provisioned_throughput diff --git a/crates/storage-cassandra/src/data/index.rs b/crates/storage-cassandra/src/data/index.rs index 803d02d81..5bcb5fe19 100644 --- a/crates/storage-cassandra/src/data/index.rs +++ b/crates/storage-cassandra/src/data/index.rs @@ -106,6 +106,12 @@ pub async fn fetch_indexes_for_table( /// Fetch a single index by `table_id` and `index_name` (hot path for query routing). /// /// Uses the `PRIMARY KEY ((table_id), index_name)` for efficient single-row lookup. +/// +/// A GSI still being built is not readable: its table is partial. The service +/// refuses a Query or Scan naming one in two ways, by phase (see +/// `extenddb_storage::gsi_backfill`). The recovery worker writes +/// `backfill_heartbeat` when it takes the index up for its backfill (see +/// `crate::gsi_backfill_phase`), so a heartbeat means the backfill has started. pub async fn fetch_index_by_name( table_id: &str, index_name: &str, @@ -113,7 +119,8 @@ pub async fn fetch_index_by_name( catalog_keyspace: &str, ) -> Result { let query = format!( - "SELECT index_id, index_type, key_schema, projection, propagation_delay_ms \ + "SELECT index_id, index_type, key_schema, projection, propagation_delay_ms, \ + index_status, backfill_heartbeat \ FROM {catalog_keyspace}.indexes WHERE table_id = ? AND index_name = ?" ); @@ -130,6 +137,15 @@ pub async fn fetch_index_by_name( .next() .ok_or_else(|| StorageError::IndexNotFound(index_name.to_owned()))?; + let index_status: String = get_column(&row, "index_status", "fetch_index_by_name")?; + if index_status == "CREATING" { + let heartbeat: Option = row.get_by_name("backfill_heartbeat").ok().flatten(); + return Err(extenddb_storage::gsi_backfill::creating_read_refusal( + index_name, + heartbeat.is_some(), + )); + } + let index_id: String = get_column(&row, "index_id", "fetch_index_by_name")?; let index_type: String = get_column(&row, "index_type", "fetch_index_by_name")?; let key_schema_text: String = get_column(&row, "key_schema", "fetch_index_by_name")?; diff --git a/crates/storage-cassandra/src/gsi_backfill_phase.rs b/crates/storage-cassandra/src/gsi_backfill_phase.rs new file mode 100644 index 000000000..d0132cefa --- /dev/null +++ b/crates/storage-cassandra/src/gsi_backfill_phase.rs @@ -0,0 +1,94 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The start of a GSI backfill, as the catalog records it. +//! +//! DescribeTable reports `Backfilling` for a `CREATING` GSI as whether its row +//! carries a `backfill_heartbeat`, and a Query or Scan naming it is refused by +//! the same test (see `extenddb_storage::gsi_backfill`). `UpdateTable` inserts +//! the row with no heartbeat. The recovery worker writes one when it takes the +//! index up, before it rebuilds the data table and starts the backfill, and the +//! backfill refreshes it after every page. Written before the backfill task +//! starts, it also tells a later scan of the recovery worker that the index is +//! taken, so the scan does not rebuild it a second time. + +use std::time::Duration; + +use cdrs_tokio::types::IntoRustByName as _; +use extenddb_storage::error::StorageError; + +use crate::engine::CassandraEngine; + +/// Record that the backfill of one index is starting, after the table's +/// `gsi_creating_phase_delay_ms` test hold, and return the hold so the +/// backfill task can wait it again once the start is recorded. +/// +/// The recovery worker is one loop, so the first wait also delays the indexes +/// queued behind this one; it is zero outside tests. +/// +/// Returns `None` when there is nothing to build: the row is no longer +/// `CREATING`, or it could not be read. The heartbeat is written only to a row +/// read as `CREATING` immediately before, because a CQL `UPDATE` of a deleted +/// row would recreate it in part. +pub(crate) async fn claim( + engine: &CassandraEngine, + table_id: &str, + index_name: &str, + table_name: &str, +) -> Option { + let catalog_ks = engine.catalog_keyspace(); + let session = engine.session_arc(); + let hold = creating_phase_delay(engine, table_name).await; + tokio::time::sleep(hold).await; + let row = crate::cassandra_util::query_optional::( + &session, + &format!( + "SELECT index_status FROM {catalog_ks}.indexes WHERE table_id = ? AND index_name = ?" + ), + cdrs_tokio::query_values!(table_id, index_name), + "gsi_backfill_claim_check", + ) + .await; + let status: Option = match row { + Ok(row) => row.and_then(|r| r.get_by_name("index_status").ok().flatten()), + Err(e) => { + tracing::warn!("gsi_recovery: re-read '{index_name}' before its backfill: {e}"); + return None; + } + }; + if status.as_deref() != Some("CREATING") { + return None; + } + let claimed = crate::cassandra_util::execute::( + &session, + &format!( + "UPDATE {catalog_ks}.indexes SET backfill_heartbeat = toTimestamp(now()) \ + WHERE table_id = ? AND index_name = ?" + ), + cdrs_tokio::query_values!(table_id, index_name), + "gsi_backfill_claim", + ) + .await; + if let Err(e) = claimed { + // The backfill still runs; its first page writes the heartbeat. + tracing::warn!("gsi_recovery: record the backfill start of '{index_name}': {e}"); + } + Some(hold) +} + +/// The `gsi_creating_phase_delay_ms` test hold for one table; zero when unset. +async fn creating_phase_delay(engine: &CassandraEngine, table_name: &str) -> Duration { + let catalog_ks = engine.catalog_keyspace(); + let key = extenddb_core::settings_keys::gsi_creating_phase_delay_key(table_name); + let row = crate::cassandra_util::query_optional::( + &engine.session_arc(), + &format!("SELECT value FROM {catalog_ks}.settings WHERE key = ?"), + cdrs_tokio::query_values!(key.as_str()), + "gsi_creating_phase_delay", + ) + .await + .ok() + .flatten(); + let value: Option = row.and_then(|r| r.get_by_name("value").ok().flatten()); + extenddb_storage::gsi_backfill::phase_delay(value.as_deref()) +} diff --git a/crates/storage-cassandra/src/lib.rs b/crates/storage-cassandra/src/lib.rs index 71f0f9bb7..8bb80aba8 100644 --- a/crates/storage-cassandra/src/lib.rs +++ b/crates/storage-cassandra/src/lib.rs @@ -32,6 +32,7 @@ mod credential_store; pub mod data; mod delete_table; pub mod engine; +mod gsi_backfill_phase; pub mod gsi_queue; mod management_store; mod metadata_engine; diff --git a/crates/storage-cassandra/src/table_helpers.rs b/crates/storage-cassandra/src/table_helpers.rs index 3a7d61998..6d82411e8 100644 --- a/crates/storage-cassandra/src/table_helpers.rs +++ b/crates/storage-cassandra/src/table_helpers.rs @@ -228,12 +228,20 @@ impl CassandraEngine { if index_type == "GSI" { let pt_str: Option = row.get_r_by_name("provisioned_throughput").ok(); + // The recovery worker writes the heartbeat when it takes the + // index up for its backfill, so a heartbeat on a CREATING index + // means the backfill has started. + let heartbeat: Option = row.get_by_name("backfill_heartbeat").ok().flatten(); let warm_json: Option = row.get_by_name("warm_throughput").ok().flatten(); gsis.push(GsiDescription { index_name: index_name.clone(), key_schema: ks, projection: proj, + backfilling: extenddb_storage::gsi_backfill::backfilling_member( + &index_status, + heartbeat.is_some(), + ), index_status, provisioned_throughput: gsi_throughput_description(pt_str.as_deref()), index_size_bytes: 0, diff --git a/crates/storage-cassandra/src/workers.rs b/crates/storage-cassandra/src/workers.rs index 5aa3d4445..102552868 100644 --- a/crates/storage-cassandra/src/workers.rs +++ b/crates/storage-cassandra/src/workers.rs @@ -692,6 +692,7 @@ pub(crate) async fn poll_gsi_backfill_recovery( &engine, account_ks, stale_threshold, + None, &shutdown, &mut backfills, ) @@ -706,6 +707,34 @@ pub(crate) async fn poll_gsi_backfill_recovery( while backfills.join_next().await.is_some() {} } +/// One scan of the recovery worker, limited to the `CREATING` indexes of one +/// table; for tests. A direct test drives the worker's claim with it, and the +/// table filter keeps the scan off the indexes the tests running beside it +/// stage. The backfills it starts keep running after it returns, as they do in +/// the worker between two scans, where +/// [`recover_stale_gsi_backfills_for_tests`] waits for them. +#[cfg(any(test, feature = "test-util"))] +#[doc(hidden)] +pub async fn recover_stale_gsi_backfills_of_table( + engine: &Arc, + account_ks: &str, + table_id: &str, + stale_threshold: Duration, +) -> Result<(), extenddb_storage::error::StorageError> { + let mut backfills = tokio::task::JoinSet::new(); + let result = recover_stale_backfills( + engine, + account_ks, + stale_threshold, + Some(table_id), + &CancellationToken::new(), + &mut backfills, + ) + .await; + backfills.detach_all(); + result +} + /// The GSI backfill recovery worker `serve` runs, with the stale threshold /// and scan interval given, until `shutdown` fires; for tests. It scans only /// the keyspace of `account_id`: the tests of one binary share one catalog, @@ -751,6 +780,7 @@ pub async fn recover_stale_gsi_backfills_for_tests( engine, &engine.account_keyspace(account_id), stale_threshold, + None, &CancellationToken::new(), &mut backfills, ) @@ -759,14 +789,15 @@ pub async fn recover_stale_gsi_backfills_for_tests( pass } -/// Rerun the stale backfills of the indexes of tables in `account_ks`, each -/// in a task of `backfills` that stops once `shutdown` fires. An index of a -/// table in another account's keyspace is left to the pass over that -/// keyspace. +/// Rerun the stale backfills of the indexes of tables in `account_ks`, or of +/// its table `only_table`, each in a task of `backfills` that stops once +/// `shutdown` fires. An index of a table in another account's keyspace is +/// left to the pass over that keyspace. async fn recover_stale_backfills( engine: &Arc, account_ks: &str, stale_threshold: Duration, + only_table: Option<&str>, shutdown: &CancellationToken, backfills: &mut tokio::task::JoinSet<()>, ) -> Result<(), extenddb_storage::error::StorageError> { @@ -804,6 +835,9 @@ async fn recover_stale_backfills( } let table_id: String = crate::cassandra_util::get_column(&row, "table_id", "gsi_recovery")?; + if only_table.is_some_and(|t| t != table_id) { + continue; + } let index_name: String = crate::cassandra_util::get_column(&row, "index_name", "gsi_recovery")?; let index_id: String = crate::cassandra_util::get_column(&row, "index_id", "gsi_recovery")?; @@ -817,7 +851,7 @@ async fn recover_stale_backfills( match crate::cassandra_util::query_optional::( &engine.session, &format!( - "SELECT account_id, key_schema, attribute_definitions \ + "SELECT account_id, key_schema, attribute_definitions, table_name \ FROM {catalog_ks}.tables WHERE table_id = ? ALLOW FILTERING" ), cdrs_tokio::query_values!(table_id.as_str()), @@ -841,9 +875,10 @@ async fn recover_stale_backfills( // The catalog holds the indexes of every account. Another account's // index is recovered by the pass over its own keyspace; recovering it // here would create its data table in this keyspace and run a - // backfill of a base table this keyspace does not hold. It is - // skipped before its definition is parsed, so a malformed row is - // reported by its owner's pass alone. + // backfill of a base table this keyspace does not hold. A claim + // written here would also make the owner's pass find the index taken + // and skip it. It is skipped before its definition is parsed, so a + // malformed row is reported by its owner's pass alone. let owner: String = crate::cassandra_util::get_column(&base_row, "account_id", "gsi_recovery_base")?; if engine.account_keyspace(&owner) != account_ks { @@ -894,6 +929,14 @@ async fn recover_stale_backfills( "gsi_recovery: recovering stale backfill for index '{index_name}' \ (table_id={table_id}, index_id={index_id})" ); + let base_table_name: String = + crate::cassandra_util::get_column(&base_row, "table_name", "gsi_recovery_base")?; + let Some(hold) = + crate::gsi_backfill_phase::claim(engine, &table_id, &index_name, &base_table_name) + .await + else { + continue; + }; // Drop and recreate the data table so we start from a clean slate. if let Err(e) = engine.drop_index_data_table(account_ks, &index_id).await { @@ -943,21 +986,26 @@ async fn recover_stale_backfills( // Once `shutdown` fires the backfill stops at its next request // and the task writes nothing more: the index stays CREATING // under its hold, its heartbeat goes stale, and a later pass runs - // the backfill again, as after a crash. + // the backfill again, as after a crash. The test-only phase hold + // waits under the same token. let Some(result) = shutdown - .run_until_cancelled(crate::data::ddl::backfill_gsi( - &session, - &account_ks_owned, - &catalog_ks_owned, - &table_id_owned, - &index_id_owned, - &index_name_owned, - &index_key_schema, - &base_attr_defs, - &base_key_schema, - &base_attr_defs, - &projection, - )) + .run_until_cancelled(async { + tokio::time::sleep(hold).await; + crate::data::ddl::backfill_gsi( + &session, + &account_ks_owned, + &catalog_ks_owned, + &table_id_owned, + &index_id_owned, + &index_name_owned, + &index_key_schema, + &base_attr_defs, + &base_key_schema, + &base_attr_defs, + &projection, + ) + .await + }) .await else { tracing::info!( diff --git a/crates/storage-cassandra/tests/direct/gsi_backfilling.rs b/crates/storage-cassandra/tests/direct/gsi_backfilling.rs new file mode 100644 index 000000000..6b875f082 --- /dev/null +++ b/crates/storage-cassandra/tests/direct/gsi_backfilling.rs @@ -0,0 +1,284 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! A `CREATING` GSI reports `Backfilling` and refuses reads by phase, as +//! measured on 2026-10-26 (see `extenddb_storage::gsi_backfill`). +//! +//! These direct tests run no recovery worker, so the first test puts the +//! catalog row in each state by hand, the way the worker leaves it: `CREATING` +//! with no `backfill_heartbeat` as `UpdateTable` inserts it, `CREATING` with +//! one once the worker has taken the index up, then `ACTIVE` with the heartbeat +//! left in place. The second drives single scans of the worker on its table. + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::time::{Duration, Instant}; + + use cdrs_tokio::query::QueryValues; + use cdrs_tokio::types::IntoRustByName as _; + use extenddb_core::types::{AttributeValue, DescribeTableInput}; + use extenddb_storage::error::StorageError; + use extenddb_storage::{DataEngine, TableEngine}; + use extenddb_storage_cassandra::CassandraEngine; + use extenddb_storage_cassandra::cassandra_util::{execute, query_optional, system_read}; + use extenddb_storage_cassandra::workers::recover_stale_gsi_backfills_of_table; + use uuid::Uuid; + + const BACKFILLING: &str = "Cannot read from backfilling global secondary index: gidx"; + + async fn set_row(engine: &CassandraEngine, table_id: &str, assignments: &str) { + let catalog_ks = engine.catalog_keyspace(); + execute::( + &engine.session_arc(), + &format!( + "UPDATE {catalog_ks}.indexes SET {assignments} \ + WHERE table_id = ? AND index_name = 'gidx'" + ), + cdrs_tokio::query_values!(table_id), + "gsi_backfilling_test", + ) + .await + .expect("set the index row"); + } + + /// The serialised `IndexStatus` and `Backfilling` members of `gidx`. + async fn described( + engine: &CassandraEngine, + account_id: &str, + table_name: &str, + ) -> (String, Option) { + let desc = engine + .describe_table( + account_id, + DescribeTableInput { + table_name: table_name.to_owned(), + }, + ) + .await + .expect("describe the table"); + let gsi = desc + .global_secondary_indexes + .expect("GSIs") + .into_iter() + .find(|g| g.index_name == "gidx") + .expect("gidx"); + let wire = serde_json::to_value(&gsi).expect("serialise the GSI description"); + (gsi.index_status, wire.get("Backfilling").cloned()) + } + + #[tokio::test] + async fn a_creating_gsi_reports_each_phase_and_refuses_reads_by_phase() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = crate::helpers::setup_engine().await; + let table = crate::helpers::TestTable::with_gsi(&engine, "GsiPhases", "gidx", "g").await; + let ki = &table.key_info; + + set_row( + &engine, + &ki.table_id, + "index_status = 'CREATING', backfill_heartbeat = null", + ) + .await; + assert_eq!( + described(&engine, &ki.account_id, &ki.table_name).await, + ("CREATING".to_owned(), Some(serde_json::Value::Bool(false))) + ); + let read = engine.index_info_by_table_id(&ki.table_id, "gidx").await; + assert!( + matches!(read, Err(StorageError::IndexNotFound(ref n)) if n == "gidx"), + "before the backfill a read is told there is no such index: {read:?}" + ); + + set_row( + &engine, + &ki.table_id, + "backfill_heartbeat = toTimestamp(now())", + ) + .await; + assert_eq!( + described(&engine, &ki.account_id, &ki.table_name).await, + ("CREATING".to_owned(), Some(serde_json::Value::Bool(true))) + ); + let read = engine.index_info_by_table_id(&ki.table_id, "gidx").await; + assert!( + matches!(read, Err(StorageError::Validation(ref m)) if m == BACKFILLING), + "during the backfill a read gets the backfilling sentence: {read:?}" + ); + + set_row(&engine, &ki.table_id, "index_status = 'ACTIVE'").await; + assert_eq!( + described(&engine, &ki.account_id, &ki.table_name).await, + ("ACTIVE".to_owned(), None) + ); + engine + .index_info_by_table_id(&ki.table_id, "gidx") + .await + .expect("an ACTIVE index resolves"); + + // A row whose status cannot be read is not served from the index. + set_row(&engine, &ki.table_id, "index_status = null").await; + let read = engine.index_info_by_table_id(&ki.table_id, "gidx").await; + assert!( + matches!(read, Err(StorageError::Internal(_))), + "a status that cannot be read fails the read: {read:?}" + ); + } + + /// One `i64` column, by its alias, from the first row of a query. + async fn scalar(engine: &CassandraEngine, cql: &str, values: QueryValues) -> Option { + query_optional::(&engine.session_arc(), cql, values, "gsi_claim_test") + .await + .expect("query") + .and_then(|row| row.get_by_name("v").ok().flatten()) + } + + /// The `index_id` of `gidx` on one table. + async fn index_id(engine: &CassandraEngine, table_id: &str) -> String { + let catalog_ks = engine.catalog_keyspace(); + query_optional::( + &engine.session_arc(), + &format!( + "SELECT index_id FROM {catalog_ks}.indexes WHERE table_id = ? AND index_name = 'gidx'" + ), + cdrs_tokio::query_values!(table_id), + "gsi_claim_test", + ) + .await + .expect("read the index row") + .and_then(|row| row.get_by_name("index_id").ok().flatten()) + .expect("index id") + } + + /// The id and the write time of the schema row of `gidx`'s data table. + async fn data_table(engine: &CassandraEngine, account_ks: &str, table: &str) -> (Uuid, i64) { + let row = system_read::( + &engine.session_arc(), + "SELECT id, WRITETIME(comment) AS v FROM system_schema.tables \ + WHERE keyspace_name = ? AND table_name = ?", + cdrs_tokio::query_values!(account_ks, table), + "gsi_claim_test", + ) + .await + .expect("read the schema row") + .into_iter() + .next() + .expect("the data table exists"); + ( + row.get_by_name("id").ok().flatten().expect("table id"), + row.get_by_name("v").ok().flatten().expect("write time"), + ) + } + + /// The recovery worker's claim. `UpdateTable` leaves a new index with no + /// heartbeat; the worker writes one before it rebuilds the data table and + /// starts the backfill, which is the start of the second phase, and a + /// later scan that finds the heartbeat fresh leaves the index to the build + /// already running. The table's phase hold keeps that build waiting while + /// the second scan runs. + #[tokio::test] + async fn the_recovery_claim_starts_the_second_phase_and_a_later_scan_leaves_the_build() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = Arc::new(crate::helpers::setup_engine().await); + let table = crate::helpers::TestTable::with_gsi(&engine, "GsiClaim", "gidx", "g").await; + let ki = &table.key_info; + let catalog_ks = engine.catalog_keyspace(); + let account_ks = engine.account_keyspace(&ki.account_id); + for n in 0..3 { + let item = std::collections::BTreeMap::from([ + ("id".to_owned(), AttributeValue::S(format!("p{n}"))), + ("g".to_owned(), AttributeValue::S("v".to_owned())), + ]); + engine + .put_item(ki, item, false, None, &Default::default(), None) + .await + .expect("put"); + } + let hold_key = extenddb_core::settings_keys::gsi_creating_phase_delay_key(&ki.table_name); + execute::( + &engine.session_arc(), + &format!("INSERT INTO {catalog_ks}.settings (key, value) VALUES (?, ?)"), + cdrs_tokio::query_values!(hold_key.as_str(), "3000"), + "gsi_claim_test", + ) + .await + .expect("set the phase hold"); + let index_id = index_id(&engine, &ki.table_id).await; + let data = extenddb_storage_cassandra::data::ddl::index_table_name(&index_id); + + // As UpdateTable leaves an index it adds. + set_row( + &engine, + &ki.table_id, + "index_status = 'CREATING', backfill_heartbeat = null", + ) + .await; + assert_eq!( + described(&engine, &ki.account_id, &ki.table_name).await, + ("CREATING".to_owned(), Some(serde_json::Value::Bool(false))) + ); + + let stale_after = Duration::from_secs(120); + recover_stale_gsi_backfills_of_table(&engine, &account_ks, &ki.table_id, stale_after) + .await + .expect("the first scan"); + assert_eq!( + described(&engine, &ki.account_id, &ki.table_name).await, + ("CREATING".to_owned(), Some(serde_json::Value::Bool(true))), + "the claim records the start of the backfill" + ); + let read = engine.index_info_by_table_id(&ki.table_id, "gidx").await; + assert!( + matches!(read, Err(StorageError::Validation(ref m)) if m == BACKFILLING), + "after the claim a read gets the backfilling sentence: {read:?}" + ); + let heartbeat_at = scalar( + &engine, + &format!( + "SELECT WRITETIME(backfill_heartbeat) AS v FROM {catalog_ks}.indexes \ + WHERE table_id = ? AND index_name = 'gidx'" + ), + cdrs_tokio::query_values!(ki.table_id.as_str()), + ) + .await + .expect("the heartbeat's write time"); + let (rebuilt, rebuilt_at) = data_table(&engine, &account_ks, &data).await; + assert!( + heartbeat_at < rebuilt_at, + "the heartbeat ({heartbeat_at}) is written before the data table is rebuilt ({rebuilt_at})" + ); + + // The backfill the first scan started is waiting out the hold. + recover_stale_gsi_backfills_of_table(&engine, &account_ks, &ki.table_id, stale_after) + .await + .expect("the second scan"); + assert_eq!( + data_table(&engine, &account_ks, &data).await.0, + rebuilt, + "the second scan left the data table to the running build" + ); + assert_eq!( + described(&engine, &ki.account_id, &ki.table_name).await, + ("CREATING".to_owned(), Some(serde_json::Value::Bool(true))) + ); + + let deadline = Instant::now() + Duration::from_secs(60); + while described(&engine, &ki.account_id, &ki.table_name).await + != ("ACTIVE".to_owned(), None) + { + assert!( + Instant::now() < deadline, + "the running build never published the index" + ); + tokio::time::sleep(Duration::from_millis(200)).await; + } + engine + .index_info_by_table_id(&ki.table_id, "gidx") + .await + .expect("an ACTIVE index resolves"); + } +} diff --git a/crates/storage-cassandra/tests/direct_integration.rs b/crates/storage-cassandra/tests/direct_integration.rs index 1586802db..2eda18233 100644 --- a/crates/storage-cassandra/tests/direct_integration.rs +++ b/crates/storage-cassandra/tests/direct_integration.rs @@ -36,6 +36,8 @@ mod consistency_shape; mod delete_item; #[path = "direct/groups.rs"] mod groups; +#[path = "direct/gsi_backfilling.rs"] +mod gsi_backfilling; #[path = "direct/gsi_worker_pass.rs"] mod gsi_worker_pass; #[path = "direct/iam_leftovers.rs"] diff --git a/crates/storage-mongodb/src/gsi_backfill_live_tests.rs b/crates/storage-mongodb/src/gsi_backfill_live_tests.rs new file mode 100644 index 000000000..9ce50b47a --- /dev/null +++ b/crates/storage-mongodb/src/gsi_backfill_live_tests.rs @@ -0,0 +1,259 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Live MongoDB tests: a GSI added by `UpdateTable` walks the service's two +//! `CREATING` phases (measured 2026-10-26, see `extenddb_storage::gsi_backfill`), +//! and a backfill resumed after a restart stays in its second phase. +//! +//! Needs a replica set, read from `EXTENDDB_TEST_MONGODB_URI`, and is +//! `#[ignore]`d like the backup live tests; run it with +//! `cargo test -p extenddb-storage-mongodb --lib -- --ignored live_gsi_`. Each +//! test uses its own catalog and data databases and drops them when it passes. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use extenddb_core::expression::ExpressionMaps; +use extenddb_core::types::{AttributeValue, DescribeTableInput, TableKeyInfo}; +use extenddb_storage::error::StorageError; +use extenddb_storage::{DataEngine, TableEngine}; +use mongodb::bson::{Document, doc}; + +use crate::MongoEngine; + +const ACCOUNT: &str = "123456789012"; +const TABLE: &str = "t_gsi_backfilling"; +const BACKFILLING: &str = "Cannot read from backfilling global secondary index: gidx"; + +async fn engine() -> MongoEngine { + let uri = std::env::var("EXTENDDB_TEST_MONGODB_URI") + .expect("set EXTENDDB_TEST_MONGODB_URI to a MongoDB replica set"); + let client = mongodb::Client::with_uri_str(uri).await.expect("client"); + let tag = uuid::Uuid::new_v4().simple().to_string(); + MongoEngine { + client: client.clone(), + catalog_db: client.database(&format!("g{}_cat", &tag[..12])), + data_db: client.database(&format!("g{}_data", &tag[..12])), + region: "us-east-1".to_owned(), + gsi_cache: Arc::default(), + tx_read_concern: mongodb::options::ReadConcern::snapshot(), + backup_liveness: crate::backup_engine::BackupLiveness::default(), + } +} + +/// A three-item table with the phase hold set to `hold_ms`, then `gidx` +/// added by `UpdateTable`, which returns at once on this backend: the index +/// is `CREATING` until the backfill worker builds it. +async fn table_with_a_new_gsi(engine: &MongoEngine, hold_ms: u32) -> TableKeyInfo { + let settings = engine.catalog_db.collection::("settings"); + settings + .insert_one(doc! { "_id": "control_plane_delay_seconds", "value": "0" }) + .await + .expect("settings"); + + let input: extenddb_core::types::CreateTableInput = serde_json::from_value(serde_json::json!({ + "TableName": TABLE, + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "BillingMode": "PAY_PER_REQUEST" + })) + .expect("input"); + engine + .create_table_impl(ACCOUNT, input, false) + .await + .expect("create table"); + let key_info = engine + .table_key_info(ACCOUNT, TABLE) + .await + .expect("key info"); + for n in 0..3 { + let item = std::collections::BTreeMap::from([ + ("pk".to_owned(), AttributeValue::S(format!("p{n}"))), + ("g".to_owned(), AttributeValue::S("v".to_owned())), + ]); + engine + .put_item( + &key_info, + item, + false, + None, + &ExpressionMaps::default(), + None, + ) + .await + .expect("put"); + } + settings + .insert_one(doc! { + "_id": extenddb_core::settings_keys::gsi_creating_phase_delay_key(TABLE), + "value": hold_ms.to_string(), + }) + .await + .expect("set the phase hold"); + + let update: extenddb_core::types::UpdateTableInput = + serde_json::from_value(serde_json::json!({ + "TableName": TABLE, + "AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}], + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gidx", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"} + }}] + })) + .expect("update input"); + engine + .update_table(ACCOUNT, update) + .await + .expect("UpdateTable succeeds"); + key_info +} + +/// What DescribeTable says about `gidx`: its status and its serialised +/// `Backfilling` member, or `None` before the catalog row is visible. +async fn gsi_state(engine: &MongoEngine) -> Option<(String, Option)> { + let desc = engine + .describe_table( + ACCOUNT, + DescribeTableInput { + table_name: TABLE.to_owned(), + }, + ) + .await + .expect("describe the table"); + let gsi = desc + .global_secondary_indexes? + .into_iter() + .find(|g| g.index_name == "gidx")?; + let wire = serde_json::to_value(&gsi).expect("serialise the GSI description"); + Some((gsi.index_status, wire.get("Backfilling").cloned())) +} + +/// The phase of `gidx`: 1 is `Backfilling` false, 2 is true, 3 is ACTIVE. +/// +/// Reads the index between two DescribeTable calls and checks the read gets +/// the answer the description implies. `None` when the index is not visible +/// yet, or when the two calls disagree, so a phase change between them cannot +/// pair one phase's description with the other's refusal. +async fn phase(engine: &MongoEngine, key_info: &TableKeyInfo) -> Option { + let before = gsi_state(engine).await?; + let read = engine + .index_info_by_table_id(&key_info.table_id, "gidx") + .await; + if gsi_state(engine).await.as_ref() != Some(&before) { + return None; + } + Some(match before { + (status, Some(serde_json::Value::Bool(false))) if status == "CREATING" => { + assert!( + matches!(read, Err(StorageError::IndexNotFound(ref n)) if n == "gidx"), + "before the backfill a read is told there is no such index: {read:?}" + ); + 1 + } + (status, Some(serde_json::Value::Bool(true))) if status == "CREATING" => { + assert!( + matches!(read, Err(StorageError::Validation(ref m)) if m == BACKFILLING), + "during the backfill a read gets the backfilling sentence: {read:?}" + ); + 2 + } + (status, None) if status == "ACTIVE" => { + read.expect("an ACTIVE index resolves"); + 3 + } + other => panic!("a state the service does not report: {other:?}"), + }) +} + +#[tokio::test] +#[ignore = "needs EXTENDDB_TEST_MONGODB_URI"] +async fn live_gsi_added_by_update_table_walks_both_creating_phases() { + let engine = engine().await; + let worker = tokio::spawn(crate::ttl_worker::gsi_backfill_worker( + Arc::new(engine.clone()), + extenddb_storage::CancellationToken::new(), + )); + let key_info = table_with_a_new_gsi(&engine, 2000).await; + + let mut seen: Vec = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(60); + while seen.last() != Some(&3) { + assert!(Instant::now() < deadline, "no ACTIVE state; seen {seen:?}"); + if let Some(phase) = phase(&engine, &key_info).await + && seen.last() != Some(&phase) + { + assert!( + seen.last().is_none_or(|&last| last < phase), + "phase {phase} after {seen:?}" + ); + seen.push(phase); + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert_eq!(seen, vec![1, 2, 3], "each phase is observed, in order"); + + worker.abort(); + engine.catalog_db.drop().await.expect("drop catalog"); + engine.data_db.drop().await.expect("drop data"); +} + +/// A process that dies during a backfill leaves the index document marked as +/// backfilling. The worker of the next process resumes the job from that +/// mark: the index reports its second phase before and during the resumed +/// backfill, and the job goes straight to its scan instead of starting the +/// first phase again, which with the hold set would wait it twice more. +#[tokio::test] +#[ignore = "needs EXTENDDB_TEST_MONGODB_URI"] +async fn live_gsi_job_resumed_after_a_restart_keeps_its_second_phase() { + const HOLD_MS: u32 = 30_000; + let engine = engine().await; + // No worker yet: the index stays as UpdateTable left it until the mark + // below stands in for a worker that set it and then died. + let key_info = table_with_a_new_gsi(&engine, HOLD_MS).await; + assert_eq!( + phase(&engine, &key_info).await, + Some(1), + "as UpdateTable left it" + ); + let marked = engine + .catalog_db + .collection::("indexes") + .update_one( + doc! { + "_id": { "table_id": &key_info.table_id, "index_name": "gidx" }, + "index_status": "CREATING", + }, + doc! { "$set": { "backfilling": true } }, + ) + .await + .expect("mark the backfill as started"); + assert_eq!(marked.matched_count, 1, "the CREATING index document"); + assert_eq!( + phase(&engine, &key_info).await, + Some(2), + "after the restart" + ); + + let started = Instant::now(); + let worker = tokio::spawn(crate::ttl_worker::gsi_backfill_worker( + Arc::new(engine.clone()), + extenddb_storage::CancellationToken::new(), + )); + loop { + match phase(&engine, &key_info).await { + Some(3) => break, + Some(2) | None => {} + Some(other) => panic!("phase {other} while the resumed job ran"), + } + assert!( + started.elapsed() < Duration::from_millis(u64::from(HOLD_MS) / 2), + "the resumed job waited on the phase hold" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + + worker.abort(); + engine.catalog_db.drop().await.expect("drop catalog"); + engine.data_db.drop().await.expect("drop data"); +} diff --git a/crates/storage-mongodb/src/gsi_backfill_phase.rs b/crates/storage-mongodb/src/gsi_backfill_phase.rs new file mode 100644 index 000000000..5a00b9da7 --- /dev/null +++ b/crates/storage-mongodb/src/gsi_backfill_phase.rs @@ -0,0 +1,98 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The `backfilling` field of a GSI catalog document, which DescribeTable +//! reports as `Backfilling` and which decides a Query or Scan refusal for a +//! `CREATING` GSI (see `extenddb_storage::gsi_backfill`). +//! +//! An index `UpdateTable` adds is inserted without the field, which reads as +//! `false`. The backfill worker sets it to `true` before it scans the first +//! batch, and the `ACTIVE` flip removes it. A job resumed after a restart +//! finds it already set. A restore builds its indexes as part of restoring +//! the table and never sets it. + +use std::time::Duration; + +use bson::{Document, doc}; +use extenddb_storage::error::StorageError; + +use crate::MongoEngine; + +/// Record that the backfill of a `CREATING` index has started, after the +/// table's `gsi_creating_phase_delay_ms` test hold, and then wait the hold +/// again. The worker runs one job at a time, so a hold also delays the jobs +/// queued behind this one. +/// +/// Returns `false` when the index is no longer `CREATING` (deleted, or +/// published by another process), in which case the job has nothing to do. +pub(crate) async fn mark_started( + storage: &MongoEngine, + index_id: &str, + table_name: &str, +) -> Result { + let hold = creating_phase_delay(storage, table_name).await; + tokio::time::sleep(hold).await; + let result = storage + .catalog_db + .collection::("indexes") + .update_one( + doc! { "index_id": index_id, "index_status": "CREATING" }, + doc! { "$set": { "backfilling": true } }, + ) + .await + .map_err(|e| StorageError::Internal(e.to_string()))?; + if result.matched_count == 0 { + return Ok(false); + } + tokio::time::sleep(hold).await; + Ok(true) +} + +/// The `Backfilling` member for a GSI catalog document. +pub(crate) fn member(index_doc: &Document, index_status: &str) -> Option { + if index_doc.get_str("backfill_mode") == Ok("restore") { + return None; + } + extenddb_storage::gsi_backfill::backfilling_member(index_status, started(index_doc)) +} + +/// Whether the worker has recorded the start of this index's backfill. +pub(crate) fn started(index_doc: &Document) -> bool { + index_doc.get_bool("backfilling").unwrap_or(false) +} + +/// The `gsi_creating_phase_delay_ms` test hold for one table; zero when unset. +async fn creating_phase_delay(storage: &MongoEngine, table_name: &str) -> Duration { + let key = extenddb_core::settings_keys::gsi_creating_phase_delay_key(table_name); + let setting = storage + .catalog_db + .collection::("settings") + .find_one(doc! { "_id": key }) + .await + .ok() + .flatten(); + extenddb_storage::gsi_backfill::phase_delay( + setting.as_ref().and_then(|d| d.get_str("value").ok()), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_added_index_reports_false_then_true_then_nothing() { + let inserted = doc! { "index_status": "CREATING" }; + assert_eq!(member(&inserted, "CREATING"), Some(false)); + let started = doc! { "index_status": "CREATING", "backfilling": true }; + assert_eq!(member(&started, "CREATING"), Some(true)); + let active = doc! { "index_status": "ACTIVE" }; + assert_eq!(member(&active, "ACTIVE"), None); + } + + #[test] + fn a_restored_index_reports_no_member() { + let restoring = doc! { "index_status": "CREATING", "backfill_mode": "restore" }; + assert_eq!(member(&restoring, "CREATING"), None); + } +} diff --git a/crates/storage-mongodb/src/lib.rs b/crates/storage-mongodb/src/lib.rs index 59b515dcc..183e2f9de 100644 --- a/crates/storage-mongodb/src/lib.rs +++ b/crates/storage-mongodb/src/lib.rs @@ -18,6 +18,9 @@ mod credential_store; mod data; mod data_engine; mod error_class; +#[cfg(test)] +mod gsi_backfill_live_tests; +mod gsi_backfill_phase; mod management_store; mod management_store_secrets; mod metadata_engine; diff --git a/crates/storage-mongodb/src/table_engine.rs b/crates/storage-mongodb/src/table_engine.rs index 63d3c514d..b853f061b 100644 --- a/crates/storage-mongodb/src/table_engine.rs +++ b/crates/storage-mongodb/src/table_engine.rs @@ -481,6 +481,7 @@ impl MongoEngine { key_schema: gsi.key_schema.clone(), projection: gsi.projection.clone(), index_status: index_status.to_string(), + backfilling: None, provisioned_throughput: gsi.provisioned_throughput.as_ref().map(|pt| { ProvisionedThroughputDescription { read_capacity_units: pt.read_capacity_units, @@ -1536,6 +1537,16 @@ impl MongoEngine { .map_err(|e| crate::error_class::catalog_read_err(&e))? .ok_or_else(|| StorageError::IndexNotFound(index_name.to_string()))?; + // A GSI still being built is not readable: its collection is partial. + // The service refuses a Query or Scan naming one in two ways, by phase; + // see `extenddb_storage::gsi_backfill`. + if index_doc.get_str("index_status") == Ok("CREATING") { + return Err(extenddb_storage::gsi_backfill::creating_read_refusal( + index_name, + crate::gsi_backfill_phase::started(&index_doc), + )); + } + let index_id = index_doc .get_str("index_id") .map_err(|_| StorageError::Internal("missing index_id".to_string()))? @@ -1788,14 +1799,13 @@ impl MongoEngine { last_decrease_date_time: None, })); + let idx_status = idx_doc.get_str("index_status").unwrap_or("ACTIVE"); gsis.push(GsiDescription { index_name: idx_name, key_schema: idx_key_schema, projection: idx_projection, - index_status: idx_doc - .get_str("index_status") - .unwrap_or("ACTIVE") - .to_string(), + index_status: idx_status.to_string(), + backfilling: crate::gsi_backfill_phase::member(idx_doc, idx_status), provisioned_throughput: idx_pt, index_size_bytes: 0, item_count: 0, diff --git a/crates/storage-mongodb/src/ttl_worker.rs b/crates/storage-mongodb/src/ttl_worker.rs index 3dd66139d..fc4887a66 100644 --- a/crates/storage-mongodb/src/ttl_worker.rs +++ b/crates/storage-mongodb/src/ttl_worker.rs @@ -180,6 +180,15 @@ async fn run_gsi_backfill_job(storage: &MongoEngine, job: &Document) -> Result<( if mode == GsiBackfillMode::Restore && !restore_backfill_is_ready(storage, &table_id).await? { return Ok(()); } + let indexes_coll = storage.catalog_db.collection::("indexes"); + if mode == GsiBackfillMode::Live + && !crate::gsi_backfill_phase::started(job) + && !crate::gsi_backfill_phase::mark_started(storage, &index_id, &key_info.table_name) + .await? + { + return drop_index_collection_if_catalog_entry_missing(storage, &indexes_coll, &index_id) + .await; + } let context = GsiBackfillContext { key_info: &key_info, @@ -189,7 +198,6 @@ async fn run_gsi_backfill_job(storage: &MongoEngine, job: &Document) -> Result<( mode, }; let mut cursor = job.get("backfill_cursor").cloned(); - let indexes_coll = storage.catalog_db.collection::("indexes"); loop { let progress = storage @@ -203,7 +211,7 @@ async fn run_gsi_backfill_job(storage: &MongoEngine, job: &Document) -> Result<( doc! { "index_id": &index_id, "index_status": "CREATING" }, doc! { "$set": { "index_status": "ACTIVE" }, - "$unset": { "backfill_cursor": "" }, + "$unset": { "backfill_cursor": "", "backfilling": "" }, }, ) .await diff --git a/crates/storage-postgres/src/create_table.rs b/crates/storage-postgres/src/create_table.rs index 49e6c1cb4..854accede 100755 --- a/crates/storage-postgres/src/create_table.rs +++ b/crates/storage-postgres/src/create_table.rs @@ -655,6 +655,7 @@ impl PostgresEngine { key_schema: g.key_schema.clone(), projection: g.projection.clone(), index_status: "ACTIVE".to_owned(), + backfilling: None, provisioned_throughput: Some(ProvisionedThroughputDescription { read_capacity_units: g .provisioned_throughput diff --git a/crates/storage-postgres/src/data/ddl.rs b/crates/storage-postgres/src/data/ddl.rs index 8c701bcef..042803de4 100755 --- a/crates/storage-postgres/src/data/ddl.rs +++ b/crates/storage-postgres/src/data/ddl.rs @@ -565,14 +565,15 @@ impl PostgresEngine { table_id: &str, index_name: &str, ) -> Result { - // A GSI still being built is not readable: its table is partial, or not - // there yet. The service answers a Query or Scan naming one with "The - // table does not have the specified index", the same as for no index at - // all, which is what `IndexNotFound` becomes on the wire. - let idx_row: Option<(String, String, serde_json::Value, serde_json::Value)> = + // A GSI still being built is not readable: its table is partial. The + // service refuses a Query or Scan naming one in two ways, by phase; see + // `extenddb_storage::gsi_backfill`. The backfill set is read before the + // row; see `GsiBackfills::snapshot`. + let started = self.gsi_backfills.snapshot(); + let idx_row: Option<(String, String, serde_json::Value, serde_json::Value, String)> = sqlx::query_as( - "SELECT index_type, index_id, key_schema, projection FROM indexes \ - WHERE table_id = $1 AND index_name = $2 AND index_status <> 'CREATING'", + "SELECT index_type, index_id, key_schema, projection, index_status \ + FROM indexes WHERE table_id = $1 AND index_name = $2", ) .bind(table_id) .bind(index_name) @@ -580,8 +581,14 @@ impl PostgresEngine { .await .map_err(|e| StorageError::Internal(e.to_string()))?; - let (idx_type_str, idx_id, ks_json, proj_json) = + let (idx_type_str, idx_id, ks_json, proj_json, status) = idx_row.ok_or_else(|| StorageError::IndexNotFound(index_name.to_owned()))?; + if status == "CREATING" { + return Err(extenddb_storage::gsi_backfill::creating_read_refusal( + index_name, + started.contains(&idx_id), + )); + } let index_type = match idx_type_str.as_str() { "GSI" => IndexType::Gsi, diff --git a/crates/storage-postgres/src/data/gsi_build.rs b/crates/storage-postgres/src/data/gsi_build.rs index f69b0f1a7..f3e2cb511 100644 --- a/crates/storage-postgres/src/data/gsi_build.rs +++ b/crates/storage-postgres/src/data/gsi_build.rs @@ -975,6 +975,7 @@ pub(crate) async fn remove_failed_build( data: &sqlx::PgPool, table_id: &str, build: &GsiBuild, + backfills: &extenddb_storage::gsi_backfill::GsiBackfills, ) { // By id, not name: the name may already belong to a newer index. let deleted = sqlx::query( @@ -987,10 +988,14 @@ pub(crate) async fn remove_failed_build( .await; match deleted { Ok(r) if r.rows_affected() == 1 => { + backfills.finish(&build.def.index_id); tokio::time::sleep(GRACE_PUBLISH).await; drop_gsi_tables(data, std::slice::from_ref(build)).await; } - Ok(_) => {} + // No CREATING row: the index was published or deleted meanwhile. + Ok(_) => backfills.finish(&build.def.index_id), + // The row may still be CREATING, so its record stays for the recovery + // pass that will take it up. Err(e) => tracing::error!( index_id = %build.def.index_id, "could not remove the catalog row of a failed GSI build: {e}" @@ -1021,6 +1026,16 @@ async fn index_row_exists( /// that failed with its error; builds before it are ACTIVE, and the caller /// abandons it and the ones after it. A build whose index was deleted while it /// ran, or that someone else published first, is not a failure. +/// +/// Each build is recorded in `backfills` from the start of its backfill until +/// its index leaves `CREATING`, which is what DescribeTable reports as +/// `Backfilling: true`; before that the index reports `false`. A build that +/// returns an error leaves the record for the caller: a passing failure keeps +/// it for the retry, and `remove_failed_build` removes it with the index. +/// `hold` is the table's `gsi_creating_phase_delay_ms` test hold, waited once +/// before the barrier and once more inside each build's recorded phase, +/// between its backfill and its flip to ACTIVE. +#[allow(clippy::too_many_arguments)] pub(crate) async fn build_gsis( catalog: &sqlx::PgPool, data: &sqlx::PgPool, @@ -1028,12 +1043,14 @@ pub(crate) async fn build_gsis( base_ks: &[KeySchemaElement], attr_defs: &[AttributeDefinition], builds: &[GsiBuild], + backfills: &extenddb_storage::gsi_backfill::GsiBackfills, + hold: Duration, ) -> Result { if builds.is_empty() { return Ok(0); } let mut published_here = 0usize; - tokio::time::sleep(GRACE_PUBLISH).await; + tokio::time::sleep(GRACE_PUBLISH + hold).await; if let Err(e) = write_barrier(data, table_id).await { // A table deleted during the wait is not a failed build. let mut gone = true; @@ -1044,13 +1061,26 @@ pub(crate) async fn build_gsis( } } if gone { + for b in builds { + backfills.finish(&b.def.index_id); + } drop_gsi_tables(data, builds).await; return Ok(0); } return Err((0, e)); } for (i, b) in builds.iter().enumerate() { + // Kept until the index leaves CREATING: removed below once the index + // is published or gone, and by `remove_failed_build` after a failure + // that would recur. A passing failure returns with it in place, so the + // index stays in its second phase until the retry publishes it. + backfills.start(&b.def.index_id); let filled = backfill(data, table_id, &b.def, base_ks, attr_defs).await; + if filled.is_ok() && !hold.is_zero() { + // After the backfill, so the end of the second phase, from the last + // page to the flip, is the part the hold lengthens. + tokio::time::sleep(hold).await; + } let published = match filled { Ok(counts) => { tracing::debug!( @@ -1073,13 +1103,17 @@ pub(crate) async fn build_gsis( Err(e) => Err(e), }; match published { - Ok(true) => published_here += 1, + Ok(true) => { + backfills.finish(&b.def.index_id); + published_here += 1; + } outcome => { // Either the flip found no CREATING row or the build failed. If the // row is gone the index was deleted (or its table was) while this // ran: drop what the delete may have raced past, and move on. match index_row_exists(catalog, table_id, &b.def.index_id).await { Ok(false) => { + backfills.finish(&b.def.index_id); drop_gsi_tables(data, std::slice::from_ref(b)).await; tracing::info!( index_id = %b.def.index_id, @@ -1090,7 +1124,10 @@ pub(crate) async fn build_gsis( let e = match outcome { Err(e) => e, // Present but not CREATING: someone else published it. - Ok(_) => continue, + Ok(_) => { + backfills.finish(&b.def.index_id); + continue; + } }; return Err((i, e)); } @@ -1308,6 +1345,8 @@ async fn reconcile_pass( &base_ks, &attr_defs, std::slice::from_ref(&build), + &engine.gsi_backfills, + Duration::ZERO, ) .await { @@ -1343,7 +1382,14 @@ async fn reconcile_pass( index_id = %index_id, "GSI build fails on every attempt; removing the index: {e}" ); - remove_failed_build(&engine.pool, &engine.data_pool, &table_id, &build).await; + remove_failed_build( + &engine.pool, + &engine.data_pool, + &table_id, + &build, + &engine.gsi_backfills, + ) + .await; if let Some(b) = backoff.as_mut() { b.succeeded(&index_id); } diff --git a/crates/storage-postgres/src/delete_table.rs b/crates/storage-postgres/src/delete_table.rs index 3e76c655d..84e382a95 100755 --- a/crates/storage-postgres/src/delete_table.rs +++ b/crates/storage-postgres/src/delete_table.rs @@ -79,7 +79,9 @@ impl PostgresEngine { ))); } - // Fetch indexes for the response description. + // Fetch indexes for the response description, after the backfill set; + // see `GsiBackfills::snapshot`. + let started = self.gsi_backfills.snapshot(); let index_rows: Vec = sqlx::query_as( r"SELECT index_name, index_id, index_type, key_schema, projection, index_status, provisioned_throughput, warm_throughput @@ -373,7 +375,7 @@ impl PostgresEngine { } // Build description from the fetched row data - let desc = self.build_table_description_from_row(account_id, row, index_rows)?; + let desc = self.build_table_description_from_row(account_id, row, index_rows, &started)?; Ok(TableDescription { table_status: TableStatus::Deleting, diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index 234e07a98..e17d73dbf 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -344,6 +344,10 @@ pub struct PostgresEngine { /// tests that count them. Shared by clones. #[cfg(feature = "test-hooks")] pub(crate) drop_attempts: Arc, + /// GSI builds in this process whose backfill has started, which is what + /// DescribeTable reports as `Backfilling` and what decides a Query or Scan + /// refusal for a `CREATING` GSI; see `extenddb_storage::gsi_backfill`. + pub(crate) gsi_backfills: extenddb_storage::gsi_backfill::GsiBackfills, } /// Table snapshots one engine may hold open at once: half the pool (at least @@ -496,6 +500,7 @@ impl PostgresEngine { shared_data_pool, #[cfg(feature = "test-hooks")] drop_attempts: Arc::default(), + gsi_backfills: extenddb_storage::gsi_backfill::GsiBackfills::default(), }) } @@ -705,6 +710,22 @@ impl PostgresEngine { } } + /// The `gsi_creating_phase_delay_ms` test hold for one table; zero when unset. + pub(crate) async fn gsi_creating_phase_delay(&self, table_name: &str) -> std::time::Duration { + let live: Result, _> = + sqlx::query_as("SELECT value FROM settings WHERE key = $1") + .bind(extenddb_core::settings_keys::gsi_creating_phase_delay_key( + table_name, + )) + .fetch_optional(&self.pool) + .await; + let value = live.unwrap_or_else(|e| { + tracing::debug!("gsi_creating_phase_delay: live read failed, using 0: {e:?}"); + None + }); + extenddb_storage::gsi_backfill::phase_delay(value.as_ref().map(|(v,)| v.as_str())) + } + /// Whether the data database has pgvector, as probed at construction. /// /// Public so that a deployment check, and the tests that pin the diff --git a/crates/storage-postgres/src/table_helpers.rs b/crates/storage-postgres/src/table_helpers.rs index b16b364b3..627bb42e6 100755 --- a/crates/storage-postgres/src/table_helpers.rs +++ b/crates/storage-postgres/src/table_helpers.rs @@ -136,6 +136,8 @@ impl PostgresEngine { account_id: &str, table_name: &str, ) -> Result { + // Before the catalog rows; see `GsiBackfills::snapshot`. + let started = self.gsi_backfills.snapshot(); let row: Option = sqlx::query_as( r"SELECT table_name, key_schema, attribute_definitions, billing_mode, provisioned_throughput, stream_specification, table_status, @@ -175,7 +177,8 @@ impl PostgresEngine { let table_name_owned = row.table_name.clone(); let table_id = row.table_id.clone(); - let mut desc = self.build_table_description_from_row(account_id, row, index_rows)?; + let mut desc = + self.build_table_description_from_row(account_id, row, index_rows, &started)?; desc.restore_summary = Self::restore_summary_on(conn, &table_id, &desc.table_status).await?; desc.vector_indexes = vector_index_descriptions( @@ -187,11 +190,16 @@ impl PostgresEngine { Ok(desc) } + /// `started` is a [`GsiBackfills::snapshot`] the caller took before it read + /// `index_rows`. + /// + /// [`GsiBackfills::snapshot`]: extenddb_storage::gsi_backfill::GsiBackfills::snapshot pub(crate) fn build_table_description_from_row( &self, account_id: &str, row: TableRow, index_rows: Vec, + started: &std::collections::HashSet, ) -> Result { let mut gsis: Vec = Vec::new(); let mut lsis: Vec = Vec::new(); @@ -231,6 +239,10 @@ impl PostgresEngine { index_name: idx.index_name.clone(), key_schema: ks, projection: proj, + backfilling: extenddb_storage::gsi_backfill::backfilling_member( + &idx.index_status, + started.contains(&idx.index_id), + ), index_status: idx.index_status, provisioned_throughput: pt.or(Some(ProvisionedThroughputDescription { read_capacity_units: 0, diff --git a/crates/storage-postgres/src/update_table.rs b/crates/storage-postgres/src/update_table.rs index dfc87a0e0..15868dfc2 100755 --- a/crates/storage-postgres/src/update_table.rs +++ b/crates/storage-postgres/src/update_table.rs @@ -996,6 +996,8 @@ impl PostgresEngine { let table_name = input.table_name.clone(); let base_ks = base_key_schema.clone(); let attr_defs = effective_attr_defs.clone(); + let backfills = self.gsi_backfills.clone(); + let hold = self.gsi_creating_phase_delay(&input.table_name).await; let task = tokio::spawn(async move { let built = build_gsis( &catalog, @@ -1004,6 +1006,8 @@ impl PostgresEngine { &base_ks, &attr_defs, &gsi_builds, + &backfills, + hold, ) .await; let Err((first_failed, e)) = built else { @@ -1029,7 +1033,7 @@ impl PostgresEngine { "Failed to build GSI '{}' on '{table_name}', removing it: {e}", b.index_name, ); - remove_failed_build(&catalog, &data, &build_table_id, b).await; + remove_failed_build(&catalog, &data, &build_table_id, b, &backfills).await; } Err(e) }); diff --git a/crates/storage-postgres/tests/gsi_backfilling.rs b/crates/storage-postgres/tests/gsi_backfilling.rs new file mode 100644 index 000000000..5a19e5761 --- /dev/null +++ b/crates/storage-postgres/tests/gsi_backfilling.rs @@ -0,0 +1,484 @@ +// SPDX-License-Identifier: Apache-2.0 +//! A GSI added by `UpdateTable` walks the service's two `CREATING` phases. +//! +//! Measured 2026-10-26 (see `extenddb_storage::gsi_backfill`): `Backfilling` +//! is `false` and a read is told the table has no such index until the +//! backfill starts, then `true` with the backfilling sentence until the index +//! is `ACTIVE`, when the member is gone and reads are served. The table's +//! `gsi_creating_phase_delay_ms` hold lengthens both phases so the walk is +//! observable on a three-item table. +//! +//! Each test builds its own throwaway database from the shipped migrations and +//! drops it when it passes; a failing test leaves it behind, named +//! `eddb_gsibf_*`. Requires `EXTENDDB_TEST_PG_CONNECTION_STRING`, a base URL +//! with no database component, pointing at a server whose role may create and +//! drop databases. Without it each test reports a skip and passes. + +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; + +use extenddb_core::expression::ExpressionMaps; +use extenddb_core::types::{ + AttributeDefinition, AttributeValue, BillingMode, CreateTableInput, DescribeTableInput, + KeySchemaElement, KeyType, ScalarAttributeType, TableDescription, TableKeyInfo, + UpdateTableInput, +}; +use extenddb_storage::error::StorageError; +use extenddb_storage::{DataEngine, TableEngine}; +use extenddb_storage_postgres::{PostgresConfig, PostgresEngine}; +use sqlx::postgres::PgPoolOptions; + +const ACCOUNT: &str = "123456789012"; +const TABLE: &str = "t_gsi_backfilling"; +const BACKFILLING: &str = "Cannot read from backfilling global secondary index: gidx"; + +/// 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 +} + +/// A scratch database holding one three-item table, an engine on it running +/// the propagation workers, and the table's phase hold. +struct Scratch { + admin: sqlx::PgPool, + db: sqlx::PgPool, + db_name: String, + engine: PostgresEngine, + key_info: TableKeyInfo, +} + +impl Scratch { + async fn new(base: &str, hold_ms: u32) -> Self { + let db_name = format!("eddb_gsibf_{}", 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(sqlx::AssertSqlSafe(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(3) + .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(sqlx::AssertSqlSafe(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, + }, + "us-east-1", + ) + .await + .expect("open a PostgresEngine on the scratch database") + .start_gsi_workers(); + + engine + .create_table( + ACCOUNT, + CreateTableInput { + table_name: 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 table"); + let key_info = engine + .table_key_info(ACCOUNT, TABLE) + .await + .expect("read the key info"); + for n in 0..3 { + let item = BTreeMap::from([ + ("pk".to_owned(), AttributeValue::S(format!("p{n}"))), + ("g".to_owned(), AttributeValue::S("v".to_owned())), + ]); + engine + .put_item( + &key_info, + item, + false, + None, + &ExpressionMaps::default(), + None, + ) + .await + .expect("put"); + } + + sqlx::query("INSERT INTO settings (key, value) VALUES ($1, $2)") + .bind(extenddb_core::settings_keys::gsi_creating_phase_delay_key( + TABLE, + )) + .bind(hold_ms.to_string()) + .execute(&db) + .await + .expect("set the phase hold"); + + Self { + admin, + db, + db_name, + engine, + key_info, + } + } + + /// Start `UpdateTable` adding `gidx` in its own task. It returns once the + /// index is ACTIVE on this backend, or once a passing build failure has + /// left it to the recovery pass. + fn add_gsi(&self) -> tokio::task::JoinHandle> { + let input: UpdateTableInput = serde_json::from_value(serde_json::json!({ + "TableName": TABLE, + "AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}], + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gidx", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + }}], + })) + .expect("build the UpdateTable input"); + let updater = self.engine.clone(); + tokio::spawn(async move { updater.update_table(ACCOUNT, input).await }) + } + + /// What DescribeTable says about `gidx`: its status and its serialised + /// `Backfilling` member, or `None` before the catalog row is visible. + async fn gsi_state(&self) -> Option<(String, Option)> { + let desc = self + .engine + .describe_table( + ACCOUNT, + DescribeTableInput { + table_name: TABLE.to_owned(), + }, + ) + .await + .expect("describe the table"); + let gsi = desc + .global_secondary_indexes? + .into_iter() + .find(|g| g.index_name == "gidx")?; + let wire = serde_json::to_value(&gsi).expect("serialise the GSI description"); + Some((gsi.index_status, wire.get("Backfilling").cloned())) + } + + /// The phase of `gidx`: 1 is `Backfilling` false, 2 is true, 3 is ACTIVE. + /// + /// Reads the index between two DescribeTable calls and checks the read + /// gets the answer the description implies. `None` when the index is not + /// visible yet, or when the two calls disagree, so a phase change between + /// them cannot pair one phase's description with the other's refusal. + async fn phase(&self) -> Option { + let before = self.gsi_state().await?; + let read = self + .engine + .index_info_by_table_id(&self.key_info.table_id, "gidx") + .await; + if self.gsi_state().await.as_ref() != Some(&before) { + return None; + } + Some(match before { + (status, Some(serde_json::Value::Bool(false))) if status == "CREATING" => { + assert!( + matches!(read, Err(StorageError::IndexNotFound(ref n)) if n == "gidx"), + "before the backfill a read is told there is no such index: {read:?}" + ); + 1 + } + (status, Some(serde_json::Value::Bool(true))) if status == "CREATING" => { + assert!( + matches!(read, Err(StorageError::Validation(ref m)) if m == BACKFILLING), + "during the backfill a read gets the backfilling sentence: {read:?}" + ); + 2 + } + (status, None) if status == "ACTIVE" => { + read.expect("an ACTIVE index resolves"); + 3 + } + other => panic!("a state the service does not report: {other:?}"), + }) + } + + async fn cleanup(self) { + drop(self.engine); + self.db.close().await; + sqlx::query(sqlx::AssertSqlSafe(format!( + "DROP DATABASE IF EXISTS \"{}\" WITH (FORCE)", + self.db_name + ))) + .execute(&self.admin) + .await + .expect("drop the scratch database"); + self.admin.close().await; + } +} + +#[tokio::test] +async fn a_gsi_added_by_update_table_walks_both_creating_phases() { + let Some(base) = base_conn() else { + eprintln!("SKIP: EXTENDDB_TEST_PG_CONNECTION_STRING is not set"); + return; + }; + let s = Scratch::new(&base, 1500).await; + let update = s.add_gsi(); + + let mut seen: Vec = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(60); + while seen.last() != Some(&3) { + assert!(Instant::now() < deadline, "no ACTIVE state; seen {seen:?}"); + if let Some(phase) = s.phase().await + && seen.last() != Some(&phase) + { + assert!( + seen.last().is_none_or(|&last| last < phase), + "phase {phase} after {seen:?}" + ); + seen.push(phase); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert_eq!(seen, vec![1, 2, 3], "each phase is observed, in order"); + update + .await + .expect("the UpdateTable task") + .expect("UpdateTable succeeds"); + + s.cleanup().await; +} + +/// From the end of its backfill to the flip to ACTIVE, the index is still in +/// its second phase: the build keeps its record until the row has left +/// CREATING, and DescribeTable and a read take the record set before the row. +/// On this backend the hold sits between the backfill and the flip, so the +/// test reads the index through that window. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_index_stays_backfilling_from_the_end_of_its_backfill_to_the_flip() { + let Some(base) = base_conn() else { + eprintln!("SKIP: EXTENDDB_TEST_PG_CONNECTION_STRING is not set"); + return; + }; + let s = Scratch::new(&base, 1500).await; + let update = s.add_gsi(); + + // The backfill has written all three items once the index table holds + // them; nothing else writes to the table in this test. + let deadline = Instant::now() + Duration::from_secs(30); + loop { + let index_id: Option<(String,)> = + sqlx::query_as("SELECT index_id FROM indexes WHERE index_name = 'gidx'") + .fetch_optional(&s.db) + .await + .expect("read the index row"); + let rows: Option = match index_id { + Some((id,)) => sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT count(*) FROM \"_ddb_{id}\"" + ))) + .fetch_one(&s.db) + .await + .ok(), + None => None, + }; + if rows == Some(3) { + break; + } + assert!( + Instant::now() < deadline, + "the backfill never wrote the items" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + + let mut readings = 0; + let deadline = Instant::now() + Duration::from_secs(30); + loop { + match s.phase().await { + Some(3) => break, + Some(2) => readings += 1, + None => {} + Some(phase) => panic!("phase {phase} after the backfill wrote every item"), + } + assert!(Instant::now() < deadline, "no ACTIVE state"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!(readings > 0, "no reading between the backfill and the flip"); + update + .await + .expect("the UpdateTable task") + .expect("UpdateTable succeeds"); + + s.cleanup().await; +} + +/// A build that fails for a passing reason leaves its index CREATING for the +/// recovery pass. The index stays in its second phase through the wait and the +/// retry, until the retry publishes it. +/// +/// The failure is a real one: the test locks the index's catalog row so the +/// flip to ACTIVE waits on it, then cancels the waiting statement, which is +/// `SQLSTATE 57014`, a failure the build treats as passing. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_passing_build_failure_keeps_the_index_backfilling_until_the_retry_publishes_it() { + let Some(base) = base_conn() else { + eprintln!("SKIP: EXTENDDB_TEST_PG_CONNECTION_STRING is not set"); + return; + }; + let s = Scratch::new(&base, 1500).await; + let update = s.add_gsi(); + + let deadline = Instant::now() + Duration::from_secs(30); + while s.phase().await != Some(2) { + assert!(Instant::now() < deadline, "the backfill never started"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + let mut lock = s.db.begin().await.expect("begin the lock transaction"); + sqlx::query("SELECT 1 FROM indexes WHERE index_name = 'gidx' FOR UPDATE") + .execute(&mut *lock) + .await + .expect("lock the index row"); + let flip = loop { + let waiting: Option<(i32,)> = sqlx::query_as( + "SELECT pid FROM pg_stat_activity \ + WHERE datname = current_database() AND wait_event_type = 'Lock' \ + AND query LIKE 'UPDATE indexes SET index_status = ''ACTIVE''%'", + ) + .fetch_optional(&s.db) + .await + .expect("read pg_stat_activity"); + if let Some((pid,)) = waiting { + break pid; + } + assert!( + Instant::now() < deadline, + "the flip to ACTIVE never waited on the lock" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + }; + let cancelled: bool = sqlx::query_scalar("SELECT pg_cancel_backend($1)") + .bind(flip) + .fetch_one(&s.db) + .await + .expect("cancel the flip"); + assert!(cancelled, "the flip's backend was signalled"); + lock.rollback().await.expect("release the index row"); + + // UpdateTable succeeds and reports the index it leaves to the recovery pass. + let returned = update + .await + .expect("the UpdateTable task") + .expect("a passing build failure is not an UpdateTable failure"); + let gsi = returned + .global_secondary_indexes + .unwrap_or_default() + .into_iter() + .find(|g| g.index_name == "gidx") + .expect("gidx in the UpdateTable response"); + assert_eq!( + (gsi.index_status.as_str(), gsi.backfilling), + ("CREATING", Some(true)), + "the UpdateTable response after the failure" + ); + for _ in 0..10 { + assert_eq!( + s.phase().await, + Some(2), + "waiting for the retry, the index is still backfilling" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + + // The pass the server's recovery worker runs every minute. + let engine = s.engine.clone(); + let retry = + tokio::spawn( + async move { extenddb_storage_postgres::reconcile_creating_gsis(&engine).await }, + ); + let deadline = Instant::now() + Duration::from_secs(60); + loop { + match s.phase().await { + Some(3) => break, + Some(2) | None => {} + Some(phase) => panic!("phase {phase} during the retry"), + } + assert!( + Instant::now() < deadline, + "the retry never published the index" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert_eq!( + retry + .await + .expect("the recovery task") + .expect("the recovery pass"), + 1, + "the retry published the index" + ); + + s.cleanup().await; +} diff --git a/crates/storage-postgres/tests/gsi_create_converge.rs b/crates/storage-postgres/tests/gsi_create_converge.rs new file mode 100644 index 000000000..b52071524 --- /dev/null +++ b/crates/storage-postgres/tests/gsi_create_converge.rs @@ -0,0 +1,481 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! Storage-level test for creating a global secondary index while concurrent +//! writers change the base table. +//! +//! `UpdateTable` creates the index, seeds it from the base table, and publishes +//! it. While that runs, four tasks overwrite existing rows (moving the index +//! key), insert new rows, and delete rows. When the index is `ACTIVE` and the +//! propagation queue has drained, the index table must equal the projection of +//! the base table, row for row: no row the backfill copied and a writer then +//! changed may keep its old image, no row a writer moved may leave its old key +//! behind, and a row the scan meets twice must not fail the creation. +//! +//! The scenario runs ten times, with the propagation delay at 5 ms and again at +//! zero. Before the build of an index added by `UpdateTable` waited, took a +//! write barrier, and backfilled under each base row's lock, a write that +//! landed while the scan ran could be dropped or race the scan, and the index +//! was left disagreeing with the base table. +//! +//! Each test builds its own throwaway database, applies the shipped migrations +//! to it, and drops it when it passes. A failing test leaves its database behind +//! on purpose, named `eddb_gsir_*`, so the state that failed can be inspected. +//! +//! 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 the test reports +//! a skip and passes, the same convention the other suites use. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicBool, Ordering}; +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::PgPool; +use sqlx::postgres::PgPoolOptions; + +const ACCOUNT: &str = "123456789012"; +const REGION: &str = "us-east-1"; +/// Base rows seeded before the index is created. +const SEED_ROWS: i64 = 3000; +/// Distinct index-key values among the seeded rows. +const SEED_GROUPS: i64 = 97; + +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(sqlx::AssertSqlSafe(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()) +} + +/// Every `.sql` file under `migrations/` and `data_migrations/`, each directory +/// in filename order, so a new migration is picked up here without editing this +/// file. +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() { + eprintln!( + "SKIP gsi_create_converge: EXTENDDB_TEST_PG_CONNECTION_STRING is not set, so there is \ + no PostgreSQL to build a scratch catalog in." + ); +} + +async fn scratch() -> Scratch { + scratch_with_delay("5").await +} + +/// Build a scratch database and engine with a chosen propagation delay. Delay +/// `"5"` keeps writes on the asynchronous queue; `"0"` makes an ACTIVE index +/// maintain writes inline. +async fn scratch_with_delay(delay_ms: &str) -> Scratch { + let base = base_conn().expect("caller checks base_conn() first"); + let db_name = format!("eddb_gsir_{}", 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(sqlx::AssertSqlSafe(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(8) + .connect(&url) + .await + .expect("connect to the scratch database"); + // One scratch database stands in for both the catalog and the data database, + // so every shipped migration from both directories is applied to it. + for sql in shipped_migrations() { + sqlx::raw_sql(sqlx::AssertSqlSafe(sql)) + .execute(&db) + .await + .expect("apply a shipped migration"); + } + // CreateTable completes inline with no control-plane worker. + 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"); + // The propagation delay the caller chose. A non-zero delay keeps writes on + // the asynchronous queue; zero returns an ACTIVE index to inline maintenance. + sqlx::query( + "INSERT INTO settings (key, value) VALUES ('index_propagation_delay_ms', $1) \ + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value", + ) + .bind(delay_ms) + .execute(&db) + .await + .expect("set the propagation delay"); + 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, + } +} + +fn item_with(pk: &str, g1: &str) -> Item { + BTreeMap::from([ + ("pk".to_owned(), AttributeValue::S(pk.to_owned())), + ("g1".to_owned(), AttributeValue::S(g1.to_owned())), + ("pad".to_owned(), AttributeValue::S("x".repeat(300))), + ]) +} + +fn key_only(pk: &str) -> Item { + BTreeMap::from([("pk".to_owned(), AttributeValue::S(pk.to_owned()))]) +} + +async fn table_id(db: &PgPool, table: &str) -> 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") +} + +async fn gsi_index_id(db: &PgPool, tid: &str) -> String { + sqlx::query_scalar("SELECT index_id FROM indexes WHERE table_id = $1 AND index_name = 'gsi1'") + .bind(tid) + .fetch_one(db) + .await + .expect("look up the index id") +} + +/// `(pk, g1)` of every base row that carries `g1`, sorted. This is the KEYS_ONLY +/// projection the index must hold. +async fn base_projection(db: &PgPool, tid: &str) -> Vec<(String, String)> { + let mut rows: Vec<(String, String)> = sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT item_data->'pk'->>'S', item_data->'g1'->>'S' FROM \"_ddb_{tid}\" \ + WHERE item_data ? 'g1'" + ))) + .fetch_all(db) + .await + .expect("read the base projection"); + rows.sort(); + rows +} + +/// `(pk, g1)` of every index row, sorted. +async fn index_rows(db: &PgPool, iid: &str) -> Vec<(String, String)> { + let mut rows: Vec<(String, String)> = sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT item_data->'pk'->>'S', item_data->'g1'->>'S' FROM \"_ddb_{iid}\"" + ))) + .fetch_all(db) + .await + .expect("read the index rows"); + rows.sort(); + rows +} + +async fn queue_depth(db: &PgPool, tid: &str) -> i64 { + sqlx::query_scalar("SELECT COUNT(*) FROM gsi_pending WHERE table_id = $1") + .bind(tid) + .fetch_one(db) + .await + .expect("count the queued rows") +} + +async fn hold_count(db: &PgPool, tid: &str) -> i64 { + sqlx::query_scalar("SELECT COUNT(*) FROM vector_index_holds WHERE table_id = $1") + .bind(tid) + .fetch_one(db) + .await + .expect("count the holds") +} + +/// One writer: a mix of overwrites that move the index key, inserts of new rows, +/// and deletes, until `stop` is set. It first waits until the index's catalog +/// row is visible, so every write it makes observes the index being created and +/// maintains it through the queue. A write that ran before the catalog row was +/// visible would miss the index through the catalog read window that every write +/// path has, which is a separate matter from the creation race under test. +async fn writer( + engine: &PostgresEngine, + db: &PgPool, + key_info: &TableKeyInfo, + tid: &str, + stop: &AtomicBool, + seed: i64, +) { + let maps = ExpressionMaps::default(); + // Wait for the index's catalog row to appear, or for the creation to end. + while !stop.load(Ordering::Relaxed) && !gsi_visible(db, tid).await { + tokio::time::sleep(Duration::from_millis(1)).await; + } + let mut i = seed; + while !stop.load(Ordering::Relaxed) { + let kind = i % 10; + if kind < 6 { + // Overwrite an existing row with a new index key (a key move). + let pk = format!("k{}", i % SEED_ROWS); + let item = item_with(&pk, &format!("h{}", i % 13)); + let _ = engine + .put_item(key_info, item, false, None, &maps, None) + .await; + } else if kind < 8 { + // Insert a new row, one that the scan may meet, miss, or meet twice. + let pk = format!("ins{seed}_{i}"); + let item = item_with(&pk, &format!("g{}", i % SEED_GROUPS)); + let _ = engine + .put_item(key_info, item, false, None, &maps, None) + .await; + } else { + // Delete an existing row. + let pk = format!("k{}", i % SEED_ROWS); + let _ = engine + .delete_item(key_info, &key_only(&pk), false, None, &maps, None) + .await; + } + i += 1; + } +} + +/// Whether the GSI's catalog row exists yet, whatever its status. +async fn gsi_visible(db: &PgPool, tid: &str) -> bool { + let n: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM indexes WHERE table_id = $1 AND index_name = 'gsi1'", + ) + .bind(tid) + .fetch_one(db) + .await + .unwrap_or(0); + n > 0 +} + +/// Wait until the propagation queue is empty and no hold is held for the table, +/// then settle once more. Returns false on timeout. +async fn wait_for_drain(db: &PgPool, tid: &str) -> bool { + for _ in 0..600 { + if queue_depth(db, tid).await == 0 && hold_count(db, tid).await == 0 { + tokio::time::sleep(Duration::from_millis(50)).await; + if queue_depth(db, tid).await == 0 && hold_count(db, tid).await == 0 { + return true; + } + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + false +} + +async fn run_once(s: &Scratch, iter: usize) -> Result<(), String> { + let table = format!("gsi_race_{iter}"); + s.engine + .create_table( + ACCOUNT, + CreateTableInput { + table_name: table.clone(), + 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 + .map_err(|e| format!("create table: {e}"))?; + let key_info = s + .engine + .table_key_info(ACCOUNT, &table) + .await + .map_err(|e| format!("key info: {e}"))?; + let tid = table_id(&s.db, &table).await; + + // Seed the base table directly, so the setup is one statement rather than + // thousands of writes. No index exists yet, so no maintenance is due. + sqlx::query(sqlx::AssertSqlSafe(format!( + "INSERT INTO \"_ddb_{tid}\" (pk, item_data) \ + SELECT 'k'||g, jsonb_build_object( \ + 'pk', jsonb_build_object('S', 'k'||g), \ + 'g1', jsonb_build_object('S', 'g'||(g % {SEED_GROUPS})), \ + 'pad', jsonb_build_object('S', repeat('x', 300))) \ + FROM generate_series(0, {}) g", + SEED_ROWS - 1 + ))) + .execute(&s.db) + .await + .map_err(|e| format!("seed: {e}"))?; + + let stop = AtomicBool::new(false); + let create_input: UpdateTableInput = serde_json::from_value(serde_json::json!({ + "TableName": table, + "AttributeDefinitions": [{"AttributeName": "g1", "AttributeType": "S"}], + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g1", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "KEYS_ONLY"}, + }}], + })) + .map_err(|e| format!("build the UpdateTable input: {e}"))?; + + let create = async { + let r = s.engine.update_table(ACCOUNT, create_input).await; + stop.store(true, Ordering::Relaxed); + r + }; + let writers = async { + tokio::join!( + writer(&s.engine, &s.db, &key_info, &tid, &stop, 1), + writer(&s.engine, &s.db, &key_info, &tid, &stop, 777), + writer(&s.engine, &s.db, &key_info, &tid, &stop, 1_500), + writer(&s.engine, &s.db, &key_info, &tid, &stop, 2_600), + ) + }; + let (create_result, _) = tokio::join!(create, writers); + create_result.map_err(|e| format!("UpdateTable creating the GSI failed: {e}"))?; + + if !wait_for_drain(&s.db, &tid).await { + return Err(format!( + "propagation did not drain: queue={}, holds={}", + queue_depth(&s.db, &tid).await, + hold_count(&s.db, &tid).await + )); + } + + let iid = gsi_index_id(&s.db, &tid).await; + let base = base_projection(&s.db, &tid).await; + let index = index_rows(&s.db, &iid).await; + + if base != index { + use std::collections::BTreeSet; + let b: BTreeSet<_> = base.iter().cloned().collect(); + let i: BTreeSet<_> = index.iter().cloned().collect(); + let missing = b.difference(&i).count(); + let stale = i.difference(&b).count(); + return Err(format!( + "index does not equal the base projection: base={}, index={}, missing from index={}, \ + stale in index={}", + base.len(), + index.len(), + missing, + stale + )); + } + eprintln!( + "iteration {iter}: base={} index={} equal", + base.len(), + index.len() + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn gsi_creation_converges_under_concurrent_writers() { + if base_conn().is_none() { + return skip(); + } + let s = scratch().await; + for iter in 0..10 { + if let Err(e) = run_once(&s, iter).await { + panic!("iteration {iter}: {e}"); + } + } + s.cleanup().await; +} + +/// The same race with the propagation delay pinned to zero, so an ACTIVE index +/// maintains writes inline rather than through the queue. Rows queued while the +/// index was building must not drain after an inline write and put back an +/// older image, so the index must still equal the base projection. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn gsi_creation_converges_under_concurrent_writers_zero_delay() { + if base_conn().is_none() { + return skip(); + } + let s = scratch_with_delay("0").await; + for iter in 0..10 { + if let Err(e) = run_once(&s, iter).await { + panic!("iteration {iter}: {e}"); + } + } + s.cleanup().await; +} diff --git a/crates/storage-sqlite/src/create_table.rs b/crates/storage-sqlite/src/create_table.rs index 2939495b5..0fda47cd6 100644 --- a/crates/storage-sqlite/src/create_table.rs +++ b/crates/storage-sqlite/src/create_table.rs @@ -686,6 +686,7 @@ impl SqliteEngine { key_schema: g.key_schema.clone(), projection: g.projection.clone(), index_status: "ACTIVE".to_owned(), + backfilling: None, provisioned_throughput: Some(ProvisionedThroughputDescription { read_capacity_units: g .provisioned_throughput diff --git a/crates/storage-sqlite/src/data/ddl.rs b/crates/storage-sqlite/src/data/ddl.rs index 4c0bcf570..50d81de9d 100644 --- a/crates/storage-sqlite/src/data/ddl.rs +++ b/crates/storage-sqlite/src/data/ddl.rs @@ -534,13 +534,14 @@ impl SqliteEngine { index_name: &str, ) -> Result { // A GSI still being built is not readable: its table is partial, or not - // there yet (a Query hit it with a 500 on main). The service answers a - // Query or Scan naming one with "The table does not have the specified - // index", the same as for no index at all, which is what `IndexNotFound` - // becomes on the wire. - let row: Option<(String, String, String, String)> = sqlx::query_as( - "SELECT index_type, index_id, key_schema, projection \ - FROM indexes WHERE table_id = ? AND index_name = ? AND index_status <> 'CREATING'", + // there yet (a Query hit it with a 500 on main). The service refuses a + // Query or Scan naming one in two ways, by phase; see + // `extenddb_storage::gsi_backfill`. The backfill set is read before the + // row; see `GsiBackfills::snapshot`. + let started = self.gsi_backfills.snapshot(); + let row: Option<(String, String, String, String, String)> = sqlx::query_as( + "SELECT index_type, index_id, key_schema, projection, index_status \ + FROM indexes WHERE table_id = ? AND index_name = ?", ) .bind(table_id) .bind(index_name) @@ -548,8 +549,14 @@ impl SqliteEngine { .await .map_err(|e| StorageError::Internal(e.to_string()))?; - let (idx_type_str, index_id, ks_str, proj_str) = + let (idx_type_str, index_id, ks_str, proj_str, status) = row.ok_or_else(|| StorageError::IndexNotFound(index_name.to_owned()))?; + if status == "CREATING" { + return Err(extenddb_storage::gsi_backfill::creating_read_refusal( + index_name, + started.contains(&index_id), + )); + } let index_type = match idx_type_str.as_str() { "GSI" => IndexType::Gsi, diff --git a/crates/storage-sqlite/src/delete_table.rs b/crates/storage-sqlite/src/delete_table.rs index 5b783789b..d7193fe49 100644 --- a/crates/storage-sqlite/src/delete_table.rs +++ b/crates/storage-sqlite/src/delete_table.rs @@ -70,6 +70,8 @@ impl SqliteEngine { } } + // After the backfill set; see `GsiBackfills::snapshot`. + let started = self.gsi_backfills.snapshot(); let index_rows: Vec = sqlx::query_as(sqlx::AssertSqlSafe(format!( "SELECT {INDEX_COLUMNS} FROM indexes WHERE table_id = ?" ))) @@ -166,7 +168,7 @@ impl SqliteEngine { self.control_plane_notify.notify_one(); } - let desc = self.build_table_description_from_row(account_id, row, index_rows)?; + let desc = self.build_table_description_from_row(account_id, row, index_rows, &started)?; Ok(TableDescription { table_status: TableStatus::Deleting, ..desc diff --git a/crates/storage-sqlite/src/gsi_backfilling_tests.rs b/crates/storage-sqlite/src/gsi_backfilling_tests.rs new file mode 100644 index 000000000..bb6c803b1 --- /dev/null +++ b/crates/storage-sqlite/src/gsi_backfilling_tests.rs @@ -0,0 +1,172 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! A GSI added by `UpdateTable` walks the service's two `CREATING` phases. +//! +//! Measured 2026-10-26 (see `extenddb_storage::gsi_backfill`): `Backfilling` +//! is `false` and a read is told the table has no such index until the +//! backfill starts, then `true` with the backfilling sentence until the index +//! is `ACTIVE`, when the member is gone and reads are served. The table's +//! `gsi_creating_phase_delay_ms` hold lengthens both phases so the walk is +//! observable on a three-item table. + +use std::time::{Duration, Instant}; + +use extenddb_core::expression::ExpressionMaps; +use extenddb_core::types::{AttributeValue, DescribeTableInput}; +use extenddb_storage::error::StorageError; +use extenddb_storage::{DataEngine, TableEngine}; +use serde_json::json; + +use crate::SqliteEngine; + +const ACCOUNT: &str = "000000000000"; +const BACKFILLING: &str = "Cannot read from backfilling global secondary index: gidx"; + +/// What DescribeTable says about `gidx`: its status and its serialised +/// `Backfilling` member, or `None` before the catalog row is visible. +async fn gsi_state(engine: &SqliteEngine) -> Option<(String, Option)> { + let desc = engine + .describe_table( + ACCOUNT, + DescribeTableInput { + table_name: "t".to_owned(), + }, + ) + .await + .expect("describe the table"); + let gsi = desc + .global_secondary_indexes? + .into_iter() + .find(|g| g.index_name == "gidx")?; + let wire = serde_json::to_value(&gsi).expect("serialise the GSI description"); + Some((gsi.index_status, wire.get("Backfilling").cloned())) +} + +#[tokio::test] +async fn a_gsi_added_by_update_table_walks_both_creating_phases() { + let engine = SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) + .await + .expect("engine"); + crate::migrations::apply_for_tests(&engine.pool).await; + // Zero control-plane delay: the table is ACTIVE at create time, since no + // transition poller runs inside a unit test. The migrations write no + // settings row for the delay, so the row is inserted here. + sqlx::query( + "INSERT OR REPLACE INTO settings (key, value) VALUES ('control_plane_delay_seconds', '0')", + ) + .execute(&engine.pool) + .await + .expect("delay"); + sqlx::query("INSERT INTO accounts (account_id, account_name) VALUES (?, 'default')") + .bind(ACCOUNT) + .execute(&engine.pool) + .await + .expect("account"); + let input: extenddb_core::types::CreateTableInput = serde_json::from_value(json!({ + "TableName": "t", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "BillingMode": "PAY_PER_REQUEST" + })) + .expect("input"); + engine + .create_table_impl(ACCOUNT, input, false) + .await + .expect("create table"); + sqlx::query("UPDATE tables SET table_status = 'ACTIVE' WHERE table_name = 't'") + .execute(&engine.pool) + .await + .expect("activate the table"); + let key_info = engine.table_key_info(ACCOUNT, "t").await.expect("key info"); + for n in 0..3 { + let item = std::collections::BTreeMap::from([ + ("pk".to_owned(), AttributeValue::S(format!("p{n}"))), + ("g".to_owned(), AttributeValue::S("v".to_owned())), + ]); + engine + .put_item( + &key_info, + item, + false, + None, + &ExpressionMaps::default(), + None, + ) + .await + .expect("put"); + } + sqlx::query("INSERT INTO settings (key, value) VALUES (?, '1000')") + .bind(extenddb_core::settings_keys::gsi_creating_phase_delay_key( + "t", + )) + .execute(&engine.pool) + .await + .expect("set the phase hold"); + + // UpdateTable returns once the index is ACTIVE on this backend, so it runs + // in its own task while this one watches DescribeTable. + let update: extenddb_core::types::UpdateTableInput = serde_json::from_value(json!({ + "TableName": "t", + "AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}], + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gidx", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"} + }}] + })) + .expect("update input"); + let updater = engine.clone(); + let task = tokio::spawn(async move { updater.update_table_impl(ACCOUNT, update).await }); + + // Phases seen, in order: 1 is Backfilling false, 2 is true, 3 is ACTIVE. + // A reading counts only when DescribeTable agrees before and after the + // read, so a phase change between the two calls cannot pair one phase's + // description with the other's refusal. + let mut seen: Vec = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(30); + while seen.last() != Some(&3) { + assert!(Instant::now() < deadline, "no ACTIVE state; seen {seen:?}"); + let before = gsi_state(&engine).await; + let read = engine + .index_info_by_table_id(&key_info.table_id, "gidx") + .await; + if before.is_none() || gsi_state(&engine).await != before { + tokio::time::sleep(Duration::from_millis(20)).await; + continue; + } + let phase = match before.expect("checked above") { + (status, Some(serde_json::Value::Bool(false))) if status == "CREATING" => { + assert!( + matches!(read, Err(StorageError::IndexNotFound(ref n)) if n == "gidx"), + "before the backfill a read is told there is no such index: {read:?}" + ); + 1 + } + (status, Some(serde_json::Value::Bool(true))) if status == "CREATING" => { + assert!( + matches!(read, Err(StorageError::Validation(ref m)) if m == BACKFILLING), + "during the backfill a read gets the backfilling sentence: {read:?}" + ); + 2 + } + (status, None) if status == "ACTIVE" => { + read.expect("an ACTIVE index resolves"); + 3 + } + other => panic!("a state the service does not report: {other:?}"), + }; + if seen.last() != Some(&phase) { + assert!( + seen.last().is_none_or(|&last| last < phase), + "phase {phase} after {seen:?}" + ); + seen.push(phase); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert_eq!(seen, vec![1, 2, 3], "each phase is observed, in order"); + task.await + .expect("the UpdateTable task") + .expect("UpdateTable succeeds"); +} diff --git a/crates/storage-sqlite/src/lib.rs b/crates/storage-sqlite/src/lib.rs index 8a3241b05..50dfe7780 100644 --- a/crates/storage-sqlite/src/lib.rs +++ b/crates/storage-sqlite/src/lib.rs @@ -172,6 +172,8 @@ mod create_table; mod credential_store; mod data; mod delete_table; +#[cfg(test)] +mod gsi_backfilling_tests; // `ServerRuntimeHooks`: the server's background workers, not run on wasm32. #[cfg(not(target_arch = "wasm32"))] mod hooks; diff --git a/crates/storage-sqlite/src/store.rs b/crates/storage-sqlite/src/store.rs index 512fa5e2f..955e13941 100644 --- a/crates/storage-sqlite/src/store.rs +++ b/crates/storage-sqlite/src/store.rs @@ -86,6 +86,10 @@ pub struct SqliteEngine { /// no entry, because nothing else ever will until a restart, and until then /// the per-table queue hold blocks every write's index maintenance. pub(crate) vector_builds_running: Arc>>, + /// GSI builds whose backfill has started, which is what DescribeTable + /// reports as `Backfilling` and what decides a Query or Scan refusal for a + /// `CREATING` GSI; see `extenddb_storage::gsi_backfill`. + pub(crate) gsi_backfills: extenddb_storage::gsi_backfill::GsiBackfills, /// The `extenddb serve` lock on the database file, held for as long as any /// clone of the engine lives. `None` outside `serve` and for in-memory /// databases. @@ -234,6 +238,7 @@ impl SqliteEngine { vector_builds_running: Arc::new( std::sync::Mutex::new(std::collections::HashSet::new()), ), + gsi_backfills: extenddb_storage::gsi_backfill::GsiBackfills::default(), serve_lock: None, backup_server_slot_count, backup_server_slots: Arc::new(tokio::sync::Semaphore::new(backup_server_slot_count)), @@ -455,6 +460,22 @@ impl SqliteEngine { } } + /// The `gsi_creating_phase_delay_ms` test hold for one table; zero when unset. + pub(crate) async fn gsi_creating_phase_delay(&self, table_name: &str) -> std::time::Duration { + let live: Result, _> = + sqlx::query_as("SELECT value FROM settings WHERE key = ?") + .bind(extenddb_core::settings_keys::gsi_creating_phase_delay_key( + table_name, + )) + .fetch_optional(&self.pool) + .await; + let value = live.unwrap_or_else(|e| { + tracing::debug!("gsi_creating_phase_delay: live read failed, using 0: {e:?}"); + None + }); + extenddb_storage::gsi_backfill::phase_delay(value.as_ref().map(|(v,)| v.as_str())) + } + /// Handle to the GSI propagation notifier, woken after an enqueue. pub(crate) fn gsi_notify(&self) -> Arc { Arc::clone(&self.gsi_notify) diff --git a/crates/storage-sqlite/src/table_helpers.rs b/crates/storage-sqlite/src/table_helpers.rs index 133748546..b647a62e1 100644 --- a/crates/storage-sqlite/src/table_helpers.rs +++ b/crates/storage-sqlite/src/table_helpers.rs @@ -46,7 +46,6 @@ sqlite_row_struct! { /// Catalog `indexes` row. pub(crate) struct IndexRow { pub index_name: String, - #[allow(dead_code)] pub index_id: String, pub index_type: String, pub key_schema: String, @@ -163,6 +162,8 @@ impl SqliteEngine { account_id: &str, table_name: &str, ) -> Result { + // Before the catalog rows; see `GsiBackfills::snapshot`. + let started = self.gsi_backfills.snapshot(); let row: Option = sqlx::query_as(sqlx::AssertSqlSafe(format!( "SELECT {TABLE_COLUMNS} FROM tables WHERE account_id = ? AND table_name = ?" ))) @@ -192,7 +193,8 @@ impl SqliteEngine { let table_name_owned = row.table_name.clone(); let table_id = row.table_id.clone(); - let mut desc = self.build_table_description_from_row(account_id, row, index_rows)?; + let mut desc = + self.build_table_description_from_row(account_id, row, index_rows, &started)?; desc.restore_summary = Self::restore_summary_on(conn, &table_id, &desc.table_status).await?; let catalog_rows = vector_rows @@ -204,11 +206,16 @@ impl SqliteEngine { Ok(desc) } + /// `started` is a [`GsiBackfills::snapshot`] the caller took before it read + /// `index_rows`. + /// + /// [`GsiBackfills::snapshot`]: extenddb_storage::gsi_backfill::GsiBackfills::snapshot pub(crate) fn build_table_description_from_row( &self, account_id: &str, row: TableRow, index_rows: Vec, + started: &std::collections::HashSet, ) -> Result { let mut gsis: Vec = Vec::new(); let mut lsis: Vec = Vec::new(); @@ -226,6 +233,10 @@ impl SqliteEngine { index_name: idx.index_name.clone(), key_schema: ks, projection: proj, + backfilling: extenddb_storage::gsi_backfill::backfilling_member( + &idx.index_status, + started.contains(&idx.index_id), + ), index_status: idx.index_status, provisioned_throughput: pt.or(Some(zero_throughput())), index_size_bytes: 0, diff --git a/crates/storage-sqlite/src/update_table.rs b/crates/storage-sqlite/src/update_table.rs index 2b1df06d7..11adae6b1 100644 --- a/crates/storage-sqlite/src/update_table.rs +++ b/crates/storage-sqlite/src/update_table.rs @@ -81,6 +81,20 @@ async fn ensure_index_name_free( Ok(()) } +/// Wait out one phase of the `gsi_creating_phase_delay_ms` test hold. A zero +/// hold, the value when the setting is unset, returns at once. +#[allow( + clippy::disallowed_methods, + reason = "only the server's settings API, the settings command and tests write the hold's \ + row, and the browser build has none of them, so on wasm32 the hold is zero and \ + this sleep never runs" +)] +async fn wait_creating_phase_hold(hold: std::time::Duration) { + if !hold.is_zero() { + tokio::time::sleep(hold).await; + } +} + impl SqliteEngine { pub(crate) async fn update_table_impl( &self, @@ -721,6 +735,18 @@ impl SqliteEngine { if let Some(create) = &update.create { let idx_id = created[ci].clone(); ci += 1; + // The row committed above as CREATING reports `Backfilling: + // false` until the record below is taken, and `true` from then + // until the flip to ACTIVE. The test hold lengthens each phase; + // it runs under the engine write lock, so it also delays every + // other write in this process while it lasts. + let hold = self.gsi_creating_phase_delay(&input.table_name).await; + wait_creating_phase_hold(hold).await; + // The record ends with this block. A build that fails below + // deletes its row. If that DELETE fails, or the flip to ACTIVE + // fails, the row stays CREATING with no record and reports the + // first phase until the startup reconciler rebuilds it. + let _backfilling = self.gsi_backfills.start_scoped(&idx_id); let result = async { let mut data_tx = self .pool @@ -769,6 +795,10 @@ impl SqliteEngine { .await; return Err(e); } + // The second hold sits between the build's commit and the flip, + // as on PostgreSQL, so a record that ended before the flip would + // show as the first phase while it lasts. + wait_creating_phase_hold(hold).await; // Backfill succeeded and the data table is populated, so the // index is now queryable: flip CREATING -> ACTIVE. DescribeTable // reports CREATING until this point (matching DynamoDB), so a diff --git a/crates/storage/src/gsi_backfill.rs b/crates/storage/src/gsi_backfill.rs new file mode 100644 index 000000000..1936c4232 --- /dev/null +++ b/crates/storage/src/gsi_backfill.rs @@ -0,0 +1,227 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The two `CREATING` phases of a GSI that `UpdateTable` adds. +//! +//! Measured against the service on 2026-10-26 (us-east-1) with a GSI added to +//! a 3000-item table, which became `ACTIVE` after 512 s and 519 s on two runs: +//! +//! | `IndexStatus` | `Backfilling` | Query or Scan naming the index | +//! |---|---|---| +//! | `CREATING` | `false` | `The table does not have the specified index: ` | +//! | `CREATING` | `true` | `Cannot read from backfilling global secondary index: ` | +//! | `ACTIVE` | absent | served | +//! +//! Both refusals are `ValidationException`. The first phase lasted about 30 s. +//! +//! Each backend decides from its own build state whether the backfill has +//! started and passes that one answer to [`backfilling_member`] for +//! DescribeTable and to [`creating_read_refusal`] for Query and Scan, so the +//! description and the refusal cannot disagree. + +use std::collections::HashSet; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use extenddb_core::types::VECTOR_INDEX_BACKFILLING_SCAN_PREFIX; + +use crate::error::StorageError; + +/// The `Backfilling` member of a GSI whose status is `index_status`: present +/// only while the index is `CREATING`, and then `true` once its backfill has +/// started. +#[must_use] +pub fn backfilling_member(index_status: &str, backfill_started: bool) -> Option { + (index_status == "CREATING").then_some(backfill_started) +} + +/// The refusal for a Query or Scan naming a `CREATING` GSI. +/// +/// Before the backfill starts it is `IndexNotFound`, which the engine reports +/// as "The table does not have the specified index", the same answer as for a +/// name that matches no index. After, it is the backfilling sentence, which the +/// engine passes through verbatim as a `ValidationException`. +#[must_use] +pub fn creating_read_refusal(index_name: &str, backfill_started: bool) -> StorageError { + if backfill_started { + StorageError::Validation(format!( + "{VECTOR_INDEX_BACKFILLING_SCAN_PREFIX}{index_name}" + )) + } else { + StorageError::IndexNotFound(index_name.to_owned()) + } +} + +/// Whether `err` is the refusal [`creating_read_refusal`] gives once the +/// backfill has started. +#[must_use] +pub fn is_backfilling_refusal(err: &StorageError) -> bool { + matches!(err, StorageError::Validation(message) + if message.starts_with(VECTOR_INDEX_BACKFILLING_SCAN_PREFIX)) +} + +/// The hold a `gsi_creating_phase_delay_ms:
` setting asks for, from its +/// stored value. Absent or unreadable means no hold. +#[must_use] +pub fn phase_delay(value: Option<&str>) -> Duration { + Duration::from_millis( + value + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0), + ) +} + +/// GSI builds in this process whose backfill has started, by index id. +/// +/// For a backend whose build runs inside the server process and records no +/// progress in its catalog (PostgreSQL and SQLite). One process serves a +/// catalog, which is the supported deployment, so the process running a build +/// is also the one answering DescribeTable for it. +/// +/// An id stays in the set until its index leaves `CREATING`: a build removes it +/// once it has published the index, found it deleted, or removed it after a +/// failure that would recur. A build that fails for a passing reason leaves it, +/// so the index keeps reporting `Backfilling: true` and the backfilling refusal +/// while it waits for the retry, which records it again; the service is not +/// known to go back to the first phase. Index ids are not reused, so an id left +/// behind by an index that another path deleted is never read again. Clones +/// share the set. +#[derive(Clone, Debug, Default)] +pub struct GsiBackfills(Arc>>); + +impl GsiBackfills { + /// Record that a backfill of `index_id` has started. The record stays + /// until [`Self::finish`] removes it. + pub fn start(&self, index_id: &str) { + self.lock().insert(index_id.to_owned()); + } + + /// Remove the record of `index_id`, once its index has left `CREATING`. + pub fn finish(&self, index_id: &str) { + self.lock().remove(index_id); + } + + /// [`Self::start`], and [`Self::finish`] when the returned guard drops, for + /// a build that deletes its index in the same call whenever it fails. + #[must_use] + pub fn start_scoped(&self, index_id: &str) -> BackfillGuard { + self.start(index_id); + BackfillGuard { + set: self.clone(), + index_id: index_id.to_owned(), + } + } + + /// The ids recorded now, for a reader to take before it reads the catalog + /// rows it pairs them with. + /// + /// A build removes an id only after the index's row has left `CREATING`, + /// so a set read first can be paired only with the same row or a newer + /// one. A `CREATING` row is then reported with a set that still holds its + /// id, and the answer never goes back to the first phase. Read the other + /// way round, a call could read the row as `CREATING` just before the flip + /// and the set just after the id was removed, and report the first phase + /// for an index whose backfill had finished. + /// + /// SQLite has two exceptions, both after a failure. Its record lasts as + /// long as the build inside UpdateTable, so when the flip to `ACTIVE` + /// fails, or the cleanup `DELETE` after a failed build fails, the id is + /// removed while the row stays `CREATING`, and the index reports the first + /// phase until the startup reconciler rebuilds it. + #[must_use] + pub fn snapshot(&self) -> HashSet { + self.lock().clone() + } + + fn lock(&self) -> MutexGuard<'_, HashSet> { + // A panic while the lock was held leaves a set that is still usable, so + // a poisoned lock is taken as it is. + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +/// Removes one backfill record from [`GsiBackfills`] when dropped. +#[derive(Debug)] +pub struct BackfillGuard { + set: GsiBackfills, + index_id: String, +} + +impl Drop for BackfillGuard { + fn drop(&mut self) { + self.set.finish(&self.index_id); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_member_is_present_only_while_creating() { + assert_eq!(backfilling_member("CREATING", false), Some(false)); + assert_eq!(backfilling_member("CREATING", true), Some(true)); + assert_eq!(backfilling_member("ACTIVE", true), None); + assert_eq!(backfilling_member("ACTIVE", false), None); + assert_eq!(backfilling_member("DELETING", true), None); + } + + #[test] + fn the_refusal_follows_the_phase_byte_for_byte() { + match creating_read_refusal("gsi_slow", false) { + StorageError::IndexNotFound(name) => assert_eq!(name, "gsi_slow"), + other => panic!("first phase: {other:?}"), + } + match creating_read_refusal("gsi_slow", true) { + StorageError::Validation(msg) => assert_eq!( + msg, + "Cannot read from backfilling global secondary index: gsi_slow" + ), + other => panic!("second phase: {other:?}"), + } + } + + #[test] + fn a_record_lasts_until_finish() { + let running = GsiBackfills::default(); + assert!(!running.snapshot().contains("i1")); + running.start("i1"); + assert!(running.clone().snapshot().contains("i1")); + assert!(!running.snapshot().contains("i2")); + // A second build of the same index (the retry after a passing failure) + // records it again; one finish ends it, because finish is called only + // once the index has left CREATING. + running.start("i1"); + running.finish("i1"); + assert!(!running.snapshot().contains("i1")); + } + + #[test] + fn a_scoped_record_lasts_as_long_as_its_guard() { + let running = GsiBackfills::default(); + let guard = running.start_scoped("i1"); + assert!(running.snapshot().contains("i1")); + drop(guard); + assert!(!running.snapshot().contains("i1")); + } + + #[test] + fn a_snapshot_keeps_the_ids_recorded_when_it_was_taken() { + let running = GsiBackfills::default(); + running.start("i1"); + let before = running.snapshot(); + running.finish("i1"); + running.start("i2"); + assert!(before.contains("i1")); + assert!(!before.contains("i2")); + assert!(!running.snapshot().contains("i1")); + } + + #[test] + fn an_absent_or_unreadable_delay_holds_nothing() { + assert_eq!(phase_delay(None), Duration::ZERO); + assert_eq!(phase_delay(Some("not a number")), Duration::ZERO); + assert_eq!(phase_delay(Some("0")), Duration::ZERO); + assert_eq!(phase_delay(Some(" 2500 ")), Duration::from_millis(2500)); + } +} diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 002d8fcc0..9f3d93207 100755 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -16,6 +16,7 @@ pub mod config; pub mod diagnostics; pub mod diagnostics_store; pub mod error; +pub mod gsi_backfill; pub mod hooks; #[doc(hidden)] #[cfg(feature = "test-util")] diff --git a/devtools/run-mongodb-tests b/devtools/run-mongodb-tests index ff13c01c6..f768bbc77 100755 --- a/devtools/run-mongodb-tests +++ b/devtools/run-mongodb-tests @@ -350,13 +350,14 @@ echo "" if [[ " ${RUN_TESTS_ARGS[*]} " == *" --rust "* \ || " ${RUN_TESTS_ARGS[*]} " == *" --rust-integration "* ]]; then # The storage-level MongoDB tests that need a live server (the stream - # records page over 16 MB and the shard ownership predicates) are - # #[ignore]d in the crate and read their server from this variable; this - # container is the one place in CI that has one. - echo "=== Running MongoDB storage-level live tests (records_live) ===" + # records page over 16 MB, the shard ownership predicates, and the phases + # of a GSI that UpdateTable adds) are #[ignore]d in the crate and read + # their server from this variable; this container is the one place in CI + # that has one. + echo "=== Running MongoDB storage-level live tests (records_live, live_gsi_) ===" echo "" EXTENDDB_TEST_MONGODB_URI="mongodb://localhost:$MONGO_PORT/?replicaSet=rs0&directConnection=true" \ - cargo test -p extenddb-storage-mongodb --lib -- --ignored records_live + cargo test -p extenddb-storage-mongodb --lib -- --ignored records_live live_gsi_ echo "" # Every test target of the crate, its unit tests and each file under # tests/, so a new test file runs here without an edit. The tests that diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index 214040065..731606e99 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -329,6 +329,7 @@ Managed via `extenddb settings set`. Changes take effect within 30 seconds witho | `search_inequality_filters` | every account | The accounts whose `SearchVectors` requests accept the extended `SearchConditionExpression` grammar, which DynamoDB accepts on the accounts and regions measured (us-east-1, eu-north-1, ap-southeast-2): `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. A malformed value in the catalog, which the CLI and the management API refuse to write, is no account. With `off`, or for an account the list does not name, a search condition is an AND of equalities. A server reads the setting only for a search whose answer depends on the grammar, and at most once a second, so a change applies within about a second without a restart. When a read fails or does not end within two seconds, the server uses the value of its last read that answered; before any read has answered, such a search answers `ServiceUnavailable` (HTTP 503). The [upgrade manual](07-upgrade-manual.md) says which searches read it | | `vector_backfill_batch_delay_ms` | `0` | **Test-oriented.** Milliseconds to pause between batches while a vector index backfills. Zero in production. A test sets it so a write is guaranteed to land while the index is still building. The pause is outside the batch transaction, so writes are still accepted throughout, but it does extend the per-table propagation hold: no index on that table advances while the build runs, GSIs included, and the accepted range goes up to 60 s per batch. | | `vector_allocation_phase_delay_ms` | `0` | **Test-oriented.** Milliseconds to hold a new vector index in the resource-allocation phase (`CREATING` with `Backfilling: false`) before the scan starts. Zero in production. Without it the phase lasts only from the `UpdateTable` transaction, which inserts the row as `CREATING` with `Backfilling: false`, until the detached build task flips the flag, which is a window no client can time reliably rather than one that cannot exist. | +| `gsi_creating_phase_delay_ms:
` | unset | **Test-oriented.** Milliseconds, 0 to 60000, by which a GSI that `UpdateTable` adds to `
` lengthens each of its two `CREATING` phases: before its backfill starts (`Backfilling: false`, reads told the index does not exist) and after (`Backfilling: true`, reads refused as backfilling). Unset in production. On SQLite the hold runs under the engine write lock, so every write to the database waits for it; on MongoDB and Cassandra it also delays the other index builds the worker has queued. The row stays in the catalog after a test sets it back to `0`. | ```bash # View all settings diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 7d8775966..067cde1c5 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -431,6 +431,12 @@ deployment, even when no catalog migration is required. **Who is affected.** A client that pages a parallel Scan of a SQLite deployment across the upgrade. The start keys that 1.1.0 returned follow the old rule. ExtendDB can refuse such a key as a key from another segment. When ExtendDB accepts it, the later pages follow the new rule, so the client can miss items or get items twice. Start such a Scan again after the upgrade. A Scan that pages across a rollback to 1.1.0 can get the same answers. PostgreSQL, MongoDB and Cassandra are not affected. No catalog migration or configuration change is required. +### v1.2.0: a GSI that `UpdateTable` adds reports `Backfilling` and refuses reads in both `CREATING` phases + +**What changed** (#454). While a GSI that `UpdateTable` added is `CREATING`, `DescribeTable` lists `Backfilling` on it: `false` before its backfill starts and `true` after. On MongoDB and Cassandra, a Query, Scan or PartiQL `SELECT` that names such an index now gets `ValidationException`. 1.1.0 served the part of the index that the build had written. On PostgreSQL and SQLite, the refusal changes once the backfill has started. 1.1.0 answered `The table does not have the specified index: `, and the answer is now `Cannot read from backfilling global secondary index: `. In a `BatchExecuteStatement`, a read of such an index gets the refusal as the error of that statement, and the other statements run. + +**Who is affected.** A client that reads a GSI before its `IndexStatus` is `ACTIVE` gets the refusal. Wait for `ACTIVE` before reading the index. A client that compares the description of a `CREATING` GSI member by member finds `Backfilling` added. No catalog migration or configuration change is required. + ### v1.1.0: latency `segments` are summed into time buckets **What changed** (#398). The latency `segments` that `/metrics` and the console's `/console/metrics-data` return come from time buckets per account and operation. 1.0.0 kept one record per request for 24 hours. Each operation's count and means are still exact over the requests that the window covers. Four things change: diff --git a/tests/python/test_gsi_backfilling.py b/tests/python/test_gsi_backfilling.py new file mode 100644 index 000000000..f7c5909e2 --- /dev/null +++ b/tests/python/test_gsi_backfilling.py @@ -0,0 +1,208 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""A GSI added by UpdateTable walks the two CREATING phases the service reports. + +Measured against Amazon DynamoDB on 2026-10-26 (us-east-1, a 3000-item table, +two runs) with whole strings, both refusals ValidationException: + +- CREATING, ``Backfilling: false``: Query and Scan on the index answer + ``The table does not have the specified index: gsi_slow`` +- CREATING, ``Backfilling: true``: both answer + ``Cannot read from backfilling global secondary index: gsi_slow`` +- ACTIVE: ``Backfilling`` is absent and both are served + +The CREATING description carries exactly the members in ``CREATING_MEMBERS``. + +ExecuteStatement naming the index is sent in each phase as well. Its answers +are ExtendDB's, derived from the same index lookup as Query and Scan: in the +first phase the PartiQL text for an index the table does not have, which +carries no index name, in the second the backfilling sentence. A +BatchExecuteStatement of a read of the index and a read of a base item gets +the same refusal for the first statement and the item for the second. Once +the index is ACTIVE, the first statement gets the refusal of a batch read +without the full primary key. The service's answer to a PartiQL read of a +CREATING index is not measured. + +On the service the first phase lasted about 30 s and the second about 480 s. +ExtendDB builds a three-item index in milliseconds, so the test sets the +``gsi_creating_phase_delay_ms:
`` hold, which lengthens both phases, and +is therefore ExtendDB-only. Setting it needs the admin credentials that +``devtools/run-tests`` exports. +""" + +from __future__ import annotations + +import os +import threading +import time + +import botocore.exceptions +import pytest +import requests + +from helpers import make_dynamodb_client + +GSI = "gsi_slow" +NOT_FOUND = f"The table does not have the specified index: {GSI}" +NOT_FOUND_STATEMENT = "The table does not have the specified index" +BATCH_KEY_REQUIRED = ( + "Select statements within BatchExecuteStatement must specify the primary key in the " + "where clause." +) +BACKFILLING = f"Cannot read from backfilling global secondary index: {GSI}" +CREATING_MEMBERS = { + "Backfilling", + "IndexArn", + "IndexName", + "IndexSizeBytes", + "IndexStatus", + "ItemCount", + "KeySchema", + "Projection", + "ProvisionedThroughput", +} +HOLD_MS = 2000 +ABSENT = "absent" + +_extenddb_only = pytest.mark.skipif( + os.environ.get("EXTENDDB_VALIDATION_MODE", "").lower() == "true", + reason="extenddb_only: skipped in validation mode", +) + + +def _set_hold(endpoint: str, table: str, ms: int) -> None: + password = os.environ.get("EXTENDDB_ADMIN_PASSWORD", "").strip() + if not password: + pytest.fail("EXTENDDB_ADMIN_PASSWORD is required to set the GSI phase hold") + user = os.environ.get("EXTENDDB_ADMIN_USER", "admin") + ca_cert = os.environ.get("EXTENDDB_CA_CERT", "") + response = requests.put( + f"{endpoint.rstrip('/')}/management/settings/gsi_creating_phase_delay_ms:{table}", + auth=(user, password), + json={"value": str(ms)}, + timeout=30, + verify=ca_cert if ca_cert else False, + ) + assert response.ok, f"setting the phase hold failed: {response.status_code} {response.text}" + + +def _outcome(call, **kwargs): + """``("OK", count)`` for a served read, ``(code, message)`` for a refusal.""" + try: + response = call(**kwargs) + return ("OK", response["Count"] if "Count" in response else len(response["Items"])) + except botocore.exceptions.ClientError as e: + return (e.response["Error"]["Code"], e.response["Error"]["Message"]) + + +def _batch(client, table: str): + """Each answer of a BatchExecuteStatement of a read of the index and a + read of the item ``p0``: ``(code, message)`` or ``("ITEM", pk)``.""" + responses = client.batch_execute_statement(Statements=[ + {"Statement": f"SELECT * FROM \"{table}\".\"{GSI}\" WHERE g = 'v'"}, + {"Statement": f"SELECT * FROM \"{table}\" WHERE pk = 'p0'"}, + ])["Responses"] + return [ + (r["Error"]["Code"], r["Error"]["Message"]) if "Error" in r + else ("ITEM", r["Item"]["pk"]["S"]) + for r in responses + ] + + +def _gsi(client, table: str): + gsis = client.describe_table(TableName=table)["Table"].get("GlobalSecondaryIndexes", []) + return next((g for g in gsis if g["IndexName"] == GSI), None) + + +@_extenddb_only +def test_added_gsi_reports_backfilling_and_refuses_reads_by_phase( + dynamodb_client, endpoint_url, table_factory +): + if endpoint_url is None: + pytest.skip("the phase hold is an ExtendDB setting") + table = table_factory() + for n in range(3): + dynamodb_client.put_item( + TableName=table, Item={"pk": {"S": f"p{n}"}, "g": {"S": "v"}} + ) + _set_hold(endpoint_url, table, HOLD_MS) + + # UpdateTable answers only once the index is ACTIVE on some backends, so it + # runs on its own client in a thread while this one watches the phases. + failures: list[Exception] = [] + + def add_gsi() -> None: + try: + make_dynamodb_client(endpoint_url).update_table( + TableName=table, + AttributeDefinitions=[{"AttributeName": "g", "AttributeType": "S"}], + GlobalSecondaryIndexUpdates=[{"Create": { + "IndexName": GSI, + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + }}], + ) + except Exception as e: # reported after the join + failures.append(e) + + updater = threading.Thread(target=add_gsi) + updater.start() + try: + # Phases seen, in order: 1 is Backfilling false, 2 is true, 3 is ACTIVE. + # A reading counts only when DescribeTable agrees before and after the + # two reads, so a phase change between them is read again. + seen: list[int] = [] + deadline = time.monotonic() + 120 + while seen[-1:] != [3]: + assert time.monotonic() < deadline, f"no ACTIVE state; seen {seen}" + before = _gsi(dynamodb_client, table) + query = _outcome( + dynamodb_client.query, + TableName=table, + IndexName=GSI, + KeyConditionExpression="g = :v", + ExpressionAttributeValues={":v": {"S": "v"}}, + ) + scan = _outcome(dynamodb_client.scan, TableName=table, IndexName=GSI) + statement = _outcome( + dynamodb_client.execute_statement, + Statement=f"SELECT * FROM \"{table}\".\"{GSI}\" WHERE g = 'v'", + ) + batch = _batch(dynamodb_client, table) + after = _gsi(dynamodb_client, table) + if before is None or before != after: + time.sleep(0.05) + continue + state = (before["IndexStatus"], before.get("Backfilling", ABSENT)) + if state == ("CREATING", False): + assert set(before) == CREATING_MEMBERS, sorted(before) + assert query == ("ValidationException", NOT_FOUND), query + assert scan == ("ValidationException", NOT_FOUND), scan + assert statement == ("ValidationException", NOT_FOUND_STATEMENT), statement + assert batch == [("ValidationError", NOT_FOUND_STATEMENT), ("ITEM", "p0")], batch + phase = 1 + elif state == ("CREATING", True): + assert set(before) == CREATING_MEMBERS, sorted(before) + assert query == ("ValidationException", BACKFILLING), query + assert scan == ("ValidationException", BACKFILLING), scan + assert statement == ("ValidationException", BACKFILLING), statement + assert batch == [("ValidationError", BACKFILLING), ("ITEM", "p0")], batch + phase = 2 + elif state == ("ACTIVE", ABSENT): + assert query == ("OK", 3), query + assert scan == ("OK", 3), scan + assert statement == ("OK", 3), statement + assert batch == [("ValidationError", BATCH_KEY_REQUIRED), ("ITEM", "p0")], batch + phase = 3 + else: + pytest.fail(f"a state the service does not report: {state}") + if seen[-1:] != [phase]: + assert not seen or seen[-1] < phase, f"phase {phase} after {seen}" + seen.append(phase) + time.sleep(0.05) + assert seen == [1, 2, 3], seen + finally: + updater.join(timeout=120) + _set_hold(endpoint_url, table, 0) + assert not failures, failures diff --git a/tests/rust/src/gsi_on_hash_only_table.rs b/tests/rust/src/gsi_on_hash_only_table.rs index ed4f34d46..af3fa5f7d 100644 --- a/tests/rust/src/gsi_on_hash_only_table.rs +++ b/tests/rust/src/gsi_on_hash_only_table.rs @@ -163,6 +163,10 @@ async fn gsi_can_be_added_to_a_table_with_no_sort_key() { ) }); wait_for_active(c, &table).await; + // The table is ACTIVE again before the index is: the service refuses a + // Query naming an index that is still CREATING, and so do the backends + // whose UpdateTable returns before the backfill ends. + wait_for_index_active(c, &table, "hashOnlyIdx").await; // The index must exist on the table description, not merely have been // accepted by UpdateTable. diff --git a/tests/rust/src/gsi_update_table_attr_defs.rs b/tests/rust/src/gsi_update_table_attr_defs.rs index 247ec548c..02808f6fa 100644 --- a/tests/rust/src/gsi_update_table_attr_defs.rs +++ b/tests/rust/src/gsi_update_table_attr_defs.rs @@ -16,11 +16,10 @@ use crate::test_base::*; use aws_sdk_dynamodb::types::{ - AttributeDefinition, CreateGlobalSecondaryIndexAction, GlobalSecondaryIndexUpdate, IndexStatus, + AttributeDefinition, CreateGlobalSecondaryIndexAction, GlobalSecondaryIndexUpdate, KeySchemaElement, KeyType, Projection, ProjectionType, ScalarAttributeType, }; use std::collections::HashMap; -use std::time::Duration; /// Items per partition. More than one is what makes a partition-only read /// observably wrong; a handful keeps the test fast while still failing on the @@ -30,25 +29,6 @@ const ITEM_COUNT: usize = 8; /// Shared by every item, so the GSI's hash key alone never narrows to one row. const GSI_HASH_VALUE: &str = "gpk-shared"; -/// Poll DescribeTable until the named index reports ACTIVE (up to 60s). -async fn wait_for_index_active(c: &aws_sdk_dynamodb::Client, table: &str, index_name: &str) { - for _ in 0..60 { - if let Ok(resp) = c.describe_table().table_name(table).send().await { - if let Some(t) = resp.table() { - let active = t.global_secondary_indexes().iter().any(|i| { - i.index_name() == Some(index_name) - && i.index_status() == Some(&IndexStatus::Active) - }); - if active { - return; - } - } - } - tokio::time::sleep(Duration::from_secs(1)).await; - } - panic!("Index {index_name} on {table} did not become ACTIVE within 60s"); -} - /// Create a composite-key table and populate one partition with `ITEM_COUNT` /// items whose sort keys are distinct, then add a GSI keyed on two non-key /// attributes supplying only those attributes' definitions. diff --git a/tests/rust/src/test_base.rs b/tests/rust/src/test_base.rs index cab50e07c..33cb3bd6b 100755 --- a/tests/rust/src/test_base.rs +++ b/tests/rust/src/test_base.rs @@ -10,8 +10,8 @@ use aws_credential_types::provider::SharedCredentialsProvider; use aws_credential_types::Credentials; use aws_sdk_dynamodb::config::Region; use aws_sdk_dynamodb::types::{ - AttributeDefinition, AttributeValue, BillingMode, GlobalSecondaryIndex, KeySchemaElement, - KeyType, Projection, ProjectionType, ScalarAttributeType, TableStatus, + AttributeDefinition, AttributeValue, BillingMode, GlobalSecondaryIndex, IndexStatus, + KeySchemaElement, KeyType, Projection, ProjectionType, ScalarAttributeType, TableStatus, }; use aws_sdk_dynamodb::Client; use aws_smithy_http_client::tls; @@ -373,6 +373,25 @@ pub async fn wait_for_active(c: &Client, name: &str) { panic!("Table {name} did not become ACTIVE within 60s"); } +/// Poll DescribeTable until the named index reports ACTIVE (up to 60s). +pub async fn wait_for_index_active(c: &Client, table: &str, index_name: &str) { + for _ in 0..60 { + if let Ok(resp) = c.describe_table().table_name(table).send().await { + if let Some(t) = resp.table() { + let active = t.global_secondary_indexes().iter().any(|i| { + i.index_name() == Some(index_name) + && i.index_status() == Some(&IndexStatus::Active) + }); + if active { + return; + } + } + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + panic!("Index {index_name} on {table} did not become ACTIVE within 60s"); +} + /// Poll DescribeTable until the table no longer exists (up to 60s). pub async fn wait_for_deleted(c: &Client, name: &str) { for _ in 0..60 {