diff --git a/Cargo.lock b/Cargo.lock index 99b0a323f..daa8e65e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1990,6 +1990,7 @@ dependencies = [ "dashmap", "extenddb-auth", "extenddb-core", + "extenddb-engine", "extenddb-storage", "extenddb-storage-mongodb", "futures", diff --git a/crates/core/src/error/messages.rs b/crates/core/src/error/messages.rs index c968c1f83..0cc93f76e 100755 --- a/crates/core/src/error/messages.rs +++ b/crates/core/src/error/messages.rs @@ -59,6 +59,13 @@ pub enum ErrorMessageKey { /// `UpdateTable` during the window, and 2026-11-30 for a second /// `DeleteTable`. TableBeingDeleted, + /// `DescribeTimeToLive` refused because the table is in the state + /// `args[0]`, `DELETING` or `CREATING`. Measured on the service for + /// `DELETING` on 2026-10-25 on three tables, every call inside the window, + /// and for `CREATING` on 2026-10-26, five calls, each while `DescribeTable` + /// read `CREATING`. `UpdateTimeToLive` has no such refusal: it runs its + /// ordinary rules. + DescribeTtlInState, MissingKeySchema, KeySchemaTooMany, KeySchemaFirstNotHash, @@ -107,6 +114,13 @@ pub fn error_message(key: ErrorMessageKey, args: &[&str]) -> String { args[0] ) } + ErrorMessageKey::DescribeTtlInState => { + format!( + "Cannot describe time to live while table is in {0} state: \ + Current table state is {0}", + args[0] + ) + } ErrorMessageKey::MissingKeySchema => { "1 validation error detected: Value null at 'keySchema' failed to satisfy constraint: \ Member must not be null" diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 56fcf97e5..9e81d8eb2 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -74,6 +74,7 @@ mod start_key; pub mod stream_capture; mod streams; mod streams_iterator_params; +mod table_lifecycle; mod tagging; mod transact_get_items; mod transact_write_helpers; diff --git a/crates/engine/src/table_lifecycle.rs b/crates/engine/src/table_lifecycle.rs new file mode 100644 index 000000000..b33c79d29 --- /dev/null +++ b/crates/engine/src/table_lifecycle.rs @@ -0,0 +1,48 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The catalog's lifecycle status for a table, for handlers that decide on it. +//! +//! `TableKeyInfo` carries no status, and the key-info read reports a `DELETING` +//! row as not found on MongoDB and Cassandra, so a handler that has to tell a +//! `DELETING` table from a missing one cannot get the answer from it. The +//! description carries the status on every backend, and the table's latest +//! stream ARN, which the tag path checks a stream ARN against in the window. +//! The callers (the two TTL handlers and the tag path) are control-plane +//! calls, so the read is not on a data-plane path. +//! +//! The read is `describe_table`: four catalog queries on PostgreSQL and SQLite +//! (`tables`, `indexes`, `vector_indexes`, `table_restores`) and two on MongoDB +//! and Cassandra (`tables`, `indexes`). `DescribeTimeToLive`, +//! `UpdateTimeToLive`, `TagResource`, `UntagResource` and `ListTagsOfResource` +//! each make it once per call. `DescribeTimeToLive` on an `ACTIVE` table sends +//! five and three, where it sent one. `UpdateTimeToLive` sends the four or two +//! more, after its write, and on a `DELETING` table it skips the TTL read after +//! the write and the index statements. + +use extenddb_core::types::{DescribeTableInput, TableDescription}; +use extenddb_storage::error::StorageError; + +use crate::OperationContext; + +/// Read `table_name`'s catalog description, for its `table_status` and its +/// `latest_stream_arn`. +/// +/// # Errors +/// +/// Returns [`StorageError::TableNotFound`] when no catalog row exists, and +/// whatever the backend raised otherwise. The caller maps it, so each operation +/// keeps the message it already answers for a missing table. +pub(crate) async fn read_table_description( + table_name: &str, + ctx: &OperationContext, +) -> Result { + ctx.storage + .describe_table( + &ctx.account_id, + DescribeTableInput { + table_name: table_name.to_owned(), + }, + ) + .await +} diff --git a/crates/engine/src/tagging.rs b/crates/engine/src/tagging.rs index 4ce1a24d7..efa2eb8bc 100755 --- a/crates/engine/src/tagging.rs +++ b/crates/engine/src/tagging.rs @@ -5,7 +5,8 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::types::{ - ListTagsOfResourceInput, ListTagsOfResourceOutput, TagResourceInput, UntagResourceInput, + ListTagsOfResourceInput, ListTagsOfResourceOutput, TableStatus, TagResourceInput, + UntagResourceInput, }; use serde_json::Value; @@ -92,32 +93,54 @@ enum WhileDeleting { Refuse, } -/// Refuse a tag change on a table that is being deleted. The service answers -/// `TagResource` and `UntagResource` on a `DELETING` table with +/// Answer a tag operation on a table that is being deleted. The service +/// answers `TagResource` and `UntagResource` on a `DELETING` table's ARN with /// `ResourceInUseException` and the sentence `DeleteTable` and `UpdateTable` /// give in that window, and serves `ListTagsOfResource` (measured -/// 2026-11-03). The key info carries no status, and the data plane reads a -/// `DELETING` table as found on PostgreSQL and SQLite, so the status is read -/// with `describe_table`. Any other answer from it is left to the existence -/// check that follows. +/// 2026-11-03). These are its answers for the first 0.6 to 2.3 s after +/// `DeleteTable` returns. After that it answers all three with +/// `ResourceNotFoundException` while `DescribeTable` still reads `DELETING` +/// (measured 2026-11-20, five runs). ExtendDB keeps the first answers for the +/// whole window. On the table's stream ARN both writes are served in the same +/// window (measured 2026-10-26), so `resource` decides: a stream's tags belong +/// to the stream, which stays describable after its table is deleted. That +/// holds for the table's latest stream only. Any other label is +/// `ResourceNotFoundException`, the service's answer for a label that names no +/// stream (measured 2026-11-20 on a `DELETING` table). The key info carries no +/// status, and the data plane reads a `DELETING` table as found on PostgreSQL +/// and SQLite, so the status is read from the catalog +/// (`table_lifecycle::read_table_description`). A failed read answers as the +/// key-info read below would: a missing table names the ARN, and any other +/// error is a fault. +/// +/// Returns whether the table is `DELETING` and the request is served: the +/// key-info read reports a `DELETING` row as not found on MongoDB and +/// Cassandra, so such a request skips it and every backend answers the window +/// the same way. async fn refuse_while_deleting( table_name: &str, + arn: &str, + resource: &str, ctx: &OperationContext, -) -> Result<(), DynamoDbError> { - if let Ok(desc) = ctx - .storage - .describe_table( - &ctx.account_id, - extenddb_core::types::DescribeTableInput { - table_name: table_name.to_owned(), - }, - ) + while_deleting: WhileDeleting, +) -> Result { + let desc = crate::table_lifecycle::read_table_description(table_name, ctx) .await - && desc.table_status == extenddb_core::types::TableStatus::Deleting - { + .map_err(|e| arn_storage_error(e, arn))?; + if desc.table_status != TableStatus::Deleting { + return Ok(false); + } + if tag_subresource_is_stream(resource) { + if desc.latest_stream_arn.as_deref() != Some(arn) { + return Err(arn_storage_error( + extenddb_storage::error::StorageError::TableNotFound(table_name.to_owned()), + arn, + )); + } + } else if while_deleting == WhileDeleting::Refuse { return Err(crate::create_table::table_being_deleted(table_name)); } - Ok(()) + Ok(true) } /// Validate that the ARN refers to an existing table owned by the caller. @@ -136,7 +159,9 @@ async fn refuse_while_deleting( /// | Table ARN with a different partition, service, or region | `ValidationException` (invalid `TableArn`) | /// | Stream ARN with a different partition, service, or region | `ValidationException` (`Invalid StreamArn`) | /// | Table does not exist | `ResourceNotFoundException` | -/// | Table is `DELETING`, for `TagResource` and `UntagResource` (`while_deleting` is `Refuse`) | `ResourceInUseException` (`Table is being deleted`) | +/// | Table is `DELETING`, for `TagResource` and `UntagResource` on the table ARN (`while_deleting` is `Refuse`) | `ResourceInUseException` (`Table is being deleted`) | +/// | Table is `DELETING`, for `ListTagsOfResource` and for the table's latest stream ARN | served | +/// | Table is `DELETING`, for a stream ARN whose label is not the table's latest stream | `ResourceNotFoundException` | /// /// Account is checked before the partition, service, and region, matching the /// service: a cross-account ARN is denied without revealing whether its other @@ -212,30 +237,41 @@ async fn validate_resource_arn( )) })?; - if while_deleting == WhileDeleting::Refuse { - refuse_while_deleting(table_name, ctx).await?; + // A served request on a DELETING table skips the key-info read, which + // reports such a row as not found on MongoDB and Cassandra. + if refuse_while_deleting(table_name, arn, resource, ctx, while_deleting).await? { + return Ok(()); } // Verify the table exists via table_key_info (lightweight check). ctx.storage .table_key_info(&ctx.account_id, table_name) .await - .map_err(|e| match e { - extenddb_storage::error::StorageError::TableNotFound(_) => { - DynamoDbError::ResourceNotFoundException(format!( - "Requested resource not found: ResourceArn: {arn} not found" - )) - } - other => sanitize_storage_error(other), - })?; + .map_err(|e| arn_storage_error(e, arn))?; Ok(()) } +/// Report a storage error from the table lookup behind a resource ARN: a +/// missing table names the ARN, as the service does, and anything else is a +/// fault. +fn arn_storage_error(e: extenddb_storage::error::StorageError, arn: &str) -> DynamoDbError { + match e { + extenddb_storage::error::StorageError::TableNotFound(_) => { + DynamoDbError::ResourceNotFoundException(format!( + "Requested resource not found: ResourceArn: {arn} not found" + )) + } + other => sanitize_storage_error(other), + } +} + /// Handle `TagResource` — add or overwrite tags on a resource. /// /// # Errors /// /// Returns `ResourceNotFoundException` if the resource does not exist. +/// Returns `ResourceInUseException` if the ARN names a table that is being +/// deleted. /// Returns `ValidationException` if the resource ARN is empty. /// Returns `InternalServerError` on storage failures. pub async fn handle_tag_resource( @@ -272,6 +308,8 @@ pub async fn handle_tag_resource( /// # Errors /// /// Returns `ResourceNotFoundException` if the resource does not exist. +/// Returns `ResourceInUseException` if the ARN names a table that is being +/// deleted. /// Returns `ValidationException` if the resource ARN is empty. /// Returns `InternalServerError` on storage failures. pub async fn handle_untag_resource( @@ -322,6 +360,10 @@ pub async fn handle_list_tags_of_resource( )); } + // Served while the table is DELETING, with the tags, as the service serves + // it in the first seconds of the window (measured 2026-10-25; the later + // answers are in `refuse_while_deleting`): the read is not a change to the + // resource. validate_resource_arn(&input.resource_arn, ctx, WhileDeleting::Serve).await?; let tags = ctx diff --git a/crates/engine/src/ttl.rs b/crates/engine/src/ttl.rs index 4b9548679..dfcf942aa 100755 --- a/crates/engine/src/ttl.rs +++ b/crates/engine/src/ttl.rs @@ -5,7 +5,7 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::types::{ - DescribeTimeToLiveInput, DescribeTimeToLiveOutput, TimeToLiveSpecificationOutput, + DescribeTimeToLiveInput, DescribeTimeToLiveOutput, TableStatus, TimeToLiveSpecificationOutput, TimeToLiveStatus, UpdateTimeToLiveInput, UpdateTimeToLiveOutput, }; use extenddb_core::validation::validate_table_name; @@ -15,10 +15,34 @@ use serde_json::Value; use crate::OperationContext; use crate::serialize_output; +/// Gate a `DescribeTimeToLive` request on the table's catalog status. +/// +/// The service refuses the call while the table is `CREATING` or `DELETING`, +/// with one sentence that names the state, and serves it while the table is +/// `ACTIVE` or `UPDATING`. Measured: `DELETING` on 2026-10-25 on three tables, +/// the refusal coming back before and after an `UpdateTimeToLive` inside the +/// same window; `CREATING` and `UPDATING` on 2026-10-26, five calls each. +/// `UpdateTimeToLive` has no equivalent refusal, so the gate is on this path +/// only. +fn check_describe_status(status: TableStatus) -> Result<(), DynamoDbError> { + let state = match status { + TableStatus::Creating => "CREATING", + TableStatus::Deleting => "DELETING", + TableStatus::Active | TableStatus::Updating => return Ok(()), + }; + Err(DynamoDbError::ValidationException( + extenddb_core::error::error_message( + extenddb_core::error::ErrorMessageKey::DescribeTtlInState, + &[state], + ), + )) +} + /// Handle `DescribeTimeToLive` — return TTL configuration for a table. /// /// # Errors /// +/// Returns `ValidationException` if the table is `CREATING` or `DELETING`. /// Returns `ResourceNotFoundException` if the table does not exist. /// Returns `InternalServerError` on storage failures. pub async fn handle_describe_time_to_live( @@ -30,6 +54,15 @@ pub async fn handle_describe_time_to_live( validate_table_name(&input.table_name, &ctx.limits)?; + // The TTL columns live on the catalog row, which outlives the status + // change, so the read below answers for a DELETING table too: the status + // is what decides, and the key-info read cannot supply it. + let status = crate::table_lifecycle::read_table_description(&input.table_name, ctx) + .await + .map_err(storage_to_dynamo)? + .table_status; + check_describe_status(status)?; + let desc = ctx .storage .describe_ttl(&ctx.account_id, &input.table_name) @@ -126,7 +159,44 @@ pub async fn handle_update_time_to_live( .await .map_err(storage_to_dynamo)?; - if input.time_to_live_specification.enabled { + // The status decides whether the index work below runs at all. It is read + // after the write, so a delete that marked the row at any point before + // this read is seen here. A mark that lands after this read and before the + // index statements is not: that work then runs on a DELETING table. A + // missing row means the delete finished after the write and removed the + // row the write landed on, so there is no index left to change. A failed + // read skips an enable's index work, with a warning, as a failed index + // statement below does: the write is made, and the TTL worker's + // pending-index pass builds the index later. A disable's drop runs after + // a failed read: skipped, the index would stay on an ACTIVE table on + // SQLite and MongoDB, where no later pass drops it (PostgreSQL's TTL + // worker drops a disabled table's index on its next pass). + let skip_index_ddl = + match crate::table_lifecycle::read_table_description(&input.table_name, ctx).await { + Ok(desc) => desc.table_status == TableStatus::Deleting, + Err(StorageError::TableNotFound(_)) => true, + Err(e) if input.time_to_live_specification.enabled => { + tracing::warn!("TTL index work skipped for {}: {e}", input.table_name); + true + } + Err(e) => { + tracing::warn!( + "TTL status read failed for {}, the index drop runs: {e}", + input.table_name + ); + false + } + }; + + if skip_index_ddl { + // No index DDL for a table being deleted: the delete removes its data + // table or collection with the index, so the catalog write above is + // the whole change. If it ran, a PostgreSQL DROP INDEX would retry for + // up to 5 s behind whatever holds the data table, and the table's + // data-plane requests would queue behind each attempt; a MongoDB + // create_index on the dropped collection would create the collection + // again, and no catalog document would be left to name it. + } else if input.time_to_live_specification.enabled { // Backends that report ENABLING (Cassandra, PostgreSQL) get the // backfill kicked off in the background: it is a full table scan, and // awaiting it made the API call take as long as the table is large. @@ -268,6 +338,36 @@ mod tests { assert!(validate_ttl_attribute_name(&max).is_ok()); } + /// DescribeTimeToLive is refused while the table is CREATING or DELETING, + /// with the service's sentence for each byte for byte, and served while it + /// is ACTIVE or UPDATING. + #[test] + fn describe_is_refused_while_creating_or_deleting() { + for (status, sentence) in [ + ( + TableStatus::Deleting, + "Cannot describe time to live while table is in DELETING state: \ + Current table state is DELETING", + ), + ( + TableStatus::Creating, + "Cannot describe time to live while table is in CREATING state: \ + Current table state is CREATING", + ), + ] { + match check_describe_status(status).unwrap_err() { + DynamoDbError::ValidationException(msg) => assert_eq!(msg, sentence), + other => panic!("expected ValidationException for {status:?}, got {other:?}"), + } + } + for status in [TableStatus::Active, TableStatus::Updating] { + assert!( + check_describe_status(status).is_ok(), + "{status:?} must be served" + ); + } + } + #[test] fn transition_gate() { use TimeToLiveStatus::{Disabled, Disabling, Enabled, Enabling}; diff --git a/crates/storage-cassandra/src/metadata_engine.rs b/crates/storage-cassandra/src/metadata_engine.rs index 412b9fcfa..04b4e85a9 100755 --- a/crates/storage-cassandra/src/metadata_engine.rs +++ b/crates/storage-cassandra/src/metadata_engine.rs @@ -951,7 +951,11 @@ impl MetadataEngine for CassandraEngine { crate::cassandra_util::get_column(&row, "table_id", "update_ttl_status")?; let previous_generation: Option = row.get_by_name("ttl_generation").ok().flatten(); - if status != "ACTIVE" { + // DELETING is admitted beside ACTIVE: the service runs + // UpdateTimeToLive's ordinary rules during the window and the write + // lands on the catalog row the delete then removes (measured + // 2026-10-25). The other non-ACTIVE statuses keep their refusal. + if status != "ACTIVE" && status != "DELETING" { return Err(StorageError::TableNotActive(table_name)); } if enabled { @@ -990,7 +994,7 @@ impl MetadataEngine for CassandraEngine { "UPDATE {}.tables SET ttl_attribute = ?, ttl_generation = ?, \ ttl_index_ready = false, ttl_backfill_cursor = null \ WHERE account_id = ? AND table_name = ? \ - IF table_status = 'ACTIVE' AND ttl_sweep_owner = null \ + IF table_status IN ('ACTIVE', 'DELETING') AND ttl_sweep_owner = null \ AND ttl_cleanup_generation = null \ AND ttl_attribute = null AND ttl_generation = null", self.catalog_keyspace() @@ -1001,7 +1005,7 @@ impl MetadataEngine for CassandraEngine { ttl_cleanup_generation = ?, ttl_index_ready = false, \ ttl_backfill_cursor = null \ WHERE account_id = ? AND table_name = ? \ - IF table_status = 'ACTIVE' AND ttl_sweep_owner = null \ + IF table_status IN ('ACTIVE', 'DELETING') AND ttl_sweep_owner = null \ AND ttl_cleanup_generation = null \ AND ttl_attribute = ? AND ttl_generation = ?", self.catalog_keyspace() diff --git a/crates/storage-cassandra/tests/direct/deleting_window.rs b/crates/storage-cassandra/tests/direct/deleting_window.rs index e45fd724d..757353d61 100644 --- a/crates/storage-cassandra/tests/direct/deleting_window.rs +++ b/crates/storage-cassandra/tests/direct/deleting_window.rs @@ -176,3 +176,54 @@ async fn update_table_on_a_creating_table_keeps_table_not_active() { ); remove_row(&engine, &account.account_id).await; } + +/// UpdateTimeToLive during the window writes the catalog row, the way the +/// service runs its ordinary TTL rules there (measured 2026-10-25), and leaves +/// the status alone. A CREATING table keeps `TableNotActive`, ExtendDB's +/// current answer: the service answers `ResourceNotFoundException` for a +/// CREATING table (measured 2026-11-20). The enable reports ENABLING, as on an +/// ACTIVE table before its backfill runs. The enable is undone before the row +/// is removed so the account keyspace's TTL entries do not outlive the test. +#[tokio::test] +async fn update_ttl_during_the_window_is_served() { + use extenddb_core::types::TimeToLiveStatus; + use extenddb_storage::MetadataEngine; + + if crate::helpers::skip_without_cassandra() { + return; + } + let (engine, account, _table) = open_window().await; + + engine + .update_ttl(&account.account_id, TABLE, "ttl", true) + .await + .expect("UpdateTimeToLive on a DELETING table"); + let desc = engine + .describe_ttl(&account.account_id, TABLE) + .await + .expect("the TTL description"); + assert_eq!(desc.attribute_name.as_deref(), Some("ttl")); + assert_eq!(desc.time_to_live_status, TimeToLiveStatus::Enabling); + assert_eq!( + status_of(&engine, &account.account_id).await.as_deref(), + Some("DELETING"), + "the write must not change the status" + ); + + engine + .update_ttl(&account.account_id, TABLE, "ttl", false) + .await + .expect("the disable direction during the window"); + + set_status(&engine, &account.account_id, "CREATING").await; + let err = engine + .update_ttl(&account.account_id, TABLE, "ttl", true) + .await + .expect_err("UpdateTimeToLive on a CREATING table"); + assert!( + matches!(&err, StorageError::TableNotActive(name) if name == TABLE), + "expected TableNotActive({TABLE:?}), got {err:?}" + ); + + remove_row(&engine, &account.account_id).await; +} diff --git a/crates/storage-mongodb/Cargo.toml b/crates/storage-mongodb/Cargo.toml index b34203e39..77912e3af 100644 --- a/crates/storage-mongodb/Cargo.toml +++ b/crates/storage-mongodb/Cargo.toml @@ -83,3 +83,6 @@ extenddb-storage = { path = "../storage", features = ["test-util"] } # need `test-util`; a dev-dependency on itself turns both on for test builds # only. extenddb-storage-mongodb = { path = ".", features = ["snapshot-test-hooks", "test-util"] } +# The DELETING-window rows call the engine's tag and TTL handlers over a +# MongoEngine (crates/storage-mongodb/src/deleting_window_tests.rs). +extenddb-engine = { path = "../engine" } diff --git a/crates/storage-mongodb/src/deleting_window_tests.rs b/crates/storage-mongodb/src/deleting_window_tests.rs index 46de42567..1947c99ea 100644 --- a/crates/storage-mongodb/src/deleting_window_tests.rs +++ b/crates/storage-mongodb/src/deleting_window_tests.rs @@ -21,6 +21,8 @@ #[path = "deleting_window_finish_tests.rs"] mod finish; +#[path = "deleting_window_ttl_tests.rs"] +mod ttl; use std::sync::Arc; diff --git a/crates/storage-mongodb/src/deleting_window_ttl_tests.rs b/crates/storage-mongodb/src/deleting_window_ttl_tests.rs new file mode 100644 index 000000000..3a0cd840d --- /dev/null +++ b/crates/storage-mongodb/src/deleting_window_ttl_tests.rs @@ -0,0 +1,344 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `UpdateTimeToLive`, the TTL index build, and the engine's tag and TTL +//! handlers while the table document is `DELETING`. The replica set and the +//! fixture come from `deleting_window_tests.rs`. + +use extenddb_core::error::DynamoDbError; +use extenddb_core::types::TimeToLiveStatus; +use serde_json::json; + +use super::*; + +impl Fixture { + /// Create `TABLE` with a stream and set its document to `DELETING`. + /// Returns the stream's ARN. + async fn open_window_with_stream(&self) -> String { + let input: CreateTableInput = serde_json::from_value(json!({ + "TableName": TABLE, + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "StreamSpecification": {"StreamEnabled": true, "StreamViewType": "KEYS_ONLY"}, + "BillingMode": "PAY_PER_REQUEST" + })) + .expect("create input"); + let desc = self + .engine + .create_table(ACCOUNT, input) + .await + .expect("create the table"); + self.set_status("DELETING").await; + desc.latest_stream_arn.expect("the table's stream ARN") + } + + /// Drop `TABLE`'s data collection, as a delete call does after it marks + /// the document `DELETING` and before it removes the document, and return + /// the collection's name. + async fn drop_data_collection(&self) -> String { + let doc = self + .engine + .catalog_db + .collection::("tables") + .find_one(doc! { "_id": { "account_id": ACCOUNT, "table_name": TABLE } }) + .await + .expect("read the table document") + .expect("the table document"); + let name = crate::data::data_collection_name(doc.get_str("table_id").expect("table_id")); + self.engine + .data_db + .collection::(&name) + .drop() + .await + .expect("drop the data collection"); + name + } + + async fn data_collections(&self) -> Vec { + self.engine + .data_db + .list_collection_names() + .await + .expect("list collections") + } +} + +/// UpdateTimeToLive during the window writes the catalog document, the way the +/// service runs its ordinary TTL rules there (measured 2026-10-25). A CREATING +/// table keeps `TableNotActive`, ExtendDB's current answer: the service +/// answers `ResourceNotFoundException` for a CREATING table (measured +/// 2026-11-20). +#[tokio::test] +async fn update_ttl_during_the_window_is_served() { + let Some(f) = Fixture::new().await else { + return; + }; + f.open_window().await; + + f.engine + .update_ttl(ACCOUNT, TABLE, "ttl", true) + .await + .expect("UpdateTimeToLive on a DELETING table"); + let desc = f + .engine + .describe_ttl(ACCOUNT, TABLE) + .await + .expect("the TTL description"); + assert_eq!(desc.time_to_live_status, TimeToLiveStatus::Enabled); + assert_eq!(desc.attribute_name.as_deref(), Some("ttl")); + assert_eq!( + f.status().await.as_deref(), + Some("DELETING"), + "the write must not change the status" + ); + + f.engine + .update_ttl(ACCOUNT, TABLE, "ttl", false) + .await + .expect("the disable direction during the window"); + let desc = f + .engine + .describe_ttl(ACCOUNT, TABLE) + .await + .expect("the TTL description"); + assert_eq!(desc.time_to_live_status, TimeToLiveStatus::Disabled); + + f.set_status("CREATING").await; + let err = f + .engine + .update_ttl(ACCOUNT, TABLE, "ttl", true) + .await + .expect_err("UpdateTimeToLive on a CREATING table"); + assert!( + matches!(&err, StorageError::TableNotActive(name) if name == TABLE), + "expected TableNotActive({TABLE:?}), got {err:?}" + ); + + f.set_status("DELETING").await; + f.finish().await; +} + +/// A TTL index build answers `TableNotActive` for a `DELETING` document before +/// `create_index`, so a build that reaches the document after the delete call +/// dropped the data collection creates no collection. MongoDB would otherwise +/// create the collection again to hold the index, and nothing would remove it +/// once the catalog document is gone. A document in another status builds the +/// index as before: an UPDATING one here. +#[tokio::test] +async fn a_ttl_index_build_refuses_a_deleting_document_only() { + let Some(f) = Fixture::new().await else { + return; + }; + f.open_window().await; + + f.set_status("UPDATING").await; + f.engine + .create_ttl_index(ACCOUNT, TABLE, "ttl") + .await + .expect("the build on an UPDATING document"); + let doc = f + .engine + .catalog_db + .collection::("tables") + .find_one(doc! { "_id": { "account_id": ACCOUNT, "table_name": TABLE } }) + .await + .expect("read the table document") + .expect("the table document"); + let indexes = f + .engine + .data_db + .collection::(&crate::data::data_collection_name( + doc.get_str("table_id").expect("table_id"), + )) + .list_index_names() + .await + .expect("list the data collection's indexes"); + assert!( + indexes.contains(&"idx_ttl_ttl".to_owned()), + "no TTL index on the UPDATING table: {indexes:?}" + ); + + f.set_status("DELETING").await; + let data_coll = f.drop_data_collection().await; + f.engine + .update_ttl(ACCOUNT, TABLE, "ttl", true) + .await + .expect("UpdateTimeToLive on a DELETING table"); + let built = f.engine.create_ttl_index(ACCOUNT, TABLE, "ttl").await; + let collections = f.data_collections().await; + assert!( + !collections.contains(&data_coll), + "{data_coll} was created again: {collections:?}" + ); + assert!( + matches!(&built, Err(StorageError::TableNotActive(name)) if name == TABLE), + "expected TableNotActive({TABLE:?}), got {built:?}" + ); + + f.finish().await; +} + +/// The engine's tag and TTL handlers against a `DELETING` document, through a +/// `MongoEngine`. The key-info read reports such a document as not found on +/// this backend, so the answers below depend on the handlers reading the +/// status first. The tag rows match the service: for the table ARN its first +/// answers after `DeleteTable` returns (measured 2026-10-25), for the stream +/// ARN its answers in the window (measured 2026-10-26), and for a stream label +/// that names no stream its `ResourceNotFoundException` (measured 2026-11-20). +/// The `DescribeTimeToLive` rows for `DELETING` and `CREATING` match it too. +/// The enable runs after the data collection is dropped, as the delete call +/// drops it before it removes the document, and leaves no collection behind. +#[tokio::test] +async fn engine_tag_and_ttl_handlers_during_the_window() { + let Some(f) = Fixture::new().await else { + return; + }; + let stream_arn = f.open_window_with_stream().await; + let ctx = extenddb_engine::OperationContext { + storage: Arc::new(f.engine.clone()), + backup: Arc::new(extenddb_engine::BackupRuntime::new(1)), + limits: Arc::new(extenddb_core::limits::LimitsConfig::default()), + region: Arc::from("us-east-1"), + account_id: Arc::from(ACCOUNT), + import_paths: Arc::from(Vec::new()), + export_paths: Arc::from(Vec::new()), + authorized_key_info: extenddb_engine::AuthorizedKeyInfo::default(), + auth_cache: extenddb_auth::AuthCacheRegistry::empty(), + table_key_info_lookup: None, + item_authorizer: None, + }; + let arn = format!("arn:aws:dynamodb:us-east-1:{ACCOUNT}:table/{TABLE}"); + // A label of the service's shape that names no stream of the table. + let made_up = format!("{arn}/stream/2000-01-01T00:00:00.000"); + let in_use = format!( + "Attempt to change a resource which is still in use: Table is being deleted: {TABLE}" + ); + let not_found = format!("Requested resource not found: ResourceArn: {made_up} not found"); + // A tag written before the delete. + f.engine + .tag_resource( + &arn, + &[Tag { + key: "env".to_owned(), + value: "test".to_owned(), + }], + ) + .await + .expect("seed a tag"); + + let tag = extenddb_engine::handle_tag_resource( + json!({"ResourceArn": arn, "Tags": [{"Key": "added", "Value": "in-window"}]}), + &ctx, + ) + .await; + assert!( + matches!(&tag, Err(DynamoDbError::ResourceInUseException(m)) if *m == in_use), + "TagResource: {tag:?}" + ); + let untag = extenddb_engine::handle_untag_resource( + json!({"ResourceArn": arn, "TagKeys": ["env"]}), + &ctx, + ) + .await; + assert!( + matches!(&untag, Err(DynamoDbError::ResourceInUseException(m)) if *m == in_use), + "UntagResource: {untag:?}" + ); + let listed = extenddb_engine::handle_list_tags_of_resource(json!({"ResourceArn": arn}), &ctx) + .await + .expect("ListTagsOfResource is served"); + assert_eq!(listed["Tags"], json!([{"Key": "env", "Value": "test"}])); + + extenddb_engine::handle_tag_resource( + json!({"ResourceArn": stream_arn, "Tags": [{"Key": "sk", "Value": "sv"}]}), + &ctx, + ) + .await + .expect("TagResource on the stream ARN is served"); + let listed = + extenddb_engine::handle_list_tags_of_resource(json!({"ResourceArn": stream_arn}), &ctx) + .await + .expect("ListTagsOfResource on the stream ARN is served"); + assert_eq!(listed["Tags"], json!([{"Key": "sk", "Value": "sv"}])); + extenddb_engine::handle_untag_resource( + json!({"ResourceArn": stream_arn, "TagKeys": ["sk"]}), + &ctx, + ) + .await + .expect("UntagResource on the stream ARN is served"); + + let tag = extenddb_engine::handle_tag_resource( + json!({"ResourceArn": made_up, "Tags": [{"Key": "fk", "Value": "fv"}]}), + &ctx, + ) + .await; + assert!( + matches!(&tag, Err(DynamoDbError::ResourceNotFoundException(m)) if *m == not_found), + "TagResource on a made-up stream label: {tag:?}" + ); + let listed = + extenddb_engine::handle_list_tags_of_resource(json!({"ResourceArn": made_up}), &ctx).await; + assert!( + matches!(&listed, Err(DynamoDbError::ResourceNotFoundException(m)) if *m == not_found), + "ListTagsOfResource on a made-up stream label: {listed:?}" + ); + assert_eq!( + f.engine + .list_tags(&made_up) + .await + .expect("read the made-up label's tag rows"), + Vec::::new(), + "no tag row is stored for a made-up stream label" + ); + + let described = + extenddb_engine::handle_describe_time_to_live(json!({"TableName": TABLE}), &ctx).await; + assert!( + matches!(&described, Err(DynamoDbError::ValidationException(m)) + if m == "Cannot describe time to live while table is in DELETING state: \ + Current table state is DELETING"), + "DescribeTimeToLive: {described:?}" + ); + + let data_coll = f.drop_data_collection().await; + let updated = extenddb_engine::handle_update_time_to_live( + json!({"TableName": TABLE, + "TimeToLiveSpecification": {"Enabled": true, "AttributeName": "ttl"}}), + &ctx, + ) + .await + .expect("UpdateTimeToLive is served"); + assert_eq!( + updated["TimeToLiveSpecification"], + json!({"Enabled": true, "AttributeName": "ttl"}) + ); + let collections = f.data_collections().await; + assert!( + !collections.contains(&data_coll), + "{data_coll} was created again: {collections:?}" + ); + let ttl = f + .engine + .describe_ttl(ACCOUNT, TABLE) + .await + .expect("the TTL description"); + assert_eq!( + ttl.attribute_name.as_deref(), + Some("ttl"), + "the catalog write landed" + ); + assert_eq!(f.status().await.as_deref(), Some("DELETING")); + + f.set_status("CREATING").await; + let described = + extenddb_engine::handle_describe_time_to_live(json!({"TableName": TABLE}), &ctx).await; + assert!( + matches!(&described, Err(DynamoDbError::ValidationException(m)) + if m == "Cannot describe time to live while table is in CREATING state: \ + Current table state is CREATING"), + "DescribeTimeToLive on CREATING: {described:?}" + ); + + drop(ctx); + f.finish().await; +} diff --git a/crates/storage-mongodb/src/metadata_engine.rs b/crates/storage-mongodb/src/metadata_engine.rs index 7fe21f9c3..5795879cb 100644 --- a/crates/storage-mongodb/src/metadata_engine.rs +++ b/crates/storage-mongodb/src/metadata_engine.rs @@ -152,9 +152,14 @@ impl MetadataEngine for MongoEngine { let result = coll .update_one( + // DELETING is admitted beside ACTIVE: the service runs + // UpdateTimeToLive's ordinary rules during the window and + // the write lands on the catalog document the delete then + // removes (measured 2026-10-25). The other non-ACTIVE + // statuses keep their refusal. doc! { "_id": { "account_id": &account_id, "table_name": &table_name }, - "table_status": "ACTIVE", + "table_status": { "$in": ["ACTIVE", "DELETING"] }, }, doc! { "$set": { @@ -352,6 +357,13 @@ impl MetadataEngine for MongoEngine { .await .map_err(|e| StorageError::Internal(e.to_string()))? .ok_or_else(|| StorageError::TableNotFound(table_name.clone()))?; + // A delete call drops the data collection after it marks the + // document DELETING, and create_index on a dropped collection + // creates it again. A build that reads the document after the mark + // refuses before create_index, which the engine logs as deferred. + if matches!(table_doc.get_str("table_status"), Ok("DELETING")) { + return Err(StorageError::TableNotActive(table_name)); + } // MongoDB interprets dots in an index key as nested traversal, // while DynamoDB treats them as part of the attribute name. The diff --git a/crates/storage-postgres/Cargo.toml b/crates/storage-postgres/Cargo.toml index 4b08d9c7a..ab78725ca 100755 --- a/crates/storage-postgres/Cargo.toml +++ b/crates/storage-postgres/Cargo.toml @@ -37,7 +37,9 @@ extenddb-storage = { path = "../storage", features = ["test-util"] } # itself turns both features on for test builds only. extenddb-storage-postgres = { path = ".", features = ["test-hooks", "test-util"] } # The store identity tests run the engine's checks over two engines on one -# scratch catalog and two filesystem stores. +# scratch catalog and two filesystem stores. The DELETING-window TTL rows call +# the engine's UpdateTimeToLive handler over a PostgresEngine, to see which +# index statements it sends for such a table. extenddb-engine = { path = "../engine" } extenddb-backup-store = { path = "../backup-store" } tempfile = "3" diff --git a/crates/storage-postgres/src/metadata_engine.rs b/crates/storage-postgres/src/metadata_engine.rs index d9ae46464..dfbd644d3 100755 --- a/crates/storage-postgres/src/metadata_engine.rs +++ b/crates/storage-postgres/src/metadata_engine.rs @@ -235,9 +235,14 @@ impl MetadataEngine for PostgresEngine { let ttl_val: Option<&str> = if enabled { Some(&attribute_name) } else { None }; let index_ready = false; + // DELETING is admitted beside ACTIVE: the service runs + // UpdateTimeToLive's ordinary rules during the window and the write + // lands on the catalog row the delete then removes (measured + // 2026-10-25). The other non-ACTIVE statuses keep their refusal. let result = sqlx::query( "UPDATE tables SET ttl_attribute = $1, ttl_index_ready = $4 \ - WHERE account_id = $2 AND table_name = $3 AND table_status = 'ACTIVE'", + WHERE account_id = $2 AND table_name = $3 \ + AND table_status IN ('ACTIVE', 'DELETING')", ) .bind(ttl_val) .bind(&account_id) diff --git a/crates/storage-postgres/tests/deleting_window.rs b/crates/storage-postgres/tests/deleting_window.rs index 1d6832f31..b85da6048 100644 --- a/crates/storage-postgres/tests/deleting_window.rs +++ b/crates/storage-postgres/tests/deleting_window.rs @@ -46,6 +46,11 @@ use extenddb_storage_postgres::{PostgresConfig, PostgresEngine}; use sqlx::PgPool; use sqlx::postgres::PgPoolOptions; +#[path = "deleting_window/tags.rs"] +mod tags; +#[path = "deleting_window/ttl.rs"] +mod ttl; + const ACCOUNT: &str = "123456789012"; const REGION: &str = "us-east-1"; const TABLE: &str = "t_deleting_window"; diff --git a/crates/storage-postgres/tests/deleting_window/tags.rs b/crates/storage-postgres/tests/deleting_window/tags.rs new file mode 100644 index 000000000..dc8014cf9 --- /dev/null +++ b/crates/storage-postgres/tests/deleting_window/tags.rs @@ -0,0 +1,56 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The tag path while a table is `DELETING`, on the window the parent module +//! opens. The handlers read the table's status from its description, because +//! the key-info read on this backend reads a `DELETING` row as found. + +use extenddb_core::error::DynamoDbError; +use extenddb_storage::MetadataEngine; +use serde_json::json; + +use super::ttl::engine_context; +use super::{ACCOUNT, TABLE, base_conn, open_window, scratch, skip}; + +/// A failed status read answers a tag write as a fault, as the TTL handlers +/// answer it, and writes no tag. The key-info read after it would read the +/// `DELETING` row as found and accept the write. The description reads +/// `table_restores` and the key-info read does not, so the read fails here +/// once that table is renamed. +#[tokio::test] +async fn a_failed_status_read_refuses_a_tag_write() { + if base_conn().is_none() { + return skip("a_failed_status_read_refuses_a_tag_write"); + } + let s = scratch().await; + open_window(&s).await; + sqlx::query("ALTER TABLE table_restores RENAME TO table_restores_hidden") + .execute(&s.catalog) + .await + .expect("rename table_restores"); + + let ctx = engine_context(&s); + let arn = format!("arn:aws:dynamodb:us-east-1:{ACCOUNT}:table/{TABLE}"); + let tagged = extenddb_engine::handle_tag_resource( + json!({"ResourceArn": arn, "Tags": [{"Key": "k", "Value": "v"}]}), + &ctx, + ) + .await; + assert!( + matches!(&tagged, Err(DynamoDbError::InternalServerError(m)) if m == "Internal server error"), + "TagResource after a failed status read: {tagged:?}" + ); + drop(ctx); + + sqlx::query("ALTER TABLE table_restores_hidden RENAME TO table_restores") + .execute(&s.catalog) + .await + .expect("rename table_restores back"); + assert_eq!( + s.engine.list_tags(&arn).await.expect("read the tag rows"), + Vec::new(), + "no tag row was written" + ); + + s.cleanup().await; +} diff --git a/crates/storage-postgres/tests/deleting_window/ttl.rs b/crates/storage-postgres/tests/deleting_window/ttl.rs new file mode 100644 index 000000000..3bd80687d --- /dev/null +++ b/crates/storage-postgres/tests/deleting_window/ttl.rs @@ -0,0 +1,301 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `UpdateTimeToLive` while a table is `DELETING`, on the window the parent +//! module opens. Amazon DynamoDB runs the ordinary TTL rules on a `DELETING` +//! table (measured 2026-10-25), so the catalog write is admitted beside +//! `ACTIVE` and refused for the other statuses. The delete removes the data +//! table with its index, so the engine sends no index DDL for such a table. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use extenddb_storage::MetadataEngine; +use serde_json::json; + +use super::{ + ACCOUNT, Scratch, TABLE, base_conn, create_table_named, open_window, scratch, skip, + start_deleting, status_of, +}; + +/// UpdateTimeToLive by the status of `TABLE`'s catalog row, on one window, +/// row after row. DELETING is admitted beside ACTIVE in both directions, the +/// way the service runs its ordinary TTL rules in the window (measured +/// 2026-10-25): the write lands on the row and leaves the status alone. A +/// CREATING table keeps `TableNotActive` and a missing one `TableNotFound`, +/// ExtendDB's current answers: the service answers `ResourceNotFoundException` +/// for a CREATING table (measured 2026-11-20). +#[tokio::test] +async fn update_ttl_by_table_status() { + // (status of `TABLE`, table named, the calls' `enabled` in order, the + // stored `ttl_attribute` after them or the last call's error) + type Row = ( + &'static str, + &'static str, + &'static [bool], + Result, String>, + ); + if base_conn().is_none() { + return skip("update_ttl_by_table_status"); + } + let s = scratch().await; + open_window(&s).await; + + let rows: [Row; 4] = [ + ("DELETING", TABLE, &[true], Ok(Some("ttl"))), + ("DELETING", TABLE, &[true, false], Ok(None)), + ( + "CREATING", + TABLE, + &[true], + Err(format!("TableNotActive({TABLE:?})")), + ), + ( + "DELETING", + "t_absent", + &[true], + Err("TableNotFound(\"t_absent\")".to_owned()), + ), + ]; + for (status, table, calls, expected) in rows { + let row = format!("{status} {table} {calls:?}"); + sqlx::query( + "UPDATE tables SET table_status = $1 WHERE account_id = $2 AND table_name = $3", + ) + .bind(status) + .bind(ACCOUNT) + .bind(TABLE) + .execute(&s.catalog) + .await + .expect("set the status"); + let (last, earlier) = calls.split_last().expect("one call at least"); + for &enabled in earlier { + s.engine + .update_ttl(ACCOUNT, table, "ttl", enabled) + .await + .unwrap_or_else(|e| panic!("{row}: an earlier call failed: {e:?}")); + } + let result = s.engine.update_ttl(ACCOUNT, table, "ttl", *last).await; + match expected { + Ok(attribute) => { + result.unwrap_or_else(|e| panic!("{row}: {e:?}")); + let stored: Option = sqlx::query_scalar( + "SELECT ttl_attribute FROM tables WHERE account_id = $1 AND table_name = $2", + ) + .bind(ACCOUNT) + .bind(table) + .fetch_one(&s.catalog) + .await + .expect("read the TTL attribute"); + assert_eq!(stored.as_deref(), attribute, "{row}"); + } + Err(error) => assert_eq!(format!("{:?}", result.expect_err(&row)), error, "{row}"), + } + assert_eq!( + status_of(&s.catalog, TABLE).await.as_deref(), + Some(status), + "{row}: the write must not change the status" + ); + } + + s.cleanup().await; +} + +/// The TTL index names in the scratch data database, which holds one table. +async fn ttl_indexes(s: &Scratch) -> Vec { + sqlx::query_scalar("SELECT indexname FROM pg_indexes WHERE indexname LIKE 'idx\\_ttl\\_%'") + .fetch_all(s.engine.data_pool()) + .await + .expect("list the TTL indexes") +} + +/// The engine's request context over the scratch engine. +pub(super) fn engine_context(s: &Scratch) -> extenddb_engine::OperationContext { + extenddb_engine::OperationContext { + storage: Arc::new(s.engine.clone()), + backup: Arc::new(extenddb_engine::BackupRuntime::new(1)), + limits: Arc::new(extenddb_core::limits::LimitsConfig::default()), + region: Arc::from("us-east-1"), + account_id: Arc::from(ACCOUNT), + import_paths: Arc::from(Vec::new()), + export_paths: Arc::from(Vec::new()), + authorized_key_info: extenddb_engine::AuthorizedKeyInfo::default(), + auth_cache: extenddb_auth::AuthCacheRegistry::empty(), + table_key_info_lookup: None, + item_authorizer: None, + } +} + +/// Create `TABLE`, enable TTL on `ttl` and build its index while the table is +/// ACTIVE. Returns the index names. +async fn table_with_a_ttl_index(s: &Scratch) -> Vec { + create_table_named(s, TABLE).await; + s.engine + .update_ttl(ACCOUNT, TABLE, "ttl", true) + .await + .expect("enable TTL while ACTIVE"); + s.engine + .create_ttl_index(ACCOUNT, TABLE, "ttl") + .await + .expect("build the TTL index while ACTIVE"); + let built = ttl_indexes(s).await; + assert_eq!(built.len(), 1, "one TTL index before the delete: {built:?}"); + built +} + +/// The disable request the handler tests send. +fn disable_ttl() -> serde_json::Value { + json!({"TableName": TABLE, + "TimeToLiveSpecification": {"Enabled": false, "AttributeName": "ttl"}}) +} + +/// Assert what a disable through the handler left: no DROP INDEX was sent +/// (the index built while the table was ACTIVE is still there), the catalog +/// write landed, and the row is DELETING. +async fn assert_disabled_without_drop_index(s: &Scratch, built: &[String]) { + assert_eq!(ttl_indexes(s).await, built, "no DROP INDEX was sent"); + let attr: Option = sqlx::query_scalar( + "SELECT ttl_attribute FROM tables WHERE account_id = $1 AND table_name = $2", + ) + .bind(ACCOUNT) + .bind(TABLE) + .fetch_one(&s.catalog) + .await + .expect("read the TTL attribute"); + assert_eq!(attr, None, "the catalog write landed"); + assert_eq!( + status_of(&s.catalog, TABLE).await.as_deref(), + Some("DELETING") + ); +} + +/// UpdateTimeToLive disabling TTL during the window, through the engine +/// handler, sends no DROP INDEX. +#[tokio::test] +async fn update_ttl_disable_during_the_window_sends_no_drop_index() { + if base_conn().is_none() { + return skip("update_ttl_disable_during_the_window_sends_no_drop_index"); + } + let s = scratch().await; + let built = table_with_a_ttl_index(&s).await; + start_deleting(&s).await; + + let ctx = engine_context(&s); + let out = extenddb_engine::handle_update_time_to_live(disable_ttl(), &ctx) + .await + .expect("UpdateTimeToLive disable during the window"); + assert_eq!( + out["TimeToLiveSpecification"], + json!({"Enabled": false, "AttributeName": "ttl"}) + ); + drop(ctx); + assert_disabled_without_drop_index(&s, &built).await; + + s.cleanup().await; +} + +/// A disable whose status read after the write fails still drops the TTL +/// index of the ACTIVE table: skipping it, as an enable skips its index +/// work, left the index on the table. The read fails because +/// `table_restores`, which `describe_table` reads and the TTL write does not, +/// is renamed for the call. +#[tokio::test] +async fn a_failed_status_read_after_a_disable_still_drops_the_index() { + if base_conn().is_none() { + return skip("a_failed_status_read_after_a_disable_still_drops_the_index"); + } + let s = scratch().await; + table_with_a_ttl_index(&s).await; + sqlx::query("ALTER TABLE table_restores RENAME TO table_restores_hidden") + .execute(&s.catalog) + .await + .expect("hide table_restores"); + + let ctx = engine_context(&s); + let out = extenddb_engine::handle_update_time_to_live(disable_ttl(), &ctx).await; + drop(ctx); + sqlx::query("ALTER TABLE table_restores_hidden RENAME TO table_restores") + .execute(&s.catalog) + .await + .expect("restore table_restores"); + let out = out.expect("UpdateTimeToLive disable with a failed status read"); + assert_eq!( + out["TimeToLiveSpecification"], + json!({"Enabled": false, "AttributeName": "ttl"}) + ); + assert_eq!(ttl_indexes(&s).await, Vec::::new(), "the drop ran"); + assert_eq!( + status_of(&s.catalog, TABLE).await.as_deref(), + Some("ACTIVE") + ); + + s.cleanup().await; +} + +/// A DELETING mark that commits while the handler's UpdateTimeToLive write +/// waits for the row lock is seen by the handler's status read, which comes +/// after the write, so the disable sends no DROP INDEX. The test holds the +/// row with `SELECT ... FOR UPDATE`, as the control-plane pass holds a due +/// DELETING row, sends the disable, waits until the handler's UPDATE waits for +/// that lock, then marks the row DELETING and commits. A status read made +/// before the write would have read ACTIVE and dropped the index. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_mark_committed_during_the_ttl_write_sends_no_drop_index() { + if base_conn().is_none() { + return skip("a_mark_committed_during_the_ttl_write_sends_no_drop_index"); + } + let s = scratch().await; + let built = table_with_a_ttl_index(&s).await; + + let mut holder = s.catalog.begin().await.expect("begin the row lock holder"); + sqlx::query("SELECT table_id FROM tables WHERE account_id = $1 AND table_name = $2 FOR UPDATE") + .bind(ACCOUNT) + .bind(TABLE) + .fetch_one(&mut *holder) + .await + .expect("lock the catalog row"); + + let ctx = engine_context(&s); + let disable = tokio::spawn(async move { + extenddb_engine::handle_update_time_to_live(disable_ttl(), &ctx).await + }); + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let waiting: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_stat_activity WHERE datname = current_database() \ + AND wait_event_type = 'Lock' AND query LIKE 'UPDATE tables SET ttl_attribute%'", + ) + .fetch_one(&s.catalog) + .await + .expect("read pg_stat_activity"); + if waiting == 1 { + break; + } + assert!( + Instant::now() < deadline && !disable.is_finished(), + "the handler's TTL write never waited for the row lock" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + sqlx::query( + "UPDATE tables SET table_status = 'DELETING' WHERE account_id = $1 AND table_name = $2", + ) + .bind(ACCOUNT) + .bind(TABLE) + .execute(&mut *holder) + .await + .expect("mark the row DELETING"); + holder.commit().await.expect("commit the mark"); + + let out = disable + .await + .expect("the handler task") + .expect("UpdateTimeToLive disable"); + assert_eq!( + out["TimeToLiveSpecification"], + json!({"Enabled": false, "AttributeName": "ttl"}) + ); + assert_disabled_without_drop_index(&s, &built).await; + + s.cleanup().await; +} diff --git a/crates/storage-sqlite/src/delete_table.rs b/crates/storage-sqlite/src/delete_table.rs index 300e4f47f..117293b0c 100644 --- a/crates/storage-sqlite/src/delete_table.rs +++ b/crates/storage-sqlite/src/delete_table.rs @@ -203,9 +203,9 @@ impl SqliteEngine { #[cfg(test)] mod tests { - use extenddb_core::types::{DeleteTableInput, UpdateTableInput}; - use extenddb_storage::TableEngine; + use extenddb_core::types::{DeleteTableInput, TimeToLiveStatus, UpdateTableInput}; use extenddb_storage::error::StorageError; + use extenddb_storage::{MetadataEngine, TableEngine}; use serde_json::json; use crate::SqliteEngine; @@ -331,6 +331,84 @@ mod tests { ); } + /// UpdateTimeToLive by the status of `t`'s catalog row, each row on a fresh + /// engine. DELETING is admitted beside ACTIVE in both directions, the way + /// the service runs its ordinary TTL rules in the window (measured + /// 2026-10-25), and the write leaves the status alone. A CREATING table + /// keeps `TableNotActive` and a missing one `TableNotFound`, ExtendDB's + /// current answers: the service answers `ResourceNotFoundException` for a + /// CREATING table (measured 2026-11-20). + #[tokio::test] + async fn update_ttl_by_table_status() { + // (status of `t`, table named, the calls' `enabled` in order, the TTL + // description after them or the last call's error) + type Row = ( + &'static str, + &'static str, + &'static [bool], + Result<(TimeToLiveStatus, Option<&'static str>), &'static str>, + ); + let rows: [Row; 4] = [ + ( + "DELETING", + "t", + &[true], + Ok((TimeToLiveStatus::Enabled, Some("ttl"))), + ), + ( + "DELETING", + "t", + &[true, false], + Ok((TimeToLiveStatus::Disabled, None)), + ), + ("CREATING", "t", &[true], Err("TableNotActive(\"t\")")), + ( + "DELETING", + "absent", + &[true], + Err("TableNotFound(\"absent\")"), + ), + ]; + for (status, table, calls, expected) in rows { + let row = format!("{status} {table} {calls:?}"); + let engine = engine_with_deleting_table().await; + sqlx::query("UPDATE tables SET table_status = ? WHERE table_name = 't'") + .bind(status) + .execute(&engine.pool) + .await + .expect("set the status"); + let (last, earlier) = calls.split_last().expect("one call at least"); + for &enabled in earlier { + engine + .update_ttl(ACCOUNT, table, "ttl", enabled) + .await + .unwrap_or_else(|e| panic!("{row}: an earlier call failed: {e:?}")); + } + let result = engine.update_ttl(ACCOUNT, table, "ttl", *last).await; + match expected { + Ok(described) => { + result.unwrap_or_else(|e| panic!("{row}: {e:?}")); + let desc = engine + .describe_ttl(ACCOUNT, table) + .await + .expect("the TTL description"); + assert_eq!( + (desc.time_to_live_status, desc.attribute_name.as_deref()), + described, + "{row}" + ); + } + Err(error) => assert_eq!(format!("{:?}", result.expect_err(&row)), error, "{row}"), + } + let after: String = + sqlx::query_scalar("SELECT table_status FROM tables WHERE table_name = 't'") + .fetch_one(&engine.pool) + .await + .expect("row still present"); + assert_eq!(after, status, "{row}: the write must not change the status"); + } + } + /// `CONCURRENT` DeleteTables on `t` at once; each takes the write lock /// before it reads the table. async fn delete_concurrently( diff --git a/crates/storage-sqlite/src/metadata.rs b/crates/storage-sqlite/src/metadata.rs index dba5f6de2..f74a03dfd 100644 --- a/crates/storage-sqlite/src/metadata.rs +++ b/crates/storage-sqlite/src/metadata.rs @@ -93,9 +93,14 @@ impl MetadataEngine for SqliteEngine { // D1: every writer holds the engine write lock. let _writer = self.write_lock.lock().await; let ttl_val: Option<&str> = if enabled { Some(&attribute_name) } else { None }; + // DELETING is admitted beside ACTIVE: the service runs + // UpdateTimeToLive's ordinary rules during the window and the write + // lands on the catalog row the delete then removes (measured + // 2026-10-25). The other non-ACTIVE statuses keep their refusal. let result = sqlx::query( "UPDATE tables SET ttl_attribute = ?, ttl_index_ready = 0 \ - WHERE account_id = ? AND table_name = ? AND table_status = 'ACTIVE'", + WHERE account_id = ? AND table_name = ? \ + AND table_status IN ('ACTIVE', 'DELETING')", ) .bind(ttl_val) .bind(&account_id) diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index dc17dbad8..f2d3a4cf0 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -57,7 +57,7 @@ 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: `. The data plane is served for the first part of the window only. In windows of 6.4 to 8.1 s, the service served `PutItem`, `GetItem`, `Query` and `Scan` for the first 2.7 to 5.7 s. It served the batch, transaction and PartiQL calls for the first 0.5 to 2.1 s. After that they answer `ResourceNotFoundException` while `DescribeTable` still reads `DELETING` (measured 2026-11-27). A write made in the window goes away with the table (measured 2026-10-25) | The same control-plane answers on PostgreSQL and SQLite. The data plane is served for the whole window, not only its first seconds. The window lasts 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: `. The data plane is served for the first part of the window only. In windows of 6.4 to 8.1 s, the service served `PutItem`, `GetItem`, `Query` and `Scan` for the first 2.7 to 5.7 s. It served the batch, transaction and PartiQL calls for the first 0.5 to 2.1 s. After that they answer `ResourceNotFoundException` while `DescribeTable` still reads `DELETING` (measured 2026-11-27). A write made in the window goes away with the table (measured 2026-10-25). `DescribeTimeToLive` answers `ValidationException` `Cannot describe time to live while table is in DELETING state: Current table state is DELETING`, and `UpdateTimeToLive` runs the rules it applies to an `ACTIVE` table (measured 2026-10-25) for the first 0.3 to 1.2 s after `DeleteTable` returns. After that it answers 400 `ResourceInUseException` `Attempt to change a resource which is still in use: Table is being deleted` while `DescribeTable` still reads `DELETING` (measured 2026-11-24). For the first 0.6 to 2.3 s after `DeleteTable` returns, `TagResource` and `UntagResource` on the table ARN answer the `Table is being deleted` sentence and `ListTagsOfResource` lists the tags. After that the three answer `ResourceNotFoundException` while `DescribeTable` still reads `DELETING` (measured 2026-11-20). On the table's stream ARN the three are served (measured 2026-10-26) | The same control-plane answers on PostgreSQL and SQLite. The data plane is served for the whole window, not only its first seconds. The window lasts 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. On all four backends `DescribeTimeToLive`, `UpdateTimeToLive` and the tag calls give the service's first answers for as long as the row is `DELETING`. The `DELETING` rows under Time to Live (TTL) and Tagging list where they differ | | `DeleteTable` of a `DELETING` table | `ResourceInUseException`: "Attempt to change a resource which is still in use: Table is being deleted: " (measured 2026-11-30; the API reference says no error is returned) | The same on PostgreSQL and SQLite while the table is `DELETING`. With a `control_plane_delay_seconds` below 1 (the default is 0.25) SQLite, and PostgreSQL with one shared database when no reader holds the table, remove the table in the first `DeleteTable`, so a concurrent `DeleteTable` waits for it and answers `ResourceNotFoundException`. Otherwise (a delay of 1 or more, a separate PostgreSQL data database, or a PostgreSQL drop deferred by a reader) the table is `DELETING` and concurrent calls answer the 400. Cassandra removes a table in the request, but a restore target whose restore failed is `DELETING` while the restore reconciler removes it, and a `DeleteTable` in that window is refused the same way. On MongoDB a table is `DELETING` while a `DeleteTable` runs, and after one that failed or stopped before it removed the table, until the control plane finishes that delete 60 seconds after the mark; a `DeleteTable` in that time is refused the same way | | The description of a DELETING table | `DeleteTable`'s answer and `DescribeTable` at the start of the window carry no `KeySchema`, `AttributeDefinitions`, `CreationDateTime`, `WarmThroughput`, `GlobalSecondaryIndexes`, `LocalSecondaryIndexes` or `VectorIndexes`, and keep the other members the table has. Later in the window (it lasted 3.5 to 9.5 seconds in 36 measured runs) the answer first loses `StreamSpecification`, then carries only `ItemCount`, `ProvisionedThroughput`, `TableArn`, `TableName`, `TableSizeBytes` and `TableStatus` (measured 2026-11-23) | Both calls carry the start-of-window shape throughout. A client that reads `DescribeTable` late in a long window sees more members than the service sends. MongoDB and Cassandra remove a table inside the request and show no window, except a Cassandra restore target whose restore failed, which is described this way while the restore reconciler removes it | | 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)) | @@ -90,6 +90,7 @@ from a request sent to that service or backend. | Cassandra TTL deployment bounds | Managed by the service | Writes for a table must be served from one Cassandra datacenter — claims and lifecycle LWTs use `LOCAL_QUORUM`/`LOCAL_SERIAL` and are linearizable only within a datacenter. Cassandra coordinators and ExtendDB hosts must remain time-synchronized because request batches use explicit timestamps, and request deadlines must stay well below the 120-second request claim lifetime. A write whose queue mutation loses an internal race is repaired by the background outbox; an ambiguous queue destroy retains a non-dischargeable marker that is rechecked every worker pass. | | Cassandra TTL lifecycle contention | Not observable | Enabling or disabling TTL, and creating an index that would invalidate a live sweep, take a short lease and retry briefly. Sustained collision reports `ResourceInUseException` with a retry hint. | | TTL modification cooldown | Enforces a cooldown period between enable/disable changes ("Time to live has been modified multiple times within a fixed interval") | No cooldown — TTL can be enabled and disabled immediately. Intentional divergence for faster local development. | +| `DescribeTimeToLive` and `UpdateTimeToLive` on a table that is not `ACTIVE` | `DescribeTimeToLive` is refused while the table is `CREATING` or `DELETING`, with `Cannot describe time to live while table is in state: Current table state is ` (measured 2026-10-25 and 2026-10-26), and served while it is `UPDATING`. `UpdateTimeToLive` on a `DELETING` table runs the rules it applies to an `ACTIVE` one: a second enable answers `TimeToLive is already enabled` (measured 2026-10-25). It does so for the first 0.3 to 1.2 s after `DeleteTable` returns. After that it answers 400 `ResourceInUseException` `Attempt to change a resource which is still in use: Table is being deleted` while `DescribeTable` still reads `DELETING` (measured 2026-11-24). It answers `ResourceNotFoundException` on a `CREATING` table and is served on an `UPDATING` one (measured 2026-11-20) | `DescribeTimeToLive` matches on all four backends. `UpdateTimeToLive` on a `DELETING` table is served for as long as the row is `DELETING`, not only for the first 0.3 to 1.2 s (#1460). It writes the catalog row and sends no index statement, because `DeleteTable` deletes the data table with its index. PostgreSQL and Cassandra then report `ENABLING` for the rest of the window, so a later `UpdateTimeToLive` in the window answers `Time to live is being updated for this table. Retry the request once the current change completes.` SQLite and MongoDB report `ENABLED` at once. On PostgreSQL the write on a `DELETING` row has no lock timeout. It waits for the row lock that the control-plane pass holds while it drops the table. On a `CREATING` or `UPDATING` table `UpdateTimeToLive` answers `ResourceInUseException` `Table is not in ACTIVE state` | ## Tagging @@ -99,6 +100,7 @@ from a request sent to that service or backend. | `ResourceArn` naming a backup (`table//backup/`) | Backups take no tags: `TagResource`, `UntagResource`, and `ListTagsOfResource` take table and stream ARNs, and the authorization reference lists no `aws:ResourceTag` key for the backup resource. The service's reply to a backup ARN was not measured | `TagResource`, `UntagResource`, and `ListTagsOfResource` refuse it with `ValidationException` ("One or more parameter values were invalid: Provided Arn is not a DynamoDB resource arn: "), the reply already given for an ARN whose resource is not `table/...`. So are `table//backup`, `table//backup/`, and any longer path under a backup. Another account's backup ARN is `AccessDeniedException` "Access is denied" when this deployment's catalog does not hold the account and gets this `ValidationException` when it does, as on the service (measured); another region's stays the region `ValidationException`, and the table is not looked up. Earlier builds accepted a backup ARN and stored its tags; such tags stay in storage but nothing reads them: `ListTagsOfResource` and `UntagResource` refuse the ARN, and authorization ignores them (see "Tag conditions on backups" under Backup and Restore). `TagResource` and `UntagResource` are still authorized against `table/*`, so a policy statement on `table/*/backup/*` does not apply to them. Measured on PostgreSQL and SQLite; the check is in the engine, the same for every backend | | Tag condition keys on tag operations | `aws:RequestTag/` and `aws:TagKeys` are populated for `TagResource` and `CreateTable`, and `aws:TagKeys` for `UntagResource` (service authorization reference, dynamodb v1.5). Whether `CreateTable` with `Tags` is also authorized as `dynamodb:TagResource` was not measured | The same three operations populate the same keys, and every other operation leaves both absent. The operator semantics (set operators, `Null`, a bare negated operator on an absent `aws:TagKeys`, tag name case) come from `iam simulate-custom-policy` runs, not from DynamoDB requests. A request that names one tag under two spellings with differing values fails closed: a `Deny` that reads the key blocks and an `Allow` that reads it does not grant; the service's answer was not measured. The variable `${aws:TagKeys}` in a condition value has no value: a positive operator is false against it and a negated one true (measured with the IAM policy simulator on 2026-10-27), and its text is not compared (measured the same way on 2026-10-31). On a table resource policy a `StringEquals` `Deny` with it did not apply for either tag order (measured 2026-10-27). Tag names in `aws:RequestTag/` match without regard to case on both (`Étag` and `étag` match on the service), but ExtendDB's Unicode case folding also equates the sharp s with `ss` (`Straße` and `STRASSE`), which the service does not (measured on IAM and on a table resource policy, 2026-10-27). An `Allow` gated on `aws:RequestTag/STRASSE` grants a request carrying `Straße` on ExtendDB where the service would not (inferred from the same measurement; the Allow direction was not run) | | A tag key repeated in one `TagResource` or `CreateTable` request | `ValidationException` "Duplicate Tag Keys provided as input: Duplicate Tag Key found " on both operations (measured 2026-10-27), and nothing is stored | `TagResource` accepts it and stores the last value, and authorization reads that value. `CreateTable` answers HTTP 500 `InternalServerError` on SQLite and PostgreSQL and creates nothing, because the tags are inserted with a plain `INSERT`. Measured on SQLite and PostgreSQL on 2026-10-27 | +| Tag requests during a table's `DELETING` window | The answers change during the window: see "Requests during a table's `DELETING` window" under Control Plane. Two tag writes that change nothing are served with 200 (measured 2026-11-20). One is a `TagResource` of a tag the table holds, with the same value. The other is an `UntagResource` of a key the table does not carry. A stream ARN whose label names no stream is `ResourceNotFoundException` `Requested resource not found: ResourceArn: not found` (measured 2026-11-20) | `TagResource` and `UntagResource` on the table ARN are refused for the whole window, a write that changes no tag included. `ListTagsOfResource` lists the tags for the whole window. The table's latest stream ARN is served. A stream ARN with another label gets the service's `ResourceNotFoundException`. On PostgreSQL and SQLite a tag write can read the status before `DeleteTable` marks the row and write after `DeleteTable` deleted the table's tag rows. The next table created with that name then lists that tag | ## Query diff --git a/tests/python/test_deleting_window_control_plane.py b/tests/python/test_deleting_window_control_plane.py index 0796483db..410c5ea42 100644 --- a/tests/python/test_deleting_window_control_plane.py +++ b/tests/python/test_deleting_window_control_plane.py @@ -15,6 +15,20 @@ ``DELETING`` (measured 2026-11-27), so these tests send their requests at once after ``DeleteTable``. ExtendDB serves them for the whole window. +``TagResource`` and ``UntagResource`` on the table ARN answer that same +sentence in the window and ``ListTagsOfResource`` is served with the tags; on +the table's stream ARN all three are served (measured 2026-10-26). The +table-ARN answers hold for the first 0.6 to 2.3 s after ``DeleteTable`` +returns; after that the service answers all three with +``ResourceNotFoundException`` ``Requested resource not found: ResourceArn: + not found`` while ``DescribeTable`` still reads ``DELETING`` (measured +2026-11-20, five runs), and the stream ARN stays served. The tests assert the +first answer after ``DeleteTable``. ``DescribeTimeToLive`` answers +``ValidationException`` ``Cannot describe time to live while table is in +DELETING state: Current table state is DELETING``, and ``UpdateTimeToLive`` is +served and answers with the specification it wrote (both measured +2026-10-25). + Against the service these tests run on its natural window. Against ExtendDB on PostgreSQL the window is held open the way a slow reader would hold it: an outside transaction keeps ``ACCESS SHARE`` on the table's data table, so the @@ -33,6 +47,7 @@ from __future__ import annotations import os +import time import pytest from botocore.exceptions import ClientError @@ -89,10 +104,11 @@ def _skip_unless_window_can_be_held(dynamodb_client, name: str) -> None: def _open_window( - dynamodb_client, is_extenddb: bool, name: str, with_index: bool = False + dynamodb_client, is_extenddb: bool, name: str, with_index: bool = False, stream: bool = False ) -> _HeldLock | None: - """Create the table (with a GSI ``gsi1`` on ``gk`` when ``with_index``) and, on - ExtendDB, hold the lock that keeps it DELETING.""" + """Create the table (with a GSI ``gsi1`` on ``gk`` when ``with_index``, with a + stream when ``stream`` is set) and, on ExtendDB, hold the lock that keeps it + DELETING.""" attributes = [{"AttributeName": "pk", "AttributeType": "S"}] extra = {} if with_index: @@ -104,6 +120,8 @@ def _open_window( "Projection": {"ProjectionType": "ALL"}, } ] + if stream: + extra["StreamSpecification"] = {"StreamEnabled": True, "StreamViewType": "KEYS_ONLY"} dynamodb_client.create_table( TableName=name, AttributeDefinitions=attributes, @@ -125,6 +143,26 @@ def _assert_in_use(exc: ClientError, name: str) -> None: assert err["Message"] == _being_deleted(name) +def _delete_table_after_tag_write(dynamodb_client, name: str): + """DeleteTable, retried while the service refuses it after a tag write. + + For a few seconds after ``TagResource`` or ``UntagResource`` the service + answers ``DeleteTable`` on the table with ``ResourceInUseException`` + ``Attempt to change a resource which is still in use: Table tags are being + updated: `` (measured 2026-10-26 and 2026-11-20). A retried + ``DeleteTable`` starts no new tag update, where another tag write would. + ExtendDB has no such state, so its first ``DeleteTable`` is answered. + """ + for _ in range(30): + try: + return dynamodb_client.delete_table(TableName=name) + except ClientError as exc: + if "tags are being updated" not in exc.response["Error"]["Message"]: + raise + time.sleep(1) + raise TimeoutError(f"DeleteTable of {name} was still refused after 30 attempts") + + class TestDeletingWindowControlPlane: def test_second_delete_table_is_being_deleted(self, dynamodb_client, is_extenddb): """A second DeleteTable while the first is still running is ResourceInUseException.""" @@ -158,13 +196,16 @@ def test_update_table_is_being_deleted(self, dynamodb_client, is_extenddb): def test_tag_changes_are_being_deleted_and_tags_are_listed(self, dynamodb_client, is_extenddb): """TagResource and UntagResource while the table is DELETING are ResourceInUseException with the DELETING sentence, and ListTagsOfResource lists the tag the table had before - DeleteTable (measured 2026-11-03).""" + DeleteTable (measured 2026-11-03). On the service these are the first answers after + DeleteTable, which hold for 0.6 to 2.3 s (measured 2026-11-20).""" name = unique_name("del-window") lock = _open_window(dynamodb_client, is_extenddb, name) + deleted = False try: arn = dynamodb_client.describe_table(TableName=name)["Table"]["TableArn"] dynamodb_client.tag_resource(ResourceArn=arn, Tags=[{"Key": "k1", "Value": "v1"}]) - dynamodb_client.delete_table(TableName=name) + _delete_table_after_tag_write(dynamodb_client, name) + deleted = True with pytest.raises(ClientError) as exc: dynamodb_client.tag_resource(ResourceArn=arn, Tags=[{"Key": "k2", "Value": "v2"}]) _assert_in_use(exc.value, name) @@ -176,6 +217,8 @@ def test_tag_changes_are_being_deleted_and_tags_are_listed(self, dynamodb_client finally: if lock is not None: lock.release() + if not deleted: + _delete_table_after_tag_write(dynamodb_client, name) wait_for_deleted(dynamodb_client, name, timeout=120.0) @@ -264,3 +307,140 @@ 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") + + +_DESCRIBE_TTL_REFUSED = ( + "ValidationException", + "Cannot describe time to live while table is in DELETING state: " + "Current table state is DELETING", +) +_MADE_UP_NOT_FOUND = ( + "ResourceNotFoundException", + "Requested resource not found: ResourceArn: {made_up} not found", +) +_TTL_ON = {"Enabled": True, "AttributeName": "ttl"} +_STREAM_TAG = [{"Key": "sk", "Value": "sv"}] + +# The TTL calls and the stream ARN tag calls in the window, one table per row: +# on the service a tag write starts a tag update that refuses the next tag +# write on the resource for a few seconds. A row is (the table has a stream, +# steps before DeleteTable, steps after it). A step is (operation, request, +# answer), where the answer is the response body or an (error code, message) +# pair. ``{name}``, ``{stream}`` (the table's LatestStreamArn) and +# ``{made_up}`` (a stream ARN of the table whose label names no stream) are +# filled in per table. Measured: the TTL rows 2026-10-25 (three tables, every +# call while DescribeTable read DELETING, the DescribeTimeToLive refusal before +# and after an UpdateTimeToLive); the stream ARN rows 2026-10-26; the made-up +# label 2026-11-20 on a DELETING table and 2026-11-24 on a table that does not +# exist. +WINDOW_ROWS = [ + pytest.param( + False, + [], + [("describe_time_to_live", {"TableName": "{name}"}, _DESCRIBE_TTL_REFUSED)], + id="describe-ttl", + ), + pytest.param( + False, + [], + [ + ( + "update_time_to_live", + {"TableName": "{name}", "TimeToLiveSpecification": _TTL_ON}, + {"TimeToLiveSpecification": _TTL_ON}, + ), + ("describe_time_to_live", {"TableName": "{name}"}, _DESCRIBE_TTL_REFUSED), + ], + id="update-ttl", + ), + pytest.param( + True, + [], + [("tag_resource", {"ResourceArn": "{stream}", "Tags": _STREAM_TAG}, {})], + id="tag-stream", + ), + pytest.param( + True, + [("tag_resource", {"ResourceArn": "{stream}", "Tags": _STREAM_TAG}, {})], + [ + ("list_tags_of_resource", {"ResourceArn": "{stream}"}, {"Tags": _STREAM_TAG}), + ("untag_resource", {"ResourceArn": "{stream}", "TagKeys": ["sk"]}, {}), + ], + id="untag-stream", + ), + pytest.param( + True, + [], + [ + ( + "tag_resource", + {"ResourceArn": "{made_up}", "Tags": [{"Key": "fk", "Value": "fv"}]}, + _MADE_UP_NOT_FOUND, + ), + ("list_tags_of_resource", {"ResourceArn": "{made_up}"}, _MADE_UP_NOT_FOUND), + ], + id="made-up-stream-label", + ), +] + + +def _fill(value, values: dict): + """``value`` with each ``{key}`` in its strings replaced from ``values``.""" + if isinstance(value, str): + return value.format(**values) + if isinstance(value, dict): + return {key: _fill(item, values) for key, item in value.items()} + if isinstance(value, list): + return [_fill(item, values) for item in value] + return value + + +def _run_step(dynamodb_client, step, values: dict) -> None: + """Send one request of a row and assert its whole answer.""" + operation, request, answer = step + call = getattr(dynamodb_client, operation) + if isinstance(answer, tuple): + code, message = answer + with pytest.raises(ClientError) as exc: + call(**_fill(request, values)) + assert_validation(exc.value, _fill(message, values), code) + else: + resp = call(**_fill(request, values)) + resp.pop("ResponseMetadata", None) + assert resp == _fill(answer, values), operation + + +class TestDeletingWindowTimeToLiveAndStreamTags: + """``DescribeTimeToLive`` is refused during the window and + ``UpdateTimeToLive`` runs its ordinary rules. The table's stream ARN is a + resource of its own: both tag writes and the read are served on it, where + the table ARN refuses the writes (``TestDeletingWindowControlPlane``). A + stream ARN whose label names no stream is ``ResourceNotFoundException``. + ``DescribeTimeToLive`` on a ``CREATING`` table is refused with the same + sentence naming ``CREATING`` (measured 2026-10-26); the fixture cannot hold + a table ``CREATING``, so that row is pinned in the engine's unit tests.""" + + @pytest.mark.parametrize("stream, before, after", WINDOW_ROWS) + def test_answers_in_the_window(self, dynamodb_client, is_extenddb, stream, before, after): + name = unique_name("del-window") + lock = _open_window(dynamodb_client, is_extenddb, name, stream=stream) + deleted = False + try: + table = dynamodb_client.describe_table(TableName=name)["Table"] + values = { + "name": name, + "stream": table.get("LatestStreamArn", ""), + "made_up": f"{table['TableArn']}/stream/2000-01-01T00:00:00.000", + } + for step in before: + _run_step(dynamodb_client, step, values) + _delete_table_after_tag_write(dynamodb_client, name) + deleted = True + for step in after: + _run_step(dynamodb_client, step, values) + finally: + if lock is not None: + lock.release() + if not deleted: + _delete_table_after_tag_write(dynamodb_client, name) + wait_for_deleted(dynamodb_client, name, timeout=120.0)