diff --git a/crates/core/src/types/stream.rs b/crates/core/src/types/stream.rs index 41426e7cc..fdb8c2c73 100755 --- a/crates/core/src/types/stream.rs +++ b/crates/core/src/types/stream.rs @@ -122,6 +122,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/gsi_updates.rs b/crates/engine/src/gsi_updates.rs index a89e39f52..6ec68af85 100644 --- a/crates/engine/src/gsi_updates.rs +++ b/crates/engine/src/gsi_updates.rs @@ -242,24 +242,45 @@ pub(crate) fn validate_gsi_updates(input: &UpdateTableInput) -> Result<(), Dynam .to_owned(), )); } - 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 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: 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.len() < create.key_schema.len() => { + return Err(DynamoDbError::ValidationException( + "Invalid KeySchema: Some index key attribute have no definition".to_owned(), + )); + } + 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() + .map(|ks| ks.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: [{}]", + keys.join(", "), + defined.join(", ") + ))); } } if let Some(delete) = &update.delete { @@ -536,6 +557,58 @@ 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 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() { + 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": keys[0], "KeyType": "HASH" }, + { "AttributeName": keys[1], "KeyType": "RANGE" }, + ], + "Projection": { "ProjectionType": "ALL" }, + }}], + }); + if let Some(d) = defs { + v["AttributeDefinitions"] = d + .split_whitespace() + .map(|n| serde_json::json!({ "AttributeName": n, "AttributeType": "S" })) + .collect(); + } + serde_json::from_value(v).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] fn an_index_name_outside_the_pattern_is_reported_at_its_member_path() { let cases = [ diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index 28fbb7b6f..137000cbb 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; @@ -44,11 +45,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 diff --git a/crates/engine/src/streams_tests.rs b/crates/engine/src/streams_tests.rs index 47f6ef771..5793a563b 100644 --- a/crates/engine/src/streams_tests.rs +++ b/crates/engine/src/streams_tests.rs @@ -4,6 +4,49 @@ //! Unit tests for the streams request handlers: iterator tokens, the measured //! constraint sentences and the not-found answers. +/// `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() + ); +} + #[test] fn shard_iterator_round_trip_backward_compat_and_fail_closed() { let stream = "arn:aws:dynamodb:us-east-1:1:table/T/stream/2026-10-20T16:17:40.188"; diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index fdc2191ab..b5dff3429 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -106,15 +106,6 @@ 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(), - )); - } // A disable carries no view type (measured 2026-10-24 on a never-streamed // table and on an enabled one alike; checked before the no-stream rule). if let Some(spec) = &input.stream_specification @@ -131,7 +122,7 @@ pub async fn handle_update_table( && 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(), )); } @@ -153,14 +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)?; - // 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 @@ -288,6 +283,26 @@ pub async fn handle_update_table( serialize_output(&output) } +/// 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, 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 + && spec.stream_view_type.is_none() + { + return Err(DynamoDbError::ValidationException( + extenddb_storage::stream_lineage::STREAM_VIEW_TYPE_REQUIRED.to_owned(), + )); + } + Ok(()) +} + /// The sentence the service refuses a stream change with when the same /// `UpdateTable` also changes the table's billing or throughput, creates or /// deletes an index, or changes deletion protection. `None` when the request diff --git a/crates/engine/src/update_table_tests.rs b/crates/engine/src/update_table_tests.rs index c31c3bfbd..5b011577b 100644 --- a/crates/engine/src/update_table_tests.rs +++ b/crates/engine/src/update_table_tests.rs @@ -6,6 +6,33 @@ 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(); +} + /// Measured 2026-10-24: a stream change beside a billing or throughput /// change, beside an index create or delete, or beside a deletion protection /// change is refused with its own sentence; alone it is not. diff --git a/crates/storage/src/stream_lineage.rs b/crates/storage/src/stream_lineage.rs index 883dc576a..f595007d1 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 @@ -85,21 +92,13 @@ 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, 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(), - ) - }), + .ok_or_else(|| StorageError::Validation(STREAM_VIEW_TYPE_REQUIRED.to_owned())), (false, true) => Ok(StreamChange::Disable), } } @@ -500,6 +499,7 @@ pub fn describe_stream( (remaining.len() > limit).then(|| remaining[limit - 1].shard_id.clone()); remaining.truncate(limit); Ok(StreamDescription { + creation_request_date_time: None, stream_status: stream_status(table, &label), stream_view_type: stream.view_type, stream_arn, 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"; diff --git a/crates/storage/src/util/arn.rs b/crates/storage/src/util/arn.rs index e9a6f4c5c..2e09eb5ff 100755 --- a/crates/storage/src/util/arn.rs +++ b/crates/storage/src/util/arn.rs @@ -54,6 +54,29 @@ 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, parsed by [`crate::stream_lineage::label_millis`], and the 19-byte +/// `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 { + let millis = if label.len() == 19 { + crate::stream_lineage::label_millis(&format!("{label}.000"))? + } else { + crate::stream_lineage::label_millis(label)? + }; + Some(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 { @@ -216,4 +239,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 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) + ); + // 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 3cdc9725a..419f13aa1 100755 --- a/crates/storage/src/util/mod.rs +++ b/crates/storage/src/util/mod.rs @@ -16,7 +16,7 @@ mod warm_throughput; pub use arn::{ ARN_PARTITION, SHARD_DOES_NOT_EXIST, STREAM_DOES_NOT_EXIST, format_stream_label, index_arn, new_stream_label, parse_stream_arn, shard_does_not_exist, stream_arn, stream_does_not_exist, - stream_not_found, table_arn, + 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_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 cd9b3618b..f81a5f0db 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 @@ -176,6 +177,47 @@ def test_describe_stream_invalid_arn(self, streams_client): error = exc.value.response["Error"] assert (error["Code"], error["Message"]) == ("AccessDeniedException", "Access is denied") + 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"] + # 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) + 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 diff --git a/tests/python/test_update_table_sentences.py b/tests/python/test_update_table_sentences.py new file mode 100644 index 000000000..e2f1959c0 --- /dev/null +++ b/tests/python/test_update_table_sentences.py @@ -0,0 +1,233 @@ +# 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, 2026-10-25 and 2026-11-25). The service answers the rows +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 + +import pytest +from botocore.exceptions import ClientError + +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} +WARM = {"ReadUnitsPerSecond": 13000, "WriteUnitsPerSecond": 5000} + + +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"] + + +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 _definitions(*names: str) -> list[dict]: + return [{"AttributeName": n, "AttributeType": "S"} for n in names] + + +BY_G = _gsi_create("by-g", [("g", "HASH")], "ALL") +IDX1_G = _gsi_create("idx1", [("g", "HASH")], "KEYS_ONLY") + + +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=STREAM_NO_VIEW) + assert _validation_message(exc_info) == STREAM_VIEW_TYPE_REQUIRED + + +class TestIndexKeyAttributeUndefined: + """A secondary index key attribute that AttributeDefinitions does not + 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( + {}, + "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=BY_G, **members + ) + 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 + + +# 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