Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
13a2940
fix(cassandra): fence concurrent DeleteTable with a lease (#553)
LeeroyHannigan Oct 30, 2026
43435e7
Merge fix/505-deleting-window-answers into fix/553-cassandra-concurre…
LeeroyHannigan Nov 14, 2026
77c8ae0
test(cassandra): drop the point-in-time recovery half of the DeleteTa…
LeeroyHannigan Nov 14, 2026
68f3e1e
test(cassandra): build the lease tests' index input against the curre…
LeeroyHannigan Nov 14, 2026
45f2a69
test(cassandra): read the data table and the row status through one h…
LeeroyHannigan Nov 14, 2026
7318dbc
Merge fix/505-deleting-window-answers into fix/553-cassandra-concurre…
LeeroyHannigan Nov 14, 2026
6fa581b
Merge fix/505-deleting-window-answers into fix/553-cassandra-concurre…
LeeroyHannigan Nov 24, 2026
9340cb7
test: assert the message of the losing DeleteTable on PostgreSQL and …
LeeroyHannigan Nov 24, 2026
1b0aebf
docs: describe the Cassandra DeleteTable claim and its lease
LeeroyHannigan Nov 24, 2026
c40ed59
Merge fix/505-deleting-window-answers into fix/553-cassandra-concurre…
LeeroyHannigan Nov 25, 2026
66a3046
fix(cassandra): release the DeleteTable lease when the removal fails
LeeroyHannigan Nov 25, 2026
bba68ad
fix(cassandra): finish a DeleteTable whose request is dropped after i…
LeeroyHannigan Nov 25, 2026
f77e591
test(cassandra): pause a DeleteTable at its renewal while a sweep tak…
LeeroyHannigan Nov 25, 2026
08b7356
docs: name the DeleteTable lease in the clock note, and fix the remov…
LeeroyHannigan Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/storage-cassandra/src/data/ddl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");

Expand Down
22 changes: 11 additions & 11 deletions crates/storage-cassandra/src/data/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing tests dropping the index tables before deleting their metadata: with main's order restored, the two delete modules pass 10 of 10. A slow DeleteTable whose row a sweep takes over has no end-to-end test either: with the renewal check disabled, 1 of 10 fails, and with the renewal's deadline condition removed only the direct method test fails. A test-hooks test that pauses a call between its drops and its renewal would cover both.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in f77e591 and 66a3046.

a_delete_whose_row_a_sweep_took_over_stops_at_its_renewal pauses a DeleteTable between its drops and its renewal, moves the deadline into the past, and lets a sweep take the row. It runs two cases. In the first, the call resumes after the sweep removed the table and the test created the name again and tagged it. In the second, the call resumes while the sweep holds the row, paused at its own renewal.

With the renewal check disabled, the first case fails: the call runs the tag delete, and the newer table loses its tag. Without the deadline condition in the compare-and-set, the second case fails: the call's renewal applies, and the call deletes the row the sweep holds. The first case passes under that control. Once the sweep finishes, the table id condition of the renewal refuses the call by itself.

The pause cannot show the order in delete_indexes_for_table, because the order only matters when a drop fails. a_delete_that_fails_after_its_claim_is_finished_by_the_next_sweep fails the first index table drop. With main's order restored it fails: the metadata is gone before the failed drop, and the sweep's pass leaves both index tables.

///
/// 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(
Expand All @@ -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 = ?");

Expand All @@ -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)
}

Expand Down
361 changes: 318 additions & 43 deletions crates/storage-cassandra/src/delete_table.rs

Large diffs are not rendered by default.

63 changes: 62 additions & 1 deletion crates/storage-cassandra/src/test_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -163,6 +170,8 @@ mod armed {
pub(super) before_legacy_registration: HashMap<String, Arc<Pause>>,
pub(super) convert_refusals: HashMap<String, usize>,
pub(super) legacy_keys_page: Option<i32>,
pub(super) index_table_drop_failures: std::collections::HashSet<String>,
pub(super) before_delete_lease_renewal: HashMap<String, Arc<Pause>>,
}

pub(super) static HOOKS: LazyLock<Mutex<Hooks>> = LazyLock::new(Mutex::default);
Expand Down Expand Up @@ -1021,3 +1030,55 @@ pub(crate) fn progress_write_fault(account_id: &str) -> Option<ProgressWriteFaul
None
}
}

/// Make the next drop of an index data table in `account_keyspace` fail with
/// an error before it reaches Cassandra. Taken once, then disarmed.
#[cfg(feature = "test-hooks")]
pub fn fail_next_index_table_drop(account_keyspace: &str) {
armed::with_hooks(|hooks| {
hooks
.index_table_drop_failures
.insert(account_keyspace.to_owned());
});
}

/// The error the next index data table drop in `account_keyspace` fails
/// with, if a test armed [`fail_next_index_table_drop`].
pub(crate) fn index_table_drop_failure(account_keyspace: &str) -> 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<Pause> {
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;
}
98 changes: 51 additions & 47 deletions crates/storage-cassandra/src/worker_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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.
Expand All @@ -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<Vec<(String, &'static str)>, StorageError> {
Expand Down Expand Up @@ -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"
);
Expand All @@ -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)
Expand Down
6 changes: 5 additions & 1 deletion crates/storage-cassandra/tests/direct/backup_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<StorageError>(
&engine.session_arc(),
"SELECT table_name FROM system_schema.tables WHERE keyspace_name = ? AND table_name = ?",
Expand Down
Loading
Loading