diff --git a/crates/core/src/validation/key_definitions.rs b/crates/core/src/validation/key_definitions.rs new file mode 100644 index 000000000..a1f87fb4c --- /dev/null +++ b/crates/core/src/validation/key_definitions.rs @@ -0,0 +1,312 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Checks that a key schema's attributes are defined in `AttributeDefinitions`, +//! shared by `CreateTable`, an `UpdateTable` GSI `Create` and a restore. +//! +//! The service's rules, measured on 2026-10-25, 2026-10-26 and 2026-11-25 +//! (us-east-1), in the order the service checks them: +//! +//! 1. A key schema with more keys than there are definitions answers +//! `Invalid KeySchema: Some index key attribute have no definition`. +//! 2. A key schema whose HASH and RANGE elements name one attribute answers +//! `Both the Hash Key and the Range Key element in the KeySchema have the +//! same name`. +//! 3. A name defined twice answers `Attribute Name is duplicated: `, +//! naming the name whose second definition comes first in the list. +//! 4. A key with no definition answers `Some index key attributes are not +//! defined in AttributeDefinitions`, listing every key of the schema and +//! every definition, each list in the order of [`listed`]. +//! +//! An `UpdateTable` GSI `Create` runs the four in that order. `CreateTable` +//! runs the first three on the table's key schema, after the table billing +//! rules and before the key schema shape checks, with rule 2 only outside the +//! multi-part table key preview. After every shape check it runs rule 4 on the +//! table's key schema, then rules 1 and 4 on each LSI's and each GSI's in turn. +//! The service checks each index's definitions before that index's shape +//! (measured 2026-11-25), so a request with both faults in one index gets the +//! shape sentence here. A restore runs `CreateTable`'s checks without rules 1 +//! and 3, which earlier releases did not apply (`validate_recorded_table`). + +use std::collections::HashSet; + +use crate::error::DynamoDbError; +use crate::types::{AttributeDefinition, KeySchemaElement, KeyType}; + +/// Rule 1's sentence. +const KEY_SCHEMA_WITHOUT_DEFINITION: &str = + "Invalid KeySchema: Some index key attribute have no definition"; + +/// Rule 1: refuse a key schema with more keys than `defs` has entries. +/// +/// # Errors +/// +/// `ValidationException` `Invalid KeySchema: Some index key attribute have no +/// definition`. +pub fn validate_definition_count( + key_schema: &[KeySchemaElement], + defs: &[AttributeDefinition], +) -> Result<(), DynamoDbError> { + if defs.len() < key_schema.len() { + return Err(DynamoDbError::ValidationException( + KEY_SCHEMA_WITHOUT_DEFINITION.to_owned(), + )); + } + Ok(()) +} + +/// Rule 2: refuse a two-element key schema whose HASH and RANGE elements name +/// one attribute. +/// +/// # Errors +/// +/// `ValidationException` `Both the Hash Key and the Range Key element in the +/// KeySchema have the same name`. +pub fn validate_hash_and_range_differ( + key_schema: &[KeySchemaElement], +) -> Result<(), DynamoDbError> { + if let [hash, range] = key_schema + && hash.key_type == KeyType::Hash + && range.key_type == KeyType::Range + && hash.attribute_name == range.attribute_name + { + return Err(DynamoDbError::ValidationException( + "Both the Hash Key and the Range Key element in the KeySchema have the same name" + .to_owned(), + )); + } + Ok(()) +} + +/// Rule 3: refuse a name defined twice in `defs`. +/// +/// # Errors +/// +/// `ValidationException` `Attribute Name is duplicated: `. +pub fn validate_unique_attribute_definitions( + defs: &[AttributeDefinition], +) -> Result<(), DynamoDbError> { + let mut seen = HashSet::with_capacity(defs.len()); + for def in defs { + if !seen.insert(def.attribute_name.as_str()) { + return Err(DynamoDbError::ValidationException(format!( + "Attribute Name is duplicated: {}", + def.attribute_name + ))); + } + } + Ok(()) +} + +/// Rule 4: refuse a key schema with a key that has no definition in `defs`. +/// +/// # Errors +/// +/// `ValidationException` `Some index key attributes are not defined in +/// AttributeDefinitions`, with every key and every definition. +pub fn validate_keys_defined( + key_schema: &[KeySchemaElement], + defs: &[AttributeDefinition], +) -> Result<(), DynamoDbError> { + if key_schema + .iter() + .all(|k| defs.iter().any(|d| d.attribute_name == k.attribute_name)) + { + return Ok(()); + } + let keys = listed(key_schema.iter().map(|k| k.attribute_name.as_str())); + let names = listed(defs.iter().map(|d| d.attribute_name.as_str())); + Err(DynamoDbError::ValidationException(format!( + "One or more parameter values were invalid: Some index key attributes are not defined in \ + AttributeDefinitions. Keys: [{}], AttributeDefinitions: [{}]", + keys.join(", "), + names.join(", ") + ))) +} + +/// The hash a `java.util.HashMap` spreads for a `String` key: Java's +/// `String.hashCode` of `name` over its UTF-16 code units (31 times the hash +/// plus each unit, wrapping at 32 bits), combined by XOR with itself shifted +/// right by 16 bits. The key's bucket in a table of `buckets` buckets is this +/// value masked by `buckets - 1`. +#[must_use] +pub fn spread_hash(name: &str) -> u32 { + let hash = name.encode_utf16().fold(0_u32, |h, unit| { + h.wrapping_mul(31).wrapping_add(u32::from(unit)) + }); + hash ^ (hash >> 16) +} + +/// The order in which the service lists the names of a key schema or of +/// `AttributeDefinitions`: the iteration order of a `java.util.HashMap` +/// created with 4 buckets and load factor 0.75, into which the names go in +/// request order. A name's bucket is its [`spread_hash`] masked by +/// `buckets - 1`. The table doubles when it holds more names than three +/// quarters of its buckets, and when a bucket that holds eight or more names +/// takes another while the table has fewer than 64 buckets. The names come out +/// bucket by bucket, in insertion order within a bucket (measured 2026-11-25, +/// with lists of up to nine names in one bucket). A repeated name keeps its +/// first position, as `HashMap::put` does. No measured list repeats a name. +/// +/// Not modelled: a bucket that holds eight or more names and takes another +/// while the table has 64 or more buckets. `HashMap` turns that bucket into a +/// tree, which it iterates in another order. That needs at least 11 names, +/// nine or more of them in one bucket. +fn listed<'a>(names: impl IntoIterator) -> Vec<&'a str> { + let mut seen = HashSet::new(); + let mut entries: Vec<(&str, u32)> = Vec::new(); + let mut buckets: u32 = 4; + for name in names { + if !seen.insert(name) { + continue; + } + let spread = spread_hash(name); + let mask = buckets - 1; + let crowded = buckets < 64 + && entries + .iter() + .filter(|&&(_, s)| s & mask == spread & mask) + .count() + >= 8; + entries.push((name, spread)); + if crowded || entries.len() > (buckets / 4 * 3) as usize { + buckets *= 2; + } + } + entries.sort_by_key(|&(_, s)| s & (buckets - 1)); + entries.into_iter().map(|(name, _)| name).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::ScalarAttributeType; + + fn defs(names: &[&str]) -> Vec { + names + .iter() + .map(|n| AttributeDefinition { + attribute_name: (*n).to_owned(), + attribute_type: ScalarAttributeType::S, + }) + .collect() + } + + fn ks(hash: &str, range: Option<&str>) -> Vec { + let mut k = vec![KeySchemaElement { + attribute_name: hash.to_owned(), + key_type: KeyType::Hash, + }]; + if let Some(r) = range { + k.push(KeySchemaElement { + attribute_name: r.to_owned(), + key_type: KeyType::Range, + }); + } + k + } + + fn message(r: Result<(), DynamoDbError>) -> String { + match r { + Err(DynamoDbError::ValidationException(m)) => m, + other => panic!("expected a ValidationException, got {other:?}"), + } + } + + #[test] + fn the_first_repeated_name_is_named() { + for (names, repeated) in [ + (&["b", "a", "b", "a"][..], "b"), + (&["a", "b", "b", "a"][..], "b"), + (&["a", "b", "a", "b"][..], "a"), + ] { + assert_eq!( + message(validate_unique_attribute_definitions(&defs(names))), + format!("Attribute Name is duplicated: {repeated}"), + "{names:?}" + ); + } + assert!(validate_unique_attribute_definitions(&defs(&["a", "b"])).is_ok()); + } + + #[test] + fn fewer_definitions_than_keys_is_the_key_schema_sentence() { + for (schema, names) in [(ks("g", Some("r")), &["pk"][..]), (ks("g", None), &[][..])] { + assert_eq!( + message(validate_definition_count(&schema, &defs(names))), + "Invalid KeySchema: Some index key attribute have no definition" + ); + } + assert!(validate_definition_count(&ks("g", Some("r")), &defs(&["pk", "x"])).is_ok()); + } + + #[test] + fn a_hash_and_a_range_on_one_name_is_refused() { + assert_eq!( + message(validate_hash_and_range_differ(&ks("g", Some("g")))), + "Both the Hash Key and the Range Key element in the KeySchema have the same name" + ); + assert!(validate_hash_and_range_differ(&ks("g", Some("r"))).is_ok()); + assert!(validate_hash_and_range_differ(&ks("g", None)).is_ok()); + } + + /// The lists of measured answers (2026-10-25 and 2026-11-25). + #[test] + fn a_missing_key_lists_every_key_and_every_definition_in_the_service_order() { + for (schema, names, expected) in [ + ( + ks("g", Some("r")), + &["pk", "g"][..], + "Keys: [r, g], AttributeDefinitions: [pk, g]", + ), + ( + ks("g", Some("r")), + &["pk", "z"][..], + "Keys: [r, g], AttributeDefinitions: [z, pk]", + ), + ( + ks("pk", Some("sk")), + &["pk", "x"][..], + "Keys: [sk, pk], AttributeDefinitions: [x, pk]", + ), + ] { + assert_eq!( + message(validate_keys_defined(&schema, &defs(names))), + format!( + "One or more parameter values were invalid: Some index key attributes are \ + not defined in AttributeDefinitions. {expected}" + ) + ); + } + assert!(validate_keys_defined(&ks("g", Some("r")), &defs(&["r", "g"])).is_ok()); + } + + /// Request order in, the service's order out (measured 2026-11-25). The + /// last two lists put nine and eight names in one bucket of a 16-bucket + /// table: the ninth makes the table double, the eighth does not. + #[test] + fn lists_follow_the_measured_order() { + for (request, service) in [ + ( + "alpha beta gamma delta epsilon zeta eta theta", + "epsilon zeta eta alpha delta theta beta gamma", + ), + ("Zed apple Mango kiwi Ünï", "Zed Mango apple kiwi Ünï"), + ("pk id userId createdAt", "createdAt pk id userId"), + ("gsiPk gsiSk", "gsiSk gsiPk"), + ("pk sk g", "sk pk g"), + ("pk g h", "h pk g"), + ("pk n b", "n b pk"), + ( + "kaaa kaaq kabb kabr kacc kacs kadd kadt kaee", + "kaaa kabb kacc kadd kaee kaaq kabr kacs kadt", + ), + ( + "kaaa kaaq kabb kabr kacc kacs kadd kadt", + "kaaa kaaq kabb kabr kacc kacs kadd kadt", + ), + ] { + assert_eq!(listed(request.split(' ')).join(" "), service, "{request}"); + } + } +} diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index 9c1bcbb21..0acc41a39 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -1,10 +1,15 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 +mod key_definitions; pub mod number; pub mod restorable_item; pub mod vector_item; pub mod warm_throughput; +pub use key_definitions::{ + spread_hash, validate_definition_count, validate_hash_and_range_differ, validate_keys_defined, + validate_unique_attribute_definitions, +}; pub use restorable_item::{ RestorableItemError, RestorableItemReason, RestorableKeySchema, RestorableLimits, SHOWN_VALUE_BYTES, validate_restorable_item, @@ -112,12 +117,62 @@ pub fn validate_create_table( input: &CreateTableInput, limits: &LimitsConfig, ) -> Result<(), DynamoDbError> { + validate_table(input, limits, false) +} + +/// Validate the table definition a backup records, before a restore creates +/// the table from it. Every check of [`validate_create_table`] runs except two: +/// a name defined twice in `AttributeDefinitions`, and a key schema with more +/// keys than there are definitions. Earlier releases accepted both at +/// `CreateTable` and stored them, so a backup can record them. Every key of +/// each key schema still needs a definition. +/// +/// # Errors +/// +/// The `ValidationException` of the first check that fails. +pub fn validate_recorded_table( + input: &CreateTableInput, + limits: &LimitsConfig, +) -> Result<(), DynamoDbError> { + validate_table(input, limits, true) +} + +fn validate_table( + input: &CreateTableInput, + limits: &LimitsConfig, + recorded: bool, +) -> Result<(), DynamoDbError> { + // The request's member constraints come first. The service answers the + // keySchema length before the definition count and the key schema shape, + // and an index name before the billing rules and a name defined twice + // (measured 2026-11-25). validate_table_name(&input.table_name, limits)?; + validate_key_schema_size(input, limits.allow_multipart_table_keys)?; + for gsi in input.global_secondary_indexes.iter().flatten() { + validate_index_name(&gsi.index_name)?; + } + for lsi in input.local_secondary_indexes.iter().flatten() { + validate_index_name(&lsi.index_name)?; + } + // Then a table billing fault, then the table's key schema against the + // definitions and a name defined twice, all before the key schema shape + // checks (measured 2026-10-26 and 2026-11-25; see key_definitions.rs). + validate_provisioned_throughput(input)?; + if !recorded { + validate_definition_count(&input.key_schema, &input.attribute_definitions)?; + } + // A multi-part table key schema may name one attribute as HASH and RANGE, + // as in earlier releases, and a backup can record such a table. + if !limits.allow_multipart_table_keys { + validate_hash_and_range_differ(&input.key_schema)?; + } + if !recorded { + validate_unique_attribute_definitions(&input.attribute_definitions)?; + } validate_key_schema(input, limits.allow_multipart_table_keys)?; validate_gsi_key_schemas(input)?; validate_lsi_key_schemas(input)?; - validate_attribute_definitions(input)?; - validate_provisioned_throughput(input)?; + validate_attribute_definitions(input, recorded)?; validate_gsi_provisioned_throughput(input)?; validate_gsi_throughput_minimum(input)?; validate_gsi_count(input, limits)?; @@ -716,7 +771,9 @@ fn format_key_schema_value(ks: &[KeySchemaElement]) -> String { /// Maximum number of HASH or RANGE elements in a multi-part key schema. const MAX_MULTIPART_KEY_ELEMENTS: usize = 4; -fn validate_key_schema( +/// The table key schema's member constraints: present, and at most two +/// elements unless multi-part table keys are allowed. +fn validate_key_schema_size( input: &CreateTableInput, allow_multipart: bool, ) -> Result<(), DynamoDbError> { @@ -726,7 +783,28 @@ fn validate_key_schema( &[], ))); } - if input.key_schema[0].key_type != KeyType::Hash { + if !allow_multipart && input.key_schema.len() > 2 { + let ks_repr = format_key_schema_value(&input.key_schema); + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value '{ks_repr}' at 'keySchema' failed to satisfy constraint: \ + Member must have length less than or equal to 2" + ))); + } + Ok(()) +} + +/// The table key schema's shape, after [`validate_key_schema_size`]: a HASH +/// element first, then a RANGE element when there are two (or the multi-part +/// rules). +fn validate_key_schema( + input: &CreateTableInput, + allow_multipart: bool, +) -> Result<(), DynamoDbError> { + if input + .key_schema + .first() + .is_some_and(|k| k.key_type != KeyType::Hash) + { return Err(DynamoDbError::ValidationException(error_message( ErrorMessageKey::KeySchemaFirstNotHash, &[], @@ -735,27 +813,15 @@ fn validate_key_schema( if allow_multipart { validate_multipart_key_schema(&input.key_schema, "table")?; - } else { + } else if input + .key_schema + .get(1) + .is_some_and(|k| k.key_type != KeyType::Range) + { // Standard DynamoDB: 1 HASH + optional 1 RANGE - if input.key_schema.len() > 2 { - let ks_repr = format_key_schema_value(&input.key_schema); - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value '{ks_repr}' at 'keySchema' failed to satisfy constraint: \ - Member must have length less than or equal to 2" - ))); - } - if input.key_schema.len() == 2 { - if input.key_schema[1].key_type != KeyType::Range { - return Err(DynamoDbError::ValidationException( - "Second KeySchemaElement is not a RANGE type".to_owned(), - )); - } - if input.key_schema[0].attribute_name == input.key_schema[1].attribute_name { - return Err(DynamoDbError::ValidationException( - "Invalid KeySchema: Some index key attribute have no definition".to_owned(), - )); - } - } + return Err(DynamoDbError::ValidationException( + "Second KeySchemaElement is not a RANGE type".to_owned(), + )); } Ok(()) } @@ -817,7 +883,6 @@ fn validate_gsi_key_schemas(input: &CreateTableInput) -> Result<(), DynamoDbErro return Ok(()); }; for gsi in gsis { - validate_index_name(&gsi.index_name)?; if gsi.key_schema.is_empty() { return Err(DynamoDbError::ValidationException(format!( "One or more parameter values were invalid: No defined key schema for index: {}", @@ -843,7 +908,6 @@ fn validate_lsi_key_schemas(input: &CreateTableInput) -> Result<(), DynamoDbErro }; let table_hash_key = &input.key_schema[0].attribute_name; for lsi in lsis { - validate_index_name(&lsi.index_name)?; match lsi.key_schema.as_slice() { [hash, range] => { if hash.key_type != KeyType::Hash { @@ -879,7 +943,10 @@ fn validate_lsi_key_schemas(input: &CreateTableInput) -> Result<(), DynamoDbErro Ok(()) } -fn validate_attribute_definitions(input: &CreateTableInput) -> Result<(), DynamoDbError> { +fn validate_attribute_definitions( + input: &CreateTableInput, + recorded: bool, +) -> Result<(), DynamoDbError> { // A vector attribute must NOT be declared in AttributeDefinitions, and this is // checked before anything else here because the attribute may simultaneously be // a legitimate key attribute: without this, naming the table's own partition key @@ -964,14 +1031,29 @@ fn validate_attribute_definitions(input: &CreateTableInput) -> Result<(), Dynamo } } - // Every key attribute must have a definition - for attr in &key_attrs { - if !def_names.contains(attr) { - return Err(DynamoDbError::ValidationException(format!( - "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [{attr}], AttributeDefinitions: [{}]", - format_attr_defs(&input.attribute_definitions) - ))); + // Every key attribute must have a definition: the table's key schema, then + // each LSI's, then each GSI's (measured order, see key_definitions.rs). The + // table's definition count came first, in `validate_table`. A recorded + // table keeps only the rule that each key has a definition. + let defs = &input.attribute_definitions; + validate_keys_defined(&input.key_schema, defs)?; + let index_schemas = input + .local_secondary_indexes + .iter() + .flatten() + .map(|lsi| &lsi.key_schema) + .chain( + input + .global_secondary_indexes + .iter() + .flatten() + .map(|gsi| &gsi.key_schema), + ); + for schema in index_schemas { + if !recorded { + validate_definition_count(schema, defs)?; } + validate_keys_defined(schema, defs)?; } // Every definition must be used by a key @@ -987,13 +1069,6 @@ fn validate_attribute_definitions(input: &CreateTableInput) -> Result<(), Dynamo Ok(()) } -fn format_attr_defs(defs: &[AttributeDefinition]) -> String { - defs.iter() - .map(|d| d.attribute_name.clone()) - .collect::>() - .join(", ") -} - /// Validate table-level throughput against the effective billing mode. /// /// # Errors @@ -2923,7 +2998,7 @@ mod tests { ], ); input.vector_indexes = Some(vec![vi_spec("vidx")]); - let err = validate_attribute_definitions(&input) + let err = validate_attribute_definitions(&input, false) .expect_err("a declared vector attribute must be refused"); assert_eq!(format!("{err}"), expected); @@ -2936,7 +3011,7 @@ mod tests { let mut spec = vi_spec("vidx"); spec.vector_attribute.attribute_name = "pk".to_owned(); input.vector_indexes = Some(vec![spec]); - let err = validate_attribute_definitions(&input) + let err = validate_attribute_definitions(&input, false) .expect_err("the partition key must not double as the vector attribute"); assert!( format!("{err}").contains("Conflicting attribute definition for 'pk'"), @@ -2998,7 +3073,7 @@ mod tests { element_type: crate::types::SearchSchemaElementType::Hash, }]); input.vector_indexes = Some(vec![spec]); - let err = validate_attribute_definitions(&input) + let err = validate_attribute_definitions(&input, false) .expect_err("an undefined SearchSchema attribute must be refused"); assert_eq!( format!("{err}"), @@ -3099,6 +3174,29 @@ mod tests { assert!(validate_create_table(&input, &limits).is_ok()); } + /// Earlier releases accepted a multi-part table key schema with a HASH and + /// a RANGE on one name, so a restore of such a table still passes. + /// `CreateTable` refuses the shape with one definition by the definition + /// count. + #[test] + fn a_multipart_table_hash_and_range_on_one_name_restores() { + let limits = LimitsConfig { + allow_multipart_table_keys: true, + ..Default::default() + }; + let input = base_input( + vec![make_ks("a", KeyType::Hash), make_ks("a", KeyType::Range)], + vec![make_ad("a", ScalarAttributeType::S)], + ); + validate_recorded_table(&input, &limits).unwrap(); + assert_eq!( + validate_create_table(&input, &limits) + .unwrap_err() + .to_string(), + "Invalid KeySchema: Some index key attribute have no definition" + ); + } + #[test] fn gsi_multipart_keys_always_allowed() { let limits = LimitsConfig::default(); // allow_multipart_table_keys = false diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index 5f0286d47..d804ea930 100755 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -1349,9 +1349,12 @@ where // 8. A stored definition the service would refuse at CreateTable is // refused here too (the service re-validates on restore): a backup row - // is data, and data can be wrong. Only CreateTable's rules apply, so a - // table CreateTable or UpdateTable accepted restores. - extenddb_core::validation::validate_create_table(&input, limits)?; + // is data, and data can be wrong. The rules are CreateTable's but two: + // a name defined twice in AttributeDefinitions and a key schema with + // more keys than definitions, which earlier releases accepted at + // CreateTable (`validate_recorded_table`). So a table CreateTable or + // UpdateTable accepted restores. + extenddb_core::validation::validate_recorded_table(&input, limits)?; let on_demand = input.billing_mode == Some(BillingMode::PayPerRequest); // 9. The maintenance claim, then the permit last: every refusal above diff --git a/crates/engine/src/backup/restore.rs b/crates/engine/src/backup/restore.rs index 31cfedd58..f2ad79236 100644 --- a/crates/engine/src/backup/restore.rs +++ b/crates/engine/src/backup/restore.rs @@ -280,11 +280,13 @@ where ))); } - // The target's input, with the overrides, validated as CreateTable does. + // The target's input, with the overrides, validated as CreateTable does, + // less the two rules earlier releases did not apply at CreateTable + // (`validate_recorded_table`). validate_override_for_source(overrides, billing_mode_name(source_table.billing_mode))?; let mut input = restore_input_from_manifest(source_table, target_table_name, overrides); index_overrides.apply(&mut input, overrides.billing_mode)?; - extenddb_core::validation::validate_create_table(&input, limits)?; + extenddb_core::validation::validate_recorded_table(&input, limits)?; // The key schema the validator holds every item to: a pure function of // the manifest, resolved here with step 2's refusals rather than after // the client was told the target is CREATING. diff --git a/crates/engine/src/backup/tests.rs b/crates/engine/src/backup/tests.rs index e0f6a5692..ac691a73e 100644 --- a/crates/engine/src/backup/tests.rs +++ b/crates/engine/src/backup/tests.rs @@ -6095,6 +6095,56 @@ async fn a_table_create_table_accepted_restores() { } } +/// An on-demand table with key pk and a GSI on gpk, with the given recorded +/// definitions and GSI key schema. +fn source_with_gsi_keys( + attribute_definitions: Vec, + gsi_keys: Vec, +) -> BackupRestoreSource { + let mut src = source(Some(definition("PAY_PER_REQUEST"))); + src.key_schema = vec![key("pk", KeyType::Hash)]; + src.attribute_definitions = attribute_definitions; + let def = src.definition.as_mut().unwrap(); + def.local_secondary_indexes = Vec::new(); + def.global_secondary_indexes[0].key_schema = gsi_keys; + src +} + +/// Earlier releases accepted a name defined twice in `AttributeDefinitions` at +/// `CreateTable` and stored both definitions. A backup of such a table restores +/// on both paths and keeps the recorded definitions. +#[tokio::test] +async fn a_backup_that_records_a_name_defined_twice_restores() { + let numeric = AttributeDefinition { + attribute_name: "gpk".to_owned(), + attribute_type: ScalarAttributeType::N, + }; + let defs = vec![attr("pk"), numeric, attr("gpk")]; + let src = source_with_gsi_keys(defs.clone(), vec![key("gpk", KeyType::Hash)]); + let input = restored_input(src, json!({})).await.unwrap(); + assert_eq!(input.attribute_definitions, defs); +} + +/// Earlier releases accepted a GSI key schema with more keys than there are +/// definitions when the keys repeat a name. A backup of such a table restores +/// on both paths and keeps the recorded definitions and keys. +#[tokio::test] +async fn a_backup_that_records_more_index_keys_than_definitions_restores() { + let defs = vec![attr("pk"), attr("gpk")]; + let gsi_keys = vec![ + key("gpk", KeyType::Hash), + key("gpk", KeyType::Hash), + key("gpk", KeyType::Range), + ]; + let src = source_with_gsi_keys(defs.clone(), gsi_keys.clone()); + let input = restored_input(src, json!({})).await.unwrap(); + assert_eq!(input.attribute_definitions, defs); + assert_eq!( + input.global_secondary_indexes.unwrap()[0].key_schema, + gsi_keys + ); +} + #[tokio::test] async fn a_missing_backup_is_backup_not_found() { let fake = Arc::new(Fake::default()); diff --git a/crates/engine/src/gsi_updates.rs b/crates/engine/src/gsi_updates.rs index 6ec68af85..7f5ae9a2b 100644 --- a/crates/engine/src/gsi_updates.rs +++ b/crates/engine/src/gsi_updates.rs @@ -244,44 +244,20 @@ 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 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.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(); + // 2026-10-25, 2026-10-26 and 2026-11-25): absent names the index; + // then come the four rules of core's key_definitions.rs, in its + // order: the definition count, the HASH and RANGE names, a name + // defined twice, then a key with no definition. + let Some(defs) = &input.attribute_definitions else { 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(", ") + "One or more parameter values were invalid: AttributeDefinitions is not specified for index: {}", + create.index_name ))); - } + }; + extenddb_core::validation::validate_definition_count(&create.key_schema, defs)?; + extenddb_core::validation::validate_hash_and_range_differ(&create.key_schema)?; + extenddb_core::validation::validate_unique_attribute_definitions(defs)?; + extenddb_core::validation::validate_keys_defined(&create.key_schema, defs)?; } if let Some(delete) = &update.delete { validate_update_index_name(&delete.index_name, position, "delete")?; @@ -559,16 +535,21 @@ 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. + /// (measured 2026-10-25, 2026-10-26 and 2026-11-25): absent names the + /// index, then fewer definitions than the index has keys, a HASH and a + /// RANGE on one name, a name defined twice, and last the sentence that + /// 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 SAME_NAME: &str = + "Both the Hash Key and the Range Key element in the KeySchema have the same name"; 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 LISTED_PK_G: &str = "One or more parameter values were invalid: Some index key \ + attributes are not defined in AttributeDefinitions. Keys: \ + [r, g], AttributeDefinitions: [pk, g]"; 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 { @@ -598,6 +579,11 @@ mod tests { (["g", "r"], Some("g"), FEWER), (["g", "r"], Some("other"), FEWER), (["r", "g"], Some("r pk"), LISTED), + (["g", "r"], Some("pk g"), LISTED_PK_G), + (["g", "r"], Some("g g"), "Attribute Name is duplicated: g"), + (["g", "g"], Some("g"), FEWER), + (["g", "g"], Some("g g"), SAME_NAME), + (["g", "g"], Some("g x"), SAME_NAME), ]; for (keys, defs, expected) in cases { assert_eq!( diff --git a/crates/engine/src/partiql/request_checks/echo.rs b/crates/engine/src/partiql/request_checks/echo.rs index 89be6da8f..e0e45b3dc 100644 --- a/crates/engine/src/partiql/request_checks/echo.rs +++ b/crates/engine/src/partiql/request_checks/echo.rs @@ -6,6 +6,7 @@ use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64; +use extenddb_core::validation::spread_hash; use serde_json::{Map, Value}; /// The longest echo of a statement list, in bytes. Every echo measured is @@ -210,12 +211,7 @@ fn print_order(members: &Map) -> Vec<(&String, &Value)> { /// The bucket of `key` in a Java `HashMap` table of `buckets` buckets. fn bucket(key: &str, buckets: usize) -> usize { - // Java's `String.hashCode`: 31 times the hash plus each UTF-16 unit, - // wrapping at 32 bits. - let hash = key.encode_utf16().fold(0_u32, |hash, unit| { - hash.wrapping_mul(31).wrapping_add(u32::from(unit)) - }); - (hash ^ (hash >> 16)) as usize & (buckets - 1) + spread_hash(key) as usize & (buckets - 1) } #[cfg(test)] diff --git a/tests/test_key_schema_definitions.py b/tests/test_key_schema_definitions.py new file mode 100644 index 000000000..eb9fbe123 --- /dev/null +++ b/tests/test_key_schema_definitions.py @@ -0,0 +1,258 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Key schemas whose attributes are missing from AttributeDefinitions. + +Amazon DynamoDB, measured on 2026-10-25, 2026-10-26 and 2026-11-25 +(us-east-1), each request twice, on CreateTable and on an UpdateTable GSI +Create: + +- The keySchema length constraint comes before the key schema rules below, + and on CreateTable so does a table billing fault. +- Then the table's key schema, or the created index's, against the + definitions: more keys than there are definitions answers ``Invalid + KeySchema: Some index key attribute have no definition``, and a HASH and a + RANGE element on one name answers ``Both the Hash Key and the Range Key + element in the KeySchema have the same name``. +- Then a name defined twice answers ``Attribute Name is duplicated: ``, + naming the name whose second definition comes first. +- On CreateTable each key schema follows in turn, the table's, each LSI's and + each GSI's: more keys than definitions answers ``Invalid KeySchema``, and a + key with no definition answers ``Some index key attributes are not defined + in AttributeDefinitions`` listing every key of that schema and every + definition. The service checks an index's definitions before its shape, and + ExtendDB checks every shape first. No row here has both faults in one index. + +The service lists both in the order of a Java HashMap, which +crates/core/src/validation/key_definitions.rs models, so the rows compare the +whole message. + +The service answers every refusal below before it looks the table up, so the +rows go to a table name no test creates. + +On UpdateTable a definition that redefines the table's own key with another +type is accepted beside a valid Create, and the table keeps its type +(measured 2026-10-25). + +Dual-target against Amazon DynamoDB and extenddb. +""" + +from __future__ import annotations + +import time + +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table + +NEVER_CREATED = "never-created-key-definitions" +INVALID = "Invalid KeySchema: Some index key attribute have no definition" +SAME_NAME = "Both the Hash Key and the Range Key element in the KeySchema have the same name" + + +def listed(keys: str, names: str) -> str: + return ("One or more parameter values were invalid: Some index key attributes are not defined in " + f"AttributeDefinitions. Keys: [{keys}], AttributeDefinitions: [{names}]") + + +def defs(spec: str) -> list[dict]: + return [{"AttributeName": p.split(":")[0], "AttributeType": p.split(":")[1]} for p in spec.split()] + + +def keys(spec: str) -> list[dict]: + """A key schema in any order, as ``name:HASH name:RANGE``.""" + return [{"AttributeName": p.split(":")[0], "KeyType": p.split(":")[1]} for p in spec.split()] + + +def _message(call) -> str: + with pytest.raises(ClientError) as exc_info: + call() + err = exc_info.value.response["Error"] + assert err["Code"] == "ValidationException", err + assert exc_info.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400, err + return err["Message"] + + +def _update(client, spec, key_schema): + return lambda: client.update_table( + TableName=NEVER_CREATED, + AttributeDefinitions=defs(spec), + GlobalSecondaryIndexUpdates=[{"Create": { + "IndexName": "never-created", + "KeySchema": key_schema, + "Projection": {"ProjectionType": "KEYS_ONLY"}, + }}], + ) + + +def _create(client, spec, table_keys, gsis=(), lsis=()): + kwargs = { + "TableName": NEVER_CREATED, + "AttributeDefinitions": defs(spec), + "KeySchema": table_keys, + "BillingMode": "PAY_PER_REQUEST", + } + if gsis: + kwargs["GlobalSecondaryIndexes"] = [ + {"IndexName": f"gsi{i}", "KeySchema": k, "Projection": {"ProjectionType": "KEYS_ONLY"}} + for i, k in enumerate(gsis) + ] + if lsis: + kwargs["LocalSecondaryIndexes"] = [ + {"IndexName": f"lsi{i}", "KeySchema": k, "Projection": {"ProjectionType": "KEYS_ONLY"}} + for i, k in enumerate(lsis) + ] + return lambda: client.create_table(**kwargs) + + +# UpdateTable GSI Create: (case, definitions, index key schema, message). +UPDATE_TABLE = [ + # A key with no definition: every key of the index and every definition. + ("range_missing", "pk:S g:S", keys("g:HASH r:RANGE"), listed("r, g", "pk, g")), + ("hash_missing", "pk:S r:S", keys("g:HASH r:RANGE"), listed("r, g", "r, pk")), + ("both_missing_two_defs", "pk:S z:S", keys("g:HASH r:RANGE"), listed("r, g", "z, pk")), + ("both_missing_three_defs", "pk:S y:S z:S", keys("g:HASH r:RANGE"), listed("r, g", "y, z, pk")), + ("hash_only_missing", "pk:S", keys("g:HASH"), listed("g", "pk")), + ("other_types", "pk:S n:N b:B", keys("n:HASH x:RANGE"), listed("x, n", "n, b, pk")), + ("service_order", "pk:S x:S", keys("g:HASH r:RANGE"), listed("r, g", "x, pk")), + # More keys than there are definitions. + ("both_missing_one_def", "pk:S", keys("g:HASH r:RANGE"), INVALID), + ("range_missing_one_def", "pk:S", keys("pk:HASH r:RANGE"), INVALID), + # A name defined twice, naming the name whose second definition comes first. + ("duplicate_index_key", "h:S h:S", keys("h:HASH"), "Attribute Name is duplicated: h"), + ("duplicate_and_a_missing_key", "h:S h:S", keys("h:HASH r:RANGE"), "Attribute Name is duplicated: h"), + ("duplicate_first_repeated", "b:S a:S b:S a:S h:S", keys("h:HASH r:RANGE"), "Attribute Name is duplicated: b"), + ("duplicate_second_definition_first", "a:S b:S b:S a:S h:S", keys("h:HASH r:RANGE"), "Attribute Name is duplicated: b"), + ("duplicate_first_definition_first", "a:S b:S a:S b:S h:S", keys("h:HASH r:RANGE"), "Attribute Name is duplicated: a"), + ("duplicate_two_types", "h:S h:N", keys("h:HASH r:RANGE"), "Attribute Name is duplicated: h"), + # Two rules apply: the definition count and the HASH and RANGE names come + # before a name defined twice. + ("count_before_duplicate", "g:S g:S", keys("g:HASH x:RANGE y:RANGE"), INVALID), + ("count_before_duplicate_other_names", "a:S a:S", keys("a:HASH b:RANGE c:RANGE"), INVALID), + ("same_name_before_duplicate", "g:S g:S", keys("g:HASH g:RANGE"), SAME_NAME), + ("count_before_same_name", "g:S", keys("g:HASH g:RANGE"), INVALID), + ("same_name", "g:S x:S", keys("g:HASH g:RANGE"), SAME_NAME), +] + + +@pytest.mark.parametrize(("case", "spec", "key_schema", "expected"), UPDATE_TABLE, + ids=[c[0] for c in UPDATE_TABLE]) +def test_update_table_gsi_create_answers_the_measured_sentence(dynamodb_client, case, spec, key_schema, + expected): + assert _message(_update(dynamodb_client, spec, key_schema)) == expected + + +KEY_SCHEMA_LENGTH = ("1 validation error detected: Value '[KeySchemaElement(attributeName=a, keyType={}), " + "KeySchemaElement(attributeName=b, keyType={}), KeySchemaElement(attributeName=c, " + "keyType=RANGE)]' at 'keySchema' failed to satisfy constraint: Member must have length " + "less than or equal to 2") + +# CreateTable: (case, definitions, table keys, GSIs, LSIs, message). +CREATE_TABLE = [ + # A key with no definition, checked on each key schema in turn: more keys + # than definitions answers INVALID, and otherwise the listing names every + # key of that schema and every definition. + ("gsi_range_missing", "pk:S g:S", keys("pk:HASH"), [keys("g:HASH r:RANGE")], [], listed("r, g", "pk, g")), + ("gsi_both_missing", "pk:S", keys("pk:HASH"), [keys("g:HASH r:RANGE")], [], INVALID), + ("table_sort_missing_one_def", "pk:S", keys("pk:HASH sk:RANGE"), [], [], INVALID), + ("table_sort_missing", "pk:S x:S", keys("pk:HASH sk:RANGE"), [], [], listed("sk, pk", "x, pk")), + ("table_pk_missing", "x:S", keys("pk:HASH"), [], [], listed("pk", "x")), + ("table_before_gsi", "pk:S g:S", keys("pk:HASH sk:RANGE"), [keys("g:HASH r:RANGE")], [], listed("sk, pk", "pk, g")), + ("table_before_lsi", "pk:S x:S", keys("pk:HASH sk:RANGE"), [], [keys("pk:HASH l:RANGE")], listed("sk, pk", "x, pk")), + ("lsi_missing", "pk:S sk:S", keys("pk:HASH sk:RANGE"), [], [keys("pk:HASH l:RANGE")], listed("l, pk", "sk, pk")), + ("lsi_before_gsi", "pk:S sk:S g:S", keys("pk:HASH sk:RANGE"), [keys("g:HASH r:RANGE")], [keys("pk:HASH l:RANGE")], + listed("l, pk", "sk, pk, g")), + ("first_gsi_first", "pk:S g:S h:S", keys("pk:HASH"), [keys("g:HASH r:RANGE"), keys("h:HASH q:RANGE")], [], + listed("r, g", "h, pk, g")), + # A name defined twice, naming the name whose second definition comes first. + ("duplicate_table_key", "pk:S pk:S", keys("pk:HASH"), [], [], "Attribute Name is duplicated: pk"), + ("duplicate_two_types", "pk:S pk:N", keys("pk:HASH"), [], [], "Attribute Name is duplicated: pk"), + ("duplicate_and_a_missing_key", "pk:S pk:S", keys("pk:HASH sk:RANGE"), [], [], "Attribute Name is duplicated: pk"), + ("duplicate_index_key", "pk:S g:S g:S", keys("pk:HASH"), [keys("g:HASH")], [], "Attribute Name is duplicated: g"), + ("duplicate_first_repeated", "b:S a:S b:S a:S pk:S", keys("pk:HASH"), [], [], "Attribute Name is duplicated: b"), + ("duplicate_second_definition_first", "a:S b:S b:S a:S pk:S", keys("pk:HASH"), [], [], + "Attribute Name is duplicated: b"), + ("duplicate_first_definition_first", "a:S b:S a:S b:S pk:S", keys("pk:HASH"), [], [], + "Attribute Name is duplicated: a"), + # Two rules apply: the keySchema length comes first, then the definition + # count, then the HASH and RANGE names, then a name defined twice, then the + # key schema shapes. + ("length_before_count", "a:S b:S", keys("a:HASH b:RANGE c:RANGE"), [], [], + KEY_SCHEMA_LENGTH.format("HASH", "RANGE")), + ("length_before_shape", "a:S b:S c:S", keys("a:RANGE b:HASH c:RANGE"), [], [], + KEY_SCHEMA_LENGTH.format("RANGE", "HASH")), + ("count_before_shape", "pk:S", keys("sk:RANGE pk:HASH"), [], [], INVALID), + ("count_before_same_name", "pk:S", keys("pk:HASH pk:RANGE"), [], [], INVALID), + ("same_name", "pk:S x:S", keys("pk:HASH pk:RANGE"), [], [], SAME_NAME), + ("same_name_before_duplicate", "pk:S pk:S", keys("pk:HASH pk:RANGE"), [], [], SAME_NAME), + ("duplicate_before_table_hash_first", "pk:S sk:S sk:S", keys("sk:RANGE pk:HASH"), [], [], + "Attribute Name is duplicated: sk"), + ("duplicate_before_table_range_second", "pk:S sk:S sk:S", keys("pk:HASH sk:HASH"), [], [], + "Attribute Name is duplicated: sk"), + ("duplicate_before_gsi_shape", "pk:S g:S g:S r:S", keys("pk:HASH"), [keys("r:RANGE g:HASH")], [], + "Attribute Name is duplicated: g"), + ("duplicate_before_lsi_shape", "pk:S sk:S l:S l:S", keys("pk:HASH sk:RANGE"), [], [keys("l:RANGE pk:HASH")], + "Attribute Name is duplicated: l"), +] + + +@pytest.mark.parametrize(("case", "spec", "table_keys", "gsis", "lsis", "expected"), CREATE_TABLE, + ids=[c[0] for c in CREATE_TABLE]) +def test_create_table_answers_the_measured_sentence(dynamodb_client, case, spec, table_keys, gsis, lsis, + expected): + assert _message(_create(dynamodb_client, spec, table_keys, gsis, lsis)) == expected + + +BILLING = ("One or more parameter values were invalid: Neither ReadCapacityUnits nor WriteCapacityUnits " + "can be specified when BillingMode is PAY_PER_REQUEST") + + +@pytest.mark.parametrize(("spec", "table_keys"), [ + ("pk:S pk:S", keys("pk:HASH")), + ("pk:S x:S", keys("pk:HASH sk:RANGE")), + ("pk:S", keys("pk:HASH sk:RANGE")), + ("pk:S sk:S", keys("sk:RANGE pk:HASH")), +], ids=["duplicate", "missing_key", "fewer_definitions", "range_first"]) +def test_create_table_reports_a_billing_fault_first(dynamodb_client, spec, table_keys): + def call(): + dynamodb_client.create_table( + TableName=NEVER_CREATED, AttributeDefinitions=defs(spec), KeySchema=table_keys, + BillingMode="PAY_PER_REQUEST", ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}) + assert _message(call) == BILLING + + +def _wait_for_index(client, table, index, timeout=1800.0): + """Wait until the table is ACTIVE and ``index`` is ACTIVE or absent.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + desc = client.describe_table(TableName=table)["Table"] + status = {i["IndexName"]: i["IndexStatus"] for i in desc.get("GlobalSecondaryIndexes", [])} + if desc["TableStatus"] == "ACTIVE" and status.get(index, "ACTIVE") == "ACTIVE": + return + time.sleep(0.5) + raise TimeoutError(f"{index} on {table} not ACTIVE after {timeout} s") + + +def test_update_table_keeps_the_type_of_a_redefined_table_key(dynamodb_client): + with scoped_table(dynamodb_client) as name: + try: + dynamodb_client.update_table( + TableName=name, + AttributeDefinitions=defs("pk:N g:S"), + GlobalSecondaryIndexUpdates=[{"Create": { + "IndexName": "by-g", + "KeySchema": keys("g:HASH"), + "Projection": {"ProjectionType": "KEYS_ONLY"}, + }}], + ) + desc = dynamodb_client.describe_table(TableName=name)["Table"] + stored = {d["AttributeName"]: d["AttributeType"] for d in desc["AttributeDefinitions"]} + assert stored == {"pk": "S", "g": "S"} + dynamodb_client.put_item(TableName=name, Item={"pk": {"S": "a"}, "g": {"S": "b"}}) + finally: + # scoped_table deletes the table next, and the service refuses + # DeleteTable while an index is being created. On the service the + # index on this empty table took about 9 and about 16 minutes to + # go ACTIVE (two runs, 2026-11-24). + _wait_for_index(dynamodb_client, name, "by-g")