diff --git a/crates/storage-cassandra/src/data/ddl.rs b/crates/storage-cassandra/src/data/ddl.rs index de2d9bf33..a54625628 100644 --- a/crates/storage-cassandra/src/data/ddl.rs +++ b/crates/storage-cassandra/src/data/ddl.rs @@ -281,6 +281,7 @@ impl CassandraEngine { account_keyspace: &str, index_id: &str, ) -> Result<(), StorageError> { + crate::test_hooks::index_table_drop_failure(account_keyspace)?; let idx_table = index_table_name(index_id); let ddl = format!("DROP TABLE IF EXISTS {account_keyspace}.{idx_table}"); diff --git a/crates/storage-cassandra/src/data/index.rs b/crates/storage-cassandra/src/data/index.rs index 803d02d81..df2c7ca64 100644 --- a/crates/storage-cassandra/src/data/index.rs +++ b/crates/storage-cassandra/src/data/index.rs @@ -639,11 +639,11 @@ pub(crate) fn sk_to_value(sk: &SortKeyValue) -> cdrs_tokio::types::value::Value } } -/// Delete index metadata and drop index data tables for a given table. +/// Drop the index data tables of a table, then delete their index metadata. /// -/// Called by: -/// - `process_control_plane_transitions` when table is DELETING → deleted -/// - `update_table` when GSI is deleted via `UpdateTable` API +/// Called by `remove_claimed_table`, the removal both `DeleteTable` and the +/// control-plane sweep run. The tables go first, so a drop that fails leaves +/// the metadata naming the index ids for the next attempt to find. /// /// Returns list of index IDs that were deleted (for caller logging/tracking). pub(crate) async fn delete_indexes_for_table( @@ -670,6 +670,13 @@ pub(crate) async fn delete_indexes_for_table( index_ids.push(index_id); } + // Drop index data tables + for index_id in &index_ids { + engine + .drop_index_data_table(account_keyspace, index_id) + .await?; + } + // Delete index metadata from catalog let delete_query = format!("DELETE FROM {catalog_keyspace}.indexes WHERE table_id = ?"); @@ -681,13 +688,6 @@ pub(crate) async fn delete_indexes_for_table( ) .await?; - // Drop index data tables - for index_id in &index_ids { - engine - .drop_index_data_table(account_keyspace, index_id) - .await?; - } - Ok(index_ids) } diff --git a/crates/storage-cassandra/src/delete_table.rs b/crates/storage-cassandra/src/delete_table.rs index 0cc7223aa..3a398e4dc 100644 --- a/crates/storage-cassandra/src/delete_table.rs +++ b/crates/storage-cassandra/src/delete_table.rs @@ -6,11 +6,44 @@ use crate::cassandra_util::PolicySession as _; use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; -use extenddb_core::types::{DeleteTableInput, TableDescription}; +use extenddb_core::types::{DeleteTableInput, TableDescription, TableStatus}; use extenddb_storage::error::StorageError; use crate::CassandraEngine; +/// How far ahead of a `DeleteTable` claim, or of a renewal of it, the row's +/// `status_transition_at` is set. +/// +/// The control-plane sweep (`process_control_plane_transitions`) selects a +/// `DELETING` row only once that deadline has passed, and takes it with +/// [`CassandraEngine::renew_delete_lease`] from the deadline it read. Until +/// then the row is left to the call that claimed it. When a statement of the +/// removal fails after the claim or the take, the actor moves the deadline to +/// the current time (`release_delete_lease`). The sweep's next pass then +/// takes the row. A call whose process stops after the claim leaves the row +/// to the sweep, which removes the table after the deadline; with no deadline +/// the sweep would never select the row, and the name would stay taken. A +/// removal that stops part way, the call's or the sweep's, keeps the catalog +/// row, since the row delete is its last statement, and a later pass takes +/// the row over once the deadline written by the last claim, renewal or +/// release has passed. +/// +/// The length decides how long a stopped call keeps the name refused, and +/// how slow a call can be before the sweep takes the row over and runs the +/// remaining drops a second time. The renewal before the name-keyed deletes +/// is what keeps two actors apart: an actor whose renewal does not apply +/// leaves those deletes and the row delete to the actor that holds the row. +/// +/// The deadline comes from this server's clock, and the sweep's select +/// compares it with the clock of the Cassandra node that runs the select. A +/// server S seconds behind that node writes a lease of 300 minus S seconds. +/// A server S seconds ahead of the node writes a lease of 300 plus S seconds. +const DELETE_CLAIM_LEASE_SECS: i64 = 300; + +fn lease_deadline_ms() -> i64 { + (chrono::Utc::now() + chrono::Duration::seconds(DELETE_CLAIM_LEASE_SECS)).timestamp_millis() +} + /// Who is deleting a table, which decides what the delete refuses. #[derive(Clone, Copy)] pub(crate) enum DeleteTableCaller<'a> { @@ -36,8 +69,149 @@ impl CassandraEngine { account_id: &str, input: DeleteTableInput, ) -> Result { - self.delete_table_as(account_id, input, DeleteTableCaller::Client) + let description = self + .delete_table_as(account_id, input, DeleteTableCaller::Client) + .await?; + // The row this call claimed is DELETING while the drops below it run, + // which is the status the service reports in the DeleteTable response + // and the status the other three backends report. + Ok(TableDescription { + table_status: TableStatus::Deleting, + ..description + }) + } + + /// Claims the catalog row for `DeleteTable`: sets `table_status` to + /// `DELETING` and `status_transition_at` to [`DELETE_CLAIM_LEASE_SECS`] + /// from now, if the row still holds `table_id` and is not `DELETING` + /// already. Returns whether the claim applied; it does not when another + /// `DeleteTable` holds the row or the row is gone. + /// + /// The table id in the condition keeps a stalled call from claiming a + /// table created into the same name after the one it read was gone. The + /// condition is the one the MongoDB backend's conditioned mark uses. + /// + /// # Errors + /// + /// Returns [`StorageError::Internal`] when the lightweight transaction + /// fails or its answer cannot be read. + #[doc(hidden)] + pub async fn claim_table_for_delete( + &self, + account_id: &str, + table_name: &str, + table_id: &str, + ) -> Result { + Ok(self + .claim_delete_lease(account_id, table_name, table_id) + .await? + .is_some()) + } + + /// [`Self::claim_table_for_delete`], returning the deadline it wrote, or + /// `None` when the claim did not apply. + pub(crate) async fn claim_delete_lease( + &self, + account_id: &str, + table_name: &str, + table_id: &str, + ) -> Result, StorageError> { + let lease_until = lease_deadline_ms(); + let claim = format!( + "UPDATE {}.tables \ + SET table_status = 'DELETING', status_transition_at = ? \ + WHERE account_id = ? AND table_name = ? \ + IF table_id = ? AND table_status != 'DELETING'", + self.catalog_keyspace() + ); + let result = crate::cassandra_util::query_lwt( + &self.session, + &claim, + cdrs_tokio::query_values!(lease_until, account_id, table_name, table_id), + ) + .await?; + Ok(crate::cassandra_util::lwt_applied(&result)?.then_some(lease_until)) + } + + /// Moves a claimed row's deadline from `held_ms` to + /// [`DELETE_CLAIM_LEASE_SECS`] from now, if the row still holds + /// `table_id`, still reads `DELETING` and still carries `held_ms`. + /// Returns the new deadline, or `None` when the swap did not apply. + /// + /// The control-plane sweep takes a row with it, from the deadline its + /// select returned; an actor renews its own claim with it before the + /// name-keyed deletes. Whoever's swap applies holds the row until the new + /// deadline. A sweeper whose select is stale, a second sweeper, and a call + /// whose row was taken over all find the deadline changed (or the row + /// gone, or holding another table id) and stop. + #[doc(hidden)] + pub async fn renew_delete_lease( + &self, + account_id: &str, + table_name: &str, + table_id: &str, + held_ms: i64, + ) -> Result, StorageError> { + let lease_until = lease_deadline_ms(); + Ok(self + .swap_delete_deadline(account_id, table_name, table_id, held_ms, lease_until) + .await? + .then_some(lease_until)) + } + + /// Hands a row this actor holds back to the control-plane sweep after a + /// statement of its removal failed. It moves the deadline `held_ms`, which + /// the actor's claim, take or last renewal wrote, to the current time with + /// the compare-and-set the renewal uses. The sweep's next pass then + /// selects the row and takes it. The swap does not apply when the row was + /// taken over or removed since, and then there is nothing to hand back. A + /// swap that fails is logged, and the row waits for `held_ms` as it does + /// when the actor's process stops. So does a row whose renewal applied but + /// whose answer was lost, since its deadline is then not `held_ms`. + async fn release_delete_lease( + &self, + account_id: &str, + table_name: &str, + table_id: &str, + held_ms: i64, + ) { + let now_ms = chrono::Utc::now().timestamp_millis(); + if let Err(error) = self + .swap_delete_deadline(account_id, table_name, table_id, held_ms, now_ms) .await + { + tracing::warn!( + "Removing table {table_name} (account {account_id}): handing the row to the \ + control-plane sweep failed: {error}; the sweep takes it after its deadline" + ); + } + } + + /// The compare-and-set of [`Self::renew_delete_lease`] and + /// [`Self::release_delete_lease`]: sets the row's deadline to `until_ms` + /// if the row still holds `table_id`, still reads `DELETING` and still + /// carries `held_ms`. Returns whether it applied. + async fn swap_delete_deadline( + &self, + account_id: &str, + table_name: &str, + table_id: &str, + held_ms: i64, + until_ms: i64, + ) -> Result { + let swap = format!( + "UPDATE {}.tables SET status_transition_at = ? \ + WHERE account_id = ? AND table_name = ? \ + IF table_id = ? AND table_status = 'DELETING' AND status_transition_at = ?", + self.catalog_keyspace() + ); + let result = crate::cassandra_util::query_lwt( + &self.session, + &swap, + cdrs_tokio::query_values!(until_ms, account_id, table_name, table_id, held_ms), + ) + .await?; + crate::cassandra_util::lwt_applied(&result) } pub(crate) async fn delete_table_as( @@ -82,8 +256,8 @@ impl CassandraEngine { match caller { DeleteTableCaller::Client => { // A DELETING row belongs to the deletion already under way - // (the removal of a restore target sets it on this backend). The - // service refuses a second DeleteTable in that window as a + // (a concurrent DeleteTable, or the removal of a restore target). + // The service refuses a second DeleteTable in that window as a // table still in use (measured 2026-10-24); checked before // deletion protection, as the SQL backends order it. let status: String = @@ -122,7 +296,9 @@ impl CassandraEngine { } } - // Fetch indexes for response + // The response is built before the claim: these two steps only read, + // so a failure here leaves the table as it was rather than claimed + // for a removal the client was told failed. let index_query = format!("SELECT * FROM {catalog_keyspace}.indexes WHERE table_id = ?"); let index_result = self @@ -141,46 +317,144 @@ impl CassandraEngine { let index_rows = index_body.into_rows().unwrap_or_default(); - // Build description for response (before deletion) let description = - self.build_table_description_from_row(account_id, table_row, index_rows.clone())?; + self.build_table_description_from_row(account_id, table_row, index_rows)?; - // Delete physical tables from the owning account keyspace. Catalog - // metadata and user data intentionally live in different keyspaces. - // - // The base table is dropped *before* the TTL queue is cleared. Clearing - // first would leave a still-live, still-TTL-enabled table whose items - // have no expiration entries and nothing to rebuild them if the drop - // below fails. + // The claim and the removal run in a task of their own, which the call + // awaits, as the PostgreSQL backend's drops do. A request dropped from + // here on (its client closed the connection) detaches the task. The + // task then finishes the removal, so the row is not left to the lease. + let claim = matches!(caller, DeleteTableCaller::Client); + let engine = self.clone(); + let account_id = account_id.to_owned(); + let table_name = input.table_name; + let table_arn = description.table_arn.clone(); + tokio::spawn(async move { + // Claim the row before the first drop. Two concurrent calls both + // read the same row; the claim applies for one of them and the + // other answers TableBeingDeleted, as the service answers the + // second of two concurrent calls (measured 2026-10-25, five + // rounds of five). + let lease = if claim { + Some( + engine + .claim_delete_lease(&account_id, &table_name, &table_id) + .await? + .ok_or_else(|| StorageError::TableBeingDeleted(table_name.clone()))?, + ) + } else { + None + }; + + // When the renewal inside does not apply, this call outlived its + // lease and the control-plane sweep took the row over; the sweep + // finishes the removal and the call answers with the description + // all the same. + let removed = engine + .remove_claimed_table(&account_id, &table_name, &table_id, &table_arn, lease) + .await; + if removed.is_err() && lease.is_some() { + // The failed removal handed the row back to the sweep. The + // wake has the poller start its next pass at once, and that + // pass takes the row and finishes the removal. A failure + // inside the sweep does not wake the poller, because the + // poller runs that pass. A wake from inside the pass would + // keep the poller polling every second while the failure + // lasts. + engine.control_plane_notify.notify_one(); + } + removed + }) + .await + .map_err(|e| StorageError::Internal(format!("DeleteTable task: {e}")))??; + Ok(description) + } + + /// Removes the table `table_id` whose catalog row this actor holds: + /// `lease` is the deadline its claim (a `DeleteTable` call) or its take + /// (the control-plane sweep) wrote, and `None` for a restore target, which + /// carries no deadline. Returns `false`, having changed nothing keyed on + /// the name, when the renewal of `lease` does not apply. + /// + /// Every statement up to the renewal is keyed on the table id and can run + /// twice: the base data table and the index data tables are dropped `IF + /// EXISTS`, the TTL entries are cleared, and the index metadata goes after + /// the index tables, so a removal that stops part way leaves the ids the + /// next attempt needs. The tags are keyed on the table ARN, which carries + /// no table id. They are deleted after the renewal, while the catalog row + /// still holds the name, and the row delete runs last. So a `CreateTable` + /// of the name is refused until the row delete frees the name. A tag + /// write that landed during the drops goes with the table. The + /// renewal is the fence: an actor whose lease was taken over, or whose row + /// was removed or created again under the name, stops before the tag + /// delete. It holds while the two statements after the renewal finish + /// within the lease it wrote. + /// + /// When a statement fails, the actor hands the row back to the sweep + /// (`release_delete_lease`) before it returns the error. The sweep's next + /// pass then runs the removal again without waiting for the lease. + pub(crate) async fn remove_claimed_table( + &self, + account_id: &str, + table_name: &str, + table_id: &str, + table_arn: &str, + lease: Option, + ) -> Result { + let mut held = lease; + let removal = self + .run_removal(account_id, table_name, table_id, table_arn, &mut held) + .await; + if removal.is_err() + && let Some(held) = held + { + self.release_delete_lease(account_id, table_name, table_id, held) + .await; + } + removal + } + + /// The statements of [`Self::remove_claimed_table`]. `held` is the + /// deadline the actor holds, which the renewal moves. + async fn run_removal( + &self, + account_id: &str, + table_name: &str, + table_id: &str, + table_arn: &str, + held: &mut Option, + ) -> Result { + let catalog_keyspace = self.catalog_keyspace(); + // Catalog metadata and user data intentionally live in different + // keyspaces. let account_keyspace = self.account_keyspace(account_id); - self.drop_data_table(&account_keyspace, &table_id) - .await - .map_err(|e| StorageError::Internal(e.to_string()))?; - self.clear_ttl_entries_for_table_id(account_id, &table_id) + + // The base table is dropped *before* the TTL queue is cleared. Clearing + // first would leave a table that still holds items with no expiration + // entries and nothing to rebuild them if the drop below fails. + self.drop_data_table(&account_keyspace, table_id).await?; + self.clear_ttl_entries_for_table_id(account_id, table_id) .await?; + crate::data::index::delete_indexes_for_table( + &self.session_arc(), + &catalog_keyspace, + &account_keyspace, + table_id, + self, + ) + .await?; - // Delete index data tables - for idx_row in &index_rows { - let index_id: String = idx_row - .get_r_by_name("index_id") - .map_err(|e| StorageError::Internal(format!("Parse index_id: {e}")))?; - self.drop_index_data_table(&account_keyspace, &index_id) - .await - .map_err(|e| StorageError::Internal(format!("Drop index table: {e}")))?; + crate::test_hooks::before_delete_lease_renewal(table_id).await; + if let Some(lease) = *held { + let Some(renewed) = self + .renew_delete_lease(account_id, table_name, table_id, lease) + .await? + else { + return Ok(false); + }; + *held = Some(renewed); } - // Delete catalog entries (indexes first due to FK) - let delete_indexes_query = - format!("DELETE FROM {catalog_keyspace}.indexes WHERE table_id = ?"); - self.session - .run( - Stmt::Write, - &delete_indexes_query, - cdrs_tokio::query_values!(table_id.as_str()), - ) - .await - .map_err(|e| StorageError::Internal(format!("Delete indexes: {e}")))?; - // Delete tags for this table so they don't survive recreation under the same name. let delete_tags_query = format!("DELETE FROM {catalog_keyspace}.tags WHERE resource_arn = ?"); @@ -188,24 +462,25 @@ impl CassandraEngine { .run( Stmt::Write, &delete_tags_query, - cdrs_tokio::query_values!(description.table_arn.as_str()), + cdrs_tokio::query_values!(table_arn), ) .await .map_err(|e| StorageError::Internal(format!("Delete tags: {e}")))?; - // Delete table catalog entry — LWT to avoid mixing plain/LWT writes on - // a row created with IF NOT EXISTS. See ADR-0021. + // Delete table catalog entry, only if it is still this incarnation. A + // lightweight transaction, to avoid mixing plain and LWT writes on a + // row created with IF NOT EXISTS. See ADR-0021. let delete_table_query = format!( "DELETE FROM {catalog_keyspace}.tables WHERE account_id = ? AND table_name = ? IF table_id = ?" ); crate::cassandra_util::query_lwt( &self.session, &delete_table_query, - cdrs_tokio::query_values!(account_id, input.table_name.as_str(), table_id.as_str()), + cdrs_tokio::query_values!(account_id, table_name, table_id), ) .await .map_err(|e| StorageError::Internal(format!("Delete table: {e}")))?; - Ok(description) + Ok(true) } } diff --git a/crates/storage-cassandra/src/test_hooks.rs b/crates/storage-cassandra/src/test_hooks.rs index f8c1d003b..c61b91de9 100644 --- a/crates/storage-cassandra/src/test_hooks.rs +++ b/crates/storage-cassandra/src/test_hooks.rs @@ -62,7 +62,14 @@ //! serial re-read after it; //! * a pause in `set_backup_deleted` between its read of the row and its //! lightweight transaction, so a test can move the row in that gap and see -//! the transaction's store condition send it under the root it names. +//! the transaction's store condition send it under the root it names; +//! * an error on the next drop of an index data table in one account +//! keyspace, so a test can see a `DeleteTable` that fails after its claim +//! hand the row to the sweep, and the sweep drop the index tables the +//! failed call left; +//! * a pause in a table's removal (`remove_claimed_table`) between its drops +//! and its lease renewal, so a test can let the control-plane sweep take +//! the row over in that gap and see the paused actor's renewal not apply. use std::time::Duration; @@ -163,6 +170,8 @@ mod armed { pub(super) before_legacy_registration: HashMap>, pub(super) convert_refusals: HashMap, pub(super) legacy_keys_page: Option, + pub(super) index_table_drop_failures: std::collections::HashSet, + pub(super) before_delete_lease_renewal: HashMap>, } pub(super) static HOOKS: LazyLock> = LazyLock::new(Mutex::default); @@ -1021,3 +1030,55 @@ pub(crate) fn progress_write_fault(account_id: &str) -> Option Result<(), StorageError> { + #[cfg(feature = "test-hooks")] + { + if armed::with_hooks(|hooks| hooks.index_table_drop_failures.remove(account_keyspace)) { + return Err(StorageError::Internal(format!( + "test hook: the drop of an index data table in {account_keyspace} failed" + ))); + } + } + let _ = account_keyspace; + Ok(()) +} + +/// Arm a pause in the next removal of the table `table_id`, by a +/// `DeleteTable` call or by the control-plane sweep, between its drops and +/// its lease renewal. The pause is taken once and then disarmed. +#[cfg(feature = "test-hooks")] +pub fn pause_before_delete_lease_renewal(table_id: &str) -> std::sync::Arc { + let pause = std::sync::Arc::new(Pause::new()); + armed::with_hooks(|hooks| { + hooks + .before_delete_lease_renewal + .insert(table_id.to_owned(), std::sync::Arc::clone(&pause)); + }); + pause +} + +/// Hold here if a test armed a pause before the lease renewal of the +/// removal of `table_id`. +pub(crate) async fn before_delete_lease_renewal(table_id: &str) { + #[cfg(feature = "test-hooks")] + if let Some(pause) = + armed::with_hooks(|hooks| hooks.before_delete_lease_renewal.remove(table_id)) + { + pause.hold().await; + } + let _ = table_id; +} diff --git a/crates/storage-cassandra/src/worker_store.rs b/crates/storage-cassandra/src/worker_store.rs index eb18ee355..0d3c07f3e 100755 --- a/crates/storage-cassandra/src/worker_store.rs +++ b/crates/storage-cassandra/src/worker_store.rs @@ -3,8 +3,6 @@ //! `WorkerStore` trait implementation and control plane transition processing. -use crate::cassandra_util::PolicySession as _; -use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use futures::future::BoxFuture; @@ -28,8 +26,10 @@ impl CassandraEngine { /// Process pending control plane transitions (H-5). /// /// Tables in CREATING state whose `status_transition_at` has passed are - /// moved to ACTIVE. Tables in DELETING state whose transition time has - /// passed are removed (along with their indexes and tags). + /// moved to ACTIVE. A DELETING table whose deadline has passed is taken + /// with a compare-and-set on that deadline and removed by the same steps + /// `DeleteTable` runs (see `remove_claimed_table`); a row the swap does + /// not take is left to the actor that holds it. /// /// Called by the background poller in `cmd_serve`. Also called at startup /// to recover in-flight operations from a previous server instance. @@ -39,7 +39,9 @@ impl CassandraEngine { /// /// # Errors /// - /// Returns [`StorageError`] if the database is unreachable or a query fails. + /// Returns [`StorageError`] if the catalog cannot be read or a row cannot + /// be parsed; a failure to remove one `DELETING` table is logged, and the + /// removal hands the row to the next pass. pub async fn process_control_plane_transitions( &self, ) -> Result, StorageError> { @@ -87,9 +89,15 @@ impl CassandraEngine { transitions.push((table_name, "CREATING → active")); } - // DELETING → remove row (with tags and data table cleanup) + // DELETING → removed. Only a DeleteTable claim, its renewals and the + // release of a failed removal give a DELETING row a deadline. So a row + // here is a claim whose call stopped, a call still running past its + // lease, or a removal by a call or an earlier pass that failed or + // stopped part way. let query = format!( - "SELECT account_id, table_name, table_arn, table_id FROM {catalog_keyspace}.tables \ + "SELECT account_id, table_name, table_arn, table_id, \ + toUnixTimestamp(status_transition_at) AS deadline_ms \ + FROM {catalog_keyspace}.tables \ WHERE table_status = 'DELETING' AND status_transition_at <= toTimestamp(now()) \ ALLOW FILTERING" ); @@ -115,48 +123,44 @@ impl CassandraEngine { let table_id: String = row .get_r_by_name("table_id") .map_err(|e| StorageError::Internal(format!("Failed to parse table_id: {e}")))?; - - // Delete tags - let tag_delete = format!("DELETE FROM {catalog_keyspace}.tags WHERE resource_arn = ?"); - self.session - .run( - Stmt::Write, - &tag_delete, - cdrs_tokio::query_values!(table_arn.as_str()), + let deadline_ms: i64 = row + .get_r_by_name("deadline_ms") + .map_err(|e| StorageError::Internal(format!("Failed to parse deadline: {e}")))?; + + // Take the row from the deadline this pass read. The swap applies + // for one actor; a row that another sweeper took, that its call + // renewed, or that was removed or created again under the name + // since the select is left alone. + let removal = async { + let Some(lease) = self + .renew_delete_lease(&account_id, &table_name, &table_id, deadline_ms) + .await? + else { + return Ok(false); + }; + // The call's removal, under this pass's lease. It returns false, + // having deleted nothing keyed on the name, when the lease is + // taken from this pass before the name-keyed deletes. + self.remove_claimed_table( + &account_id, + &table_name, + &table_id, + &table_arn, + Some(lease), ) .await - .map_err(|e| StorageError::Internal(format!("Failed to delete tags: {e}")))?; - - // Delete indexes (catalog + data tables) - let account_keyspace = self.account_keyspace(&account_id); - self.clear_ttl_entries_for_table_id(&account_id, &table_id) - .await?; - crate::data::index::delete_indexes_for_table( - &self.session_arc(), - &catalog_keyspace, - &account_keyspace, - &table_id, - self, - ) - .await?; - - // Delete table row — LWT to avoid mixing plain/LWT writes on a row - // created with IF NOT EXISTS. See ADR-0021. - let table_delete = format!( - "DELETE FROM {catalog_keyspace}.tables WHERE account_id = ? AND table_name = ? IF EXISTS" - ); - crate::cassandra_util::query_lwt( - &self.session, - &table_delete, - cdrs_tokio::query_values!(account_id.as_str(), table_name.as_str()), - ) - .await - .map_err(|e| StorageError::Internal(format!("Failed to delete table: {e}")))?; - - // Drop base table in account keyspace - self.drop_data_table(&account_keyspace, &table_id).await?; - - transitions.push((table_name, "DELETING → deleted")); + }; + match removal.await { + Ok(true) => transitions.push((table_name, "DELETING → deleted")), + Ok(false) => {} + // Logged, so one row that cannot be removed does not stop the + // rows after it. A removal that fails hands the row back first, + // so the next pass takes it again. + Err(error) => tracing::warn!( + "Control-plane sweep: removing table {table_name} (account {account_id}): \ + {error}; retrying on a later pass" + ), + } } Ok(transitions) diff --git a/crates/storage-cassandra/tests/direct/backup_engine.rs b/crates/storage-cassandra/tests/direct/backup_engine.rs index de6cbfa56..f3b9fa4a3 100644 --- a/crates/storage-cassandra/tests/direct/backup_engine.rs +++ b/crates/storage-cassandra/tests/direct/backup_engine.rs @@ -3914,7 +3914,11 @@ async fn test_a_failed_record_whose_target_is_deleting_is_listed_once_stale_and_ } /// Whether `table` exists in `account_id`'s keyspace. -async fn data_table_exists(engine: &CassandraEngine, account_id: &str, table: &str) -> bool { +pub(crate) async fn data_table_exists( + engine: &CassandraEngine, + account_id: &str, + table: &str, +) -> bool { !extenddb_storage_cassandra::cassandra_util::system_read::( &engine.session_arc(), "SELECT table_name FROM system_schema.tables WHERE keyspace_name = ? AND table_name = ?", diff --git a/crates/storage-cassandra/tests/direct/concurrent_delete_table.rs b/crates/storage-cassandra/tests/direct/concurrent_delete_table.rs new file mode 100644 index 000000000..576f66867 --- /dev/null +++ b/crates/storage-cassandra/tests/direct/concurrent_delete_table.rs @@ -0,0 +1,479 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Direct tests for two `DeleteTable` calls on one table. +//! +//! Amazon DynamoDB answers the second of two concurrent `DeleteTable` calls on +//! an `ACTIVE` table with `ResourceInUseException` and the sentence `Attempt to +//! change a resource which is still in use: Table is being deleted: ` +//! (measured 2026-10-25, five rounds of five). On this backend `DeleteTable` +//! claims the row as `DELETING` with a lightweight transaction and then drops +//! the data and the catalog row inside the same call; these tests run against +//! the window that call opens. +//! +//! `create_table` in this harness leaves a fresh table `CREATING` with a 250 ms +//! activation deadline, so the tests activate their tables first (`activate`) +//! and the claim they reach is the one on an `ACTIVE` row; one round of the +//! first test deletes a `CREATING` table, which the claim also admits. +//! +//! The claim sets the row's `status_transition_at` five minutes ahead, which +//! the control-plane sweep (`process_control_plane_transitions`, run by other +//! tests in this binary against the shared catalog keyspace) waits for before +//! it removes a `DELETING` row. The stopped-claim test moves that deadline into +//! the past by hand and runs the sweep itself. Each test runs inside +//! `removing_rows_after`, so a test that fails leaves no row behind for a later +//! sweep to reach after its account keyspace is gone. + +use std::sync::Arc; +use std::time::Duration; + +use extenddb_core::types::{TableStatus, Tag}; +use extenddb_storage::error::StorageError; +use extenddb_storage::{MetadataEngine, TableEngine}; + +use crate::delete_table_support::{ + activate, catalog_rows, create_input, create_one, data_table_exists, delete_input, + move_deadline_into_the_past, removing_rows_after, row_deadline_ms, row_status, row_table_id, + wait_for_row_gone, +}; +use crate::helpers::{TestAccount, setup_engine, test_config}; + +/// The round of `two_concurrent_delete_tables_have_one_winner` that deletes a +/// table still `CREATING`. The claim admits a `CREATING` row on purpose: this +/// backend has always deleted one, and refusing it is a separate change. +const CREATING_ROUND: usize = 9; + +/// Two concurrent `DeleteTable` calls on one `ACTIVE` table: the claim applies +/// for one of them, the other answers `TableBeingDeleted`, which is the +/// service's answer for the second of two concurrent calls (measured +/// 2026-10-25, five rounds of five). Ten rounds, a fresh table each; +/// afterwards neither the catalog row nor the data table remains. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn two_concurrent_delete_tables_have_one_winner() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, account_id) = (engine.clone(), id.clone()); + async move { + let shared = Arc::new(engine.clone()); + for round in 0..10 { + let name = format!("ConcurrentDelete{round}"); + let created = create_one(&engine, &account_id, &name).await; + if round != CREATING_ROUND { + activate(&engine, &account_id, &name).await; + } + + let tasks: Vec<_> = (0..2) + .map(|_| { + let engine = Arc::clone(&shared); + let account_id = account_id.clone(); + let name = name.clone(); + tokio::spawn(async move { + engine.delete_table(&account_id, delete_input(&name)).await + }) + }) + .collect(); + + let mut ok = 0; + let mut being_deleted = 0; + for task in tasks { + match task.await.expect("task") { + Ok(description) => { + assert_eq!( + description.table_status, + TableStatus::Deleting, + "round {round}: the winner reports DELETING" + ); + ok += 1; + } + Err(StorageError::TableBeingDeleted(reported)) if reported == name => { + being_deleted += 1; + } + Err(other) => panic!("round {round}: unexpected {other:?}"), + } + } + assert_eq!((ok, being_deleted), (1, 1), "round {round}"); + assert_eq!( + row_status(&engine, &account_id, &name).await, + None, + "round {round}: the catalog row is gone" + ); + assert!( + !data_table_exists(&engine, &account_id, &created.table_id).await, + "round {round}: the data table is gone" + ); + } + } + }; + removing_rows_after(&engine, &id, test).await; +} + +/// The second half of #553. The deleted table's tags are keyed on the table +/// ARN, and a table created into the same name holds its tags under the same +/// key. Here a `CreateTable` takes the name back as soon as the winner releases +/// it and tags the new table at once, while a second `DeleteTable` is still in +/// flight; the new table keeps its tags, because the second call is refused at +/// the claim and runs none of the deletes. Its tags must not include the first +/// table's `first-only` key. +/// +/// The second call is started a little behind the first so that it meets a +/// delete already under way; under the create loop's load either of the two +/// can reach the claim first, so the test counts the outcomes rather than +/// naming a winner. The call that loses answers `TableBeingDeleted` when it +/// meets the claim and `TableNotFound` when the other one had already +/// finished, and both mean it ran no deletes of its own. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_table_created_during_a_delete_keeps_its_tags() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, account_id) = (engine.clone(), id.clone()); + async move { + let shared = Arc::new(engine.clone()); + for round in 0..5 { + recreate_during_a_delete(&shared, &account_id, round).await; + } + } + }; + removing_rows_after(&engine, &id, test).await; +} + +/// One round of `a_table_created_during_a_delete_keeps_its_tags`. +async fn recreate_during_a_delete( + shared: &Arc, + account_id: &str, + round: usize, +) { + let engine = shared.as_ref(); + let name = format!("RecreatedDuringDelete{round}"); + let first = create_one(engine, account_id, &name).await; + activate(engine, account_id, &name).await; + engine + .tag_resource( + &first.table_arn, + &[ + Tag { + key: "owner".to_owned(), + value: "first".to_owned(), + }, + Tag { + key: "first-only".to_owned(), + value: "yes".to_owned(), + }, + ], + ) + .await + .expect("tag the first table"); + + let deletes: Vec<_> = (0..2) + .map(|index| { + let engine = Arc::clone(shared); + let account_id = account_id.to_owned(); + let name = name.clone(); + tokio::spawn(async move { + // The second call starts a little behind so it meets a + // delete already under way rather than an untouched table. + if index == 1 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + engine.delete_table(&account_id, delete_input(&name)).await + }) + }) + .collect(); + // Takes the name back the moment the winner releases it, and writes the + // new table's tags while the second call may still be running. A delete + // that is not fenced takes them away from here. + let creator = { + let engine = Arc::clone(shared); + let account_id = account_id.to_owned(); + let name = name.clone(); + tokio::spawn(async move { + for _ in 0..3_000 { + match engine.create_table(&account_id, create_input(&name)).await { + Ok(description) => { + engine + .tag_resource( + &description.table_arn, + &[Tag { + key: "owner".to_owned(), + value: "second".to_owned(), + }], + ) + .await + .expect("tag the new table"); + return Some(description); + } + Err(StorageError::TableAlreadyExists(_)) => { + tokio::time::sleep(Duration::from_millis(1)).await; + } + Err(other) => panic!("recreating {name}: {other:?}"), + } + } + None + }) + }; + + let mut ok = 0; + let mut refused = 0; + for task in deletes { + match task.await.expect("task") { + Ok(_) => ok += 1, + Err(StorageError::TableBeingDeleted(reported)) if reported == name => refused += 1, + Err(StorageError::TableNotFound(_)) => refused += 1, + Err(other) => panic!("round {round}: unexpected {other:?}"), + } + } + assert_eq!( + (ok, refused), + (1, 1), + "round {round}: one call deletes the table and the other runs no deletes" + ); + let recreated = creator + .await + .expect("task") + .expect("the name became free again"); + assert_ne!( + recreated.table_id, first.table_id, + "round {round}: a new incarnation" + ); + + let tags = engine + .list_tags(&recreated.table_arn) + .await + .expect("read the new table's tags"); + assert_eq!( + tags.iter() + .map(|tag| (tag.key.as_str(), tag.value.as_str())) + .collect::>(), + vec![("owner", "second")], + "round {round}: the new table keeps its tags" + ); + assert_eq!( + row_table_id(engine, account_id, &name).await.as_deref(), + Some(recreated.table_id.as_str()), + "round {round}: the catalog row is the new table's" + ); + + engine + .delete_table(account_id, delete_input(&name)) + .await + .expect("remove the new table"); +} + +/// The claim is conditioned on the table id as well as on the status, so a +/// call holding the id of a table that has since been deleted and created +/// again under the name does not claim the newer table. +#[tokio::test] +async fn a_claim_carrying_another_table_id_does_not_apply() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, account_id) = (engine.clone(), id.clone()); + async move { + let name = "ClaimedWithAnotherId"; + create_one(&engine, &account_id, name).await; + activate(&engine, &account_id, name).await; + let other_table_id = uuid::Uuid::new_v4().to_string(); + assert!( + !engine + .claim_table_for_delete(&account_id, name, &other_table_id) + .await + .expect("claim"), + "a claim carrying another table id does not apply" + ); + assert_eq!( + row_status(&engine, &account_id, name).await.as_deref(), + Some("ACTIVE") + ); + engine + .delete_table(&account_id, delete_input(name)) + .await + .expect("remove the table"); + } + }; + removing_rows_after(&engine, &id, test).await; +} + +/// The lease is renewed with a compare-and-set on the deadline the holder +/// last wrote. A renewal that carries an older deadline belongs to an actor +/// whose row was taken over since, and does not apply. +#[tokio::test] +async fn a_renewal_against_a_stale_deadline_does_not_apply() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, account_id) = (engine.clone(), id.clone()); + async move { + let name = "RenewedWithStaleDeadline"; + let created = create_one(&engine, &account_id, name).await; + activate(&engine, &account_id, name).await; + assert!( + engine + .claim_table_for_delete(&account_id, name, &created.table_id) + .await + .expect("claim"), + "the claim applies to an ACTIVE row" + ); + let first = row_deadline_ms(&engine, &account_id, name) + .await + .expect("the claim sets a deadline"); + let second = engine + .renew_delete_lease(&account_id, name, &created.table_id, first) + .await + .expect("renew") + .expect("a renewal carrying the current deadline applies"); + assert!(second >= first, "a renewal moves the deadline forward"); + assert_eq!( + engine + .renew_delete_lease(&account_id, name, &created.table_id, first) + .await + .expect("renew again"), + None, + "a renewal carrying the deadline that was already replaced does not apply" + ); + assert_eq!( + row_deadline_ms(&engine, &account_id, name).await, + Some(second), + "the row keeps the deadline of the renewal that applied" + ); + move_deadline_into_the_past(&engine, &account_id, name).await; + engine + .process_control_plane_transitions() + .await + .expect("sweep the claimed row"); + wait_for_row_gone(&engine, &account_id, name).await; + } + }; + removing_rows_after(&engine, &id, test).await; +} + +// ── A claim whose call stopped ────────────────────────────────────────────── + +/// A `DeleteTable` that stops after its claim, because its process dies or a +/// statement after the claim fails, leaves the row `DELETING` with the claim's +/// deadline ahead of it. Until that deadline the control-plane sweep leaves the +/// row alone, so it does not run the removal beside a call that is still +/// dropping; once it has passed, the sweep removes the row, the data table and +/// the tags, and the name can be created again. The test claims the row and +/// stops there, moves the deadline into the past rather than waiting five +/// minutes, and runs the sweep itself. +#[tokio::test] +async fn a_claim_left_by_a_stopped_call_is_swept_after_its_deadline() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, account_id) = (engine.clone(), id.clone()); + async move { claim_then_sweep(&engine, &account_id).await } + }; + removing_rows_after(&engine, &id, test).await; +} + +/// The body of `a_claim_left_by_a_stopped_call_is_swept_after_its_deadline`. +async fn claim_then_sweep(engine: &extenddb_storage_cassandra::CassandraEngine, account_id: &str) { + let name = "ClaimedThenStopped"; + let created = create_one(engine, account_id, name).await; + activate(engine, account_id, name).await; + engine + .tag_resource( + &created.table_arn, + &[Tag { + key: "owner".to_owned(), + value: "first".to_owned(), + }], + ) + .await + .expect("tag the table"); + + let claimed_at_ms = chrono::Utc::now().timestamp_millis(); + assert!( + engine + .claim_table_for_delete(account_id, name, &created.table_id) + .await + .expect("claim"), + "the claim applies to an ACTIVE row" + ); + assert!( + !engine + .claim_table_for_delete(account_id, name, &created.table_id) + .await + .expect("second claim"), + "a second claim does not apply" + ); + assert_eq!( + row_status(engine, account_id, name).await.as_deref(), + Some("DELETING") + ); + let lease_ms = row_deadline_ms(engine, account_id, name) + .await + .expect("the claim sets a deadline") + - claimed_at_ms; + assert!( + (299_000..=310_000).contains(&lease_ms), + "the deadline is five minutes after the claim, got {lease_ms} ms" + ); + + engine + .process_control_plane_transitions() + .await + .expect("sweep before the deadline"); + assert_eq!( + row_status(engine, account_id, name).await.as_deref(), + Some("DELETING"), + "before the deadline the sweep leaves the row to the call" + ); + assert!( + data_table_exists(engine, account_id, &created.table_id).await, + "the data table is still there" + ); + + move_deadline_into_the_past(engine, account_id, name).await; + engine + .process_control_plane_transitions() + .await + .expect("sweep after the deadline"); + // Another test's sweep may have taken the row first; this sweep then + // leaves it to that one, so wait for the removal rather than assume it. + wait_for_row_gone(engine, account_id, name).await; + assert!( + !data_table_exists(engine, account_id, &created.table_id).await, + "the data table is gone" + ); + let catalog = engine.catalog_keyspace(); + assert_eq!( + catalog_rows( + engine, + &format!("SELECT tag_key FROM {catalog}.tags WHERE resource_arn = ?"), + cdrs_tokio::query_values!(created.table_arn.as_str()), + ) + .await, + 0, + "the tags are gone" + ); + + let again = create_one(engine, account_id, name).await; + assert_ne!(again.table_id, created.table_id, "a new incarnation"); + engine + .delete_table(account_id, delete_input(name)) + .await + .expect("remove the new table"); +} diff --git a/crates/storage-cassandra/tests/direct/delete_table_lease.rs b/crates/storage-cassandra/tests/direct/delete_table_lease.rs new file mode 100644 index 000000000..a48879a15 --- /dev/null +++ b/crates/storage-cassandra/tests/direct/delete_table_lease.rs @@ -0,0 +1,698 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Direct tests for who may finish a `DeleteTable` on this backend. +//! +//! A `DeleteTable` claims the catalog row as `DELETING` with a deadline five +//! minutes ahead. The control-plane sweep takes a row whose deadline has +//! passed with a compare-and-set on that deadline. The actor that holds the +//! row renews it with the same swap, deletes the tags (the delete keyed on +//! the name), and last deletes the row on its table id. These tests put a +//! second actor beside the one that holds the row, and a table created into +//! the name in between, and check that the newer table keeps its catalog row +//! and its tags. An actor whose removal fails moves the deadline to the +//! current time, so the sweep's next pass finishes the removal. A +//! `DeleteTable` whose request is dropped after its claim still finishes it. +//! +//! Rows with a deadline in the past are visible to every sweep in this binary, +//! so the tests wait on the state they expect rather than on the sweep they +//! started, and each runs inside `removing_rows_after`, which removes the +//! account's catalog rows whether the test passes or fails. + +use std::time::Duration; + +use extenddb_core::types::Tag; +use extenddb_storage::{MetadataEngine, TableEngine}; +use extenddb_storage_cassandra::CassandraEngine; + +use crate::delete_table_support::{ + activate, catalog_rows, create_input, create_one, data_table_exists, delete_input, gsi_input, + move_deadline_into_the_past, removing_rows_after, row_deadline_ms, row_status, row_table_id, + tags_of, wait_for_data_table_gone, wait_for_row_gone, wait_for_status, +}; +use crate::helpers::{TestAccount, setup_engine, test_config}; + +/// A claim whose call stopped, its deadline passed, and two servers' sweeps +/// started 300 ms apart. The first sweep takes the row by moving its deadline, +/// so the second one's select no longer returns it, and the first holds the +/// row until it has deleted it. A table created into the name once the row is +/// gone keeps its catalog row, its tag and its data table. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn two_sweeps_over_a_stopped_claim_leave_a_newer_table_alone() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let other_server = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, id) = (engine.clone(), id.clone()); + async move { + let name = "SweptByTwoServers"; + let first = engine + .create_table(&id, gsi_input(name, 6)) + .await + .expect("create the first table"); + activate(&engine, &id, name).await; + assert!( + engine + .claim_table_for_delete(&id, name, &first.table_id) + .await + .expect("claim"), + "the claim applies" + ); + move_deadline_into_the_past(&engine, &id, name).await; + + let sweep_a = { + let engine = engine.clone(); + tokio::spawn(async move { engine.process_control_plane_transitions().await }) + }; + tokio::time::sleep(Duration::from_millis(300)).await; + let sweep_b = + tokio::spawn(async move { other_server.process_control_plane_transitions().await }); + + wait_for_row_gone(&engine, &id, name).await; + let second = create_one(&engine, &id, name).await; + tag_second(&engine, &second.table_arn).await; + sweep_a.await.expect("task").expect("first sweep"); + sweep_b.await.expect("task").expect("second sweep"); + + assert_eq!( + row_table_id(&engine, &id, name).await.as_deref(), + Some(second.table_id.as_str()), + "the new table keeps its catalog row" + ); + assert_eq!( + tags_of(&engine, &second.table_arn).await, + second_tag(), + "the new table keeps its tag" + ); + assert!(data_table_exists(&engine, &id, &second.table_id).await); + assert!(!data_table_exists(&engine, &id, &first.table_id).await); + engine + .delete_table(&id, delete_input(name)) + .await + .expect("remove the new table"); + } + }; + removing_rows_after(&engine, &id, test).await; +} + +/// A sweep holds a row from its select, and while it drops the index tables +/// the row is removed and the name created again (here the row delete is run +/// by hand, the last statement of whichever actor finished first). The sweep's +/// renewal then finds the row holding another table id, so it stops before the +/// delete keyed on the name and the row delete, and does not report the +/// table as removed; the newer table keeps its catalog row and its tag. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_sweep_whose_row_was_replaced_leaves_the_newer_table_alone() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, id) = (engine.clone(), id.clone()); + async move { + let name = "ReplacedUnderTheSweep"; + let first = engine + .create_table(&id, gsi_input(name, 6)) + .await + .expect("create the first table"); + activate(&engine, &id, name).await; + assert!( + engine + .claim_table_for_delete(&id, name, &first.table_id) + .await + .expect("claim") + ); + move_deadline_into_the_past(&engine, &id, name).await; + + let sweep = { + let engine = engine.clone(); + tokio::spawn(async move { engine.process_control_plane_transitions().await }) + }; + // The sweep is past its select once its take has moved the + // deadline, or once the table's index metadata is gone. + let catalog = engine.catalog_keyspace(); + let started = std::time::Instant::now(); + loop { + let taken = row_deadline_ahead(&engine, &id, name).await; + let metadata_gone = catalog_rows( + &engine, + &format!("SELECT index_id FROM {catalog}.indexes WHERE table_id = ?"), + cdrs_tokio::query_values!(first.table_id.as_str()), + ) + .await + == 0; + if taken || metadata_gone { + break; + } + assert!( + started.elapsed() < Duration::from_secs(60), + "the sweep never started" + ); + tokio::time::sleep(Duration::from_millis(5)).await; + } + let row_delete = format!( + "DELETE FROM {catalog}.tables WHERE account_id = ? AND table_name = ? \ + IF table_id = ?" + ); + extenddb_storage_cassandra::cassandra_util::query_lwt( + engine.session(), + &row_delete, + cdrs_tokio::query_values!(id.as_str(), name, first.table_id.as_str()), + ) + .await + .expect("remove the row"); + let second = create_one(&engine, &id, name).await; + tag_second(&engine, &second.table_arn).await; + + let swept = sweep.await.expect("task").expect("the sweep"); + assert_eq!( + row_table_id(&engine, &id, name).await.as_deref(), + Some(second.table_id.as_str()), + "the new table keeps its catalog row" + ); + assert_eq!( + tags_of(&engine, &second.table_arn).await, + second_tag(), + "the new table keeps its tag" + ); + assert!(data_table_exists(&engine, &id, &second.table_id).await); + assert!( + !swept.iter().any(|(table, _)| table == name), + "the sweep stopped at its renewal: {swept:?}" + ); + engine + .delete_table(&id, delete_input(name)) + .await + .expect("remove the new table"); + } + }; + removing_rows_after(&engine, &id, test).await; +} + +/// True when the row's deadline is more than four minutes away, which only a +/// fresh claim or a take by a sweep writes. +async fn row_deadline_ahead(engine: &CassandraEngine, id: &str, name: &str) -> bool { + row_deadline_ms(engine, id, name) + .await + .is_some_and(|deadline| deadline > chrono::Utc::now().timestamp_millis() + 240_000) +} + +/// The tag of the table created into a deleted table's name. The tags are the +/// one delete keyed on the name rather than the table id, so a stale actor +/// that runs its name-keyed delete after this table exists takes them away. +const SECOND_TAG: (&str, &str) = ("owner", "second"); + +async fn tag_second(engine: &CassandraEngine, arn: &str) { + engine + .tag_resource( + arn, + &[Tag { + key: SECOND_TAG.0.to_owned(), + value: SECOND_TAG.1.to_owned(), + }], + ) + .await + .expect("tag the new table"); +} + +/// [`SECOND_TAG`] as [`tags_of`] reads it back. +fn second_tag() -> Vec<(String, String)> { + vec![(SECOND_TAG.0.to_owned(), SECOND_TAG.1.to_owned())] +} + +/// A `DeleteTable` of a table with eight indexes, and, once its base data +/// table is gone and while it drops the index tables, a tag written at the +/// storage layer, below the engine's validation. The delete keyed on the name +/// runs after the drops, so the row goes with the table, and a table created +/// into the name afterwards has no tags. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_tag_written_during_the_drops_goes_with_the_table() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, id) = (engine.clone(), id.clone()); + async move { + let name = "WrittenDuringTheDrops"; + let first = engine + .create_table(&id, gsi_input(name, 8)) + .await + .expect("create the table"); + activate(&engine, &id, name).await; + let call = { + let (engine, id) = (engine.clone(), id.clone()); + tokio::spawn(async move { engine.delete_table(&id, delete_input(name)).await }) + }; + wait_for_status(&engine, &id, name, "DELETING").await; + wait_for_data_table_gone(&engine, &id, &first.table_id).await; + engine + .tag_resource( + &first.table_arn, + &[Tag { + key: "left-by".to_owned(), + value: "the deleted table".to_owned(), + }], + ) + .await + .expect("write a tag row"); + call.await.expect("task").expect("DeleteTable"); + + let second = engine + .create_table(&id, create_input(name)) + .await + .expect("create the name again"); + assert_eq!( + tags_of(&engine, &second.table_arn).await, + Vec::<(String, String)>::new(), + "the new table has no tags" + ); + engine + .delete_table(&id, delete_input(name)) + .await + .expect("remove the new table"); + } + }; + removing_rows_after(&engine, &id, test).await; +} + +/// Two claims whose calls stopped, in two accounts, both past their deadline; +/// one account's keyspace is gone, so removing its table fails at the TTL +/// clear. The sweep logs that row and goes on: it returns `Ok`, and the other +/// account's row is removed. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_row_the_sweep_cannot_remove_does_not_stop_the_others() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let broken = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let healthy = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let (broken_id, healthy_id) = (broken.account_id.clone(), healthy.account_id.clone()); + let test = { + let (engine, broken_id, healthy_id) = + (engine.clone(), broken_id.clone(), healthy_id.clone()); + let inner_engine = engine.clone(); + let healthy_guard = healthy_id.clone(); + async move { + let inner = async move { + for (id, name) in [(&broken_id, "Unremovable"), (&healthy_id, "Removable")] { + let table = create_one(&engine, id, name).await; + activate(&engine, id, name).await; + assert!( + engine + .claim_table_for_delete(id, name, &table.table_id) + .await + .expect("claim") + ); + } + // Dropped before either deadline passes, so no sweep can remove + // the first table while its keyspace is still there. + let keyspace = engine.account_keyspace(&broken_id); + engine + .session() + .query(format!("DROP KEYSPACE IF EXISTS {keyspace}")) + .await + .expect("drop the account keyspace"); + move_deadline_into_the_past(&engine, &broken_id, "Unremovable").await; + move_deadline_into_the_past(&engine, &healthy_id, "Removable").await; + + engine + .process_control_plane_transitions() + .await + .expect("the sweep logs the row it cannot remove and goes on"); + wait_for_row_gone(&engine, &healthy_id, "Removable").await; + assert_eq!( + row_status(&engine, &broken_id, "Unremovable") + .await + .as_deref(), + Some("DELETING"), + "the row whose removal failed is left for a later pass" + ); + }; + removing_rows_after(&inner_engine, &healthy_guard, inner).await; + } + }; + removing_rows_after(&engine, &broken.account_id, test).await; +} + +/// The order of a `DeleteTable`: the delete keyed on the name runs after the +/// drops. Eight rounds, each a tagged table with one index; while the call +/// runs, the moment its base data table is gone the table's tag row is still +/// there (the index table is dropped between the two), and once the call +/// returns it is gone. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_tag_rows_outlive_the_drops_and_go_with_the_row() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, id) = (engine.clone(), id.clone()); + async move { + for round in 0..8 { + let name = format!("NameKeyedLast{round}"); + let table = engine + .create_table(&id, gsi_input(&name, 1)) + .await + .expect("create the table"); + activate(&engine, &id, &name).await; + engine + .tag_resource( + &table.table_arn, + &[Tag { + key: "owner".to_owned(), + value: "deleted".to_owned(), + }], + ) + .await + .expect("tag the table"); + let call = { + let (engine, id, name) = (engine.clone(), id.clone(), name.clone()); + tokio::spawn(async move { engine.delete_table(&id, delete_input(&name)).await }) + }; + wait_for_data_table_gone(&engine, &id, &table.table_id).await; + let during = tag_rows(&engine, &table.table_arn).await; + call.await.expect("task").expect("DeleteTable"); + let after = tag_rows(&engine, &table.table_arn).await; + assert_eq!( + during, 1, + "round {round}: the tag row is there once the data table is gone" + ); + assert_eq!(after, 0, "round {round}: it goes with the table"); + } + } + }; + removing_rows_after(&engine, &id, test).await; +} + +/// How many tag rows the catalog holds for `arn`. +async fn tag_rows(engine: &CassandraEngine, arn: &str) -> usize { + catalog_rows( + engine, + &format!( + "SELECT tag_key FROM {}.tags WHERE resource_arn = ?", + engine.catalog_keyspace() + ), + cdrs_tokio::query_values!(arn), + ) + .await +} + +/// A `DeleteTable` of a table with two indexes whose first index table drop +/// fails, after the claim. The call answers that error and hands the row back +/// to the sweep. The row's deadline is then no later than the current time. +/// So the sweep's next pass takes the row without waiting five minutes for +/// the lease. The index tables go before their metadata, so the metadata +/// outlives the failed drop, and that pass drops both index tables. +#[cfg(feature = "test-hooks")] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_delete_that_fails_after_its_claim_is_finished_by_the_next_sweep() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, id) = (engine.clone(), id.clone()); + async move { + let name = "FailsAfterTheClaim"; + let table = engine + .create_table(&id, gsi_input(name, 2)) + .await + .expect("create the table"); + activate(&engine, &id, name).await; + let index_tables = index_table_names(&engine, &table.table_id).await; + assert_eq!(tables_left(&engine, &id, &index_tables).await, 2); + let keyspace = engine.account_keyspace(&id); + extenddb_storage_cassandra::test_hooks::fail_next_index_table_drop(&keyspace); + match engine.delete_table(&id, delete_input(name)).await { + Err(extenddb_storage::error::StorageError::Internal(message)) => assert_eq!( + message, + format!("test hook: the drop of an index data table in {keyspace} failed") + ), + other => panic!("expected the failed drop's error, got {other:?}"), + } + assert_eq!( + row_status(&engine, &id, name).await.as_deref(), + Some("DELETING") + ); + let deadline = row_deadline_ms(&engine, &id, name) + .await + .expect("the row keeps a deadline"); + assert!( + deadline <= chrono::Utc::now().timestamp_millis(), + "the call hands the row to the sweep, but its deadline is {deadline}" + ); + + engine + .process_control_plane_transitions() + .await + .expect("the sweep"); + // Another test's sweep may take the row first. + wait_for_row_gone(&engine, &id, name).await; + assert!(!data_table_exists(&engine, &id, &table.table_id).await); + assert_eq!( + tables_left(&engine, &id, &index_tables).await, + 0, + "the sweep drops both index tables" + ); + } + }; + removing_rows_after(&engine, &id, test).await; +} + +/// How many of `names` are tables in the account's keyspace. +#[cfg(feature = "test-hooks")] +async fn tables_left(engine: &CassandraEngine, account_id: &str, names: &[String]) -> usize { + let mut left = 0; + for name in names { + if crate::backup_engine::data_table_exists(engine, account_id, name).await { + left += 1; + } + } + left +} + +/// The names of the index data tables of `table_id`, read from its index +/// metadata. +#[cfg(feature = "test-hooks")] +async fn index_table_names(engine: &CassandraEngine, table_id: &str) -> Vec { + use cdrs_tokio::types::IntoRustByName as _; + extenddb_storage_cassandra::cassandra_util::query_rows::( + &engine.session_arc(), + &format!( + "SELECT index_id FROM {}.indexes WHERE table_id = ?", + engine.catalog_keyspace() + ), + cdrs_tokio::query_values!(table_id), + "index ids", + ) + .await + .expect("read the index metadata") + .iter() + .map(|row| { + let index_id: String = row.get_r_by_name("index_id").expect("index_id"); + extenddb_storage_cassandra::data::ddl::index_table_name(&index_id) + }) + .collect() +} + +/// A `DeleteTable` whose request is dropped once its claim applies, as a +/// request is when its client closes the connection. The claim and the +/// removal run in a task that the request only awaits. So the table is still +/// removed, within seconds and not after the five-minute lease. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_delete_whose_request_is_dropped_after_its_claim_still_removes_the_table() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, id) = (engine.clone(), id.clone()); + async move { + let name = "DroppedAfterTheClaim"; + let table = engine + .create_table(&id, gsi_input(name, 4)) + .await + .expect("create the table"); + activate(&engine, &id, name).await; + let call = { + let (engine, id) = (engine.clone(), id.clone()); + tokio::spawn(async move { engine.delete_table(&id, delete_input(name)).await }) + }; + wait_for_status(&engine, &id, name, "DELETING").await; + call.abort(); + wait_for_row_gone(&engine, &id, name).await; + assert!(!data_table_exists(&engine, &id, &table.table_id).await); + } + }; + removing_rows_after(&engine, &id, test).await; +} + +/// How long a test waits for a removal to reach a pause it armed. +#[cfg(feature = "test-hooks")] +const PAUSE_LIMIT: Duration = Duration::from_secs(60); + +/// When the paused call of +/// `a_delete_whose_row_a_sweep_took_over_stops_at_its_renewal` resumes. +#[cfg(feature = "test-hooks")] +#[derive(Clone, Copy, Debug)] +enum Resume { + /// Once the sweep has removed the table and the name was created again + /// and tagged. + AfterTheSweepFinished, + /// While the sweep holds the row: it has taken the row, run its drops, + /// and is paused before its own renewal. + WhileTheSweepHoldsTheRow, +} + +/// A `DeleteTable` paused between its drops and its renewal, and a sweep that +/// takes its row over once the deadline is moved into the past. The call's +/// renewal then does not apply, so the call stops before the tag delete and +/// the row delete, and answers 200 with `DELETING`. Resumed after the sweep +/// finished, it leaves the tag of the table created into the name since. +/// Resumed while the sweep holds the row, it leaves the row and its tag to +/// the sweep, which then finishes the removal. +#[cfg(feature = "test-hooks")] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_delete_whose_row_a_sweep_took_over_stops_at_its_renewal() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let account = TestAccount::new(&engine, &test_config().keyspace_prefix).await; + let id = account.account_id.clone(); + let test = { + let (engine, id) = (engine.clone(), id.clone()); + async move { + let cases = [ + Resume::AfterTheSweepFinished, + Resume::WhileTheSweepHoldsTheRow, + ]; + for (round, resume) in cases.into_iter().enumerate() { + let name = format!("TakenOverAtTheRenewal{round}"); + taken_over_at_the_renewal(&engine, &id, &name, resume).await; + } + } + }; + removing_rows_after(&engine, &id, test).await; +} + +/// One case of `a_delete_whose_row_a_sweep_took_over_stops_at_its_renewal`. +#[cfg(feature = "test-hooks")] +async fn taken_over_at_the_renewal(engine: &CassandraEngine, id: &str, name: &str, resume: Resume) { + use extenddb_storage_cassandra::test_hooks::pause_before_delete_lease_renewal; + + let first = engine + .create_table(id, gsi_input(name, 1)) + .await + .expect("create the table"); + activate(engine, id, name).await; + engine + .tag_resource( + &first.table_arn, + &[Tag { + key: "owner".to_owned(), + value: "first".to_owned(), + }], + ) + .await + .expect("tag the table"); + let call_pause = pause_before_delete_lease_renewal(&first.table_id); + let call = { + let (engine, id, name) = (engine.clone(), id.to_owned(), name.to_owned()); + tokio::spawn(async move { engine.delete_table(&id, delete_input(&name)).await }) + }; + tokio::time::timeout(PAUSE_LIMIT, call_pause.reached()) + .await + .expect("the call reaches its renewal"); + // Armed before the deadline moves, so whichever sweep takes the row + // pauses there. + let sweep_pause = matches!(resume, Resume::WhileTheSweepHoldsTheRow) + .then(|| pause_before_delete_lease_renewal(&first.table_id)); + move_deadline_into_the_past(engine, id, name).await; + let sweep = { + let engine = engine.clone(); + tokio::spawn(async move { engine.process_control_plane_transitions().await }) + }; + + match sweep_pause { + None => { + wait_for_row_gone(engine, id, name).await; + let second = create_one(engine, id, name).await; + tag_second(engine, &second.table_arn).await; + call_pause.release(); + let answer = call.await.expect("task").expect("DeleteTable"); + assert_eq!( + answer.table_status, + extenddb_core::types::TableStatus::Deleting, + "{resume:?}: the call answers DELETING" + ); + assert_eq!( + row_table_id(engine, id, name).await.as_deref(), + Some(second.table_id.as_str()), + "{resume:?}: the new table keeps its catalog row" + ); + assert_eq!( + tags_of(engine, &second.table_arn).await, + second_tag(), + "{resume:?}: the new table keeps its tag" + ); + engine + .delete_table(id, delete_input(name)) + .await + .expect("remove the new table"); + } + Some(sweep_pause) => { + tokio::time::timeout(PAUSE_LIMIT, sweep_pause.reached()) + .await + .expect("the sweep reaches its renewal"); + call_pause.release(); + let answer = call.await.expect("task"); + let row_after_the_call = row_table_id(engine, id, name).await; + let tags_after_the_call = tag_rows(engine, &first.table_arn).await; + // Released before the checks, so a failing check does not leave + // another test's sweep held at this pause. + sweep_pause.release(); + assert_eq!( + answer.expect("DeleteTable").table_status, + extenddb_core::types::TableStatus::Deleting, + "{resume:?}: the call answers DELETING" + ); + assert_eq!( + row_after_the_call.as_deref(), + Some(first.table_id.as_str()), + "{resume:?}: the call leaves the row to the sweep" + ); + assert_eq!( + tags_after_the_call, 1, + "{resume:?}: the call runs no tag delete" + ); + wait_for_row_gone(engine, id, name).await; + assert_eq!( + tag_rows(engine, &first.table_arn).await, + 0, + "{resume:?}: the sweep deletes the tags" + ); + } + } + sweep.await.expect("task").expect("the sweep"); + assert!( + !data_table_exists(engine, id, &first.table_id).await, + "{resume:?}: the data table is gone" + ); +} diff --git a/crates/storage-cassandra/tests/direct/delete_table_support.rs b/crates/storage-cassandra/tests/direct/delete_table_support.rs new file mode 100644 index 000000000..b269b2a9e --- /dev/null +++ b/crates/storage-cassandra/tests/direct/delete_table_support.rs @@ -0,0 +1,347 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Helpers shared by the direct `DeleteTable` tests (`concurrent_delete_table` +//! and `delete_table_lease`): a one-key table, and reads of the catalog row, +//! the data table and the name-keyed rows that a delete removes. + +use extenddb_core::types::{ + AttributeDefinition, BillingMode, CreateTableInput, DeleteTableInput, GsiInput, + KeySchemaElement, KeyType, Projection, ProjectionType, ScalarAttributeType, TableDescription, +}; +use extenddb_storage::{MetadataEngine, TableEngine}; +use extenddb_storage_cassandra::CassandraEngine; + +/// How long the waits below poll before they fail the test. +const WAIT_LIMIT: std::time::Duration = std::time::Duration::from_secs(60); + +/// Runs `body` as its own task, then removes every catalog row the account +/// holds, whether `body` returned or panicked, and re-raises its panic. +/// +/// The catalog keyspace is shared by every test in this binary. A test that +/// fails between a claim and its own clean-up would otherwise leave a +/// `DELETING` row there; once the test's account keyspace is dropped, the +/// control-plane sweep that next reaches the row fails on the missing +/// keyspace, inside whichever test ran it. Each row goes by its table id, +/// with the condition `DeleteTable` uses, together with its index rows and +/// its tags. +pub(crate) async fn removing_rows_after(engine: &CassandraEngine, account_id: &str, body: F) +where + F: std::future::Future + Send + 'static, +{ + let outcome = tokio::spawn(body).await; + remove_account_rows(engine, account_id).await; + if let Err(error) = outcome { + std::panic::resume_unwind(error.into_panic()); + } +} + +/// Best effort: a failure here must not hide the panic being re-raised. +async fn remove_account_rows(engine: &CassandraEngine, account_id: &str) { + use cdrs_tokio::types::IntoRustByName; + let catalog = engine.catalog_keyspace(); + let select = format!( + "SELECT table_name, table_id, table_arn FROM {catalog}.tables WHERE account_id = ?" + ); + let rows = match engine + .session() + .query_with_values(&select, cdrs_tokio::query_values!(account_id)) + .await + .ok() + .and_then(|frame| frame.response_body().ok()) + .and_then(cdrs_tokio::frame::message_response::ResponseBody::into_rows) + { + Some(rows) => rows, + None => return, + }; + for row in rows { + let name: Result = row.get_r_by_name("table_name"); + let table_id: Result = row.get_r_by_name("table_id"); + let arn: Result = row.get_r_by_name("table_arn"); + let (Ok(name), Ok(table_id), Ok(arn)) = (name, table_id, arn) else { + continue; + }; + let _ = engine + .session() + .query_with_values( + &format!("DELETE FROM {catalog}.tags WHERE resource_arn = ?"), + cdrs_tokio::query_values!(arn.as_str()), + ) + .await; + let _ = engine + .session() + .query_with_values( + &format!("DELETE FROM {catalog}.indexes WHERE table_id = ?"), + cdrs_tokio::query_values!(table_id.as_str()), + ) + .await; + let _ = extenddb_storage_cassandra::cassandra_util::query_lwt( + engine.session(), + &format!( + "DELETE FROM {catalog}.tables WHERE account_id = ? AND table_name = ? \ + IF table_id = ?" + ), + cdrs_tokio::query_values!(account_id, name.as_str(), table_id.as_str()), + ) + .await; + } +} + +/// Activates a `CREATING` row as the activation sweep does, scoped to this +/// row: `ACTIVE`, deadline cleared, `IF table_status = 'CREATING'`. In this +/// harness `create_table` writes `CREATING` with a 250 ms activation deadline +/// and nothing else activates it unless some test happens to run the sweep. +pub(crate) async fn activate(engine: &CassandraEngine, account_id: &str, name: &str) { + let query = format!( + "UPDATE {}.tables SET table_status = 'ACTIVE', status_transition_at = null \ + WHERE account_id = ? AND table_name = ? IF table_status = 'CREATING'", + engine.catalog_keyspace() + ); + extenddb_storage_cassandra::cassandra_util::query_lwt( + engine.session(), + &query, + cdrs_tokio::query_values!(account_id, name), + ) + .await + .expect("activate the table"); + assert_eq!( + row_status(engine, account_id, name).await.as_deref(), + Some("ACTIVE"), + "{name} is ACTIVE" + ); +} + +/// Moves a claimed row's deadline one second into the past, the state a claim +/// reaches five minutes after its call stopped. +pub(crate) async fn move_deadline_into_the_past( + engine: &CassandraEngine, + account_id: &str, + name: &str, +) { + let past_ms = chrono::Utc::now().timestamp_millis() - 1_000; + let query = format!( + "UPDATE {}.tables SET status_transition_at = ? \ + WHERE account_id = ? AND table_name = ? IF EXISTS", + engine.catalog_keyspace() + ); + engine + .session() + .query_with_values(&query, cdrs_tokio::query_values!(past_ms, account_id, name)) + .await + .expect("move the deadline into the past"); +} + +/// Polls until the name has no catalog row. +pub(crate) async fn wait_for_row_gone(engine: &CassandraEngine, account_id: &str, name: &str) { + let started = std::time::Instant::now(); + while row_status(engine, account_id, name).await.is_some() { + assert!( + started.elapsed() < WAIT_LIMIT, + "{name}: the row is still there" + ); + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } +} + +/// Polls until the row reads `status`. +pub(crate) async fn wait_for_status( + engine: &CassandraEngine, + account_id: &str, + name: &str, + status: &str, +) { + let started = std::time::Instant::now(); + while row_status(engine, account_id, name).await.as_deref() != Some(status) { + assert!( + started.elapsed() < WAIT_LIMIT, + "{name}: never read {status}" + ); + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + } +} + +/// Polls until the table's base data table has been dropped. +pub(crate) async fn wait_for_data_table_gone( + engine: &CassandraEngine, + account_id: &str, + table_id: &str, +) { + let started = std::time::Instant::now(); + while data_table_exists(engine, account_id, table_id).await { + assert!( + started.elapsed() < WAIT_LIMIT, + "data table of {table_id} still there" + ); + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } +} + +/// The tags stored for `arn`, as `(key, value)` pairs in key order. +pub(crate) async fn tags_of(engine: &CassandraEngine, arn: &str) -> Vec<(String, String)> { + engine + .list_tags(arn) + .await + .expect("read the tags") + .into_iter() + .map(|tag| (tag.key, tag.value)) + .collect() +} + +/// [`create_input`] with `gsis` global secondary indexes, one CQL table each +/// for the delete to drop. +pub(crate) fn gsi_input(name: &str, gsis: usize) -> CreateTableInput { + let mut input = create_input(name); + let mut indexes = Vec::new(); + for i in 0..gsis { + let attribute = format!("g{i}"); + input.attribute_definitions.push(AttributeDefinition { + attribute_name: attribute.clone(), + attribute_type: ScalarAttributeType::S, + }); + indexes.push(GsiInput { + index_name: format!("Idx{i}"), + key_schema: vec![KeySchemaElement { + attribute_name: attribute, + key_type: KeyType::Hash, + }], + projection: Projection { + projection_type: ProjectionType::All, + non_key_attributes: None, + }, + provisioned_throughput: None, + warm_throughput: None, + }); + } + input.global_secondary_indexes = Some(indexes); + input +} + +/// A table with one string partition key, created through the engine so the +/// test has the ARN and the table id the catalog holds. +pub(crate) async fn create_one( + engine: &CassandraEngine, + account_id: &str, + name: &str, +) -> TableDescription { + engine + .create_table(account_id, create_input(name)) + .await + .expect("create the table") +} + +pub(crate) fn create_input(name: &str) -> CreateTableInput { + CreateTableInput { + table_name: name.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() + } +} + +pub(crate) fn delete_input(name: &str) -> DeleteTableInput { + DeleteTableInput { + table_name: name.to_owned(), + } +} + +/// True when the table's data table is still in the account keyspace. +pub(crate) async fn data_table_exists( + engine: &CassandraEngine, + account_id: &str, + table_id: &str, +) -> bool { + let data_table = format!("items_{}", table_id.replace('-', "_")); + crate::backup_engine::data_table_exists(engine, account_id, &data_table).await +} + +pub(crate) async fn row_status( + engine: &CassandraEngine, + account_id: &str, + name: &str, +) -> Option { + row_column(engine, account_id, name, "table_status").await +} + +/// The table id the catalog row holds, which says which incarnation of the +/// name the row belongs to. +pub(crate) async fn row_table_id( + engine: &CassandraEngine, + account_id: &str, + name: &str, +) -> Option { + row_column(engine, account_id, name, "table_id").await +} + +pub(crate) async fn row_column( + engine: &CassandraEngine, + account_id: &str, + name: &str, + column: &str, +) -> Option { + use cdrs_tokio::types::IntoRustByName; + let query = format!( + "SELECT {column} FROM {}.tables WHERE account_id = ? AND table_name = ?", + engine.catalog_keyspace() + ); + let rows = engine + .session() + .query_with_values(&query, cdrs_tokio::query_values!(account_id, name)) + .await + .expect("read the row") + .response_body() + .expect("response body") + .into_rows() + .unwrap_or_default(); + rows.first() + .map(|row| row.get_r_by_name(column).expect("column")) +} + +/// How many rows a catalog query returns. +pub(crate) async fn catalog_rows( + engine: &CassandraEngine, + query: &str, + values: cdrs_tokio::query::QueryValues, +) -> usize { + engine + .session() + .query_with_values(query, values) + .await + .expect("query the catalog") + .response_body() + .expect("response body") + .into_rows() + .unwrap_or_default() + .len() +} + +/// The row's `status_transition_at` in milliseconds since the epoch. +pub(crate) async fn row_deadline_ms( + engine: &CassandraEngine, + account_id: &str, + name: &str, +) -> Option { + use cdrs_tokio::types::IntoRustByName; + let query = format!( + "SELECT toUnixTimestamp(status_transition_at) AS deadline_ms FROM {}.tables \ + WHERE account_id = ? AND table_name = ?", + engine.catalog_keyspace() + ); + let rows = engine + .session() + .query_with_values(&query, cdrs_tokio::query_values!(account_id, name)) + .await + .expect("read the row") + .response_body() + .expect("response body") + .into_rows() + .unwrap_or_default(); + rows.first() + .and_then(|row| row.get_by_name("deadline_ms").expect("deadline_ms")) +} diff --git a/crates/storage-cassandra/tests/direct/deleting_window.rs b/crates/storage-cassandra/tests/direct/deleting_window.rs index e45fd724d..5c560bfcf 100644 --- a/crates/storage-cassandra/tests/direct/deleting_window.rs +++ b/crates/storage-cassandra/tests/direct/deleting_window.rs @@ -7,10 +7,12 @@ //! Amazon DynamoDB answers a second `DeleteTable` and an `UpdateTable` in that //! window with `ResourceInUseException` and the sentence `Attempt to change a //! resource which is still in use: Table is being deleted: ` (measured -//! 2026-10-24). On this backend `DeleteTable` drops the data and the catalog -//! row in one call and never sets `DELETING` itself; the removal of a restore -//! target does. The window is produced here by setting the row's status -//! directly. +//! 2026-10-24). On this backend `DeleteTable` claims the row as `DELETING` +//! with a lightweight transaction and then drops the data and the catalog row +//! inside the same call, so the window lasts as long as the drops. The tests +//! here need it held open for longer than that, and set the row's status +//! directly; `concurrent_delete_table.rs` runs against the window the request +//! itself opens. //! //! The catalog keyspace is shared by every test in this binary, and the //! control-plane sweep (`process_control_plane_transitions`) removes any @@ -28,6 +30,7 @@ use extenddb_storage::TableEngine; use extenddb_storage::error::StorageError; use extenddb_storage_cassandra::CassandraEngine; +use crate::delete_table_support::row_status; use crate::helpers::{TestAccount, TestTable, setup_engine, test_config}; const TABLE: &str = "DeletingWindowTable"; @@ -61,25 +64,6 @@ async fn remove_row(engine: &CassandraEngine, account_id: &str) { .expect("remove the table row"); } -async fn status_of(engine: &CassandraEngine, account_id: &str) -> Option { - use cdrs_tokio::types::IntoRustByName; - let query = format!( - "SELECT table_status FROM {}.tables WHERE account_id = ? AND table_name = ?", - engine.catalog_keyspace() - ); - let rows = engine - .session() - .query_with_values(&query, cdrs_tokio::query_values!(account_id, TABLE)) - .await - .expect("read the row") - .response_body() - .expect("response body") - .into_rows() - .unwrap_or_default(); - rows.first() - .map(|row| row.get_r_by_name("table_status").expect("table_status")) -} - fn update_input() -> UpdateTableInput { UpdateTableInput { table_name: TABLE.to_owned(), @@ -130,7 +114,9 @@ async fn a_second_delete_table_during_the_window_is_table_being_deleted() { "expected TableBeingDeleted({TABLE:?}), got {err:?}" ); assert_eq!( - status_of(&engine, &account.account_id).await.as_deref(), + row_status(&engine, &account.account_id, TABLE) + .await + .as_deref(), Some("DELETING") ); remove_row(&engine, &account.account_id).await; diff --git a/crates/storage-cassandra/tests/direct_integration.rs b/crates/storage-cassandra/tests/direct_integration.rs index 42ecd27d2..65956cc3e 100644 --- a/crates/storage-cassandra/tests/direct_integration.rs +++ b/crates/storage-cassandra/tests/direct_integration.rs @@ -28,12 +28,18 @@ mod backup_engine; mod cassandra_engine; #[path = "direct/concurrent_account_creation.rs"] mod concurrent_account_creation; +#[path = "direct/concurrent_delete_table.rs"] +mod concurrent_delete_table; #[path = "direct/consistency_levels.rs"] mod consistency_levels; #[path = "direct/consistency_shape.rs"] mod consistency_shape; #[path = "direct/delete_item.rs"] mod delete_item; +#[path = "direct/delete_table_lease.rs"] +mod delete_table_lease; +#[path = "direct/delete_table_support.rs"] +mod delete_table_support; #[path = "direct/deleting_window.rs"] mod deleting_window; #[path = "direct/groups.rs"] diff --git a/docs/cassandra-setup.md b/docs/cassandra-setup.md index 0af0a5ba5..073336c72 100644 --- a/docs/cassandra-setup.md +++ b/docs/cassandra-setup.md @@ -441,7 +441,12 @@ backend is experimental rather than production-ready. before opening a table to writes, or quiesce it briefly while enable and backfill complete. - **Clock synchronization.** Keep Cassandra coordinators and ExtendDB hosts - time-synchronized; request batches use explicit timestamps. + time-synchronized. Request batches use explicit timestamps, and the + `DeleteTable` lease uses the clocks too. The server sets the deadline of + the lease from its own clock, 300 s after the claim. The control-plane + sweep compares that deadline with the clock of the Cassandra node. A server + S seconds behind the node writes a lease of 300 minus S seconds. A server S + seconds ahead of the node writes a lease of 300 plus S seconds. - **No vector search.** The Cassandra backend does not implement vector indexes or `SearchVectors`; every vector operation is refused. diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index 70f33ba4d..466acade5 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -57,9 +57,11 @@ from a request sent to that service or backend. |------|----------|------| | Table creation delay | Returns `CREATING` immediately; transitions to `ACTIVE` typically within seconds. Same behavior for on-demand and provisioned | Configurable via `control_plane_delay_seconds` runtime setting (default: 5s) | | DeletionProtectionEnabled | Enforced | Enforced (accepted and stored, DeleteTable rejects when enabled) | -| Requests during a table's `DELETING` window | A second `DeleteTable` and an `UpdateTable` answer `ResourceInUseException` `Attempt to change a resource which is still in use: Table is being deleted: `; `PutItem`, `GetItem`, `Query` and `Scan` are served until the table is gone, and a write made in the window goes away with the table (measured 2026-10-25) | The same on PostgreSQL and SQLite while `DeleteTable` leaves the row `DELETING` and the data tables in place for the control plane to drop: on PostgreSQL at any `control_plane_delay_seconds` while another session holds a lock on one of the table's relations, and with a delay of 1 or more; on SQLite with a delay of 1 or more. With a separate data database, the immediate path on PostgreSQL also marks the row `DELETING`, from its catalog commit until its data commit has dropped the data tables and the row is removed. A request that reaches a data table after the drop answers `ResourceNotFoundException`. On MongoDB the collections are dropped inside the `DeleteTable` call a few milliseconds after the document is marked, so the data plane reads a `DELETING` document as not found (`ResourceNotFoundException`); serving a write there would recreate the collection after its drop. On Cassandra `DeleteTable` is synchronous and never marks the row `DELETING`; the only `DELETING` row on that backend is a restore target the backup reconciler or its failed restore is removing, whose data is partial, and the data plane reads it as not found | +| Requests during a table's `DELETING` window | A second `DeleteTable` and an `UpdateTable` answer `ResourceInUseException` `Attempt to change a resource which is still in use: Table is being deleted: `; `PutItem`, `GetItem`, `Query` and `Scan` are served until the table is gone, and a write made in the window goes away with the table (measured 2026-10-25) | The same on PostgreSQL and SQLite while `DeleteTable` leaves the row `DELETING` and the data tables in place for the control plane to drop: on PostgreSQL at any `control_plane_delay_seconds` while another session holds a lock on one of the table's relations, and with a delay of 1 or more; on SQLite with a delay of 1 or more. With a separate data database, the immediate path on PostgreSQL also marks the row `DELETING`, from its catalog commit until its data commit has dropped the data tables and the row is removed. A request that reaches a data table after the drop answers `ResourceNotFoundException`. On MongoDB the collections are dropped inside the `DeleteTable` call a few milliseconds after the document is marked, so the data plane reads a `DELETING` document as not found (`ResourceNotFoundException`); serving a write there would recreate the collection after its drop. On Cassandra `DeleteTable` claims the row with a lightweight transaction before its first drop. The claim marks the row `DELETING` with a deadline 300 s ahead, and the call then removes the table and answers 200 with `DELETING`. A second `DeleteTable` during the drops answers `ResourceInUseException` with the `Table is being deleted` sentence. A data-plane request during the drops answers `ResourceNotFoundException` when the server's key-info cache holds no entry for the table. With an entry it answers 200 until the base data table is dropped, and 500 after that. A `DeleteTable` whose server process stops after its claim leaves the row `DELETING` (see the row on a stopped claim below). The other `DELETING` row on that backend is a restore target that the backup reconciler or its failed restore is removing. Its data is partial, and the data plane reads it as not found | | U+0000 in a key attribute name, an index key attribute name or a projected attribute name | Accepted; `DescribeTable` returns each name byte for byte (measured 2026-09-18 and 2026-10-24, and again on 2026-11-04) | The same on all four backends. PostgreSQL `jsonb` cannot hold U+0000, so a PostgreSQL deployment stores these names through an escape, U+0000 as U+0001 U+0001 and U+0001 as U+0001 U+0002. Catalog migration 11 applies the escape to the names an earlier release stored (see the [Upgrade Manual](manuals/07-upgrade-manual.md#general-upgrade-procedure)) | | Stream disable and enable | `UpdateTable StreamEnabled=false` answers `UPDATING`; the stream reports `DISABLED` a few seconds later with every shard closed, and every write acknowledged before that lands in the closed stream. `StreamEnabled=true` afterwards creates a new stream with a later label; both streams stay listed, and a disabled stream stays describable after its table is deleted | The shards close inside the `UpdateTable` call and the response says `ACTIVE`. A write that reaches storage after the close is acknowledged and recorded in no stream (on MongoDB it is recorded past the shard's `EndingSequenceNumber` instead); the window is one write wide. A disabled stream is removed with its table. A stream created by a release before this one loses its ARN once the table is disabled and re-enabled (its label lived only in the table row) | +| The `DeleteTable` response on Cassandra | 200 with `TableStatus` `DELETING`, and `DescribeTable` reads `DELETING` for a few seconds after it (3 to 5 s in the rounds of 2026-10-25) | 200 with `TableStatus` `DELETING`. The table is already gone when the answer arrives, because the claim, the drops and the removal of the row run inside the request. A `DescribeTable` sent after the 200 answers `ResourceNotFoundException` | +| A `DeleteTable` that fails or stops after its claim (Cassandra) | The table is gone a few seconds after the service accepts its `DeleteTable` (measured 2026-10-25) | When a statement after the claim fails, the call answers 500 and moves the row's deadline to the current time. It also wakes the control-plane sweep, which removes the table at its next pass. A retry before that pass answers `ResourceInUseException` with the `Table is being deleted` sentence. A request that its client drops after the claim does not stop the removal. When the server process stops after the claim, the row stays `DELETING`, and a retry answers `ResourceInUseException` with the `Table is being deleted` sentence until the sweep removes the table. The row's deadline is 300 s after the claim, or after the renewal that the call makes after its drops. The sweep takes the row at its first pass after that deadline and removes the table in that pass. The sweep runs at least every 60 s, so the name is free within about 6 minutes of the claim or the renewal. A sweep that cannot remove a row logs it, gives it back to its next pass and goes on to the next row | ## Streams diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index ad4618e8a..69d76734f 100755 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -485,7 +485,7 @@ If the health check fails, start extenddb. If it succeeds, check your `--endpoin ### Table stuck in CREATING or DELETING state -**Cause:** The background transition poller processes status changes when notified by CreateTable/DeleteTable, or on a 60-second defensive sweep. If the server was stopped while a table was in a transitional state, the transition completes on the next server startup. +**Cause:** The background transition poller processes status changes when notified by CreateTable/DeleteTable, or on a 60-second defensive sweep. If the server was stopped while a table was in a transitional state, the transition completes on the next server startup. On Cassandra, a `DeleteTable` claim that the stopped server left waits for its deadline instead (the third cause below). A second cause, on PostgreSQL only, is a session holding any lock on one of the table's relations (the base data table, a GSI or LSI data table, or a vector-index data table): a reader (a table snapshot, an in-catalog backup, a Scan or Query, `pg_dump`, any client transaction that read the table), an open write transaction, an index build, or `VACUUM`. DeleteTable then returns `DELETING` instead of dropping the tables in the request: at once for a reader, and after about a second for any other holder, which is how long its drops wait before they give up. The poller then checks the table for holders about once a second without waiting on them, and drops it at the first check that finds none, so the table disappears within about a second of the last holder's release however many tables are waiting this way, also when the server was restarted in between. A table snapshot or an in-catalog backup that ends also wakes the poller, which then checks at once. Until then a CreateTable of the same name is refused with `ResourceInUseException`, and a DeleteTable of the table is refused with `ResourceInUseException` (`Table is being deleted: `). A table that stays `DELETING` for longer has a long-running holder. To find it, list the table's relations on the catalog database: @@ -511,11 +511,14 @@ SELECT l.pid, l.mode, a.query_start, l.relation::regclass AS relation, a.query FROM unnest(ARRAY['_ddb_', '_ddb_']) AS n); ``` +A third cause, on Cassandra only, is a `DeleteTable` whose server process stopped after the call claimed the table's row. The claim keeps the row `DELETING` until its deadline, 300 s after the claim or after the call's renewal of it. A restart does not move the deadline. The 60-second sweep removes the table at its first pass after the deadline, so the table disappears within about 6 minutes. Until then the server refuses a `DeleteTable` of the table with `ResourceInUseException` (`Table is being deleted: `). When a `DeleteTable` fails after its claim, the call moves the deadline to the current time. It also wakes the sweep, which removes the table at its next pass. + **Fix:** If a table appears stuck: 1. Check that extenddb is running (`extenddb status`). 2. Wait for the configured `control_plane_delay_seconds` (default: 0.25) — the poller is woken immediately when a table enters a transitional state. 3. On PostgreSQL, look for a session holding a lock on the table (above); the delete finishes within about a second of its end. -4. If the server was restarted, transitions are recovered automatically at startup. +4. If the server was restarted, transitions are recovered automatically at startup, except a Cassandra `DeleteTable` claim, which waits for its deadline (step 5). +5. On Cassandra, wait about 6 minutes for a table that a stopped `DeleteTable` claimed: the sweep removes it after the claim's deadline (above). ### Data tables without a catalog row (PostgreSQL, separate data database) diff --git a/tests/python/test_deleting_window_control_plane.py b/tests/python/test_deleting_window_control_plane.py index b776ebf10..34189b8b1 100644 --- a/tests/python/test_deleting_window_control_plane.py +++ b/tests/python/test_deleting_window_control_plane.py @@ -243,3 +243,68 @@ def test_index_reads_after_the_table_is_gone_are_not_found(self, dynamodb_client with pytest.raises(ClientError) as exc: dynamodb_client.scan(TableName=name, IndexName="gsi1") assert_validation(exc.value, NOT_FOUND, "ResourceNotFoundException") + + +class TestConcurrentDeleteTable: + """Two DeleteTable calls sent at once, which needs no held window. + + The service answers one of them 200 and the other + ``ResourceInUseException`` with the sentence above (measured 2026-10-25, + five rounds of five). Cassandra and MongoDB answer the same. PostgreSQL + and SQLite with ``control_plane_delay_seconds`` under 1 (the CI setting) + remove the catalog row inside the request, so a second call that arrives + after the first has finished finds no row and answers + ``ResourceNotFoundException``; that answer is accepted there only. The + PostgreSQL and SQLite CI legs run ``devtools/run-tests`` without + ``--backend``, so an empty ``EXTENDDB_TEST_BACKEND`` counts as one of them. + Two 200s mean both calls ran the deletion. + """ + + ROUNDS = 3 + ROW_REMOVED_IN_REQUEST = ("", "postgres", "sqlite") + + def test_only_one_of_two_concurrent_delete_tables_deletes( + self, dynamodb_client, endpoint_url, is_extenddb + ): + from concurrent.futures import ThreadPoolExecutor + + from helpers import make_dynamodb_client + + for round_index in range(self.ROUNDS): + name = unique_name("del-pair") + dynamodb_client.create_table( + TableName=name, + AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}], + KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], + BillingMode="PAY_PER_REQUEST", + ) + wait_for_active(dynamodb_client, name) + + def _delete(_worker: int, table: str = name): + client = make_dynamodb_client(endpoint_url) + try: + return ("ok", client.delete_table(TableName=table)) + except ClientError as exc: + return ("err", exc) + + with ThreadPoolExecutor(max_workers=2) as pool: + outcomes = list(pool.map(_delete, range(2))) + + accepted = [o for kind, o in outcomes if kind == "ok"] + refused = [o for kind, o in outcomes if kind == "err"] + assert len(accepted) == 1, ( + f"round {round_index}: {len(accepted)} of the two DeleteTable calls were " + f"accepted; one call deletes the table and the other is refused" + ) + assert accepted[0]["TableDescription"]["TableStatus"] == "DELETING" + expected = {"ResourceInUseException": _being_deleted(name)} + if is_extenddb and BACKEND in self.ROW_REMOVED_IN_REQUEST: + # ExtendDB's DeleteTable answer for a table it has removed, on + # PostgreSQL (a local server, 2026-11-24) and SQLite, which + # share the engine's mapping. The service adds the table name. + expected["ResourceNotFoundException"] = NOT_FOUND + code = refused[0].response["Error"]["Code"] + assert code in expected, (round_index, BACKEND, refused[0].response["Error"]) + assert_validation(refused[0], expected[code], code) + + wait_for_deleted(dynamodb_client, name, timeout=120.0)