From ebe8352575c96bc51e1d50fc2a693e3cf6c3c1b0 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:48:32 +0000 Subject: [PATCH 01/12] DescribeStream returns CreationRequestDateTime The service returns CreationRequestDateTime in StreamDescription on every stream, enabled or disabled (measured 2026-10-24). ExtendDB omitted it on every backend. The value is derived from the stream label rather than stored. stream_label_creation_date_time parses the 23-byte label format_stream_label writes and the 19-byte label SQLite, PostgreSQL and MongoDB wrote on v0.1.3 to v0.1.13 and Cassandra up to v0.1.14, so a stream enabled on those versions reports the member too. The engine sets the member in handle_describe_stream, so all four backends return it. On the service the member is a stored request time that preceded the label's instant by 0 to 13 ms in three measurements (2026-10-25); on ExtendDB the two name the same millisecond. Fixes #517 --- crates/core/src/types/stream.rs | 8 ++ crates/engine/src/streams.rs | 56 +++++++++- crates/storage-cassandra/src/stream_engine.rs | 1 + crates/storage-mongodb/src/stream_engine.rs | 1 + crates/storage-postgres/src/stream_engine.rs | 1 + crates/storage-sqlite/src/stream.rs | 1 + crates/storage/src/util/arn.rs | 103 ++++++++++++++++++ crates/storage/src/util/mod.rs | 4 +- tests/python/test_streams.py | 43 ++++++++ 9 files changed, 214 insertions(+), 4 deletions(-) diff --git a/crates/core/src/types/stream.rs b/crates/core/src/types/stream.rs index 870169b9a..ad0edad0c 100755 --- a/crates/core/src/types/stream.rs +++ b/crates/core/src/types/stream.rs @@ -119,6 +119,14 @@ pub struct StreamDescription { pub stream_arn: String, #[serde(rename = "StreamLabel")] pub stream_label: String, + /// When the stream was requested, epoch seconds. The service returns it + /// on every stream, enabled or disabled. Backends leave it `None`; the + /// engine derives it from `stream_label` at the response boundary. + #[serde( + rename = "CreationRequestDateTime", + skip_serializing_if = "Option::is_none" + )] + pub creation_request_date_time: Option, #[serde(rename = "StreamStatus")] pub stream_status: StreamStatus, #[serde(rename = "StreamViewType")] diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index c8ba419bc..8a70d0f9d 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -7,9 +7,10 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::types::{ DescribeStreamInput, DescribeStreamOutput, GetRecordsInput, GetRecordsOutput, GetShardIteratorInput, GetShardIteratorOutput, ListStreamsInput, ListStreamsOutput, - ShardIteratorType, + ShardIteratorType, StreamDescription, }; use extenddb_storage::error::StorageError; +use extenddb_storage::util::stream_label_creation_date_time; use serde_json::Value; use crate::OperationContext; @@ -35,11 +36,19 @@ pub async fn handle_describe_stream( .map_err(storage_to_dynamo)?; let output = DescribeStreamOutput { - stream_description: desc, + stream_description: with_creation_request_date_time(desc), }; serialize_output(&output) } +/// The service returns `CreationRequestDateTime` on every stream, enabled or +/// disabled. The label is the creation instant to the millisecond, so it is +/// derived here for every backend rather than stored by each. +fn with_creation_request_date_time(mut desc: StreamDescription) -> StreamDescription { + desc.creation_request_date_time = stream_label_creation_date_time(&desc.stream_label); + desc +} + /// Handle `ListStreams`. /// /// # Errors @@ -419,6 +428,49 @@ fn storage_to_dynamo(e: StorageError) -> DynamoDbError { #[cfg(test)] mod tests { + /// `DescribeStream` renders `CreationRequestDateTime` as the label's + /// instant in epoch seconds, next to the members it already had, and + /// omits the member only when the label is not a timestamp. + #[test] + fn describe_stream_output_carries_creation_request_date_time() { + use extenddb_core::types::{ + DescribeStreamOutput, StreamDescription, StreamStatus, StreamViewType, + }; + let desc = StreamDescription { + creation_request_date_time: None, + stream_arn: "arn:aws:dynamodb:us-east-1:1:table/T/stream/2026-10-24T11:31:45.748" + .to_owned(), + stream_label: "2026-10-24T11:31:45.748".to_owned(), + stream_status: StreamStatus::Disabled, + stream_view_type: StreamViewType::KeysOnly, + table_name: "T".to_owned(), + key_schema: Vec::new(), + shards: Vec::new(), + last_evaluated_shard_id: None, + }; + let v = crate::serialize_output(&DescribeStreamOutput { + stream_description: super::with_creation_request_date_time(desc.clone()), + }) + .unwrap(); + let sd = &v["StreamDescription"]; + assert_eq!(sd["CreationRequestDateTime"], 1_792_841_505.748); + assert_eq!(sd["StreamLabel"], "2026-10-24T11:31:45.748"); + assert_eq!(sd["StreamStatus"], "DISABLED"); + + let v = crate::serialize_output(&DescribeStreamOutput { + stream_description: super::with_creation_request_date_time(StreamDescription { + stream_label: "not-a-label".to_owned(), + ..desc + }), + }) + .unwrap(); + assert!( + v["StreamDescription"] + .get("CreationRequestDateTime") + .is_none() + ); + } + /// AT_SEQUENCE_NUMBER converts to AFTER by subtracting 1 and padding to /// the backend's stored width. Verify that an unpadded client input is /// normalised correctly for both the 21-digit (postgres/sqlite/mongodb) diff --git a/crates/storage-cassandra/src/stream_engine.rs b/crates/storage-cassandra/src/stream_engine.rs index 8c83b0927..3d538db44 100755 --- a/crates/storage-cassandra/src/stream_engine.rs +++ b/crates/storage-cassandra/src/stream_engine.rs @@ -389,6 +389,7 @@ impl StreamEngine for CassandraEngine { }; Ok(StreamDescription { + creation_request_date_time: None, stream_arn: stream_arn_str, stream_label, stream_status, diff --git a/crates/storage-mongodb/src/stream_engine.rs b/crates/storage-mongodb/src/stream_engine.rs index 097b3bb2a..7d3063560 100644 --- a/crates/storage-mongodb/src/stream_engine.rs +++ b/crates/storage-mongodb/src/stream_engine.rs @@ -491,6 +491,7 @@ impl StreamEngine for MongoEngine { }; Ok(StreamDescription { + creation_request_date_time: None, stream_arn: stream_arn_val, stream_label, stream_status, diff --git a/crates/storage-postgres/src/stream_engine.rs b/crates/storage-postgres/src/stream_engine.rs index 970a81755..df023e23c 100755 --- a/crates/storage-postgres/src/stream_engine.rs +++ b/crates/storage-postgres/src/stream_engine.rs @@ -372,6 +372,7 @@ impl StreamEngine for PostgresEngine { }; Ok(StreamDescription { + creation_request_date_time: None, stream_arn, stream_label, stream_status, diff --git a/crates/storage-sqlite/src/stream.rs b/crates/storage-sqlite/src/stream.rs index 7cd3d4729..5e667f624 100644 --- a/crates/storage-sqlite/src/stream.rs +++ b/crates/storage-sqlite/src/stream.rs @@ -276,6 +276,7 @@ impl StreamEngine for SqliteEngine { }; Ok(StreamDescription { + creation_request_date_time: None, stream_arn, stream_label, stream_status, diff --git a/crates/storage/src/util/arn.rs b/crates/storage/src/util/arn.rs index f463ee1f0..f2652f513 100755 --- a/crates/storage/src/util/arn.rs +++ b/crates/storage/src/util/arn.rs @@ -54,6 +54,57 @@ pub fn new_stream_label() -> String { format_stream_label(time::OffsetDateTime::now_utc()) } +/// The instant a [`format_stream_label`] label names, as the epoch-seconds +/// number `DescribeStream` renders in `CreationRequestDateTime` (measured on +/// the service 2026-10-24: present on every stream, enabled or disabled). The +/// label is the stream's creation instant to the millisecond, so no stored +/// column is needed. +/// +/// Two shapes are accepted: the 23-byte `YYYY-MM-DDThh:mm:ss.sss` this module +/// writes, and the 19-byte `YYYY-MM-DDThh:mm:ss` that SQLite, PostgreSQL and +/// MongoDB wrote on v0.1.3 to v0.1.13 and Cassandra up to v0.1.14, which a +/// stream enabled on those versions and never re-enabled still carries. The +/// legacy shape names the instant with a `.000` fraction. `None` for any +/// other shape. +#[must_use] +#[allow(clippy::cast_precision_loss)] // epoch ms fit f64's 53-bit mantissa +pub fn stream_label_creation_date_time(label: &str) -> Option { + let b = label.as_bytes(); + let has_fraction = match b.len() { + 19 => false, + 23 if b[19] == b'.' => true, + _ => return None, + }; + if b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' { + return None; + } + let num = |range: std::ops::Range| -> Option { + let s = &label[range]; + if s.bytes().all(|c| c.is_ascii_digit()) { + s.parse().ok() + } else { + None + } + }; + let year = i32::try_from(num(0..4)?).ok()?; + let month = time::Month::try_from(u8::try_from(num(5..7)?).ok()?).ok()?; + let date = time::Date::from_calendar_date(year, month, u8::try_from(num(8..10)?).ok()?).ok()?; + let millis = if has_fraction { + u16::try_from(num(20..23)?).ok()? + } else { + 0 + }; + let clock = time::Time::from_hms_milli( + u8::try_from(num(11..13)?).ok()?, + u8::try_from(num(14..16)?).ok()?, + u8::try_from(num(17..19)?).ok()?, + millis, + ) + .ok()?; + let secs = date.with_time(clock).assume_utc().unix_timestamp(); + Some((secs * 1000 + i64::from(millis)) as f64 / 1000.0) +} + /// Returns an ARN for the specified `DynamoDB` stream. #[must_use] pub fn stream_arn(region: &str, account_id: &str, table_name: &str, stream_label: &str) -> String { @@ -212,4 +263,56 @@ mod stream_label_tests { "2026-01-01T22:04:05.500" ); } + + /// `CreationRequestDateTime` is the label's instant, to the millisecond, + /// and round-trips through the formatter. + #[test] + fn creation_date_time_is_the_label_instant() { + use super::stream_label_creation_date_time; + assert_eq!( + stream_label_creation_date_time("1970-01-01T00:00:00.000"), + Some(0.0) + ); + assert_eq!( + stream_label_creation_date_time("1970-01-01T00:00:01.748"), + Some(1.748) + ); + // 2026-10-24T11:31:45.748Z, the label in the issue. + assert_eq!( + stream_label_creation_date_time("2026-10-24T11:31:45.748"), + Some(1_792_841_505.748) + ); + // The 19-byte legacy label (v0.1.3 to v0.1.13 writers) is the instant + // with a .000 fraction. + assert_eq!( + stream_label_creation_date_time("2026-07-04T10:20:30"), + Some(1_783_160_430.0) + ); + // 2026-01-02T03:04:05.007 UTC, through the formatter. + let label = format_stream_label(at((2026, 1, 2), (3, 4, 5, 7_000), 0)); + assert_eq!( + stream_label_creation_date_time(&label), + Some(1_767_323_045.007) + ); + } + + #[test] + fn creation_date_time_refuses_other_shapes() { + use super::stream_label_creation_date_time; + for bad in [ + "", + "2026-10-24T11:31:4", + "2026-10-24T11:31:4S", + "2026-10-24T11:31:45.7480", + "2026-10-24T11:31:45.748Z", + "2026-10-24 11:31:45.748", + "2026-10-24 11:31:45", + "2026-13-24T11:31:45.748", + "2026-10-24T25:31:45.748", + "2026-1O-24T11:31:45.748", + "2026-10-24T11:31:45:748", + ] { + assert_eq!(stream_label_creation_date_time(bad), None, "{bad:?}"); + } + } } diff --git a/crates/storage/src/util/mod.rs b/crates/storage/src/util/mod.rs index bb2493827..329ceb16a 100755 --- a/crates/storage/src/util/mod.rs +++ b/crates/storage/src/util/mod.rs @@ -14,8 +14,8 @@ mod shard_stream; pub use arn::{ ARN_PARTITION, STREAM_DOES_NOT_EXIST, format_stream_label, index_arn, new_stream_label, - parse_stream_arn, shard_not_in_stream, stream_arn, stream_does_not_exist, stream_not_found, - table_arn, + parse_stream_arn, shard_not_in_stream, stream_arn, stream_does_not_exist, + stream_label_creation_date_time, stream_not_found, table_arn, }; pub use backup_id::{ BackupArnError, BackupArnParts, MAX_BACKUP_ARN_LEN, backup_arn, backup_creation_date_time, diff --git a/tests/python/test_streams.py b/tests/python/test_streams.py index 4ce98acf1..fab8ac6cf 100755 --- a/tests/python/test_streams.py +++ b/tests/python/test_streams.py @@ -17,6 +17,7 @@ import os import time import uuid +from datetime import datetime, timezone import boto3 import botocore.config @@ -174,6 +175,48 @@ def test_describe_stream_invalid_arn(self, streams_client): "ValidationException", ) + def test_creation_request_date_time_is_the_label_instant( + self, dynamodb_client, streams_client + ): + """CreationRequestDateTime is present on an enabled and on a disabled + stream and equals the instant the StreamLabel names (UTC, to the + millisecond).""" + name, stream_arn = _create_stream_table(dynamodb_client) + try: + desc = streams_client.describe_stream(StreamArn=stream_arn)["StreamDescription"] + assert desc["StreamStatus"] == "ENABLED" + self._assert_creation_matches_label(desc) + + dynamodb_client.update_table( + TableName=name, StreamSpecification={"StreamEnabled": False} + ) + wait_for_active(dynamodb_client, name) + table = dynamodb_client.describe_table(TableName=name)["Table"] + # The service drops StreamSpecification from DescribeTable once the + # stream is disabled; ExtendDB answers {StreamEnabled: false} until + # every backend does the same. + assert "StreamSpecification" not in table or table["StreamSpecification"] == { + "StreamEnabled": False + } + assert table["LatestStreamArn"] == stream_arn + desc = streams_client.describe_stream(StreamArn=stream_arn)["StreamDescription"] + self._assert_creation_matches_label(desc) + finally: + dynamodb_client.delete_table(TableName=name) + wait_for_deleted(dynamodb_client, name) + + @staticmethod + def _assert_creation_matches_label(desc: dict) -> None: + label = desc["StreamLabel"] + expected = ( + datetime.strptime(label, "%Y-%m-%dT%H:%M:%S.%f") + .replace(tzinfo=timezone.utc) + .timestamp() + ) + created = desc["CreationRequestDateTime"] + assert isinstance(created, datetime), created + assert abs(created.timestamp() - expected) < 0.0005, (label, created) + def _arn_with_another_label(stream_arn: str) -> str: """The ARN of a stream the table never had: the last three digits of the From 6eff5029fec32cc6704bd49ddc986d93984f26bf Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:48:32 +0000 Subject: [PATCH 02/12] UpdateTable: service sentences for a stream without a view type and a GSI without definitions UpdateTable StreamSpecification {StreamEnabled: true} with no StreamViewType is refused by the service with "One or more parameter values were invalid: If stream is being enabled then UpdateViewType is required" (measured 2026-10-24 on a never-streamed table and on a table whose stream is enabled). ExtendDB said "StreamViewType must be specified when StreamEnabled is true". The service reports a Create whose key attribute has no definition, and a PROVISIONED billing mode with no ProvisionedThroughput, before the missing view type, and the view type before the table lookup (measured 2026-10-25); the check now runs after the billing and index rules and before the backend call. The throughput sentence is the service's: "ProvisionedThroughput must be specified when BillingMode is PROVISIONED". An UpdateTable GlobalSecondaryIndexUpdates Create whose key attribute is not defined is refused by the service with one of three sentences by the shape of AttributeDefinitions (measured 2026-10-25): member absent, "AttributeDefinitions is not specified for index: ", naming the first Create in request order; member present and lacking the key, "Some index key attributes are not defined in AttributeDefinitions. Keys: [..], AttributeDefinitions: [..]"; member present and empty, "Invalid KeySchema: Some index key attribute have no definition". ExtendDB rendered the second sentence for every shape. The UpdateTable check has its own rendering in the engine and does not call core's CreateTable validation, so the CreateTable sentence is unchanged. The update_table tests move to update_table_tests.rs unchanged. Fixes #519 Fixes #520 --- crates/engine/src/update_table.rs | 241 +++++--------------- crates/engine/src/update_table_tests.rs | 238 +++++++++++++++++++ tests/python/test_update_table_sentences.py | 170 ++++++++++++++ 3 files changed, 469 insertions(+), 180 deletions(-) create mode 100644 crates/engine/src/update_table_tests.rs create mode 100644 tests/python/test_update_table_sentences.py diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index 6db763f82..14970ac8a 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -103,22 +103,12 @@ pub async fn handle_update_table( )); } - // Validate: enabling streams requires a view type. - if let Some(spec) = &input.stream_specification - && spec.stream_enabled - && spec.stream_view_type.is_none() - { - return Err(DynamoDbError::ValidationException( - "StreamViewType must be specified when StreamEnabled is true".to_owned(), - )); - } - // Switching to PROVISIONED requires explicit throughput values. if matches!(input.billing_mode, Some(BillingMode::Provisioned)) && input.provisioned_throughput.is_none() { return Err(DynamoDbError::ValidationException( - "One or more parameter values were invalid: ProvisionedThroughput must be specified when changing BillingMode to PROVISIONED".to_owned(), + "One or more parameter values were invalid: ProvisionedThroughput must be specified when BillingMode is PROVISIONED".to_owned(), )); } @@ -141,6 +131,7 @@ pub async fn handle_update_table( } validate_gsi_updates(&input)?; + validate_stream_specification(&input)?; // A created GSI's projected attributes count toward the table's limit // together with the indexes it already has: the total CreateTable checks, @@ -203,6 +194,25 @@ pub async fn handle_update_table( serialize_output(&output) } +/// Enabling a stream requires a view type. The sentence is the service's +/// (measured 2026-10-24 on a never-streamed table and on a table whose stream +/// is enabled). The service reports a defective index Create and a missing +/// ProvisionedThroughput before this (measured 2026-10-25), and this before +/// the table lookup, so the call sits after the billing and index rules and +/// before the backend call, where it also precedes the already-enabled +/// refusal. The `CreateTable` form has its own sentence. +fn validate_stream_specification(input: &UpdateTableInput) -> Result<(), DynamoDbError> { + if let Some(spec) = &input.stream_specification + && spec.stream_enabled + && spec.stream_view_type.is_none() + { + return Err(DynamoDbError::ValidationException( + "One or more parameter values were invalid: If stream is being enabled then UpdateViewType is required".to_owned(), + )); + } + Ok(()) +} + /// The per-entry rules for `GlobalSecondaryIndexUpdates`, checked before any /// storage read: each entry has exactly one of Create, Update, or Delete, /// and a Create has a valid name, a key schema of defined attributes, and @@ -239,24 +249,47 @@ fn validate_gsi_updates(input: &UpdateTableInput) -> Result<(), DynamoDbError> { "One or more parameter values were invalid: KeySchema must not be empty for GSI creation".to_owned(), )); } - // Validate that all key attributes are defined in AttributeDefinitions - let attr_defs = input.attribute_definitions.as_deref().unwrap_or(&[]); - for ks in &create.key_schema { - if !attr_defs - .iter() - .any(|ad| ad.attribute_name == ks.attribute_name) - { + // Every key attribute must be in AttributeDefinitions. The + // service's sentence depends on the member's shape (measured + // 2026-10-25): absent names the index; present but lacking + // the key lists the keys and the definitions (the CreateTable + // sentence, whose CreateTable copy lives in core's validation + // and is not shared with this path); an empty list has its + // own sentence. + let missing: Vec<&str> = match &input.attribute_definitions { + None => { return Err(DynamoDbError::ValidationException(format!( - "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. \ - Keys: [{}], AttributeDefinitions: [{}]", - ks.attribute_name, - attr_defs - .iter() - .map(|ad| ad.attribute_name.as_str()) - .collect::>() - .join(", ") + "One or more parameter values were invalid: AttributeDefinitions is not specified for index: {}", + create.index_name ))); } + Some(defs) if defs.is_empty() => { + return Err(DynamoDbError::ValidationException( + "Invalid KeySchema: Some index key attribute have no definition" + .to_owned(), + )); + } + Some(defs) => create + .key_schema + .iter() + .filter(|ks| !defs.iter().any(|ad| ad.attribute_name == ks.attribute_name)) + .map(|ks| ks.attribute_name.as_str()) + .collect(), + }; + if let Some(first_missing) = missing.first() { + let defined: Vec<&str> = input + .attribute_definitions + .as_deref() + .unwrap_or(&[]) + .iter() + .map(|ad| ad.attribute_name.as_str()) + .collect(); + return Err(DynamoDbError::ValidationException(format!( + "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. \ + Keys: [{}], AttributeDefinitions: [{}]", + first_missing, + defined.join(", ") + ))); } } if let Some(delete) = &update.delete { @@ -347,157 +380,5 @@ fn update_table_err_to_dynamo( } #[cfg(test)] -mod tests { - use super::*; - use extenddb_storage::error::StorageError; - - #[test] - fn a_created_gsi_throughput_below_one_is_refused() { - let input = |pt: Value| -> UpdateTableInput { - serde_json::from_value(serde_json::json!({ - "TableName": "t", - "AttributeDefinitions": [{ "AttributeName": "g", "AttributeType": "S" }], - "GlobalSecondaryIndexUpdates": [{ "Create": { - "IndexName": "gix", - "KeySchema": [{ "AttributeName": "g", "KeyType": "HASH" }], - "Projection": { "ProjectionType": "ALL" }, - "ProvisionedThroughput": pt, - }}], - })) - .unwrap() - }; - for (read, write) in [(0, 0), (0, 1), (1, 0), (-1, 5)] { - let pt = serde_json::json!({ "ReadCapacityUnits": read, "WriteCapacityUnits": write }); - match validate_gsi_updates(&input(pt)).unwrap_err() { - DynamoDbError::ValidationException(m) => { - assert!(m.ends_with("for index: gix"), "{m}"); - } - other => panic!("({read}, {write}): {other:?}"), - } - } - let ok = serde_json::json!({ "ReadCapacityUnits": 1, "WriteCapacityUnits": 1 }); - validate_gsi_updates(&input(ok)).unwrap(); - } - - #[test] - fn projected_total_counts_kept_indexes_and_created_ones() { - use extenddb_core::types::{ - GlobalSecondaryIndexUpdate, GsiDescription, LsiDescription, Projection, ProjectionType, - TableDescription, - }; - let include = |n: usize| Projection { - projection_type: ProjectionType::Include, - non_key_attributes: Some((0..n).map(|i| format!("a{i}")).collect()), - }; - let existing = TableDescription { - global_secondary_indexes: Some(vec![ - GsiDescription { - index_name: "kept".to_owned(), - key_schema: Vec::new(), - projection: include(30), - index_status: "ACTIVE".to_owned(), - provisioned_throughput: None, - index_size_bytes: 0, - item_count: 0, - index_arn: String::new(), - }, - GsiDescription { - index_name: "dropped".to_owned(), - key_schema: Vec::new(), - projection: include(50), - index_status: "ACTIVE".to_owned(), - provisioned_throughput: None, - index_size_bytes: 0, - item_count: 0, - index_arn: String::new(), - }, - ]), - local_secondary_indexes: Some(vec![LsiDescription { - index_name: "lsi".to_owned(), - key_schema: Vec::new(), - projection: include(20), - index_size_bytes: 0, - item_count: 0, - index_arn: String::new(), - }]), - ..Default::default() - }; - let create = |n: usize| -> GlobalSecondaryIndexUpdate { - serde_json::from_value(serde_json::json!({ "Create": { - "IndexName": "new", "KeySchema": [], - "Projection": serde_json::to_value(include(n)).unwrap(), - }})) - .unwrap() - }; - let delete: GlobalSecondaryIndexUpdate = - serde_json::from_value(serde_json::json!({ "Delete": { "IndexName": "dropped" } })) - .unwrap(); - - assert_eq!(projected_after_gsi_updates(&existing, &[create(1)]), 101); - assert_eq!( - projected_after_gsi_updates(&existing, &[create(1), delete]), - 51 - ); - assert!( - extenddb_core::validation::validate_projected_attribute_total( - projected_after_gsi_updates(&existing, &[create(1)]) - ) - .is_err() - ); - } - - /// A backend that cannot serve the request reports a 400, not a 500. - /// - /// This arm was missing while CreateTable had it, so the same refusal - /// answered differently depending on which operation carried it. It matters - /// for a backend whose vector capability is decided at runtime rather than at - /// compile time: its refusal arrives through this path. - #[test] - fn an_unsupported_feature_is_a_validation_exception() { - let err = update_table_err_to_dynamo( - StorageError::Unsupported("Vector indexes are not supported here".to_owned()), - "t", - ); - match err { - DynamoDbError::ValidationException(msg) => { - assert_eq!(msg, "Vector indexes are not supported here"); - } - other => panic!("expected ValidationException, got {other:?}"), - } - } - - /// The backend's whole message survives, unwrapped and unprefixed, because - /// the service's own wording for this case names both the table and the index - /// and no layer above the backend knows either. - #[test] - fn a_resource_in_use_refusal_keeps_the_backend_message() { - let measured = extenddb_core::types::vector_index_delete_in_allocation_phase("t", "vidx"); - let err = update_table_err_to_dynamo(StorageError::IndexesInUse(measured.clone()), "t"); - match err { - DynamoDbError::ResourceInUseException(msg) => assert_eq!(msg, measured), - other => panic!("expected ResourceInUseException, got {other:?}"), - } - } - - /// The measured whole string, byte for byte, from probe P2 on 2026-08-19. - #[test] - fn the_allocation_phase_refusal_is_the_measured_whole_string() { - assert_eq!( - extenddb_core::types::vector_index_delete_in_allocation_phase( - "eddbprobe-backfill", - "vidx2" - ), - "Attempt to change a resource which is still in use: Index creation is in resource \ - allocation phase. Retry deletion during backfilling phase or when the index is \ - active. Table: eddbprobe-backfill Index: vidx2" - ); - } - - /// A genuine fault still reports a 500 and is still logged as one. - #[test] - fn an_internal_failure_is_still_an_internal_server_error() { - let err = - update_table_err_to_dynamo(StorageError::Internal("disk on fire".to_owned()), "t"); - assert!(matches!(err, DynamoDbError::InternalServerError(_))); - } -} +#[path = "update_table_tests.rs"] +mod tests; diff --git a/crates/engine/src/update_table_tests.rs b/crates/engine/src/update_table_tests.rs new file mode 100644 index 000000000..aa4cfda3a --- /dev/null +++ b/crates/engine/src/update_table_tests.rs @@ -0,0 +1,238 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Tests for `update_table`. + +use super::*; +use extenddb_storage::error::StorageError; + +/// Enabling a stream without a view type is refused with the service's +/// sentence; a view type, or a disable, passes this check. +#[test] +fn enabling_a_stream_without_a_view_type_is_refused() { + let input = |spec: Value| -> UpdateTableInput { + serde_json::from_value(serde_json::json!({ + "TableName": "t", + "StreamSpecification": spec, + })) + .unwrap() + }; + match validate_stream_specification(&input(serde_json::json!({ "StreamEnabled": true }))) + .unwrap_err() + { + DynamoDbError::ValidationException(m) => assert_eq!( + m, + "One or more parameter values were invalid: If stream is being enabled then UpdateViewType is required" + ), + other => panic!("{other:?}"), + } + validate_stream_specification(&input(serde_json::json!({ + "StreamEnabled": true, "StreamViewType": "NEW_IMAGE" + }))) + .unwrap(); + validate_stream_specification(&input(serde_json::json!({ "StreamEnabled": false }))).unwrap(); +} + +/// A created index whose key attribute is not in AttributeDefinitions is +/// refused with the sentence the service picks by the member's shape +/// (measured 2026-10-25): absent names the index, present but lacking the +/// key lists the key and the definitions, empty has its own sentence. +#[test] +fn a_created_gsi_on_an_undefined_key_attribute_is_refused_by_member_shape() { + let input = |defs: Option| -> UpdateTableInput { + let mut v = serde_json::json!({ + "TableName": "t", + "GlobalSecondaryIndexUpdates": [{ "Create": { + "IndexName": "gix", + "KeySchema": [ + { "AttributeName": "g", "KeyType": "HASH" }, + { "AttributeName": "r", "KeyType": "RANGE" }, + ], + "Projection": { "ProjectionType": "ALL" }, + }}], + }); + if let Some(d) = defs { + v["AttributeDefinitions"] = d; + } + serde_json::from_value(v).unwrap() + }; + let message = |defs: Option| match validate_gsi_updates(&input(defs)).unwrap_err() { + DynamoDbError::ValidationException(m) => m, + other => panic!("{other:?}"), + }; + assert_eq!( + message(None), + "One or more parameter values were invalid: AttributeDefinitions is not specified for index: gix" + ); + assert_eq!( + message(Some(serde_json::json!([]))), + "Invalid KeySchema: Some index key attribute have no definition" + ); + assert_eq!( + message(Some( + serde_json::json!([{ "AttributeName": "g", "AttributeType": "S" }]) + )), + "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [r], AttributeDefinitions: [g]" + ); + assert_eq!( + message(Some( + serde_json::json!([{ "AttributeName": "other", "AttributeType": "S" }]) + )), + "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [g], AttributeDefinitions: [other]" + ); + validate_gsi_updates(&input(Some(serde_json::json!([ + { "AttributeName": "g", "AttributeType": "S" }, + { "AttributeName": "r", "AttributeType": "S" }, + ])))) + .unwrap(); +} + +#[test] +fn a_created_gsi_throughput_below_one_is_refused() { + let input = |pt: Value| -> UpdateTableInput { + serde_json::from_value(serde_json::json!({ + "TableName": "t", + "AttributeDefinitions": [{ "AttributeName": "g", "AttributeType": "S" }], + "GlobalSecondaryIndexUpdates": [{ "Create": { + "IndexName": "gix", + "KeySchema": [{ "AttributeName": "g", "KeyType": "HASH" }], + "Projection": { "ProjectionType": "ALL" }, + "ProvisionedThroughput": pt, + }}], + })) + .unwrap() + }; + for (read, write) in [(0, 0), (0, 1), (1, 0), (-1, 5)] { + let pt = serde_json::json!({ "ReadCapacityUnits": read, "WriteCapacityUnits": write }); + match validate_gsi_updates(&input(pt)).unwrap_err() { + DynamoDbError::ValidationException(m) => { + assert!(m.ends_with("for index: gix"), "{m}"); + } + other => panic!("({read}, {write}): {other:?}"), + } + } + let ok = serde_json::json!({ "ReadCapacityUnits": 1, "WriteCapacityUnits": 1 }); + validate_gsi_updates(&input(ok)).unwrap(); +} + +#[test] +fn projected_total_counts_kept_indexes_and_created_ones() { + use extenddb_core::types::{ + GlobalSecondaryIndexUpdate, GsiDescription, LsiDescription, Projection, ProjectionType, + TableDescription, + }; + let include = |n: usize| Projection { + projection_type: ProjectionType::Include, + non_key_attributes: Some((0..n).map(|i| format!("a{i}")).collect()), + }; + let existing = TableDescription { + global_secondary_indexes: Some(vec![ + GsiDescription { + index_name: "kept".to_owned(), + key_schema: Vec::new(), + projection: include(30), + index_status: "ACTIVE".to_owned(), + provisioned_throughput: None, + index_size_bytes: 0, + item_count: 0, + index_arn: String::new(), + }, + GsiDescription { + index_name: "dropped".to_owned(), + key_schema: Vec::new(), + projection: include(50), + index_status: "ACTIVE".to_owned(), + provisioned_throughput: None, + index_size_bytes: 0, + item_count: 0, + index_arn: String::new(), + }, + ]), + local_secondary_indexes: Some(vec![LsiDescription { + index_name: "lsi".to_owned(), + key_schema: Vec::new(), + projection: include(20), + index_size_bytes: 0, + item_count: 0, + index_arn: String::new(), + }]), + ..Default::default() + }; + let create = |n: usize| -> GlobalSecondaryIndexUpdate { + serde_json::from_value(serde_json::json!({ "Create": { + "IndexName": "new", "KeySchema": [], + "Projection": serde_json::to_value(include(n)).unwrap(), + }})) + .unwrap() + }; + let delete: GlobalSecondaryIndexUpdate = + serde_json::from_value(serde_json::json!({ "Delete": { "IndexName": "dropped" } })) + .unwrap(); + + assert_eq!(projected_after_gsi_updates(&existing, &[create(1)]), 101); + assert_eq!( + projected_after_gsi_updates(&existing, &[create(1), delete]), + 51 + ); + assert!( + extenddb_core::validation::validate_projected_attribute_total(projected_after_gsi_updates( + &existing, + &[create(1)] + )) + .is_err() + ); +} + +/// A backend that cannot serve the request reports a 400, not a 500. +/// +/// This arm was missing while CreateTable had it, so the same refusal +/// answered differently depending on which operation carried it. It matters +/// for a backend whose vector capability is decided at runtime rather than at +/// compile time: its refusal arrives through this path. +#[test] +fn an_unsupported_feature_is_a_validation_exception() { + let err = update_table_err_to_dynamo( + StorageError::Unsupported("Vector indexes are not supported here".to_owned()), + "t", + ); + match err { + DynamoDbError::ValidationException(msg) => { + assert_eq!(msg, "Vector indexes are not supported here"); + } + other => panic!("expected ValidationException, got {other:?}"), + } +} + +/// The backend's whole message survives, unwrapped and unprefixed, because +/// the service's own wording for this case names both the table and the index +/// and no layer above the backend knows either. +#[test] +fn a_resource_in_use_refusal_keeps_the_backend_message() { + let measured = extenddb_core::types::vector_index_delete_in_allocation_phase("t", "vidx"); + let err = update_table_err_to_dynamo(StorageError::IndexesInUse(measured.clone()), "t"); + match err { + DynamoDbError::ResourceInUseException(msg) => assert_eq!(msg, measured), + other => panic!("expected ResourceInUseException, got {other:?}"), + } +} + +/// The measured whole string, byte for byte, from probe P2 on 2026-08-19. +#[test] +fn the_allocation_phase_refusal_is_the_measured_whole_string() { + assert_eq!( + extenddb_core::types::vector_index_delete_in_allocation_phase( + "eddbprobe-backfill", + "vidx2" + ), + "Attempt to change a resource which is still in use: Index creation is in resource \ + allocation phase. Retry deletion during backfilling phase or when the index is \ + active. Table: eddbprobe-backfill Index: vidx2" + ); +} + +/// A genuine fault still reports a 500 and is still logged as one. +#[test] +fn an_internal_failure_is_still_an_internal_server_error() { + let err = update_table_err_to_dynamo(StorageError::Internal("disk on fire".to_owned()), "t"); + assert!(matches!(err, DynamoDbError::InternalServerError(_))); +} diff --git a/tests/python/test_update_table_sentences.py b/tests/python/test_update_table_sentences.py new file mode 100644 index 000000000..09d35d909 --- /dev/null +++ b/tests/python/test_update_table_sentences.py @@ -0,0 +1,170 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""UpdateTable refusals whose sentence the service fixes. + +Each row asserts the code and the whole message as DynamoDB returns them +(measured 2026-10-24 and 2026-10-25). +""" + +from __future__ import annotations + +import pytest +from botocore.exceptions import ClientError + +from helpers import wait_for_active + +STREAM_VIEW_TYPE_REQUIRED = ( + "One or more parameter values were invalid: " + "If stream is being enabled then UpdateViewType is required" +) + + +def _validation_message(exc_info) -> str: + err = exc_info.value.response["Error"] + assert err["Code"] == "ValidationException" + assert exc_info.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400 + return err["Message"] + + +class TestStreamSpecification: + """StreamEnabled without StreamViewType.""" + + def test_never_streamed_table(self, table_factory, dynamodb_client): + name = table_factory() + with pytest.raises(ClientError) as exc_info: + dynamodb_client.update_table( + TableName=name, StreamSpecification={"StreamEnabled": True} + ) + assert _validation_message(exc_info) == STREAM_VIEW_TYPE_REQUIRED + + def test_table_with_an_enabled_stream(self, table_factory, dynamodb_client): + """The view type check comes before the already-enabled check.""" + name = table_factory( + StreamSpecification={ + "StreamEnabled": True, + "StreamViewType": "NEW_AND_OLD_IMAGES", + } + ) + with pytest.raises(ClientError) as exc_info: + dynamodb_client.update_table( + TableName=name, StreamSpecification={"StreamEnabled": True} + ) + assert _validation_message(exc_info) == STREAM_VIEW_TYPE_REQUIRED + + +class TestValidationOrder: + """Which refusal a request with two defects gets (measured 2026-10-25).""" + + def test_index_without_definitions_precedes_the_view_type(self, table_factory, dynamodb_client): + name = table_factory() + with pytest.raises(ClientError) as exc_info: + dynamodb_client.update_table( + TableName=name, + StreamSpecification={"StreamEnabled": True}, + GlobalSecondaryIndexUpdates=[ + { + "Create": { + "IndexName": "by-g", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + } + } + ], + ) + assert _validation_message(exc_info) == ( + "One or more parameter values were invalid: " + "AttributeDefinitions is not specified for index: by-g" + ) + + def test_missing_throughput_precedes_the_view_type(self, table_factory, dynamodb_client): + name = table_factory() + with pytest.raises(ClientError) as exc_info: + dynamodb_client.update_table( + TableName=name, + StreamSpecification={"StreamEnabled": True}, + BillingMode="PROVISIONED", + ) + assert _validation_message(exc_info) == ( + "One or more parameter values were invalid: " + "ProvisionedThroughput must be specified when BillingMode is PROVISIONED" + ) + + +class TestIndexKeyAttributeUndefined: + """A secondary index key attribute that AttributeDefinitions does not define.""" + + @staticmethod + def _create_by_g(): + return [ + { + "Create": { + "IndexName": "by-g", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + } + } + ] + + def test_update_table_without_the_member_names_the_index(self, table_factory, dynamodb_client): + name = table_factory() + with pytest.raises(ClientError) as exc_info: + dynamodb_client.update_table( + TableName=name, + GlobalSecondaryIndexUpdates=self._create_by_g(), + ) + assert _validation_message(exc_info) == ( + "One or more parameter values were invalid: " + "AttributeDefinitions is not specified for index: by-g" + ) + # The refusal left the table as it was. + wait_for_active(dynamodb_client, name) + desc = dynamodb_client.describe_table(TableName=name)["Table"] + assert "GlobalSecondaryIndexes" not in desc + + def test_update_table_with_the_member_lacking_the_key_lists_keys_and_definitions( + self, table_factory, dynamodb_client + ): + name = table_factory() + with pytest.raises(ClientError) as exc_info: + dynamodb_client.update_table( + TableName=name, + AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}], + GlobalSecondaryIndexUpdates=self._create_by_g(), + ) + assert _validation_message(exc_info) == ( + "One or more parameter values were invalid: " + "Some index key attributes are not defined in AttributeDefinitions. " + "Keys: [g], AttributeDefinitions: [pk]" + ) + + def test_update_table_with_an_empty_member_has_its_own_sentence(self, table_factory, dynamodb_client): + name = table_factory() + with pytest.raises(ClientError) as exc_info: + dynamodb_client.update_table( + TableName=name, + AttributeDefinitions=[], + GlobalSecondaryIndexUpdates=self._create_by_g(), + ) + assert _validation_message(exc_info) == "Invalid KeySchema: Some index key attribute have no definition" + + def test_create_table_lists_keys_and_definitions(self, dynamodb_client): + with pytest.raises(ClientError) as exc_info: + dynamodb_client.create_table( + TableName="never-created-by-g", + AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}], + KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], + BillingMode="PAY_PER_REQUEST", + GlobalSecondaryIndexes=[ + { + "IndexName": "by-g", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + } + ], + ) + assert _validation_message(exc_info) == ( + "One or more parameter values were invalid: " + "Some index key attributes are not defined in AttributeDefinitions. " + "Keys: [g], AttributeDefinitions: [pk]" + ) From cd2e20fd8540d6ec788abb2be6309c78e87ba178 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:17:46 +0000 Subject: [PATCH 03/12] fix(storage): parse the stream label once for CreationRequestDateTime Main added stream_lineage::label_millis, which reads the 23-byte stream label as epoch milliseconds for the shard ids. This branch added stream_label_creation_date_time with its own parser of the same label. The second parser goes. stream_label_creation_date_time now calls label_millis and keeps the 19-byte arm for the labels earlier releases wrote, by giving them a .000 fraction first. --- crates/storage/src/util/arn.rs | 46 +++++++--------------------------- 1 file changed, 9 insertions(+), 37 deletions(-) diff --git a/crates/storage/src/util/arn.rs b/crates/storage/src/util/arn.rs index 39761d1fd..058319477 100755 --- a/crates/storage/src/util/arn.rs +++ b/crates/storage/src/util/arn.rs @@ -61,48 +61,20 @@ pub fn new_stream_label() -> String { /// column is needed. /// /// Two shapes are accepted: the 23-byte `YYYY-MM-DDThh:mm:ss.sss` this module -/// writes, and the 19-byte `YYYY-MM-DDThh:mm:ss` that SQLite, PostgreSQL and -/// MongoDB wrote on v0.1.3 to v0.1.13 and Cassandra up to v0.1.14, which a -/// stream enabled on those versions and never re-enabled still carries. The -/// legacy shape names the instant with a `.000` fraction. `None` for any -/// other shape. +/// writes, parsed by [`crate::stream_lineage::label_millis`], and the 19-byte +/// `YYYY-MM-DDThh:mm:ss` that SQLite, PostgreSQL and MongoDB wrote on v0.1.3 +/// to v0.1.13 and Cassandra up to v0.1.14, which a stream enabled on those +/// versions and never re-enabled still carries. The legacy shape names the +/// instant with a `.000` fraction. `None` for any other shape. #[must_use] #[allow(clippy::cast_precision_loss)] // epoch ms fit f64's 53-bit mantissa pub fn stream_label_creation_date_time(label: &str) -> Option { - let b = label.as_bytes(); - let has_fraction = match b.len() { - 19 => false, - 23 if b[19] == b'.' => true, - _ => return None, - }; - if b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' { - return None; - } - let num = |range: std::ops::Range| -> Option { - let s = &label[range]; - if s.bytes().all(|c| c.is_ascii_digit()) { - s.parse().ok() - } else { - None - } - }; - let year = i32::try_from(num(0..4)?).ok()?; - let month = time::Month::try_from(u8::try_from(num(5..7)?).ok()?).ok()?; - let date = time::Date::from_calendar_date(year, month, u8::try_from(num(8..10)?).ok()?).ok()?; - let millis = if has_fraction { - u16::try_from(num(20..23)?).ok()? + let millis = if label.len() == 19 { + crate::stream_lineage::label_millis(&format!("{label}.000"))? } else { - 0 + crate::stream_lineage::label_millis(label)? }; - let clock = time::Time::from_hms_milli( - u8::try_from(num(11..13)?).ok()?, - u8::try_from(num(14..16)?).ok()?, - u8::try_from(num(17..19)?).ok()?, - millis, - ) - .ok()?; - let secs = date.with_time(clock).assume_utc().unix_timestamp(); - Some((secs * 1000 + i64::from(millis)) as f64 / 1000.0) + Some(millis as f64 / 1000.0) } /// Returns an ARN for the specified `DynamoDB` stream. From f20de8a1ba5d8b1fe491a12815cbf3a8d00f90d0 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:28:47 +0000 Subject: [PATCH 04/12] fix(storage): stream_change answers the measured enable sentence Main's stream_change refuses an enable without a view type with the engine's old sentence, and its comment says the engine still answers that sentence. This branch moved the engine to the measured sentence, "If stream is being enabled then UpdateViewType is required". The storage arm now carries the same sentence, so the one condition has one message. The arm stays unreachable through the engine, which checks it first. --- crates/storage/src/stream_lineage.rs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/crates/storage/src/stream_lineage.rs b/crates/storage/src/stream_lineage.rs index f979c6037..f36383a72 100644 --- a/crates/storage/src/stream_lineage.rs +++ b/crates/storage/src/stream_lineage.rs @@ -85,19 +85,15 @@ pub fn stream_change( (false, false) => Err(StorageError::Validation(format!( "Table has no stream to disable: TableName: {table_name}" ))), - // Unreachable through the engine, which refuses an enable without a - // view type before storage with this same sentence. The service's - // sentence for that case, measured 2026-10-24, is "One or more - // parameter values were invalid: If stream is being enabled then - // UpdateViewType is required", and it precedes the already-enabled - // check; the engine's sentence pre-dates this change and is not - // changed here. + // Unreachable through the engine, whose `validate_stream_specification` + // refuses an enable without a view type before storage with this same + // sentence (measured 2026-10-24), and before the already-enabled check. (true, false) => requested .stream_view_type .map(StreamChange::Enable) .ok_or_else(|| { StorageError::Validation( - "StreamViewType must be specified when StreamEnabled is true".to_owned(), + "One or more parameter values were invalid: If stream is being enabled then UpdateViewType is required".to_owned(), ) }), (false, true) => Ok(StreamChange::Disable), From c665aac07a3534d2c834786aed74503888ed53bb Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:20:21 +0000 Subject: [PATCH 05/12] refactor(storage): one constant for the stream view type sentence The engine's validate_stream_specification and storage's stream_change each wrote out the sentence for an UpdateTable that enables a stream without a view type. The sentence now lives once, as stream_lineage::STREAM_VIEW_TYPE_REQUIRED, and both sites read it. The engine unit test keeps the literal, so the constant stays checked against the measured text. --- crates/engine/src/update_table.rs | 6 +++--- crates/storage/src/stream_lineage.rs | 15 +++++++++------ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index dbb30bf79..5346d0f85 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -281,8 +281,8 @@ pub async fn handle_update_table( } /// Enabling a stream requires a view type. The sentence is the service's -/// (measured 2026-10-24 on a never-streamed table and on a table whose stream -/// is enabled). The service reports a defective index Create and a missing +/// ([`extenddb_storage::stream_lineage::STREAM_VIEW_TYPE_REQUIRED`]). The +/// service reports a defective index Create and a missing /// ProvisionedThroughput before this (measured 2026-10-25), and this before /// the table lookup, so the call sits after the billing and index rules and /// before the backend call, where it also precedes the already-enabled @@ -293,7 +293,7 @@ fn validate_stream_specification(input: &UpdateTableInput) -> Result<(), DynamoD && spec.stream_view_type.is_none() { return Err(DynamoDbError::ValidationException( - "One or more parameter values were invalid: If stream is being enabled then UpdateViewType is required".to_owned(), + extenddb_storage::stream_lineage::STREAM_VIEW_TYPE_REQUIRED.to_owned(), )); } Ok(()) diff --git a/crates/storage/src/stream_lineage.rs b/crates/storage/src/stream_lineage.rs index f36383a72..3e8b5e1ac 100644 --- a/crates/storage/src/stream_lineage.rs +++ b/crates/storage/src/stream_lineage.rs @@ -34,6 +34,13 @@ use crate::util::{ /// Fixed shards per stream (hash-based partition-key assignment). pub const SHARDS_PER_STREAM: u32 = 4; +/// The service's refusal of an `UpdateTable` that enables a stream without a +/// `StreamViewType` (measured 2026-10-24 on a never-streamed table and on a +/// table whose stream is enabled). The engine answers it before storage is +/// called; [`stream_change`] answers it for a caller that reaches storage +/// without that check. +pub const STREAM_VIEW_TYPE_REQUIRED: &str = "One or more parameter values were invalid: If stream is being enabled then UpdateViewType is required"; + /// A `CreateTable` request with a disabled `StreamSpecification` dropped. /// /// The service does not store `{StreamEnabled: false}`: `DescribeTable` on @@ -87,15 +94,11 @@ pub fn stream_change( ))), // Unreachable through the engine, whose `validate_stream_specification` // refuses an enable without a view type before storage with this same - // sentence (measured 2026-10-24), and before the already-enabled check. + // sentence, and before the already-enabled check. (true, false) => requested .stream_view_type .map(StreamChange::Enable) - .ok_or_else(|| { - StorageError::Validation( - "One or more parameter values were invalid: If stream is being enabled then UpdateViewType is required".to_owned(), - ) - }), + .ok_or_else(|| StorageError::Validation(STREAM_VIEW_TYPE_REQUIRED.to_owned())), (false, true) => Ok(StreamChange::Disable), } } From 6459ee88b7759d27d7bf79931bcb33765989a2d8 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:20:21 +0000 Subject: [PATCH 06/12] test(streams): assert the answers main now gives after a disable Main drops a disabled StreamSpecification from DescribeTable on every backend and reports the stream DISABLED. The CreationRequestDateTime wire row accepted either DescribeTable shape and did not check the stream status. It now asserts the member is absent and the status reads DISABLED. The fold row sends an index Create without AttributeDefinitions beside a stream change. Its comment said ExtendDB still answered its own sentence for an undefined index key, so the row checked only the order. This branch answers the service's sentence for that shape, so the row asserts the whole message. --- tests/python/test_stream_disable_fold.py | 11 ++++------- tests/python/test_streams.py | 11 +++++------ 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/tests/python/test_stream_disable_fold.py b/tests/python/test_stream_disable_fold.py index 9620a0954..30771d322 100644 --- a/tests/python/test_stream_disable_fold.py +++ b/tests/python/test_stream_disable_fold.py @@ -211,13 +211,10 @@ def test_a_stream_change_beside_an_index_create_is_refused(run): def test_the_index_definition_check_precedes_the_companion_rule(run): row = run["disable_plus_gsi_undefined_attribute"] assert (row["status"], row["code"]) == (400, "ValidationException"), row - # The index definition check comes first. The service's sentence is - # "AttributeDefinitions is not specified for index: gsi2"; ExtendDB's own - # sentence for an undefined index key ("Some index key attributes are not - # defined in AttributeDefinitions. Keys: [g], ...") pre-dates this change, - # so only the ordering is asserted here. - assert row["message"].startswith(INVALID), row - assert "AttributeDefinitions" in row["message"] and "stream" not in row["message"], row + # The index definition check comes first: the request carries no + # AttributeDefinitions, so the answer is the service's sentence for that + # shape (measured 2026-10-25), not the stream companion sentence. + assert row["message"] == INVALID + "AttributeDefinitions is not specified for index: gsi2", row def test_the_already_enabled_check_precedes_the_companion_rule(run): diff --git a/tests/python/test_streams.py b/tests/python/test_streams.py index 287334e82..f81a5f0db 100755 --- a/tests/python/test_streams.py +++ b/tests/python/test_streams.py @@ -194,14 +194,13 @@ def test_creation_request_date_time_is_the_label_instant( ) wait_for_active(dynamodb_client, name) table = dynamodb_client.describe_table(TableName=name)["Table"] - # The service drops StreamSpecification from DescribeTable once the - # stream is disabled; ExtendDB answers {StreamEnabled: false} until - # every backend does the same. - assert "StreamSpecification" not in table or table["StreamSpecification"] == { - "StreamEnabled": False - } + # A disabled stream is dropped from DescribeTable's + # StreamSpecification, as on the service; LatestStreamArn keeps + # naming the closed stream. + assert "StreamSpecification" not in table assert table["LatestStreamArn"] == stream_arn desc = streams_client.describe_stream(StreamArn=stream_arn)["StreamDescription"] + assert desc["StreamStatus"] == "DISABLED" self._assert_creation_matches_label(desc) finally: dynamodb_client.delete_table(TableName=name) From 484c0f42cbbf74ece1804dc169aee1bab3d4e189 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:28:26 +0000 Subject: [PATCH 07/12] test(update-table): one data table per kind of row in the sentence tests tests/python/test_update_table_sentences.py had one test function per measured row. Its eight rows are now four data tables, each with one parametrized test: - the view type rows, on a never-streamed and a stream-enabled table - the two order rows of #519 - the three AttributeDefinitions member shapes, on a table - the CreateTable listing row Each row keeps its request members and its expected message. The two #519 order rows now go to a table name that does not exist, as the CreateTable row already did. The service answers both before the table lookup (measured 2026-11-25, twice each, on a name that does not exist). --- tests/python/test_update_table_sentences.py | 221 ++++++++++---------- 1 file changed, 111 insertions(+), 110 deletions(-) diff --git a/tests/python/test_update_table_sentences.py b/tests/python/test_update_table_sentences.py index 09d35d909..bccb9f740 100644 --- a/tests/python/test_update_table_sentences.py +++ b/tests/python/test_update_table_sentences.py @@ -4,7 +4,9 @@ """UpdateTable refusals whose sentence the service fixes. Each row asserts the code and the whole message as DynamoDB returns them -(measured 2026-10-24 and 2026-10-25). +(measured 2026-10-24, 2026-10-25 and 2026-11-25). The service answers the rows +of the NEVER_CREATED tables before it looks the table up, so they go to a name +no test creates. The other rows need a table. """ from __future__ import annotations @@ -14,10 +16,14 @@ from helpers import wait_for_active +NEVER_CREATED = "never-created-by-g" + STREAM_VIEW_TYPE_REQUIRED = ( "One or more parameter values were invalid: " "If stream is being enabled then UpdateViewType is required" ) +NO_DEFINITION = "Invalid KeySchema: Some index key attribute have no definition" +STREAM_NO_VIEW = {"StreamEnabled": True} def _validation_message(exc_info) -> str: @@ -27,144 +33,139 @@ def _validation_message(exc_info) -> str: return err["Message"] -class TestStreamSpecification: - """StreamEnabled without StreamViewType.""" +def _gsi_create(name: str, keys: list[tuple[str, str]], projection: str) -> list[dict]: + return [ + { + "Create": { + "IndexName": name, + "KeySchema": [{"AttributeName": a, "KeyType": t} for a, t in keys], + "Projection": {"ProjectionType": projection}, + } + } + ] - def test_never_streamed_table(self, table_factory, dynamodb_client): - name = table_factory() - with pytest.raises(ClientError) as exc_info: - dynamodb_client.update_table( - TableName=name, StreamSpecification={"StreamEnabled": True} - ) - assert _validation_message(exc_info) == STREAM_VIEW_TYPE_REQUIRED - def test_table_with_an_enabled_stream(self, table_factory, dynamodb_client): - """The view type check comes before the already-enabled check.""" - name = table_factory( - StreamSpecification={ - "StreamEnabled": True, - "StreamViewType": "NEW_AND_OLD_IMAGES", - } - ) +def _definitions(*names: str) -> list[dict]: + return [{"AttributeName": n, "AttributeType": "S"} for n in names] + + +BY_G = _gsi_create("by-g", [("g", "HASH")], "ALL") + + +class TestStreamSpecification: + """StreamEnabled without StreamViewType. The view type check comes before + the already-enabled check.""" + + @pytest.mark.parametrize( + "table_spec", + [ + pytest.param({}, id="never-streamed"), + pytest.param( + { + "StreamSpecification": { + "StreamEnabled": True, + "StreamViewType": "NEW_AND_OLD_IMAGES", + } + }, + id="stream-enabled", + ), + ], + ) + def test_the_view_type_is_required(self, table_factory, dynamodb_client, table_spec): + name = table_factory(**table_spec) with pytest.raises(ClientError) as exc_info: - dynamodb_client.update_table( - TableName=name, StreamSpecification={"StreamEnabled": True} - ) + dynamodb_client.update_table(TableName=name, StreamSpecification=STREAM_NO_VIEW) assert _validation_message(exc_info) == STREAM_VIEW_TYPE_REQUIRED class TestValidationOrder: - """Which refusal a request with two defects gets (measured 2026-10-25).""" + """Which refusal a request with two defects gets. A defective index Create + and the billing rules come before the view type.""" - def test_index_without_definitions_precedes_the_view_type(self, table_factory, dynamodb_client): - name = table_factory() - with pytest.raises(ClientError) as exc_info: - dynamodb_client.update_table( - TableName=name, - StreamSpecification={"StreamEnabled": True}, - GlobalSecondaryIndexUpdates=[ - { - "Create": { - "IndexName": "by-g", - "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], - "Projection": {"ProjectionType": "ALL"}, - } - } - ], - ) - assert _validation_message(exc_info) == ( + NEVER_CREATED_ROWS = [ + pytest.param( + {"StreamSpecification": STREAM_NO_VIEW, "GlobalSecondaryIndexUpdates": BY_G}, "One or more parameter values were invalid: " - "AttributeDefinitions is not specified for index: by-g" - ) + "AttributeDefinitions is not specified for index: by-g", + id="index-without-definitions-before-the-view-type", + ), + pytest.param( + {"StreamSpecification": STREAM_NO_VIEW, "BillingMode": "PROVISIONED"}, + "One or more parameter values were invalid: " + "ProvisionedThroughput must be specified when BillingMode is PROVISIONED", + id="missing-throughput-before-the-view-type", + ), + ] - def test_missing_throughput_precedes_the_view_type(self, table_factory, dynamodb_client): - name = table_factory() + @pytest.mark.parametrize("members, expected", NEVER_CREATED_ROWS) + def test_the_service_refusal_comes_first(self, dynamodb_client, members, expected): with pytest.raises(ClientError) as exc_info: - dynamodb_client.update_table( - TableName=name, - StreamSpecification={"StreamEnabled": True}, - BillingMode="PROVISIONED", - ) - assert _validation_message(exc_info) == ( - "One or more parameter values were invalid: " - "ProvisionedThroughput must be specified when BillingMode is PROVISIONED" - ) + dynamodb_client.update_table(TableName=NEVER_CREATED, **members) + assert _validation_message(exc_info) == expected class TestIndexKeyAttributeUndefined: - """A secondary index key attribute that AttributeDefinitions does not define.""" + """A secondary index key attribute that AttributeDefinitions does not + define.""" - @staticmethod - def _create_by_g(): - return [ - { - "Create": { - "IndexName": "by-g", - "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], - "Projection": {"ProjectionType": "ALL"}, - } - } - ] - - def test_update_table_without_the_member_names_the_index(self, table_factory, dynamodb_client): + TABLE_ROWS = [ + pytest.param( + {}, + "One or more parameter values were invalid: " + "AttributeDefinitions is not specified for index: by-g", + id="member-absent-names-the-index", + ), + pytest.param( + {"AttributeDefinitions": _definitions("pk")}, + "One or more parameter values were invalid: " + "Some index key attributes are not defined in AttributeDefinitions. " + "Keys: [g], AttributeDefinitions: [pk]", + id="member-lacking-the-key-lists-keys-and-definitions", + ), + pytest.param( + {"AttributeDefinitions": []}, + NO_DEFINITION, + id="member-empty", + ), + ] + + @pytest.mark.parametrize("members, expected", TABLE_ROWS) + def test_update_table_on_a_table(self, table_factory, dynamodb_client, members, expected): name = table_factory() with pytest.raises(ClientError) as exc_info: dynamodb_client.update_table( - TableName=name, - GlobalSecondaryIndexUpdates=self._create_by_g(), + TableName=name, GlobalSecondaryIndexUpdates=BY_G, **members ) - assert _validation_message(exc_info) == ( - "One or more parameter values were invalid: " - "AttributeDefinitions is not specified for index: by-g" - ) + assert _validation_message(exc_info) == expected # The refusal left the table as it was. wait_for_active(dynamodb_client, name) desc = dynamodb_client.describe_table(TableName=name)["Table"] assert "GlobalSecondaryIndexes" not in desc - def test_update_table_with_the_member_lacking_the_key_lists_keys_and_definitions( - self, table_factory, dynamodb_client - ): - name = table_factory() - with pytest.raises(ClientError) as exc_info: - dynamodb_client.update_table( - TableName=name, - AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}], - GlobalSecondaryIndexUpdates=self._create_by_g(), - ) - assert _validation_message(exc_info) == ( - "One or more parameter values were invalid: " - "Some index key attributes are not defined in AttributeDefinitions. " - "Keys: [g], AttributeDefinitions: [pk]" - ) - - def test_update_table_with_an_empty_member_has_its_own_sentence(self, table_factory, dynamodb_client): - name = table_factory() - with pytest.raises(ClientError) as exc_info: - dynamodb_client.update_table( - TableName=name, - AttributeDefinitions=[], - GlobalSecondaryIndexUpdates=self._create_by_g(), - ) - assert _validation_message(exc_info) == "Invalid KeySchema: Some index key attribute have no definition" - - def test_create_table_lists_keys_and_definitions(self, dynamodb_client): - with pytest.raises(ClientError) as exc_info: - dynamodb_client.create_table( - TableName="never-created-by-g", - AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}], - KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], - BillingMode="PAY_PER_REQUEST", - GlobalSecondaryIndexes=[ + NEVER_CREATED_ROWS = [ + pytest.param( + "create_table", + { + "AttributeDefinitions": _definitions("pk"), + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "BillingMode": "PAY_PER_REQUEST", + "GlobalSecondaryIndexes": [ { "IndexName": "by-g", "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], "Projection": {"ProjectionType": "ALL"}, } ], - ) - assert _validation_message(exc_info) == ( + }, "One or more parameter values were invalid: " "Some index key attributes are not defined in AttributeDefinitions. " - "Keys: [g], AttributeDefinitions: [pk]" - ) + "Keys: [g], AttributeDefinitions: [pk]", + id="create-table-lists-keys-and-definitions", + ), + ] + + @pytest.mark.parametrize("operation, members, expected", NEVER_CREATED_ROWS) + def test_on_a_name_no_table_has(self, dynamodb_client, operation, members, expected): + with pytest.raises(ClientError) as exc_info: + getattr(dynamodb_client, operation)(TableName=NEVER_CREATED, **members) + assert _validation_message(exc_info) == expected From ae5072c412eebe7593b58edf59e110c32f2c8909 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:29:35 +0000 Subject: [PATCH 08/12] fix(update-table): check the view type before the WarmThroughput rule This branch ran validate_gsi_updates and validate_stream_specification after validate_warm_throughput_is_only_operation, so each request below got an only-operation sentence. The service checks both first. It answers the sentence after each colon (measured 2026-11-25, twice each, on a table name that does not exist): - StreamSpecification {StreamEnabled: true} with no view type, plus WarmThroughput: "If stream is being enabled then UpdateViewType is required" - the same plus DeletionProtectionEnabled: the same view type sentence - the first request plus a GSI Create without AttributeDefinitions: "AttributeDefinitions is not specified for index: idx1" - WarmThroughput, BillingMode PAY_PER_REQUEST and a GSI Create without AttributeDefinitions: the same index sentence UpdateTable now checks the billing rules, then the index rules, then the view type, then the WarmThroughput rule. Main answered the WarmThroughput sentence for the last request too. It now gets the service's index sentence. The four requests are rows of TestValidationOrder in tests/python/test_update_table_sentences.py. --- crates/engine/src/update_table.rs | 18 +++++---- tests/python/test_update_table_sentences.py | 41 ++++++++++++++++++++- 2 files changed, 50 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index 5346d0f85..b5dff3429 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -144,15 +144,18 @@ pub async fn handle_update_table( )); } + crate::gsi_updates::validate_gsi_updates(&input)?; + validate_stream_specification(&input)?; + // A table-level WarmThroughput stands alone in its request, with the // measured per-companion sentences (measured 2026-10-23). Checked before // the value rules, as the service does: it fired on requests whose values // were otherwise valid. GlobalSecondaryIndexUpdates is accepted beside it. + // The index rules and the view type check above come first: the service + // answers their sentences beside WarmThroughput, with or without + // DeletionProtectionEnabled or BillingMode (measured 2026-11-25). extenddb_core::validation::validate_warm_throughput_is_only_operation(&input)?; - crate::gsi_updates::validate_gsi_updates(&input)?; - validate_stream_specification(&input)?; - // A stream change travels alone. Measured 2026-10-24: beside BillingMode or // ProvisionedThroughput the service refuses with the IOPS sentence, beside // any GlobalSecondaryIndexUpdates entry with the index sentence, and @@ -283,10 +286,11 @@ pub async fn handle_update_table( /// Enabling a stream requires a view type. The sentence is the service's /// ([`extenddb_storage::stream_lineage::STREAM_VIEW_TYPE_REQUIRED`]). The /// service reports a defective index Create and a missing -/// ProvisionedThroughput before this (measured 2026-10-25), and this before -/// the table lookup, so the call sits after the billing and index rules and -/// before the backend call, where it also precedes the already-enabled -/// refusal. The `CreateTable` form has its own sentence. +/// ProvisionedThroughput before this, and this before the warm throughput +/// rule and the table lookup (measured 2026-10-25 and 2026-11-25), so the call +/// sits after the billing and index rules and before the warm rule and the +/// backend call, where it also precedes the already-enabled refusal. The +/// `CreateTable` form has its own sentence. fn validate_stream_specification(input: &UpdateTableInput) -> Result<(), DynamoDbError> { if let Some(spec) = &input.stream_specification && spec.stream_enabled diff --git a/tests/python/test_update_table_sentences.py b/tests/python/test_update_table_sentences.py index bccb9f740..cd672dc2d 100644 --- a/tests/python/test_update_table_sentences.py +++ b/tests/python/test_update_table_sentences.py @@ -24,6 +24,7 @@ ) NO_DEFINITION = "Invalid KeySchema: Some index key attribute have no definition" STREAM_NO_VIEW = {"StreamEnabled": True} +WARM = {"ReadUnitsPerSecond": 13000, "WriteUnitsPerSecond": 5000} def _validation_message(exc_info) -> str: @@ -50,6 +51,7 @@ def _definitions(*names: str) -> list[dict]: BY_G = _gsi_create("by-g", [("g", "HASH")], "ALL") +IDX1_G = _gsi_create("idx1", [("g", "HASH")], "KEYS_ONLY") class TestStreamSpecification: @@ -79,8 +81,9 @@ def test_the_view_type_is_required(self, table_factory, dynamodb_client, table_s class TestValidationOrder: - """Which refusal a request with two defects gets. A defective index Create - and the billing rules come before the view type.""" + """Which refusal a request with two or more defects gets. A defective + index Create and the billing rules come before the view type, and both the + index Create and the view type come before the WarmThroughput rule.""" NEVER_CREATED_ROWS = [ pytest.param( @@ -95,6 +98,40 @@ class TestValidationOrder: "ProvisionedThroughput must be specified when BillingMode is PROVISIONED", id="missing-throughput-before-the-view-type", ), + pytest.param( + {"StreamSpecification": STREAM_NO_VIEW, "WarmThroughput": WARM}, + STREAM_VIEW_TYPE_REQUIRED, + id="view-type-before-warm-throughput", + ), + pytest.param( + { + "StreamSpecification": STREAM_NO_VIEW, + "WarmThroughput": WARM, + "DeletionProtectionEnabled": True, + }, + STREAM_VIEW_TYPE_REQUIRED, + id="view-type-before-warm-throughput-with-deletion-protection", + ), + pytest.param( + { + "StreamSpecification": STREAM_NO_VIEW, + "WarmThroughput": WARM, + "GlobalSecondaryIndexUpdates": IDX1_G, + }, + "One or more parameter values were invalid: " + "AttributeDefinitions is not specified for index: idx1", + id="index-before-view-type-and-warm-throughput", + ), + pytest.param( + { + "WarmThroughput": WARM, + "BillingMode": "PAY_PER_REQUEST", + "GlobalSecondaryIndexUpdates": IDX1_G, + }, + "One or more parameter values were invalid: " + "AttributeDefinitions is not specified for index: idx1", + id="index-before-warm-throughput-with-billing-mode", + ), ] @pytest.mark.parametrize("members, expected", NEVER_CREATED_ROWS) From 0598f8e26d3e022cc806e3b2073bb144beb7aa44 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:30:18 +0000 Subject: [PATCH 09/12] fix(update-table): fewer definitions than index keys answers Invalid KeySchema For an UpdateTable GSI Create, this branch answered "Invalid KeySchema: Some index key attribute have no definition" only when AttributeDefinitions was empty. The service answers it whenever the member has fewer entries than the created index has keys. For an index on g HASH and r RANGE, the definitions [g], [r] and [other] each get it. (Measured 2026-11-25, twice each, on a table name that does not exist.) This branch listed the missing key instead. When the member is not shorter than the key schema and a key is still undefined, the service lists every key of the index. For keys r HASH and g RANGE with the definitions [r, pk] it answers "Keys: [r, g], AttributeDefinitions: [r, pk]". This branch answered "Keys: [g]". The listing now names every key of the index, in key schema order, and every definition, in request order. The service orders a list of two or more names in another way. For keys g and r with the definitions [pk, x], it answers "Keys: [r, g], AttributeDefinitions: [x, pk]". The unit table in gsi_updates.rs and two rows of TestIndexKeyAttributeUndefined in tests/python/test_update_table_sentences.py hold both rules. --- crates/engine/src/gsi_updates.rs | 104 ++++++++++---------- tests/python/test_update_table_sentences.py | 29 +++++- 2 files changed, 78 insertions(+), 55 deletions(-) diff --git a/crates/engine/src/gsi_updates.rs b/crates/engine/src/gsi_updates.rs index 0b2626b91..6ec68af85 100644 --- a/crates/engine/src/gsi_updates.rs +++ b/crates/engine/src/gsi_updates.rs @@ -244,43 +244,41 @@ pub(crate) fn validate_gsi_updates(input: &UpdateTableInput) -> Result<(), Dynam } // Every key attribute must be in AttributeDefinitions. The // service's sentence depends on the member's shape (measured - // 2026-10-25): absent names the index; present but lacking - // the key lists the keys and the definitions (the CreateTable - // sentence, whose CreateTable copy lives in core's validation - // and is not shared with this path); an empty list has its - // own sentence. - let missing: Vec<&str> = match &input.attribute_definitions { + // 2026-10-25 and 2026-11-25): absent names the index; fewer + // definitions than the index has keys has its own sentence; + // otherwise the sentence lists every key of the index and every + // definition (the CreateTable sentence, whose CreateTable copy + // lives in core's validation and is not shared with this path). + let defs = match &input.attribute_definitions { None => { return Err(DynamoDbError::ValidationException(format!( "One or more parameter values were invalid: AttributeDefinitions is not specified for index: {}", create.index_name ))); } - Some(defs) if defs.is_empty() => { + Some(defs) if defs.len() < create.key_schema.len() => { return Err(DynamoDbError::ValidationException( "Invalid KeySchema: Some index key attribute have no definition".to_owned(), )); } - Some(defs) => create + Some(defs) => defs, + }; + if !create + .key_schema + .iter() + .all(|ks| defs.iter().any(|ad| ad.attribute_name == ks.attribute_name)) + { + let keys: Vec<&str> = create .key_schema .iter() - .filter(|ks| !defs.iter().any(|ad| ad.attribute_name == ks.attribute_name)) .map(|ks| ks.attribute_name.as_str()) - .collect(), - }; - if let Some(first_missing) = missing.first() { - let defined: Vec<&str> = input - .attribute_definitions - .as_deref() - .unwrap_or(&[]) - .iter() - .map(|ad| ad.attribute_name.as_str()) .collect(); + let defined: Vec<&str> = defs.iter().map(|ad| ad.attribute_name.as_str()).collect(); return Err(DynamoDbError::ValidationException(format!( "One or more parameter values were invalid: Some index key attributes \ are not defined in AttributeDefinitions. Keys: [{}], \ AttributeDefinitions: [{}]", - first_missing, + keys.join(", "), defined.join(", ") ))); } @@ -561,56 +559,54 @@ mod tests { /// A created index whose key attribute is not in AttributeDefinitions is /// refused with the sentence the service picks by the member's shape - /// (measured 2026-10-25): absent names the index, present but lacking the - /// key lists the key and the definitions, empty has its own sentence. + /// (measured 2026-10-25 and 2026-11-25): absent names the index, fewer + /// definitions than the index has keys has its own sentence, and + /// otherwise the sentence lists every key of the index and every + /// definition. #[test] fn a_created_gsi_on_an_undefined_key_attribute_is_refused_by_member_shape() { - let input = |defs: Option| -> UpdateTableInput { + const FEWER: &str = "Invalid KeySchema: Some index key attribute have no definition"; + const LISTED: &str = "One or more parameter values were invalid: Some index key \ + attributes are not defined in AttributeDefinitions. Keys: [r, g], \ + AttributeDefinitions: [r, pk]"; + const ABSENT: &str = "One or more parameter values were invalid: AttributeDefinitions \ + is not specified for index: gix"; + let input = |keys: [&str; 2], defs: Option<&str>| -> UpdateTableInput { let mut v = serde_json::json!({ "TableName": "t", "GlobalSecondaryIndexUpdates": [{ "Create": { "IndexName": "gix", "KeySchema": [ - { "AttributeName": "g", "KeyType": "HASH" }, - { "AttributeName": "r", "KeyType": "RANGE" }, + { "AttributeName": keys[0], "KeyType": "HASH" }, + { "AttributeName": keys[1], "KeyType": "RANGE" }, ], "Projection": { "ProjectionType": "ALL" }, }}], }); if let Some(d) = defs { - v["AttributeDefinitions"] = d; + v["AttributeDefinitions"] = d + .split_whitespace() + .map(|n| serde_json::json!({ "AttributeName": n, "AttributeType": "S" })) + .collect(); } serde_json::from_value(v).unwrap() }; - let message = |defs: Option| match validate_gsi_updates(&input(defs)).unwrap_err() { - DynamoDbError::ValidationException(m) => m, - other => panic!("{other:?}"), - }; - assert_eq!( - message(None), - "One or more parameter values were invalid: AttributeDefinitions is not specified for index: gix" - ); - assert_eq!( - message(Some(serde_json::json!([]))), - "Invalid KeySchema: Some index key attribute have no definition" - ); - assert_eq!( - message(Some( - serde_json::json!([{ "AttributeName": "g", "AttributeType": "S" }]) - )), - "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [r], AttributeDefinitions: [g]" - ); - assert_eq!( - message(Some( - serde_json::json!([{ "AttributeName": "other", "AttributeType": "S" }]) - )), - "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [g], AttributeDefinitions: [other]" - ); - validate_gsi_updates(&input(Some(serde_json::json!([ - { "AttributeName": "g", "AttributeType": "S" }, - { "AttributeName": "r", "AttributeType": "S" }, - ])))) - .unwrap(); + // Definitions as space-separated names; `None` leaves the member out. + let cases = [ + (["g", "r"], None, ABSENT), + (["g", "r"], Some(""), FEWER), + (["g", "r"], Some("g"), FEWER), + (["g", "r"], Some("other"), FEWER), + (["r", "g"], Some("r pk"), LISTED), + ]; + for (keys, defs, expected) in cases { + assert_eq!( + message(validate_gsi_updates(&input(keys, defs))), + expected, + "keys {keys:?}, definitions {defs:?}" + ); + } + validate_gsi_updates(&input(["g", "r"], Some("g r"))).unwrap(); } #[test] diff --git a/tests/python/test_update_table_sentences.py b/tests/python/test_update_table_sentences.py index cd672dc2d..66a4ceff2 100644 --- a/tests/python/test_update_table_sentences.py +++ b/tests/python/test_update_table_sentences.py @@ -143,7 +143,10 @@ def test_the_service_refusal_comes_first(self, dynamodb_client, members, expecte class TestIndexKeyAttributeUndefined: """A secondary index key attribute that AttributeDefinitions does not - define.""" + define. UpdateTable picks the sentence by the member's shape: absent names + the index, fewer definitions than the index has keys has its own sentence, + and otherwise the sentence lists every key of the index and every + definition.""" TABLE_ROWS = [ pytest.param( @@ -180,6 +183,30 @@ def test_update_table_on_a_table(self, table_factory, dynamodb_client, members, assert "GlobalSecondaryIndexes" not in desc NEVER_CREATED_ROWS = [ + pytest.param( + "update_table", + { + "AttributeDefinitions": _definitions("g"), + "GlobalSecondaryIndexUpdates": _gsi_create( + "idx1", [("g", "HASH"), ("r", "RANGE")], "KEYS_ONLY" + ), + }, + NO_DEFINITION, + id="update-table-fewer-definitions-than-keys", + ), + pytest.param( + "update_table", + { + "AttributeDefinitions": _definitions("r", "pk"), + "GlobalSecondaryIndexUpdates": _gsi_create( + "idx1", [("r", "HASH"), ("g", "RANGE")], "KEYS_ONLY" + ), + }, + "One or more parameter values were invalid: " + "Some index key attributes are not defined in AttributeDefinitions. " + "Keys: [r, g], AttributeDefinitions: [r, pk]", + id="update-table-lists-every-key-of-the-index", + ), pytest.param( "create_table", { From 34b6c92c983bb402bfbd94b816de1bb56af1b700 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:30:33 +0000 Subject: [PATCH 10/12] test(storage): assert stream_change's sentence for an enable without a view type No test called stream_change with an enable and no view type, so main's old sentence put back in that arm passed every storage stream test. The new test sends that request against a table with no stream specification and against a disabled one. It asserts the measured sentence by equality: "One or more parameter values were invalid: If stream is being enabled then UpdateViewType is required". With main's sentence back in the arm, the test fails and the other 33 storage stream tests pass. --- crates/storage/src/stream_lineage_tests.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/storage/src/stream_lineage_tests.rs b/crates/storage/src/stream_lineage_tests.rs index 04510ab3c..2e3a8cbae 100644 --- a/crates/storage/src/stream_lineage_tests.rs +++ b/crates/storage/src/stream_lineage_tests.rs @@ -79,6 +79,19 @@ fn the_two_refusals_are_the_measured_sentences() { ); } +#[test] +fn an_enable_without_a_view_type_is_the_measured_sentence() { + for current in [None, Some(spec(false, None))] { + match stream_change("t", current.as_ref(), &spec(true, None)) { + Err(StorageError::Validation(m)) => assert_eq!( + m, + "One or more parameter values were invalid: If stream is being enabled then UpdateViewType is required" + ), + other => panic!("{other:?}"), + } + } +} + #[test] fn a_refused_disable_of_a_disabled_stream_closes_the_current_label_first() { let label = "2026-10-20T10:00:00.000"; From f3c65cd5646df0ebe1b0e636a50fed29a3b1f973 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:31:12 +0000 Subject: [PATCH 11/12] docs(storage): name the releases that wrote the 19-byte stream label The doc of stream_label_creation_date_time and its test comment gave the wrong releases for the 19-byte YYYY-MM-DDThh:mm:ss label. The message of the commit that added them did too. The release tags show these writers: - PostgreSQL, from v0.1.0 to v0.1.13 (to_char(NOW(), 'YYYY-MM-DD"T"HH24:MI:SS')) - SQLite, which first appears at v0.1.3, up to v0.1.13 (strftime('%Y-%m-%dT%H:%M:%S','now')) - MongoDB, which first appears at v0.1.4, up to v0.1.13 (its own format_stream_label) Cassandra first appears at v0.1.14, which writes the 23-byte label on every backend. This commit does not change the parser. --- crates/storage/src/util/arn.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/storage/src/util/arn.rs b/crates/storage/src/util/arn.rs index 058319477..2e09eb5ff 100755 --- a/crates/storage/src/util/arn.rs +++ b/crates/storage/src/util/arn.rs @@ -62,10 +62,10 @@ pub fn new_stream_label() -> String { /// /// Two shapes are accepted: the 23-byte `YYYY-MM-DDThh:mm:ss.sss` this module /// writes, parsed by [`crate::stream_lineage::label_millis`], and the 19-byte -/// `YYYY-MM-DDThh:mm:ss` that SQLite, PostgreSQL and MongoDB wrote on v0.1.3 -/// to v0.1.13 and Cassandra up to v0.1.14, which a stream enabled on those -/// versions and never re-enabled still carries. The legacy shape names the -/// instant with a `.000` fraction. `None` for any other shape. +/// `YYYY-MM-DDThh:mm:ss` that PostgreSQL wrote from v0.1.0, SQLite from v0.1.3 +/// and MongoDB from v0.1.4, each up to v0.1.13, which a stream enabled on +/// those versions and never re-enabled still carries. The legacy shape names +/// the instant with a `.000` fraction. `None` for any other shape. #[must_use] #[allow(clippy::cast_precision_loss)] // epoch ms fit f64's 53-bit mantissa pub fn stream_label_creation_date_time(label: &str) -> Option { @@ -258,8 +258,8 @@ mod stream_label_tests { stream_label_creation_date_time("2026-10-24T11:31:45.748"), Some(1_792_841_505.748) ); - // The 19-byte legacy label (v0.1.3 to v0.1.13 writers) is the instant - // with a .000 fraction. + // The 19-byte label that PostgreSQL, SQLite and MongoDB wrote up to + // v0.1.13 is the instant with a .000 fraction. assert_eq!( stream_label_creation_date_time("2026-07-04T10:20:30"), Some(1_783_160_430.0) From 7fbb1bd2adaea6b18d475cec719ddba22368c805 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:44:50 +0000 Subject: [PATCH 12/12] test(update-table): one data table for the rows a never-created name answers tests/python/test_update_table_sentences.py had two tables of rows that go to a table name that does not exist. TestValidationOrder held the six order rows. TestIndexKeyAttributeUndefined held the two UpdateTable member shapes and the CreateTable listing row. Both tables compared the message by equality, and the second had an operation column. The nine rows are now one table, NEVER_CREATED_ROWS, with the operation column, and one parametrized test, test_on_a_name_no_table_has. Each row keeps its request members and its expected message. The five rows that need a table stay in their two classes. --- tests/python/test_update_table_sentences.py | 224 ++++++++++---------- 1 file changed, 111 insertions(+), 113 deletions(-) diff --git a/tests/python/test_update_table_sentences.py b/tests/python/test_update_table_sentences.py index 66a4ceff2..e2f1959c0 100644 --- a/tests/python/test_update_table_sentences.py +++ b/tests/python/test_update_table_sentences.py @@ -5,8 +5,8 @@ Each row asserts the code and the whole message as DynamoDB returns them (measured 2026-10-24, 2026-10-25 and 2026-11-25). The service answers the rows -of the NEVER_CREATED tables before it looks the table up, so they go to a name -no test creates. The other rows need a table. +of NEVER_CREATED_ROWS before it looks the table up, so they go to a name no +test creates. The other rows need a table. """ from __future__ import annotations @@ -80,67 +80,6 @@ def test_the_view_type_is_required(self, table_factory, dynamodb_client, table_s assert _validation_message(exc_info) == STREAM_VIEW_TYPE_REQUIRED -class TestValidationOrder: - """Which refusal a request with two or more defects gets. A defective - index Create and the billing rules come before the view type, and both the - index Create and the view type come before the WarmThroughput rule.""" - - NEVER_CREATED_ROWS = [ - pytest.param( - {"StreamSpecification": STREAM_NO_VIEW, "GlobalSecondaryIndexUpdates": BY_G}, - "One or more parameter values were invalid: " - "AttributeDefinitions is not specified for index: by-g", - id="index-without-definitions-before-the-view-type", - ), - pytest.param( - {"StreamSpecification": STREAM_NO_VIEW, "BillingMode": "PROVISIONED"}, - "One or more parameter values were invalid: " - "ProvisionedThroughput must be specified when BillingMode is PROVISIONED", - id="missing-throughput-before-the-view-type", - ), - pytest.param( - {"StreamSpecification": STREAM_NO_VIEW, "WarmThroughput": WARM}, - STREAM_VIEW_TYPE_REQUIRED, - id="view-type-before-warm-throughput", - ), - pytest.param( - { - "StreamSpecification": STREAM_NO_VIEW, - "WarmThroughput": WARM, - "DeletionProtectionEnabled": True, - }, - STREAM_VIEW_TYPE_REQUIRED, - id="view-type-before-warm-throughput-with-deletion-protection", - ), - pytest.param( - { - "StreamSpecification": STREAM_NO_VIEW, - "WarmThroughput": WARM, - "GlobalSecondaryIndexUpdates": IDX1_G, - }, - "One or more parameter values were invalid: " - "AttributeDefinitions is not specified for index: idx1", - id="index-before-view-type-and-warm-throughput", - ), - pytest.param( - { - "WarmThroughput": WARM, - "BillingMode": "PAY_PER_REQUEST", - "GlobalSecondaryIndexUpdates": IDX1_G, - }, - "One or more parameter values were invalid: " - "AttributeDefinitions is not specified for index: idx1", - id="index-before-warm-throughput-with-billing-mode", - ), - ] - - @pytest.mark.parametrize("members, expected", NEVER_CREATED_ROWS) - def test_the_service_refusal_comes_first(self, dynamodb_client, members, expected): - with pytest.raises(ClientError) as exc_info: - dynamodb_client.update_table(TableName=NEVER_CREATED, **members) - assert _validation_message(exc_info) == expected - - class TestIndexKeyAttributeUndefined: """A secondary index key attribute that AttributeDefinitions does not define. UpdateTable picks the sentence by the member's shape: absent names @@ -182,54 +121,113 @@ def test_update_table_on_a_table(self, table_factory, dynamodb_client, members, desc = dynamodb_client.describe_table(TableName=name)["Table"] assert "GlobalSecondaryIndexes" not in desc - NEVER_CREATED_ROWS = [ - pytest.param( - "update_table", - { - "AttributeDefinitions": _definitions("g"), - "GlobalSecondaryIndexUpdates": _gsi_create( - "idx1", [("g", "HASH"), ("r", "RANGE")], "KEYS_ONLY" - ), - }, - NO_DEFINITION, - id="update-table-fewer-definitions-than-keys", - ), - pytest.param( - "update_table", - { - "AttributeDefinitions": _definitions("r", "pk"), - "GlobalSecondaryIndexUpdates": _gsi_create( - "idx1", [("r", "HASH"), ("g", "RANGE")], "KEYS_ONLY" - ), - }, - "One or more parameter values were invalid: " - "Some index key attributes are not defined in AttributeDefinitions. " - "Keys: [r, g], AttributeDefinitions: [r, pk]", - id="update-table-lists-every-key-of-the-index", - ), - pytest.param( - "create_table", - { - "AttributeDefinitions": _definitions("pk"), - "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], - "BillingMode": "PAY_PER_REQUEST", - "GlobalSecondaryIndexes": [ - { - "IndexName": "by-g", - "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], - "Projection": {"ProjectionType": "ALL"}, - } - ], - }, - "One or more parameter values were invalid: " - "Some index key attributes are not defined in AttributeDefinitions. " - "Keys: [g], AttributeDefinitions: [pk]", - id="create-table-lists-keys-and-definitions", - ), - ] - @pytest.mark.parametrize("operation, members, expected", NEVER_CREATED_ROWS) - def test_on_a_name_no_table_has(self, dynamodb_client, operation, members, expected): - with pytest.raises(ClientError) as exc_info: - getattr(dynamodb_client, operation)(TableName=NEVER_CREATED, **members) - assert _validation_message(exc_info) == expected +# Rows the service answers before it looks the table up: (operation, request +# members, message). The first six pin which refusal a request with two or +# more defects gets: a defective index Create and the billing rules come before +# the view type, and both the index Create and the view type come before the +# WarmThroughput rule. +NEVER_CREATED_ROWS = [ + pytest.param( + "update_table", + {"StreamSpecification": STREAM_NO_VIEW, "GlobalSecondaryIndexUpdates": BY_G}, + "One or more parameter values were invalid: " + "AttributeDefinitions is not specified for index: by-g", + id="index-without-definitions-before-the-view-type", + ), + pytest.param( + "update_table", + {"StreamSpecification": STREAM_NO_VIEW, "BillingMode": "PROVISIONED"}, + "One or more parameter values were invalid: " + "ProvisionedThroughput must be specified when BillingMode is PROVISIONED", + id="missing-throughput-before-the-view-type", + ), + pytest.param( + "update_table", + {"StreamSpecification": STREAM_NO_VIEW, "WarmThroughput": WARM}, + STREAM_VIEW_TYPE_REQUIRED, + id="view-type-before-warm-throughput", + ), + pytest.param( + "update_table", + { + "StreamSpecification": STREAM_NO_VIEW, + "WarmThroughput": WARM, + "DeletionProtectionEnabled": True, + }, + STREAM_VIEW_TYPE_REQUIRED, + id="view-type-before-warm-throughput-with-deletion-protection", + ), + pytest.param( + "update_table", + { + "StreamSpecification": STREAM_NO_VIEW, + "WarmThroughput": WARM, + "GlobalSecondaryIndexUpdates": IDX1_G, + }, + "One or more parameter values were invalid: " + "AttributeDefinitions is not specified for index: idx1", + id="index-before-view-type-and-warm-throughput", + ), + pytest.param( + "update_table", + { + "WarmThroughput": WARM, + "BillingMode": "PAY_PER_REQUEST", + "GlobalSecondaryIndexUpdates": IDX1_G, + }, + "One or more parameter values were invalid: " + "AttributeDefinitions is not specified for index: idx1", + id="index-before-warm-throughput-with-billing-mode", + ), + pytest.param( + "update_table", + { + "AttributeDefinitions": _definitions("g"), + "GlobalSecondaryIndexUpdates": _gsi_create( + "idx1", [("g", "HASH"), ("r", "RANGE")], "KEYS_ONLY" + ), + }, + NO_DEFINITION, + id="update-table-fewer-definitions-than-keys", + ), + pytest.param( + "update_table", + { + "AttributeDefinitions": _definitions("r", "pk"), + "GlobalSecondaryIndexUpdates": _gsi_create( + "idx1", [("r", "HASH"), ("g", "RANGE")], "KEYS_ONLY" + ), + }, + "One or more parameter values were invalid: " + "Some index key attributes are not defined in AttributeDefinitions. " + "Keys: [r, g], AttributeDefinitions: [r, pk]", + id="update-table-lists-every-key-of-the-index", + ), + pytest.param( + "create_table", + { + "AttributeDefinitions": _definitions("pk"), + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "BillingMode": "PAY_PER_REQUEST", + "GlobalSecondaryIndexes": [ + { + "IndexName": "by-g", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"}, + } + ], + }, + "One or more parameter values were invalid: " + "Some index key attributes are not defined in AttributeDefinitions. " + "Keys: [g], AttributeDefinitions: [pk]", + id="create-table-lists-keys-and-definitions", + ), +] + + +@pytest.mark.parametrize("operation, members, expected", NEVER_CREATED_ROWS) +def test_on_a_name_no_table_has(dynamodb_client, operation, members, expected): + with pytest.raises(ClientError) as exc_info: + getattr(dynamodb_client, operation)(TableName=NEVER_CREATED, **members) + assert _validation_message(exc_info) == expected