From 1ad6576224277909ca54f4d0456810c6b323885e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:30:55 +0000 Subject: [PATCH 01/13] fix(table): check each key schema's definitions as the service does CreateTable and an UpdateTable GSI Create refused an undefined key attribute with one sentence that named only the first missing key. Amazon DynamoDB (measured 2026-10-25 and 2026-10-26 at 01:30 and 01:36 UTC, each request twice) applies these rules: - A name defined twice in AttributeDefinitions answers `Attribute Name is duplicated: `, naming the first name whose second definition comes first, before any key check. ExtendDB accepted duplicates. - The table's key schema is checked first, then each LSI's, then each GSI's. A schema with more keys than there are definitions answers `Invalid KeySchema: Some index key attribute have no definition`; otherwise 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 two checks live in the new validation/key_definitions.rs and both operations call them. The service orders the two lists in a way that follows neither the request nor the alphabet; ExtendDB lists them in request order. The UpdateTable unit test row that expected the listing sentence for one definition and two keys now expects the key schema sentence, as measured. --- crates/core/src/validation/key_definitions.rs | 165 ++++++++++++++++++ crates/core/src/validation/mod.rs | 27 ++- crates/engine/src/update_table.rs | 47 +---- crates/engine/src/update_table_tests.rs | 23 ++- 4 files changed, 202 insertions(+), 60 deletions(-) create mode 100644 crates/core/src/validation/key_definitions.rs diff --git a/crates/core/src/validation/key_definitions.rs b/crates/core/src/validation/key_definitions.rs new file mode 100644 index 000000000..18f71d438 --- /dev/null +++ b/crates/core/src/validation/key_definitions.rs @@ -0,0 +1,165 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Checks that a key schema's attributes are defined in `AttributeDefinitions`, +//! shared by `CreateTable` and an `UpdateTable` GSI `Create`. +//! +//! The service's rules, measured on 2026-10-25 and 2026-10-26 (us-east-1): +//! +//! - A name defined twice answers `Attribute Name is duplicated: `, +//! naming the first name whose second definition comes first in the list. +//! This comes before every key check. +//! - Each key schema is then checked in turn: the table's, each LSI's, each +//! GSI's. A schema with more keys than there are definitions answers +//! `Invalid KeySchema: Some index key attribute have no definition`. A +//! schema with a key that has no definition answers `Some index key +//! attributes are not defined in AttributeDefinitions`, listing every key of +//! that schema and every definition. +//! +//! The service lists the keys and definitions in an order that follows neither +//! the request nor the alphabet; ExtendDB lists them in request order. + +use crate::error::DynamoDbError; +use crate::types::{AttributeDefinition, KeySchemaElement}; + +/// Refuse a name defined twice in `defs`. +/// +/// # Errors +/// +/// `ValidationException` `Attribute Name is duplicated: `. +pub fn validate_unique_attribute_definitions( + defs: &[AttributeDefinition], +) -> Result<(), DynamoDbError> { + for (i, def) in defs.iter().enumerate() { + if defs[..i] + .iter() + .any(|earlier| earlier.attribute_name == def.attribute_name) + { + return Err(DynamoDbError::ValidationException(format!( + "Attribute Name is duplicated: {}", + def.attribute_name + ))); + } + } + Ok(()) +} + +/// Refuse a key schema whose keys are not all defined in `defs`. +/// +/// # Errors +/// +/// `ValidationException` with the `Invalid KeySchema` sentence when the schema +/// has more keys than `defs` has entries, otherwise with the `Some index key +/// attributes are not defined` sentence when any key has no definition. +pub fn validate_key_schema_defined( + key_schema: &[KeySchemaElement], + defs: &[AttributeDefinition], +) -> Result<(), DynamoDbError> { + if defs.len() < key_schema.len() { + return Err(DynamoDbError::ValidationException( + "Invalid KeySchema: Some index key attribute have no definition".to_owned(), + )); + } + let defined = |name: &str| defs.iter().any(|d| d.attribute_name == name); + if key_schema.iter().all(|k| defined(&k.attribute_name)) { + return Ok(()); + } + let keys: Vec<&str> = key_schema + .iter() + .map(|k| k.attribute_name.as_str()) + .collect(); + let names: Vec<&str> = defs.iter().map(|d| d.attribute_name.as_str()).collect(); + 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(", ") + ))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::{KeyType, 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:?}"), + } + } + + const INVALID: &str = "Invalid KeySchema: Some index key attribute have no definition"; + + #[test] + fn the_first_repeated_name_is_named() { + assert_eq!( + message(validate_unique_attribute_definitions(&defs(&[ + "b", "a", "b", "a" + ]))), + "Attribute Name is duplicated: b" + ); + assert!(validate_unique_attribute_definitions(&defs(&["a", "b"])).is_ok()); + } + + #[test] + fn fewer_definitions_than_keys_is_the_key_schema_sentence() { + assert_eq!( + message(validate_key_schema_defined( + &ks("g", Some("r")), + &defs(&["pk"]) + )), + INVALID + ); + assert_eq!( + message(validate_key_schema_defined(&ks("g", None), &[])), + INVALID + ); + } + + #[test] + fn a_missing_key_lists_every_key_and_every_definition() { + assert_eq!( + message(validate_key_schema_defined( + &ks("g", Some("r")), + &defs(&["pk", "g"]) + )), + "One or more parameter values were invalid: Some index key attributes are not defined \ + in AttributeDefinitions. Keys: [g, r], AttributeDefinitions: [pk, g]" + ); + // As many definitions as keys, none of them a key. + assert_eq!( + message(validate_key_schema_defined( + &ks("g", Some("r")), + &defs(&["pk", "z"]) + )), + "One or more parameter values were invalid: Some index key attributes are not defined \ + in AttributeDefinitions. Keys: [g, r], AttributeDefinitions: [pk, z]" + ); + assert!(validate_key_schema_defined(&ks("g", Some("r")), &defs(&["r", "g"])).is_ok()); + } +} diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index 3decb4666..ec71130c8 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -1,8 +1,10 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 +mod key_definitions; pub mod number; pub mod vector_item; +pub use key_definitions::{validate_key_schema_defined, validate_unique_attribute_definitions}; pub use vector_item::{ MAX_HASH_KEY_SIZE, MAX_INLINE_FILTER_SIZE, validate_vector_write, validate_vector_write_changed, vector_components, vector_norm, @@ -941,14 +943,16 @@ 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). + validate_unique_attribute_definitions(&input.attribute_definitions)?; + let defs = &input.attribute_definitions; + validate_key_schema_defined(&input.key_schema, defs)?; + for lsi in input.local_secondary_indexes.iter().flatten() { + validate_key_schema_defined(&lsi.key_schema, defs)?; + } + for gsi in input.global_secondary_indexes.iter().flatten() { + validate_key_schema_defined(&gsi.key_schema, defs)?; } // Every definition must be used by a key @@ -964,13 +968,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 diff --git a/crates/engine/src/update_table.rs b/crates/engine/src/update_table.rs index 14970ac8a..9b965b3ca 100755 --- a/crates/engine/src/update_table.rs +++ b/crates/engine/src/update_table.rs @@ -251,46 +251,17 @@ fn validate_gsi_updates(input: &UpdateTableInput) -> Result<(), DynamoDbError> { } // 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: 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(); + // 2026-10-25 and 2026-10-26): absent names the index; a name + // defined twice is refused first; then the CreateTable rules + // for the index's key schema (core's key_definitions.rs). + 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: [{}]", - first_missing, - defined.join(", ") + "One or more parameter values were invalid: AttributeDefinitions is not specified for index: {}", + create.index_name ))); - } + }; + extenddb_core::validation::validate_unique_attribute_definitions(defs)?; + extenddb_core::validation::validate_key_schema_defined(&create.key_schema, defs)?; } if let Some(delete) = &update.delete { extenddb_core::validation::validate_index_name(&delete.index_name)?; diff --git a/crates/engine/src/update_table_tests.rs b/crates/engine/src/update_table_tests.rs index aa4cfda3a..cd8828388 100644 --- a/crates/engine/src/update_table_tests.rs +++ b/crates/engine/src/update_table_tests.rs @@ -35,8 +35,9 @@ fn enabling_a_stream_without_a_view_type_is_refused() { /// 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-10-26): absent names the index; fewer +/// definitions than keys, including none, has the key schema sentence; +/// otherwise the sentence lists every key and every definition. #[test] fn a_created_gsi_on_an_undefined_key_attribute_is_refused_by_member_shape() { let input = |defs: Option| -> UpdateTableInput { @@ -72,13 +73,21 @@ fn a_created_gsi_on_an_undefined_key_attribute_is_refused_by_member_shape() { 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]" + "Invalid KeySchema: Some index key attribute have no definition" ); 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]" + message(Some(serde_json::json!([ + { "AttributeName": "pk", "AttributeType": "S" }, + { "AttributeName": "g", "AttributeType": "S" }, + ]))), + "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [g, r], AttributeDefinitions: [pk, g]" + ); + assert_eq!( + message(Some(serde_json::json!([ + { "AttributeName": "g", "AttributeType": "S" }, + { "AttributeName": "g", "AttributeType": "S" }, + ]))), + "Attribute Name is duplicated: g" ); validate_gsi_updates(&input(Some(serde_json::json!([ { "AttributeName": "g", "AttributeType": "S" }, From c9aeb0b8556aa320d177a67442accd4dc0637f8f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:30:55 +0000 Subject: [PATCH 02/13] test(table): undefined and duplicated key attribute definitions Dual-target wire tests from the 2026-10-25 and 2026-10-26 measurements: UpdateTable GSI Create with a missing hash or range key, both keys, fewer definitions than keys and names defined twice; CreateTable with missing keys on the table, an LSI and GSIs in each order, fewer definitions than keys and names defined twice; and an UpdateTable that redefines the table's own key with another type, which keeps the stored type. The lists in the sentence are compared as sets, since the service's order is not the request's. --- tests/test_key_schema_definitions.py | 198 +++++++++++++++++++++++++++ 1 file changed, 198 insertions(+) create mode 100644 tests/test_key_schema_definitions.py diff --git a/tests/test_key_schema_definitions.py b/tests/test_key_schema_definitions.py new file mode 100644 index 000000000..87d6225dc --- /dev/null +++ b/tests/test_key_schema_definitions.py @@ -0,0 +1,198 @@ +# 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 and 2026-10-26 at 01:30 UTC +(us-east-1), each request twice, on CreateTable and on an UpdateTable GSI +Create: + +- A name defined twice answers ``Attribute Name is duplicated: ``, + naming the first name whose second definition comes first, before every + key check. +- The table's key schema is checked first, then each LSI's, then each GSI's. + A schema with more keys than there are definitions answers ``Invalid + KeySchema: Some index key attribute have no definition``. Otherwise 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 orders both lists in a way that follows neither the request nor +the alphabet, and ExtendDB lists them in request order, so these tests compare +the lists as sets. + +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 re + +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table + +INVALID = "Invalid KeySchema: Some index key attribute have no definition" +LISTED = re.compile( + r"^One or more parameter values were invalid: Some index key attributes are not defined in " + r"AttributeDefinitions\. Keys: \[([^\]]*)\], AttributeDefinitions: \[([^\]]*)\]$" +) + + +def defs(spec: str) -> list[dict]: + return [{"AttributeName": p.split(":")[0], "AttributeType": p.split(":")[1]} for p in spec.split()] + + +def ks(hash_key: str, range_key: str | None = None) -> list[dict]: + out = [{"AttributeName": hash_key, "KeyType": "HASH"}] + if range_key: + out.append({"AttributeName": range_key, "KeyType": "RANGE"}) + return out + + +def _message(call) -> str: + with pytest.raises(ClientError) as exc_info: + call() + err = exc_info.value.response["Error"] + assert err["Code"] == "ValidationException", err + return err["Message"] + + +def _listed(message: str) -> tuple[set[str], set[str]]: + m = LISTED.match(message) + assert m, message + return set(m.group(1).split(", ")), set(m.group(2).split(", ")) + + +@pytest.fixture(scope="module") +def table(dynamodb_client): + with scoped_table(dynamodb_client) as name: + yield name + + +def _update(client, table, spec, hash_key, range_key=None): + return lambda: client.update_table( + TableName=table, + AttributeDefinitions=defs(spec), + GlobalSecondaryIndexUpdates=[{"Create": { + "IndexName": "never-created", + "KeySchema": ks(hash_key, range_key), + "Projection": {"ProjectionType": "KEYS_ONLY"}, + }}], + ) + + +def _create(client, spec, table_keys, gsis=(), lsis=()): + kwargs = { + "TableName": "never-created-key-definitions", + "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: (definitions, index hash, index range, keys listed, definitions listed) +UPDATE_LISTED = [ + ("range_missing", "pk:S g:S", "g", "r", {"g", "r"}, {"pk", "g"}), + ("hash_missing", "pk:S r:S", "g", "r", {"g", "r"}, {"pk", "r"}), + ("both_missing_two_defs", "pk:S z:S", "g", "r", {"g", "r"}, {"pk", "z"}), + ("both_missing_three_defs", "pk:S y:S z:S", "g", "r", {"g", "r"}, {"pk", "y", "z"}), + ("hash_only_missing", "pk:S", "g", None, {"g"}, {"pk"}), + ("other_types", "pk:S n:N b:B", "n", "x", {"n", "x"}, {"pk", "n", "b"}), +] + + +@pytest.mark.parametrize(("case", "spec", "h", "r", "keys", "names"), UPDATE_LISTED, + ids=[c[0] for c in UPDATE_LISTED]) +def test_update_table_lists_every_key_and_definition(dynamodb_client, table, case, spec, h, r, keys, names): + message = _message(_update(dynamodb_client, table, spec, h, r)) + assert _listed(message) == (keys, names) + + +@pytest.mark.parametrize(("spec", "h", "r"), [("pk:S", "g", "r"), ("pk:S", "pk", "r")], + ids=["both_missing_one_def", "range_missing_one_def"]) +def test_update_table_with_fewer_definitions_than_keys(dynamodb_client, table, spec, h, r): + assert _message(_update(dynamodb_client, table, spec, h, r)) == INVALID + + +@pytest.mark.parametrize(("spec", "h", "r", "name"), [ + ("h:S h:S", "h", None, "h"), + ("h:S h:S", "h", "r", "h"), + ("b:S a:S b:S a:S h:S", "h", "r", "b"), + ("h:S h:N", "h", "r", "h"), +], ids=["index_key", "and_a_missing_key", "first_repeated", "two_types"]) +def test_update_table_refuses_a_name_defined_twice(dynamodb_client, table, spec, h, r, name): + assert _message(_update(dynamodb_client, table, spec, h, r)) == f"Attribute Name is duplicated: {name}" + + +# CreateTable: (definitions, table keys, GSIs, LSIs, keys listed or None for the +# key schema sentence, definitions listed) +CREATE = [ + ("gsi_range_missing", "pk:S g:S", ks("pk"), [ks("g", "r")], [], {"g", "r"}, {"pk", "g"}), + ("gsi_both_missing", "pk:S", ks("pk"), [ks("g", "r")], [], None, None), + ("table_sort_missing_one_def", "pk:S", ks("pk", "sk"), [], [], None, None), + ("table_sort_missing", "pk:S x:S", ks("pk", "sk"), [], [], {"pk", "sk"}, {"pk", "x"}), + ("table_pk_missing", "x:S", ks("pk"), [], [], {"pk"}, {"x"}), + ("table_before_gsi", "pk:S g:S", ks("pk", "sk"), [ks("g", "r")], [], {"pk", "sk"}, {"pk", "g"}), + ("table_before_lsi", "pk:S x:S", ks("pk", "sk"), [], [ks("pk", "l")], {"pk", "sk"}, {"pk", "x"}), + ("lsi_missing", "pk:S sk:S", ks("pk", "sk"), [], [ks("pk", "l")], {"pk", "l"}, {"pk", "sk"}), + ("lsi_before_gsi", "pk:S sk:S g:S", ks("pk", "sk"), [ks("g", "r")], [ks("pk", "l")], + {"pk", "l"}, {"pk", "sk", "g"}), + ("first_gsi_first", "pk:S g:S h:S", ks("pk"), [ks("g", "r"), ks("h", "q")], [], + {"g", "r"}, {"pk", "g", "h"}), +] + + +@pytest.mark.parametrize(("case", "spec", "table_keys", "gsis", "lsis", "keys", "names"), CREATE, + ids=[c[0] for c in CREATE]) +def test_create_table_checks_each_key_schema_in_turn(dynamodb_client, case, spec, table_keys, gsis, lsis, + keys, names): + message = _message(_create(dynamodb_client, spec, table_keys, gsis, lsis)) + if keys is None: + assert message == INVALID + else: + assert _listed(message) == (keys, names) + + +@pytest.mark.parametrize(("spec", "table_keys", "gsis", "name"), [ + ("pk:S pk:S", ks("pk"), [], "pk"), + ("pk:S pk:N", ks("pk"), [], "pk"), + ("pk:S pk:S", ks("pk", "sk"), [], "pk"), + ("pk:S g:S g:S", ks("pk"), [ks("g")], "g"), + ("b:S a:S b:S a:S pk:S", ks("pk"), [], "b"), +], ids=["table_key", "two_types", "and_a_missing_key", "index_key", "first_repeated"]) +def test_create_table_refuses_a_name_defined_twice(dynamodb_client, spec, table_keys, gsis, name): + message = _message(_create(dynamodb_client, spec, table_keys, gsis)) + assert message == f"Attribute Name is duplicated: {name}" + + +def test_update_table_keeps_the_type_of_a_redefined_table_key(dynamodb_client): + with scoped_table(dynamodb_client) as name: + dynamodb_client.update_table( + TableName=name, + AttributeDefinitions=defs("pk:N g:S"), + GlobalSecondaryIndexUpdates=[{"Create": { + "IndexName": "by-g", + "KeySchema": ks("g"), + "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"} From a430c57cce3a756b035b1729102d9363fda35cc7 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:30:55 +0000 Subject: [PATCH 03/13] fix(table): billing faults first, a linear duplicate check, the list order documented Amazon DynamoDB reports a CreateTable billing fault (throughput with PAY_PER_REQUEST, or none with PROVISIONED) before a duplicated or missing definition (measured 2026-10-26 at 02:27 and 02:34 UTC, each case twice). The billing check now runs before the definition checks. The duplicate check compared every definition with every earlier one, and UpdateTable runs it once per GSI Create: 8,000 definitions with 200 Creates took 22.9 s. It now makes one pass with a set of seen names and still names the first name whose second definition comes first. The module comment states where the service checks a duplicate (after the billing checks, the one-name-twice rule and the length rule) and where ExtendDB does (after the key schema shape checks). docs/differences-from-dynamodb.md records the order of the two lists in the listing sentence. --- crates/core/src/validation/key_definitions.rs | 20 +++++++++++-------- crates/core/src/validation/mod.rs | 4 +++- docs/differences-from-dynamodb.md | 1 + 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/crates/core/src/validation/key_definitions.rs b/crates/core/src/validation/key_definitions.rs index 18f71d438..ee14e246f 100644 --- a/crates/core/src/validation/key_definitions.rs +++ b/crates/core/src/validation/key_definitions.rs @@ -8,7 +8,9 @@ //! //! - A name defined twice answers `Attribute Name is duplicated: `, //! naming the first name whose second definition comes first in the list. -//! This comes before every key check. +//! The service checks it after the table billing checks, the one-name-twice +//! rule and the length rule below, and before the other key schema checks; +//! ExtendDB checks it after all key schema shape checks. //! - Each key schema is then checked in turn: the table's, each LSI's, each //! GSI's. A schema with more keys than there are definitions answers //! `Invalid KeySchema: Some index key attribute have no definition`. A @@ -19,6 +21,8 @@ //! The service lists the keys and definitions in an order that follows neither //! the request nor the alphabet; ExtendDB lists them in request order. +use std::collections::HashSet; + use crate::error::DynamoDbError; use crate::types::{AttributeDefinition, KeySchemaElement}; @@ -30,11 +34,9 @@ use crate::types::{AttributeDefinition, KeySchemaElement}; pub fn validate_unique_attribute_definitions( defs: &[AttributeDefinition], ) -> Result<(), DynamoDbError> { - for (i, def) in defs.iter().enumerate() { - if defs[..i] - .iter() - .any(|earlier| earlier.attribute_name == def.attribute_name) - { + 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 @@ -60,8 +62,10 @@ pub fn validate_key_schema_defined( "Invalid KeySchema: Some index key attribute have no definition".to_owned(), )); } - let defined = |name: &str| defs.iter().any(|d| d.attribute_name == name); - if key_schema.iter().all(|k| defined(&k.attribute_name)) { + if key_schema + .iter() + .all(|k| defs.iter().any(|d| d.attribute_name == k.attribute_name)) + { return Ok(()); } let keys: Vec<&str> = key_schema diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index ec71130c8..7a39a52e6 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -103,8 +103,10 @@ pub fn validate_create_table( validate_key_schema(input, limits.allow_multipart_table_keys)?; validate_gsi_key_schemas(input)?; validate_lsi_key_schemas(input)?; - validate_attribute_definitions(input)?; + // The service reports a table billing fault before any definition fault + // (measured 2026-10-26). validate_provisioned_throughput(input)?; + validate_attribute_definitions(input)?; validate_gsi_provisioned_throughput(input)?; validate_gsi_throughput_minimum(input)?; validate_gsi_count(input, limits)?; diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index 80c1f671b..ec6e573c5 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -48,6 +48,7 @@ adaptation when switching between ExtendDB and the real service. |------|----------|------| | Table creation delay | Returns `CREATING` immediately; transitions to `ACTIVE` typically within seconds. Same behavior for on-demand and provisioned | Configurable via `control_plane_delay_seconds` runtime setting (default: 5s) | | DeletionProtectionEnabled | Enforced | Enforced (accepted and stored, DeleteTable rejects when enabled) | +| Order of the lists in `Some index key attributes are not defined in AttributeDefinitions. Keys: [...], AttributeDefinitions: [...]` (CreateTable, UpdateTable GSI Create) | Every key of the schema and every definition, in an order that follows neither the request nor the alphabet and does not depend on the attribute types (measured 2026-10-26: definitions `[pk, r]` render `[r, pk]`, keys `hk, rk` render `[rk, hk]`) | The same keys and definitions, the keys in key schema order and the definitions in request order. A client that reads the first element of `Keys` can see a different name | ## Time to Live (TTL) From 2bb47d61b8c7c29a41550e598c0961ba1a80468b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:30:55 +0000 Subject: [PATCH 04/13] test(table): billing faults before definition faults; wait for the index CreateTable with PAY_PER_REQUEST and throughput beside a duplicated name, a missing key, or fewer definitions than keys answers the billing sentence (measured 2026-10-26 at 02:27 and 02:34 UTC). The redefinition test waits for its new index to be active before the table is deleted, since the service refuses DeleteTable while an index is being created, and writes an item with the stored key type. The measurement times in the docstring are corrected to 01:27 and 01:29 UTC, plus the two later runs. --- tests/test_key_schema_definitions.py | 43 ++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/tests/test_key_schema_definitions.py b/tests/test_key_schema_definitions.py index 87d6225dc..29da06e51 100644 --- a/tests/test_key_schema_definitions.py +++ b/tests/test_key_schema_definitions.py @@ -3,13 +3,14 @@ """Key schemas whose attributes are missing from AttributeDefinitions. -Amazon DynamoDB, measured on 2026-10-25 and 2026-10-26 at 01:30 UTC -(us-east-1), each request twice, on CreateTable and on an UpdateTable GSI -Create: +Amazon DynamoDB, measured on 2026-10-25 and 2026-10-26 at 01:27, 01:29, +02:27 and 02:34 UTC (us-east-1), each request twice, on CreateTable and on +an UpdateTable GSI Create: +- A table billing fault is reported first. - A name defined twice answers ``Attribute Name is duplicated: ``, - naming the first name whose second definition comes first, before every - key check. + naming the first name whose second definition comes first, before a + missing key. - The table's key schema is checked first, then each LSI's, then each GSI's. A schema with more keys than there are definitions answers ``Invalid KeySchema: Some index key attribute have no definition``. Otherwise a key @@ -31,6 +32,7 @@ from __future__ import annotations import re +import time import pytest from botocore.exceptions import ClientError @@ -170,6 +172,23 @@ def test_create_table_checks_each_key_schema_in_turn(dynamodb_client, case, spec assert _listed(message) == (keys, names) +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", ks("pk")), + ("pk:S x:S", ks("pk", "sk")), + ("pk:S", ks("pk", "sk")), +], ids=["duplicate", "missing_key", "fewer_definitions"]) +def test_create_table_reports_a_billing_fault_first(dynamodb_client, spec, table_keys): + def call(): + dynamodb_client.create_table( + TableName="never-created-key-definitions", AttributeDefinitions=defs(spec), KeySchema=table_keys, + BillingMode="PAY_PER_REQUEST", ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}) + assert _message(call) == BILLING + + @pytest.mark.parametrize(("spec", "table_keys", "gsis", "name"), [ ("pk:S pk:S", ks("pk"), [], "pk"), ("pk:S pk:N", ks("pk"), [], "pk"), @@ -182,6 +201,17 @@ def test_create_table_refuses_a_name_defined_twice(dynamodb_client, spec, table_ assert message == f"Attribute Name is duplicated: {name}" +def _wait_for_index(client, table, index, timeout=120.0): + 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": + 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: dynamodb_client.update_table( @@ -196,3 +226,6 @@ def test_update_table_keeps_the_type_of_a_redefined_table_key(dynamodb_client): desc = dynamodb_client.describe_table(TableName=name)["Table"] stored = {d["AttributeName"]: d["AttributeType"] for d in desc["AttributeDefinitions"]} assert stored == {"pk": "S", "g": "S"} + # The table cannot be deleted while the index is being created. + _wait_for_index(dynamodb_client, name, "by-g") + dynamodb_client.put_item(TableName=name, Item={"pk": {"S": "a"}, "g": {"S": "b"}}) From 2d0ddcd6264b3a62bcb43e22dfec438d9af35f2a Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:12:54 +0000 Subject: [PATCH 05/13] fix(table): check key definitions in the service's order The service checks a key schema against AttributeDefinitions in this order (measured 2026-11-25, twice each, on table names that do not exist): 1. More keys than there are definitions: "Invalid KeySchema: Some index key attribute have no definition". 2. A HASH and a RANGE element on one name: "Both the Hash Key and the Range Key element in the KeySchema have the same name". 3. A name defined twice: "Attribute Name is duplicated: ". 4. A key with no definition: the sentence that lists the keys and the definitions. On an UpdateTable GSI Create this branch checked a name defined twice first, and it had no rule 2. The Create now runs the four rules in this order, after the sentence for an absent AttributeDefinitions. So [g, g] with keys g, x and y answers Invalid KeySchema. With keys g HASH and g RANGE it answers the rule 2 sentence. On CreateTable the service checks the index names, then the table billing rules, then rules 1 to 3 on the table's key schema. All of them come before any key schema shape check. The keySchema length constraint comes before rule 1 and the shape checks. CreateTable now runs them in that order, after the length constraint, which stays first as on main. After the shape checks it runs rule 4 on the table's key schema, then rules 1 and 4 on each index's. A name defined twice beside a shape fault now answers the duplicate sentence. These requests now get the service's answer, where main gave another: - a billing fault beside a table key schema that starts with RANGE: the billing sentence (main: "First KeySchemaElement is not a HASH type") - one definition for two table keys, RANGE first: Invalid KeySchema (main: the same First KeySchemaElement sentence) - a table HASH and RANGE on one name, with two definitions: the rule 2 sentence (main: Invalid KeySchema) - three table keys, RANGE first: the keySchema length constraint (main: the First KeySchemaElement sentence) Main checked each index's name with its key schema shape, after the table's key schema shape. validate_key_schema_defined splits into validate_definition_count (rule 1) and validate_keys_defined (rule 4). The new validate_hash_and_range_differ (rule 2) replaces the check of a table HASH and RANGE on one name in validate_key_schema, so both paths use one check. That check was the last production copy of the Invalid KeySchema sentence outside key_definitions.rs, where the sentence is now one constant. The measured requests are rows of test_update_table_checks_in_the_service_order and test_create_table_checks_in_the_service_order in tests/test_key_schema_definitions.py, sent to a table name that does not exist. --- crates/core/src/validation/key_definitions.rs | 129 ++++++++++++------ crates/core/src/validation/mod.rs | 109 ++++++++++----- crates/engine/src/gsi_updates.rs | 20 ++- tests/test_key_schema_definitions.py | 112 ++++++++++++--- 4 files changed, 267 insertions(+), 103 deletions(-) diff --git a/crates/core/src/validation/key_definitions.rs b/crates/core/src/validation/key_definitions.rs index ee14e246f..a260c1017 100644 --- a/crates/core/src/validation/key_definitions.rs +++ b/crates/core/src/validation/key_definitions.rs @@ -4,19 +4,27 @@ //! Checks that a key schema's attributes are defined in `AttributeDefinitions`, //! shared by `CreateTable` and an `UpdateTable` GSI `Create`. //! -//! The service's rules, measured on 2026-10-25 and 2026-10-26 (us-east-1): +//! 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: //! -//! - A name defined twice answers `Attribute Name is duplicated: `, -//! naming the first name whose second definition comes first in the list. -//! The service checks it after the table billing checks, the one-name-twice -//! rule and the length rule below, and before the other key schema checks; -//! ExtendDB checks it after all key schema shape checks. -//! - Each key schema is then checked in turn: the table's, each LSI's, each -//! GSI's. A schema with more keys than there are definitions answers -//! `Invalid KeySchema: Some index key attribute have no definition`. A -//! schema with a key that has no definition answers `Some index key -//! attributes are not defined in AttributeDefinitions`, listing every key of -//! that schema and every definition. +//! 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. +//! +//! 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. 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. //! //! The service lists the keys and definitions in an order that follows neither //! the request nor the alphabet; ExtendDB lists them in request order. @@ -24,9 +32,54 @@ use std::collections::HashSet; use crate::error::DynamoDbError; -use crate::types::{AttributeDefinition, KeySchemaElement}; +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(()) +} -/// Refuse a name defined twice in `defs`. +/// Rule 3: refuse a name defined twice in `defs`. /// /// # Errors /// @@ -46,22 +99,16 @@ pub fn validate_unique_attribute_definitions( Ok(()) } -/// Refuse a key schema whose keys are not all defined in `defs`. +/// Rule 4: refuse a key schema with a key that has no definition in `defs`. /// /// # Errors /// -/// `ValidationException` with the `Invalid KeySchema` sentence when the schema -/// has more keys than `defs` has entries, otherwise with the `Some index key -/// attributes are not defined` sentence when any key has no definition. -pub fn validate_key_schema_defined( +/// `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 defs.len() < key_schema.len() { - return Err(DynamoDbError::ValidationException( - "Invalid KeySchema: Some index key attribute have no definition".to_owned(), - )); - } if key_schema .iter() .all(|k| defs.iter().any(|d| d.attribute_name == k.attribute_name)) @@ -84,7 +131,7 @@ pub fn validate_key_schema_defined( #[cfg(test)] mod tests { use super::*; - use crate::types::{KeyType, ScalarAttributeType}; + use crate::types::ScalarAttributeType; fn defs(names: &[&str]) -> Vec { names @@ -117,8 +164,6 @@ mod tests { } } - const INVALID: &str = "Invalid KeySchema: Some index key attribute have no definition"; - #[test] fn the_first_repeated_name_is_named() { assert_eq!( @@ -132,23 +177,29 @@ mod tests { #[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_key_schema_defined( - &ks("g", Some("r")), - &defs(&["pk"]) - )), - INVALID - ); - assert_eq!( - message(validate_key_schema_defined(&ks("g", None), &[])), - INVALID + 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()); } #[test] fn a_missing_key_lists_every_key_and_every_definition() { assert_eq!( - message(validate_key_schema_defined( + message(validate_keys_defined( &ks("g", Some("r")), &defs(&["pk", "g"]) )), @@ -157,13 +208,13 @@ mod tests { ); // As many definitions as keys, none of them a key. assert_eq!( - message(validate_key_schema_defined( + message(validate_keys_defined( &ks("g", Some("r")), &defs(&["pk", "z"]) )), "One or more parameter values were invalid: Some index key attributes are not defined \ in AttributeDefinitions. Keys: [g, r], AttributeDefinitions: [pk, z]" ); - assert!(validate_key_schema_defined(&ks("g", Some("r")), &defs(&["r", "g"])).is_ok()); + assert!(validate_keys_defined(&ks("g", Some("r")), &defs(&["r", "g"])).is_ok()); } } diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index d42c46ebd..da5c0d8da 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -6,7 +6,10 @@ pub mod restorable_item; pub mod vector_item; pub mod warm_throughput; -pub use key_definitions::{validate_key_schema_defined, validate_unique_attribute_definitions}; +pub use key_definitions::{ + 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, @@ -114,13 +117,28 @@ pub fn validate_create_table( input: &CreateTableInput, limits: &LimitsConfig, ) -> 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)?; + validate_definition_count(&input.key_schema, &input.attribute_definitions)?; + validate_hash_and_range_differ(&input.key_schema)?; + 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)?; - // The service reports a table billing fault before any definition fault - // (measured 2026-10-26). - validate_provisioned_throughput(input)?; validate_attribute_definitions(input)?; validate_gsi_provisioned_throughput(input)?; validate_gsi_throughput_minimum(input)?; @@ -720,7 +738,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> { @@ -730,7 +750,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, &[], @@ -739,27 +780,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(()) } @@ -821,7 +850,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: {}", @@ -847,7 +875,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 { @@ -969,15 +996,25 @@ fn validate_attribute_definitions(input: &CreateTableInput) -> Result<(), Dynamo } // 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). - validate_unique_attribute_definitions(&input.attribute_definitions)?; + // each LSI's, then each GSI's (measured order, see key_definitions.rs). The + // table's definition count came first, in `validate_create_table`. let defs = &input.attribute_definitions; - validate_key_schema_defined(&input.key_schema, defs)?; - for lsi in input.local_secondary_indexes.iter().flatten() { - validate_key_schema_defined(&lsi.key_schema, defs)?; - } - for gsi in input.global_secondary_indexes.iter().flatten() { - validate_key_schema_defined(&gsi.key_schema, defs)?; + 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 { + validate_definition_count(schema, defs)?; + validate_keys_defined(schema, defs)?; } // Every definition must be used by a key diff --git a/crates/engine/src/gsi_updates.rs b/crates/engine/src/gsi_updates.rs index 9c2bb00ff..f97091f52 100644 --- a/crates/engine/src/gsi_updates.rs +++ b/crates/engine/src/gsi_updates.rs @@ -244,17 +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-10-26): absent names the index; a name - // defined twice is refused first; then the CreateTable rules - // for the index's key schema (core's key_definitions.rs). + // 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: 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_key_schema_defined(&create.key_schema, 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")?; @@ -533,12 +536,14 @@ 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, 2026-10-26 and 2026-11-25): absent names the - /// index, fewer definitions than the index has keys has the key schema - /// sentence, a name defined twice is refused, and otherwise the sentence + /// 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]"; @@ -576,6 +581,9 @@ mod tests { (["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/tests/test_key_schema_definitions.py b/tests/test_key_schema_definitions.py index 29da06e51..001ca7f0c 100644 --- a/tests/test_key_schema_definitions.py +++ b/tests/test_key_schema_definitions.py @@ -3,20 +3,25 @@ """Key schemas whose attributes are missing from AttributeDefinitions. -Amazon DynamoDB, measured on 2026-10-25 and 2026-10-26 at 01:27, 01:29, -02:27 and 02:34 UTC (us-east-1), each request twice, on CreateTable and on -an UpdateTable GSI Create: - -- A table billing fault is reported first. -- A name defined twice answers ``Attribute Name is duplicated: ``, - naming the first name whose second definition comes first, before a - missing key. -- The table's key schema is checked first, then each LSI's, then each GSI's. - A schema with more keys than there are definitions answers ``Invalid - KeySchema: Some index key attribute have no definition``. Otherwise a key - with no definition answers ``Some index key attributes are not defined in - AttributeDefinitions`` listing every key of that schema and every - definition. +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 orders both lists in a way that follows neither the request nor the alphabet, and ExtendDB lists them in request order, so these tests compare @@ -39,7 +44,9 @@ 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" LISTED = re.compile( r"^One or more parameter values were invalid: Some index key attributes are not defined in " r"AttributeDefinitions\. Keys: \[([^\]]*)\], AttributeDefinitions: \[([^\]]*)\]$" @@ -57,6 +64,11 @@ def ks(hash_key: str, range_key: str | None = None) -> list[dict]: return out +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() @@ -77,13 +89,13 @@ def table(dynamodb_client): yield name -def _update(client, table, spec, hash_key, range_key=None): +def _update(client, table, spec, key_schema): return lambda: client.update_table( TableName=table, AttributeDefinitions=defs(spec), GlobalSecondaryIndexUpdates=[{"Create": { "IndexName": "never-created", - "KeySchema": ks(hash_key, range_key), + "KeySchema": key_schema, "Projection": {"ProjectionType": "KEYS_ONLY"}, }}], ) @@ -91,7 +103,7 @@ def _update(client, table, spec, hash_key, range_key=None): def _create(client, spec, table_keys, gsis=(), lsis=()): kwargs = { - "TableName": "never-created-key-definitions", + "TableName": NEVER_CREATED, "AttributeDefinitions": defs(spec), "KeySchema": table_keys, "BillingMode": "PAY_PER_REQUEST", @@ -123,14 +135,14 @@ def _create(client, spec, table_keys, gsis=(), lsis=()): @pytest.mark.parametrize(("case", "spec", "h", "r", "keys", "names"), UPDATE_LISTED, ids=[c[0] for c in UPDATE_LISTED]) def test_update_table_lists_every_key_and_definition(dynamodb_client, table, case, spec, h, r, keys, names): - message = _message(_update(dynamodb_client, table, spec, h, r)) + message = _message(_update(dynamodb_client, table, spec, ks(h, r))) assert _listed(message) == (keys, names) @pytest.mark.parametrize(("spec", "h", "r"), [("pk:S", "g", "r"), ("pk:S", "pk", "r")], ids=["both_missing_one_def", "range_missing_one_def"]) def test_update_table_with_fewer_definitions_than_keys(dynamodb_client, table, spec, h, r): - assert _message(_update(dynamodb_client, table, spec, h, r)) == INVALID + assert _message(_update(dynamodb_client, table, spec, ks(h, r))) == INVALID @pytest.mark.parametrize(("spec", "h", "r", "name"), [ @@ -140,7 +152,26 @@ def test_update_table_with_fewer_definitions_than_keys(dynamodb_client, table, s ("h:S h:N", "h", "r", "h"), ], ids=["index_key", "and_a_missing_key", "first_repeated", "two_types"]) def test_update_table_refuses_a_name_defined_twice(dynamodb_client, table, spec, h, r, name): - assert _message(_update(dynamodb_client, table, spec, h, r)) == f"Attribute Name is duplicated: {name}" + message = _message(_update(dynamodb_client, table, spec, ks(h, r))) + assert message == f"Attribute Name is duplicated: {name}" + + +# UpdateTable GSI Create on a table name that does not exist, where two rules +# apply: (definitions, index key schema, message). The definition count and the +# HASH and RANGE names come before a name defined twice. +UPDATE_ORDER = [ + ("count_before_duplicate", "g:S g:S", "g:HASH x:RANGE y:RANGE", INVALID), + ("count_before_duplicate_other_names", "a:S a:S", "a:HASH b:RANGE c:RANGE", INVALID), + ("same_name_before_duplicate", "g:S g:S", "g:HASH g:RANGE", SAME_NAME), + ("count_before_same_name", "g:S", "g:HASH g:RANGE", INVALID), + ("same_name", "g:S x:S", "g:HASH g:RANGE", SAME_NAME), +] + + +@pytest.mark.parametrize(("case", "spec", "key_spec", "expected"), UPDATE_ORDER, + ids=[c[0] for c in UPDATE_ORDER]) +def test_update_table_checks_in_the_service_order(dynamodb_client, case, spec, key_spec, expected): + assert _message(_update(dynamodb_client, NEVER_CREATED, spec, keys(key_spec))) == expected # CreateTable: (definitions, table keys, GSIs, LSIs, keys listed or None for the @@ -172,6 +203,42 @@ def test_create_table_checks_each_key_schema_in_turn(dynamodb_client, case, spec assert _listed(message) == (keys, names) +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 where two rules apply: (definitions, table keys, GSIs, LSIs, +# message). 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. +CREATE_ORDER = [ + ("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", ks("pk"), [keys("r:RANGE g:HASH")], [], + "Attribute Name is duplicated: g"), + ("duplicate_before_lsi_shape", "pk:S sk:S l:S l:S", ks("pk", "sk"), [], [keys("l:RANGE pk:HASH")], + "Attribute Name is duplicated: l"), +] + + +@pytest.mark.parametrize(("case", "spec", "table_keys", "gsis", "lsis", "expected"), CREATE_ORDER, + ids=[c[0] for c in CREATE_ORDER]) +def test_create_table_checks_in_the_service_order(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") @@ -180,11 +247,12 @@ def test_create_table_checks_each_key_schema_in_turn(dynamodb_client, case, spec ("pk:S pk:S", ks("pk")), ("pk:S x:S", ks("pk", "sk")), ("pk:S", ks("pk", "sk")), -], ids=["duplicate", "missing_key", "fewer_definitions"]) + ("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-key-definitions", AttributeDefinitions=defs(spec), KeySchema=table_keys, + TableName=NEVER_CREATED, AttributeDefinitions=defs(spec), KeySchema=table_keys, BillingMode="PAY_PER_REQUEST", ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}) assert _message(call) == BILLING From cb0b9c05ecf7f6139e9fa6a1fa20a087268c5cec Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:13:04 +0000 Subject: [PATCH 06/13] fix(table): list the keys and definitions in the service's order The service lists the names in "Keys: [..], AttributeDefinitions: [..]" in the iteration order of a java.util.HashMap that starts with 4 buckets and load factor 0.75. A name's bucket comes from its Java String.hashCode over UTF-16 code units, spread as h ^ (h >>> 16). Within a bucket the names keep their request order. The table also doubles when a bucket that holds eight names takes a ninth while the table has fewer than 64 buckets. This branch listed the keys in key schema order and the definitions in request order. Take keys g and r with the definitions [pk, x]. This branch answered "Keys: [g, r], AttributeDefinitions: [pk, x]", and the service answers "Keys: [r, g], AttributeDefinitions: [x, pk]". validate_keys_defined now renders both lists through listed(), which models that order. Before the requests went out, the model predicted every list that the wire and unit rows assert. The service answered all 28 requests as predicted (2026-11-25, each list twice). Two of the lists put nine and eight names in one bucket of a 16-bucket table. The ninth name doubles the table, and the eighth does not. Its doc names the case it does not model: a ninth name in one bucket when the table has 64 buckets or more. The rows of tests/test_key_schema_definitions.py now compare the whole message, in place of the two lists as sets. A new row sends [pk, x]. The row in docs/differences-from-dynamodb.md that described the order difference goes. --- crates/core/src/validation/key_definitions.rs | 131 ++++++++++++++---- crates/engine/src/gsi_updates.rs | 2 +- docs/differences-from-dynamodb.md | 1 - tests/test_key_schema_definitions.py | 77 +++++----- 4 files changed, 138 insertions(+), 73 deletions(-) diff --git a/crates/core/src/validation/key_definitions.rs b/crates/core/src/validation/key_definitions.rs index a260c1017..5229eb91d 100644 --- a/crates/core/src/validation/key_definitions.rs +++ b/crates/core/src/validation/key_definitions.rs @@ -16,7 +16,7 @@ //! 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. +//! 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 @@ -25,9 +25,6 @@ //! 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. -//! -//! The service lists the keys and definitions in an order that follows neither -//! the request nor the alphabet; ExtendDB lists them in request order. use std::collections::HashSet; @@ -115,11 +112,8 @@ pub fn validate_keys_defined( { return Ok(()); } - let keys: Vec<&str> = key_schema - .iter() - .map(|k| k.attribute_name.as_str()) - .collect(); - let names: Vec<&str> = defs.iter().map(|d| d.attribute_name.as_str()).collect(); + 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: [{}]", @@ -128,6 +122,51 @@ pub fn validate_keys_defined( ))) } +/// 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 `spread & (buckets - 1)`, where `spread` +/// is the Java `String.hashCode` of the name over its UTF-16 code units, +/// combined by XOR with itself shifted right by 16 bits. The table doubles +/// when it holds more names than three quarters of its buckets, and when a +/// bucket that holds eight names takes a ninth 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 takes its ninth name in a table of 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 hash = name.encode_utf16().fold(0_u32, |h, unit| { + h.wrapping_mul(31).wrapping_add(u32::from(unit)) + }); + let spread = hash ^ (hash >> 16); + 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::*; @@ -196,25 +235,63 @@ mod tests { 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() { - assert_eq!( - message(validate_keys_defined( - &ks("g", Some("r")), - &defs(&["pk", "g"]) - )), - "One or more parameter values were invalid: Some index key attributes are not defined \ - in AttributeDefinitions. Keys: [g, r], AttributeDefinitions: [pk, g]" - ); - // As many definitions as keys, none of them a key. - assert_eq!( - message(validate_keys_defined( - &ks("g", Some("r")), - &defs(&["pk", "z"]) - )), - "One or more parameter values were invalid: Some index key attributes are not defined \ - in AttributeDefinitions. Keys: [g, r], AttributeDefinitions: [pk, z]" - ); + 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/engine/src/gsi_updates.rs b/crates/engine/src/gsi_updates.rs index f97091f52..7f5ae9a2b 100644 --- a/crates/engine/src/gsi_updates.rs +++ b/crates/engine/src/gsi_updates.rs @@ -549,7 +549,7 @@ mod tests { 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: \ - [g, r], AttributeDefinitions: [pk, g]"; + [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 { diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index baf61ad52..a88689353 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -57,7 +57,6 @@ from a request sent to that service or backend. |------|----------|------| | Table creation delay | Returns `CREATING` immediately; transitions to `ACTIVE` typically within seconds. Same behavior for on-demand and provisioned | Configurable via `control_plane_delay_seconds` runtime setting (default: 5s) | | DeletionProtectionEnabled | Enforced | Enforced (accepted and stored, DeleteTable rejects when enabled) | -| Order of the lists in `Some index key attributes are not defined in AttributeDefinitions. Keys: [...], AttributeDefinitions: [...]` (CreateTable, UpdateTable GSI Create) | Every key of the schema and every definition, in an order that follows neither the request nor the alphabet and does not depend on the attribute types (measured 2026-10-26: definitions `[pk, r]` render `[r, pk]`, keys `hk, rk` render `[rk, hk]`) | The same keys and definitions, the keys in key schema order and the definitions in request order. A client that reads the first element of `Keys` can see a different name | | U+0000 in a key attribute name, an index key attribute name or a projected attribute name | Accepted; `DescribeTable` returns each name byte for byte (measured 2026-09-18 and 2026-10-24, and again on 2026-11-04) | The same on all four backends. PostgreSQL `jsonb` cannot hold U+0000, so a PostgreSQL deployment stores these names through an escape, U+0000 as U+0001 U+0001 and U+0001 as U+0001 U+0002. Catalog migration 11 applies the escape to the names an earlier release stored (see the [Upgrade Manual](manuals/07-upgrade-manual.md#general-upgrade-procedure)) | | Stream disable and enable | `UpdateTable StreamEnabled=false` answers `UPDATING`; the stream reports `DISABLED` a few seconds later with every shard closed, and every write acknowledged before that lands in the closed stream. `StreamEnabled=true` afterwards creates a new stream with a later label; both streams stay listed, and a disabled stream stays describable after its table is deleted | The shards close inside the `UpdateTable` call and the response says `ACTIVE`. A write that reaches storage after the close is acknowledged and recorded in no stream (on MongoDB it is recorded past the shard's `EndingSequenceNumber` instead); the window is one write wide. A disabled stream is removed with its table. A stream created by a release before this one loses its ARN once the table is disabled and re-enabled (its label lived only in the table row) | diff --git a/tests/test_key_schema_definitions.py b/tests/test_key_schema_definitions.py index 001ca7f0c..26eaef44c 100644 --- a/tests/test_key_schema_definitions.py +++ b/tests/test_key_schema_definitions.py @@ -23,9 +23,9 @@ 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 orders both lists in a way that follows neither the request nor -the alphabet, and ExtendDB lists them in request order, so these tests compare -the lists as sets. +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. 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 @@ -36,7 +36,6 @@ from __future__ import annotations -import re import time import pytest @@ -47,10 +46,11 @@ 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" -LISTED = re.compile( - r"^One or more parameter values were invalid: Some index key attributes are not defined in " - r"AttributeDefinitions\. Keys: \[([^\]]*)\], AttributeDefinitions: \[([^\]]*)\]$" -) + + +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]: @@ -77,12 +77,6 @@ def _message(call) -> str: return err["Message"] -def _listed(message: str) -> tuple[set[str], set[str]]: - m = LISTED.match(message) - assert m, message - return set(m.group(1).split(", ")), set(m.group(2).split(", ")) - - @pytest.fixture(scope="module") def table(dynamodb_client): with scoped_table(dynamodb_client) as name: @@ -121,22 +115,22 @@ def _create(client, spec, table_keys, gsis=(), lsis=()): return lambda: client.create_table(**kwargs) -# UpdateTable GSI Create: (definitions, index hash, index range, keys listed, definitions listed) +# UpdateTable GSI Create: (definitions, index hash, index range, message) UPDATE_LISTED = [ - ("range_missing", "pk:S g:S", "g", "r", {"g", "r"}, {"pk", "g"}), - ("hash_missing", "pk:S r:S", "g", "r", {"g", "r"}, {"pk", "r"}), - ("both_missing_two_defs", "pk:S z:S", "g", "r", {"g", "r"}, {"pk", "z"}), - ("both_missing_three_defs", "pk:S y:S z:S", "g", "r", {"g", "r"}, {"pk", "y", "z"}), - ("hash_only_missing", "pk:S", "g", None, {"g"}, {"pk"}), - ("other_types", "pk:S n:N b:B", "n", "x", {"n", "x"}, {"pk", "n", "b"}), + ("range_missing", "pk:S g:S", "g", "r", listed("r, g", "pk, g")), + ("hash_missing", "pk:S r:S", "g", "r", listed("r, g", "r, pk")), + ("both_missing_two_defs", "pk:S z:S", "g", "r", listed("r, g", "z, pk")), + ("both_missing_three_defs", "pk:S y:S z:S", "g", "r", listed("r, g", "y, z, pk")), + ("hash_only_missing", "pk:S", "g", None, listed("g", "pk")), + ("other_types", "pk:S n:N b:B", "n", "x", listed("x, n", "n, b, pk")), + ("service_order", "pk:S x:S", "g", "r", listed("r, g", "x, pk")), ] -@pytest.mark.parametrize(("case", "spec", "h", "r", "keys", "names"), UPDATE_LISTED, +@pytest.mark.parametrize(("case", "spec", "h", "r", "expected"), UPDATE_LISTED, ids=[c[0] for c in UPDATE_LISTED]) -def test_update_table_lists_every_key_and_definition(dynamodb_client, table, case, spec, h, r, keys, names): - message = _message(_update(dynamodb_client, table, spec, ks(h, r))) - assert _listed(message) == (keys, names) +def test_update_table_lists_every_key_and_definition(dynamodb_client, table, case, spec, h, r, expected): + assert _message(_update(dynamodb_client, table, spec, ks(h, r))) == expected @pytest.mark.parametrize(("spec", "h", "r"), [("pk:S", "g", "r"), ("pk:S", "pk", "r")], @@ -174,33 +168,28 @@ def test_update_table_checks_in_the_service_order(dynamodb_client, case, spec, k assert _message(_update(dynamodb_client, NEVER_CREATED, spec, keys(key_spec))) == expected -# CreateTable: (definitions, table keys, GSIs, LSIs, keys listed or None for the -# key schema sentence, definitions listed) +# CreateTable: (definitions, table keys, GSIs, LSIs, message) CREATE = [ - ("gsi_range_missing", "pk:S g:S", ks("pk"), [ks("g", "r")], [], {"g", "r"}, {"pk", "g"}), - ("gsi_both_missing", "pk:S", ks("pk"), [ks("g", "r")], [], None, None), - ("table_sort_missing_one_def", "pk:S", ks("pk", "sk"), [], [], None, None), - ("table_sort_missing", "pk:S x:S", ks("pk", "sk"), [], [], {"pk", "sk"}, {"pk", "x"}), - ("table_pk_missing", "x:S", ks("pk"), [], [], {"pk"}, {"x"}), - ("table_before_gsi", "pk:S g:S", ks("pk", "sk"), [ks("g", "r")], [], {"pk", "sk"}, {"pk", "g"}), - ("table_before_lsi", "pk:S x:S", ks("pk", "sk"), [], [ks("pk", "l")], {"pk", "sk"}, {"pk", "x"}), - ("lsi_missing", "pk:S sk:S", ks("pk", "sk"), [], [ks("pk", "l")], {"pk", "l"}, {"pk", "sk"}), + ("gsi_range_missing", "pk:S g:S", ks("pk"), [ks("g", "r")], [], listed("r, g", "pk, g")), + ("gsi_both_missing", "pk:S", ks("pk"), [ks("g", "r")], [], INVALID), + ("table_sort_missing_one_def", "pk:S", ks("pk", "sk"), [], [], INVALID), + ("table_sort_missing", "pk:S x:S", ks("pk", "sk"), [], [], listed("sk, pk", "x, pk")), + ("table_pk_missing", "x:S", ks("pk"), [], [], listed("pk", "x")), + ("table_before_gsi", "pk:S g:S", ks("pk", "sk"), [ks("g", "r")], [], listed("sk, pk", "pk, g")), + ("table_before_lsi", "pk:S x:S", ks("pk", "sk"), [], [ks("pk", "l")], listed("sk, pk", "x, pk")), + ("lsi_missing", "pk:S sk:S", ks("pk", "sk"), [], [ks("pk", "l")], listed("l, pk", "sk, pk")), ("lsi_before_gsi", "pk:S sk:S g:S", ks("pk", "sk"), [ks("g", "r")], [ks("pk", "l")], - {"pk", "l"}, {"pk", "sk", "g"}), + listed("l, pk", "sk, pk, g")), ("first_gsi_first", "pk:S g:S h:S", ks("pk"), [ks("g", "r"), ks("h", "q")], [], - {"g", "r"}, {"pk", "g", "h"}), + listed("r, g", "h, pk, g")), ] -@pytest.mark.parametrize(("case", "spec", "table_keys", "gsis", "lsis", "keys", "names"), CREATE, +@pytest.mark.parametrize(("case", "spec", "table_keys", "gsis", "lsis", "expected"), CREATE, ids=[c[0] for c in CREATE]) def test_create_table_checks_each_key_schema_in_turn(dynamodb_client, case, spec, table_keys, gsis, lsis, - keys, names): - message = _message(_create(dynamodb_client, spec, table_keys, gsis, lsis)) - if keys is None: - assert message == INVALID - else: - assert _listed(message) == (keys, names) + expected): + assert _message(_create(dynamodb_client, spec, table_keys, gsis, lsis)) == expected KEY_SCHEMA_LENGTH = ("1 validation error detected: Value '[KeySchemaElement(attributeName=a, keyType={}), " From 94721d8c1a38d166e2223fd28846e292b5d1903a Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:13:04 +0000 Subject: [PATCH 07/13] test(table): pin which repeated name the duplicate sentence names The only ordered duplicate row was [b, a, b, a], and two rules give b for it. The service names the name whose second definition comes first. The other rule names the first defined name that repeats. [a, b, b, a] tells them apart. The service answers b for it and a for [a, b, a, b] (measured 2026-11-25, twice each, on CreateTable and on an UpdateTable GSI Create). Both lists are now rows of the two duplicate tables in tests/test_key_schema_definitions.py and of the_first_repeated_name_is_named. With the check changed to name the first defined name that repeats, the unit test and the two [a, b, b, a] wire rows fail. The two [a, b, a, b] rows pass under both rules. --- crates/core/src/validation/key_definitions.rs | 17 +++++++++++------ tests/test_key_schema_definitions.py | 10 ++++++++-- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/crates/core/src/validation/key_definitions.rs b/crates/core/src/validation/key_definitions.rs index 5229eb91d..b6df7c6c4 100644 --- a/crates/core/src/validation/key_definitions.rs +++ b/crates/core/src/validation/key_definitions.rs @@ -205,12 +205,17 @@ mod tests { #[test] fn the_first_repeated_name_is_named() { - assert_eq!( - message(validate_unique_attribute_definitions(&defs(&[ - "b", "a", "b", "a" - ]))), - "Attribute Name is duplicated: b" - ); + 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()); } diff --git a/tests/test_key_schema_definitions.py b/tests/test_key_schema_definitions.py index 26eaef44c..6391de417 100644 --- a/tests/test_key_schema_definitions.py +++ b/tests/test_key_schema_definitions.py @@ -143,8 +143,11 @@ def test_update_table_with_fewer_definitions_than_keys(dynamodb_client, table, s ("h:S h:S", "h", None, "h"), ("h:S h:S", "h", "r", "h"), ("b:S a:S b:S a:S h:S", "h", "r", "b"), + ("a:S b:S b:S a:S h:S", "h", "r", "b"), + ("a:S b:S a:S b:S h:S", "h", "r", "a"), ("h:S h:N", "h", "r", "h"), -], ids=["index_key", "and_a_missing_key", "first_repeated", "two_types"]) +], ids=["index_key", "and_a_missing_key", "first_repeated", "second_definition_first", + "first_definition_first", "two_types"]) def test_update_table_refuses_a_name_defined_twice(dynamodb_client, table, spec, h, r, name): message = _message(_update(dynamodb_client, table, spec, ks(h, r))) assert message == f"Attribute Name is duplicated: {name}" @@ -252,7 +255,10 @@ def call(): ("pk:S pk:S", ks("pk", "sk"), [], "pk"), ("pk:S g:S g:S", ks("pk"), [ks("g")], "g"), ("b:S a:S b:S a:S pk:S", ks("pk"), [], "b"), -], ids=["table_key", "two_types", "and_a_missing_key", "index_key", "first_repeated"]) + ("a:S b:S b:S a:S pk:S", ks("pk"), [], "b"), + ("a:S b:S a:S b:S pk:S", ks("pk"), [], "a"), +], ids=["table_key", "two_types", "and_a_missing_key", "index_key", "first_repeated", + "second_definition_first", "first_definition_first"]) def test_create_table_refuses_a_name_defined_twice(dynamodb_client, spec, table_keys, gsis, name): message = _message(_create(dynamodb_client, spec, table_keys, gsis)) assert message == f"Attribute Name is duplicated: {name}" From d23aac18826040401ce9195251e5e0886c684f42 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:13:17 +0000 Subject: [PATCH 08/13] fix(backup): restore the tables earlier releases created Both restore paths ran validate_create_table on the input they build from the backup. This branch added two rules to it: a name defined twice in AttributeDefinitions, and a key schema with more keys than there are definitions. Main's CreateTable accepted both shapes and stored them. So a backup of such a table restored on main, and this branch refused it: - definitions [pk S, gpk N, gpk S] with an index on gpk: "Attribute Name is duplicated: gpk" - index keys [gpk HASH, gpk HASH, gpk RANGE] with the definitions [pk S, gpk S]: "Invalid KeySchema: Some index key attribute have no definition" validate_recorded_table is a second entry point to the same checks. It runs every check of validate_create_table except those two rules. It keeps the rule main applied, that every key of each key schema has a definition. RestoreTableFromBackup calls it on the legacy path (backup.rs) and on the manifest path (backup/restore.rs). The comment on the legacy call now names the two rules. Two engine tests restore each table on both paths and check that the restore keeps the recorded definitions and keys: a_backup_that_records_a_name_defined_twice_restores and a_backup_that_records_more_index_keys_than_definitions_restores. At 1ad8ac04e both fail with the two sentences above. --- crates/core/src/validation/key_definitions.rs | 6 ++- crates/core/src/validation/mod.rs | 53 +++++++++++++++---- crates/engine/src/backup.rs | 9 ++-- crates/engine/src/backup/restore.rs | 6 ++- crates/engine/src/backup/tests.rs | 50 +++++++++++++++++ 5 files changed, 108 insertions(+), 16 deletions(-) diff --git a/crates/core/src/validation/key_definitions.rs b/crates/core/src/validation/key_definitions.rs index b6df7c6c4..6d8f9d644 100644 --- a/crates/core/src/validation/key_definitions.rs +++ b/crates/core/src/validation/key_definitions.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Checks that a key schema's attributes are defined in `AttributeDefinitions`, -//! shared by `CreateTable` and an `UpdateTable` GSI `Create`. +//! 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: @@ -24,7 +24,9 @@ //! 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. +//! 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; diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index da5c0d8da..7a13ea635 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -116,6 +116,31 @@ pub fn validate_index_name(name: &str) -> Result<(), DynamoDbError> { 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, @@ -133,13 +158,17 @@ pub fn validate_create_table( // 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)?; - validate_definition_count(&input.key_schema, &input.attribute_definitions)?; + if !recorded { + validate_definition_count(&input.key_schema, &input.attribute_definitions)?; + } validate_hash_and_range_differ(&input.key_schema)?; - validate_unique_attribute_definitions(&input.attribute_definitions)?; + 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_attribute_definitions(input, recorded)?; validate_gsi_provisioned_throughput(input)?; validate_gsi_throughput_minimum(input)?; validate_gsi_count(input, limits)?; @@ -910,7 +939,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 @@ -997,7 +1029,8 @@ fn validate_attribute_definitions(input: &CreateTableInput) -> Result<(), Dynamo // 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_create_table`. + // 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 @@ -1013,7 +1046,9 @@ fn validate_attribute_definitions(input: &CreateTableInput) -> Result<(), Dynamo .map(|gsi| &gsi.key_schema), ); for schema in index_schemas { - validate_definition_count(schema, defs)?; + if !recorded { + validate_definition_count(schema, defs)?; + } validate_keys_defined(schema, defs)?; } @@ -2959,7 +2994,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); @@ -2972,7 +3007,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'"), @@ -3034,7 +3069,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}"), 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()); From 0efed552114c1778ea727a899ba19b28f7044717 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:13:17 +0000 Subject: [PATCH 09/13] test(table): wait for the created index before the table is deleted On the service, test_update_table_keeps_the_type_of_a_redefined_table_key failed in 2 of 2 runs and left its table behind. The index on the empty table took about 9 and about 16 minutes to go ACTIVE, and _wait_for_index stopped after 120 seconds. scoped_table then called DeleteTable, which the service refuses while an index is being created. _wait_for_index now waits up to 30 minutes and treats an absent index as done. The test calls it in a finally block, so scoped_table deletes the table only after the index is ACTIVE, also when an assertion fails. The PutItem now runs before that wait. On ExtendDB the index is ACTIVE within seconds, so the local run time does not change. This revision was not run against the service, because the test creates a table. --- tests/test_key_schema_definitions.py | 40 ++++++++++++++++------------ 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/tests/test_key_schema_definitions.py b/tests/test_key_schema_definitions.py index 6391de417..e6e5bec36 100644 --- a/tests/test_key_schema_definitions.py +++ b/tests/test_key_schema_definitions.py @@ -264,12 +264,13 @@ def test_create_table_refuses_a_name_defined_twice(dynamodb_client, spec, table_ assert message == f"Attribute Name is duplicated: {name}" -def _wait_for_index(client, table, index, timeout=120.0): +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": + 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") @@ -277,18 +278,23 @@ def _wait_for_index(client, table, index, timeout=120.0): def test_update_table_keeps_the_type_of_a_redefined_table_key(dynamodb_client): with scoped_table(dynamodb_client) as name: - dynamodb_client.update_table( - TableName=name, - AttributeDefinitions=defs("pk:N g:S"), - GlobalSecondaryIndexUpdates=[{"Create": { - "IndexName": "by-g", - "KeySchema": ks("g"), - "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"} - # The table cannot be deleted while the index is being created. - _wait_for_index(dynamodb_client, name, "by-g") - dynamodb_client.put_item(TableName=name, Item={"pk": {"S": "a"}, "g": {"S": "b"}}) + try: + dynamodb_client.update_table( + TableName=name, + AttributeDefinitions=defs("pk:N g:S"), + GlobalSecondaryIndexUpdates=[{"Create": { + "IndexName": "by-g", + "KeySchema": ks("g"), + "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") From 289fde9f8808f29eaa89dec3a4618a6d35dcb581 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:32:46 +0000 Subject: [PATCH 10/13] fix(table): keep main's rules for a multi-part table key schema Main checked a table HASH and RANGE on one name only outside the multi-part table key preview (allow_multipart_table_keys). With the preview on, main created a table keyed a HASH and a RANGE with the one definition [a S]. The same-name rule of this branch ran in both modes. So the restore of such a table failed with "Both the Hash Key and the Range Key element in the KeySchema have the same name". The rule now runs on the table's key schema only outside the preview, where main ran its check. A new core test restores that table, and CreateTable still refuses it by the definition count. Without the guard, the test fails with the same-name sentence. --- crates/core/src/validation/key_definitions.rs | 14 +++++----- crates/core/src/validation/mod.rs | 28 ++++++++++++++++++- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/crates/core/src/validation/key_definitions.rs b/crates/core/src/validation/key_definitions.rs index 6d8f9d644..a5cd120bb 100644 --- a/crates/core/src/validation/key_definitions.rs +++ b/crates/core/src/validation/key_definitions.rs @@ -20,13 +20,13 @@ //! //! 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. 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`). +//! 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; diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index 7a13ea635..4814d54dc 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -161,7 +161,11 @@ fn validate_table( if !recorded { validate_definition_count(&input.key_schema, &input.attribute_definitions)?; } - validate_hash_and_range_differ(&input.key_schema)?; + // Main checked a table HASH and RANGE on one name only outside the + // multi-part preview, and a backup can record such a multi-part table. + if !limits.allow_multipart_table_keys { + validate_hash_and_range_differ(&input.key_schema)?; + } if !recorded { validate_unique_attribute_definitions(&input.attribute_definitions)?; } @@ -3170,6 +3174,28 @@ mod tests { assert!(validate_create_table(&input, &limits).is_ok()); } + /// Main 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 From e770ef3d8d2cfcd13aad8947c34b8f472009824c Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:46:28 +0000 Subject: [PATCH 11/13] docs(core): state the bucket resize and the multi-part guard without a branch name The doc of listed() said that the table doubles when a bucket that holds eight names takes a ninth. The code, like HashMap.putVal, acts on a bucket that holds eight or more names when it takes another. A bucket of nine that takes a tenth also doubles the table below 64 buckets. At 64 buckets or more it becomes a tree. The doc now says so in both places. Two comments in crates/core/src/validation/mod.rs described what "main" checked and accepted. Once this branch merges, main is this code. They now say what earlier releases did. --- crates/core/src/validation/key_definitions.rs | 18 +++++++++--------- crates/core/src/validation/mod.rs | 11 ++++++----- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/crates/core/src/validation/key_definitions.rs b/crates/core/src/validation/key_definitions.rs index a5cd120bb..26595a968 100644 --- a/crates/core/src/validation/key_definitions.rs +++ b/crates/core/src/validation/key_definitions.rs @@ -131,16 +131,16 @@ pub fn validate_keys_defined( /// is the Java `String.hashCode` of the name over its UTF-16 code units, /// combined by XOR with itself shifted right by 16 bits. The table doubles /// when it holds more names than three quarters of its buckets, and when a -/// bucket that holds eight names takes a ninth 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. +/// 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 takes its ninth name in a table of 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. +/// 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(); diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index 4814d54dc..b84be6b8e 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -161,8 +161,8 @@ fn validate_table( if !recorded { validate_definition_count(&input.key_schema, &input.attribute_definitions)?; } - // Main checked a table HASH and RANGE on one name only outside the - // multi-part preview, and a backup can record such a multi-part table. + // 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)?; } @@ -3174,9 +3174,10 @@ mod tests { assert!(validate_create_table(&input, &limits).is_ok()); } - /// Main 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. + /// 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 { From fb4ea9daa085e10a70e5ea561c52ef5dc13b6b10 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:36:48 +0000 Subject: [PATCH 12/13] refactor(core): one function for the Java HashMap hash of a name listed() in crates/core/src/validation/key_definitions.rs and bucket() in crates/engine/src/partiql/request_checks/echo.rs each computed the same value. It is Java's String.hashCode over the UTF-16 code units of a name, spread as h ^ (h >>> 16). The first orders the names in the "Keys: [..], AttributeDefinitions: [..]" sentence, the second the members of a PartiQL statement echo. spread_hash() in key_definitions.rs, exported from extenddb_core::validation, now computes it for both. The echo tests cover bucket(), and lists_follow_the_measured_order covers listed(). --- crates/core/src/validation/key_definitions.rs | 34 ++++++++++++------- crates/core/src/validation/mod.rs | 2 +- .../engine/src/partiql/request_checks/echo.rs | 8 ++--- 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/crates/core/src/validation/key_definitions.rs b/crates/core/src/validation/key_definitions.rs index 26595a968..a1f87fb4c 100644 --- a/crates/core/src/validation/key_definitions.rs +++ b/crates/core/src/validation/key_definitions.rs @@ -124,18 +124,29 @@ pub fn validate_keys_defined( ))) } +/// 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 `spread & (buckets - 1)`, where `spread` -/// is the Java `String.hashCode` of the name over its UTF-16 code units, -/// combined by XOR with itself shifted right by 16 bits. 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. +/// 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 @@ -149,10 +160,7 @@ fn listed<'a>(names: impl IntoIterator) -> Vec<&'a str> { if !seen.insert(name) { continue; } - let hash = name.encode_utf16().fold(0_u32, |h, unit| { - h.wrapping_mul(31).wrapping_add(u32::from(unit)) - }); - let spread = hash ^ (hash >> 16); + let spread = spread_hash(name); let mask = buckets - 1; let crowded = buckets < 64 && entries diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index b84be6b8e..0acc41a39 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -7,7 +7,7 @@ pub mod vector_item; pub mod warm_throughput; pub use key_definitions::{ - validate_definition_count, validate_hash_and_range_differ, validate_keys_defined, + spread_hash, validate_definition_count, validate_hash_and_range_differ, validate_keys_defined, validate_unique_attribute_definitions, }; pub use restorable_item::{ 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)] From fc2186a0ec8063ed15d6c96b613ccce5eee88eee Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:53:40 +0000 Subject: [PATCH 13/13] test(table): UPDATE_TABLE and CREATE_TABLE data tables, on a name that does not exist tests/test_key_schema_definitions.py had eight parametrized tests over two request shapes, an UpdateTable GSI Create and a CreateTable. Three of them, the UpdateTable listing, definition count and duplicate rows, created a table through a module fixture, also on the service. Their measurements went to a table name that does not exist. The service answers every refusal in the file before it looks the table up. The 47 rows of seven of these tests are now two tables, UPDATE_TABLE and CREATE_TABLE, each with one parametrized test. Every row has its full expected message and goes to NEVER_CREATED. The fixture goes. The four billing rows keep their test, which sends ProvisionedThroughput. Each row keeps its request and its expected message. _message now also asserts the status 400. ks() repeated keys() for a HASH key and an optional RANGE key. It goes, and its 48 calls now use keys(). --- tests/test_key_schema_definitions.py | 198 +++++++++++---------------- 1 file changed, 78 insertions(+), 120 deletions(-) diff --git a/tests/test_key_schema_definitions.py b/tests/test_key_schema_definitions.py index e6e5bec36..eb9fbe123 100644 --- a/tests/test_key_schema_definitions.py +++ b/tests/test_key_schema_definitions.py @@ -27,6 +27,9 @@ 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). @@ -57,13 +60,6 @@ def defs(spec: str) -> list[dict]: return [{"AttributeName": p.split(":")[0], "AttributeType": p.split(":")[1]} for p in spec.split()] -def ks(hash_key: str, range_key: str | None = None) -> list[dict]: - out = [{"AttributeName": hash_key, "KeyType": "HASH"}] - if range_key: - out.append({"AttributeName": range_key, "KeyType": "RANGE"}) - return out - - 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()] @@ -74,18 +70,13 @@ def _message(call) -> str: call() err = exc_info.value.response["Error"] assert err["Code"] == "ValidationException", err + assert exc_info.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400, err return err["Message"] -@pytest.fixture(scope="module") -def table(dynamodb_client): - with scoped_table(dynamodb_client) as name: - yield name - - -def _update(client, table, spec, key_schema): +def _update(client, spec, key_schema): return lambda: client.update_table( - TableName=table, + TableName=NEVER_CREATED, AttributeDefinitions=defs(spec), GlobalSecondaryIndexUpdates=[{"Create": { "IndexName": "never-created", @@ -115,84 +106,41 @@ def _create(client, spec, table_keys, gsis=(), lsis=()): return lambda: client.create_table(**kwargs) -# UpdateTable GSI Create: (definitions, index hash, index range, message) -UPDATE_LISTED = [ - ("range_missing", "pk:S g:S", "g", "r", listed("r, g", "pk, g")), - ("hash_missing", "pk:S r:S", "g", "r", listed("r, g", "r, pk")), - ("both_missing_two_defs", "pk:S z:S", "g", "r", listed("r, g", "z, pk")), - ("both_missing_three_defs", "pk:S y:S z:S", "g", "r", listed("r, g", "y, z, pk")), - ("hash_only_missing", "pk:S", "g", None, listed("g", "pk")), - ("other_types", "pk:S n:N b:B", "n", "x", listed("x, n", "n, b, pk")), - ("service_order", "pk:S x:S", "g", "r", listed("r, g", "x, pk")), +# 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", "h", "r", "expected"), UPDATE_LISTED, - ids=[c[0] for c in UPDATE_LISTED]) -def test_update_table_lists_every_key_and_definition(dynamodb_client, table, case, spec, h, r, expected): - assert _message(_update(dynamodb_client, table, spec, ks(h, r))) == expected - - -@pytest.mark.parametrize(("spec", "h", "r"), [("pk:S", "g", "r"), ("pk:S", "pk", "r")], - ids=["both_missing_one_def", "range_missing_one_def"]) -def test_update_table_with_fewer_definitions_than_keys(dynamodb_client, table, spec, h, r): - assert _message(_update(dynamodb_client, table, spec, ks(h, r))) == INVALID - - -@pytest.mark.parametrize(("spec", "h", "r", "name"), [ - ("h:S h:S", "h", None, "h"), - ("h:S h:S", "h", "r", "h"), - ("b:S a:S b:S a:S h:S", "h", "r", "b"), - ("a:S b:S b:S a:S h:S", "h", "r", "b"), - ("a:S b:S a:S b:S h:S", "h", "r", "a"), - ("h:S h:N", "h", "r", "h"), -], ids=["index_key", "and_a_missing_key", "first_repeated", "second_definition_first", - "first_definition_first", "two_types"]) -def test_update_table_refuses_a_name_defined_twice(dynamodb_client, table, spec, h, r, name): - message = _message(_update(dynamodb_client, table, spec, ks(h, r))) - assert message == f"Attribute Name is duplicated: {name}" - - -# UpdateTable GSI Create on a table name that does not exist, where two rules -# apply: (definitions, index key schema, message). The definition count and the -# HASH and RANGE names come before a name defined twice. -UPDATE_ORDER = [ - ("count_before_duplicate", "g:S g:S", "g:HASH x:RANGE y:RANGE", INVALID), - ("count_before_duplicate_other_names", "a:S a:S", "a:HASH b:RANGE c:RANGE", INVALID), - ("same_name_before_duplicate", "g:S g:S", "g:HASH g:RANGE", SAME_NAME), - ("count_before_same_name", "g:S", "g:HASH g:RANGE", INVALID), - ("same_name", "g:S x:S", "g:HASH g:RANGE", SAME_NAME), -] - - -@pytest.mark.parametrize(("case", "spec", "key_spec", "expected"), UPDATE_ORDER, - ids=[c[0] for c in UPDATE_ORDER]) -def test_update_table_checks_in_the_service_order(dynamodb_client, case, spec, key_spec, expected): - assert _message(_update(dynamodb_client, NEVER_CREATED, spec, keys(key_spec))) == expected - - -# CreateTable: (definitions, table keys, GSIs, LSIs, message) -CREATE = [ - ("gsi_range_missing", "pk:S g:S", ks("pk"), [ks("g", "r")], [], listed("r, g", "pk, g")), - ("gsi_both_missing", "pk:S", ks("pk"), [ks("g", "r")], [], INVALID), - ("table_sort_missing_one_def", "pk:S", ks("pk", "sk"), [], [], INVALID), - ("table_sort_missing", "pk:S x:S", ks("pk", "sk"), [], [], listed("sk, pk", "x, pk")), - ("table_pk_missing", "x:S", ks("pk"), [], [], listed("pk", "x")), - ("table_before_gsi", "pk:S g:S", ks("pk", "sk"), [ks("g", "r")], [], listed("sk, pk", "pk, g")), - ("table_before_lsi", "pk:S x:S", ks("pk", "sk"), [], [ks("pk", "l")], listed("sk, pk", "x, pk")), - ("lsi_missing", "pk:S sk:S", ks("pk", "sk"), [], [ks("pk", "l")], listed("l, pk", "sk, pk")), - ("lsi_before_gsi", "pk:S sk:S g:S", ks("pk", "sk"), [ks("g", "r")], [ks("pk", "l")], - listed("l, pk", "sk, pk, g")), - ("first_gsi_first", "pk:S g:S h:S", ks("pk"), [ks("g", "r"), ks("h", "q")], [], - listed("r, g", "h, pk, g")), -] - - -@pytest.mark.parametrize(("case", "spec", "table_keys", "gsis", "lsis", "expected"), CREATE, - ids=[c[0] for c in CREATE]) -def test_create_table_checks_each_key_schema_in_turn(dynamodb_client, case, spec, table_keys, gsis, lsis, - expected): - assert _message(_create(dynamodb_client, spec, table_keys, gsis, lsis)) == expected +@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={}), " @@ -200,11 +148,36 @@ def test_create_table_checks_each_key_schema_in_turn(dynamodb_client, case, spec "keyType=RANGE)]' at 'keySchema' failed to satisfy constraint: Member must have length " "less than or equal to 2") -# CreateTable where two rules apply: (definitions, table keys, GSIs, LSIs, -# message). 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. -CREATE_ORDER = [ +# 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"), [], [], @@ -217,17 +190,17 @@ def test_create_table_checks_each_key_schema_in_turn(dynamodb_client, case, spec "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", ks("pk"), [keys("r:RANGE g:HASH")], [], + ("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", ks("pk", "sk"), [], [keys("l:RANGE pk:HASH")], + ("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_ORDER, - ids=[c[0] for c in CREATE_ORDER]) -def test_create_table_checks_in_the_service_order(dynamodb_client, case, spec, table_keys, gsis, lsis, - expected): +@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 @@ -236,9 +209,9 @@ def test_create_table_checks_in_the_service_order(dynamodb_client, case, spec, t @pytest.mark.parametrize(("spec", "table_keys"), [ - ("pk:S pk:S", ks("pk")), - ("pk:S x:S", ks("pk", "sk")), - ("pk:S", ks("pk", "sk")), + ("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): @@ -249,21 +222,6 @@ def call(): assert _message(call) == BILLING -@pytest.mark.parametrize(("spec", "table_keys", "gsis", "name"), [ - ("pk:S pk:S", ks("pk"), [], "pk"), - ("pk:S pk:N", ks("pk"), [], "pk"), - ("pk:S pk:S", ks("pk", "sk"), [], "pk"), - ("pk:S g:S g:S", ks("pk"), [ks("g")], "g"), - ("b:S a:S b:S a:S pk:S", ks("pk"), [], "b"), - ("a:S b:S b:S a:S pk:S", ks("pk"), [], "b"), - ("a:S b:S a:S b:S pk:S", ks("pk"), [], "a"), -], ids=["table_key", "two_types", "and_a_missing_key", "index_key", "first_repeated", - "second_definition_first", "first_definition_first"]) -def test_create_table_refuses_a_name_defined_twice(dynamodb_client, spec, table_keys, gsis, name): - message = _message(_create(dynamodb_client, spec, table_keys, gsis)) - assert message == f"Attribute Name is duplicated: {name}" - - 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 @@ -284,7 +242,7 @@ def test_update_table_keeps_the_type_of_a_redefined_table_key(dynamodb_client): AttributeDefinitions=defs("pk:N g:S"), GlobalSecondaryIndexUpdates=[{"Create": { "IndexName": "by-g", - "KeySchema": ks("g"), + "KeySchema": keys("g:HASH"), "Projection": {"ProjectionType": "KEYS_ONLY"}, }}], )