Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
1ad6576
fix(table): check each key schema's definitions as the service does
LeeroyHannigan Oct 31, 2026
c9aeb0b
test(table): undefined and duplicated key attribute definitions
LeeroyHannigan Oct 31, 2026
a430c57
fix(table): billing faults first, a linear duplicate check, the list …
LeeroyHannigan Oct 31, 2026
2bb47d6
test(table): billing faults before definition faults; wait for the index
LeeroyHannigan Oct 31, 2026
1ad8ac0
Merge fix/517-519-520-stream-update-table-sentences into fix/index-ke…
LeeroyHannigan Nov 16, 2026
19eb118
Merge fix/517-519-520-stream-update-table-sentences into fix/index-ke…
LeeroyHannigan Nov 25, 2026
2d0ddcd
fix(table): check key definitions in the service's order
LeeroyHannigan Nov 25, 2026
cb0b9c0
fix(table): list the keys and definitions in the service's order
LeeroyHannigan Nov 25, 2026
94721d8
test(table): pin which repeated name the duplicate sentence names
LeeroyHannigan Nov 25, 2026
d23aac1
fix(backup): restore the tables earlier releases created
LeeroyHannigan Nov 25, 2026
0efed55
test(table): wait for the created index before the table is deleted
LeeroyHannigan Nov 25, 2026
289fde9
fix(table): keep main's rules for a multi-part table key schema
LeeroyHannigan Nov 25, 2026
e770ef3
docs(core): state the bucket resize and the multi-part guard without …
LeeroyHannigan Nov 25, 2026
fb4ea9d
refactor(core): one function for the Java HashMap hash of a name
LeeroyHannigan Nov 25, 2026
fc2186a
test(table): UPDATE_TABLE and CREATE_TABLE data tables, on a name tha…
LeeroyHannigan Nov 25, 2026
1619dfe
Merge fix/517-519-520-stream-update-table-sentences into fix/index-ke…
LeeroyHannigan Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
312 changes: 312 additions & 0 deletions crates/core/src/validation/key_definitions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,312 @@
// Copyright 2026 ExtendDB contributors
// SPDX-License-Identifier: Apache-2.0

//! Checks that a key schema's attributes are defined in `AttributeDefinitions`,
//! shared by `CreateTable`, an `UpdateTable` GSI `Create` and a restore.
//!
//! The service's rules, measured on 2026-10-25, 2026-10-26 and 2026-11-25
//! (us-east-1), in the order the service checks them:
//!
//! 1. A key schema with more keys than there are definitions answers
//! `Invalid KeySchema: Some index key attribute have no definition`.
//! 2. A key schema whose HASH and RANGE elements name one attribute answers
//! `Both the Hash Key and the Range Key element in the KeySchema have the
//! same name`.
//! 3. A name defined twice answers `Attribute Name is duplicated: <name>`,
//! naming the name whose second definition comes first in the list.
//! 4. A key with no definition answers `Some index key attributes are not
//! defined in AttributeDefinitions`, listing every key of the schema and
//! every definition, each list in the order of [`listed`].
//!
//! An `UpdateTable` GSI `Create` runs the four in that order. `CreateTable`
//! runs the first three on the table's key schema, after the table billing
//! rules and before the key schema shape checks, with rule 2 only outside the
//! multi-part table key preview. After every shape check it runs rule 4 on the
//! table's key schema, then rules 1 and 4 on each LSI's and each GSI's in turn.
//! The service checks each index's definitions before that index's shape
//! (measured 2026-11-25), so a request with both faults in one index gets the
//! shape sentence here. A restore runs `CreateTable`'s checks without rules 1
//! and 3, which earlier releases did not apply (`validate_recorded_table`).

use std::collections::HashSet;

use crate::error::DynamoDbError;
use crate::types::{AttributeDefinition, KeySchemaElement, KeyType};

/// Rule 1's sentence.
const KEY_SCHEMA_WITHOUT_DEFINITION: &str =
"Invalid KeySchema: Some index key attribute have no definition";

/// Rule 1: refuse a key schema with more keys than `defs` has entries.
///
/// # Errors
///
/// `ValidationException` `Invalid KeySchema: Some index key attribute have no
/// definition`.
pub fn validate_definition_count(
key_schema: &[KeySchemaElement],
defs: &[AttributeDefinition],
) -> Result<(), DynamoDbError> {
if defs.len() < key_schema.len() {
return Err(DynamoDbError::ValidationException(
KEY_SCHEMA_WITHOUT_DEFINITION.to_owned(),
));
}
Ok(())
}

/// Rule 2: refuse a two-element key schema whose HASH and RANGE elements name
/// one attribute.
///
/// # Errors
///
/// `ValidationException` `Both the Hash Key and the Range Key element in the
/// KeySchema have the same name`.
pub fn validate_hash_and_range_differ(
key_schema: &[KeySchemaElement],
) -> Result<(), DynamoDbError> {
if let [hash, range] = key_schema

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The service gives this sentence for the two elements in either order. Twice each: UpdateTable GSI Create [g RANGE, g HASH] with definitions [g, g] answers it on the service and Attribute Name is duplicated: g here; with [g, x] the service refuses and this head creates the index; on a missing table the service gives the sentence and this head ResourceNotFoundException. CreateTable [pk RANGE, pk HASH] answers it on the service, and here Attribute Name is duplicated: pk with [pk, pk] and First KeySchemaElement is not a HASH type with [pk, x]. Base answers each of these as this head does. Matching the two names whatever the key types, with rows for the reversed order, would hold it.

&& hash.key_type == KeyType::Hash
&& range.key_type == KeyType::Range
&& hash.attribute_name == range.attribute_name
{
return Err(DynamoDbError::ValidationException(
"Both the Hash Key and the Range Key element in the KeySchema have the same name"
.to_owned(),
));
}
Ok(())
}

/// Rule 3: refuse a name defined twice in `defs`.
///
/// # Errors
///
/// `ValidationException` `Attribute Name is duplicated: <name>`.
pub fn validate_unique_attribute_definitions(
defs: &[AttributeDefinition],
) -> Result<(), DynamoDbError> {
let mut seen = HashSet::with_capacity(defs.len());
for def in defs {
if !seen.insert(def.attribute_name.as_str()) {
return Err(DynamoDbError::ValidationException(format!(
"Attribute Name is duplicated: {}",
def.attribute_name
)));
}
}
Ok(())
}

/// Rule 4: refuse a key schema with a key that has no definition in `defs`.
///
/// # Errors
///
/// `ValidationException` `Some index key attributes are not defined in
/// AttributeDefinitions`, with every key and every definition.
pub fn validate_keys_defined(
key_schema: &[KeySchemaElement],
defs: &[AttributeDefinition],
) -> Result<(), DynamoDbError> {
if key_schema
.iter()
.all(|k| defs.iter().any(|d| d.attribute_name == k.attribute_name))
{
return Ok(());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The order of the two lists can be matched. It is the iteration order of a Java HashMap with 4 starting buckets and load factor 0.75, keyed by String.hashCode spread as h ^ (h >>> 16), with insertion order within a bucket. All 66 lists in 33 answers from the service fit it, as do the 5 examples in #554, and 8 new lists predicted before sending (13 names, mixed case, accented names and an emoji) matched the service twice each. This head's order differs in 22 of the 33, for example the service's Keys: [sk, pk], AttributeDefinitions: [x, pk] against [pk, sk] and [pk, x] here. Rendering both lists in that order would let docs/differences-from-dynamodb.md:60 go, and the tests that compare the lists as sets could compare the message.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cb0b9c0. listed in key_definitions.rs renders both lists in that order. It has one more rule: the table also doubles when a bucket that holds eight or more names takes another, below 64 buckets. Nine and eight names in one bucket of 16 settle that rule on the service. listed does not model a bucket that holds eight or more names and takes another while the table has 64 or more buckets. There HashMap builds a tree. That case needs at least 11 names.

Before the requests went out, the model predicted the 14 answers of this round, and the service answered each one as predicted, twice. The wire rows now compare the whole message, with a new row for [pk, x], and the docs/differences-from-dynamodb.md row is gone.

}
let keys = listed(key_schema.iter().map(|k| k.attribute_name.as_str()));
let names = listed(defs.iter().map(|d| d.attribute_name.as_str()));
Err(DynamoDbError::ValidationException(format!(
"One or more parameter values were invalid: Some index key attributes are not defined in \
AttributeDefinitions. Keys: [{}], AttributeDefinitions: [{}]",
keys.join(", "),
names.join(", ")
)))
}

/// The hash a `java.util.HashMap` spreads for a `String` key: Java's
/// `String.hashCode` of `name` over its UTF-16 code units (31 times the hash
/// plus each unit, wrapping at 32 bits), combined by XOR with itself shifted
/// right by 16 bits. The key's bucket in a table of `buckets` buckets is this
/// value masked by `buckets - 1`.
#[must_use]
pub fn spread_hash(name: &str) -> u32 {
let hash = name.encode_utf16().fold(0_u32, |h, unit| {
h.wrapping_mul(31).wrapping_add(u32::from(unit))
});
hash ^ (hash >> 16)
}

/// The order in which the service lists the names of a key schema or of
/// `AttributeDefinitions`: the iteration order of a `java.util.HashMap`
/// created with 4 buckets and load factor 0.75, into which the names go in
/// request order. A name's bucket is its [`spread_hash`] masked by
/// `buckets - 1`. The table doubles when it holds more names than three
/// quarters of its buckets, and when a bucket that holds eight or more names
/// takes another while the table has fewer than 64 buckets. The names come out
/// bucket by bucket, in insertion order within a bucket (measured 2026-11-25,
/// with lists of up to nine names in one bucket). A repeated name keeps its
/// first position, as `HashMap::put` does. No measured list repeats a name.
///
/// Not modelled: a bucket that holds eight or more names and takes another
/// while the table has 64 or more buckets. `HashMap` turns that bucket into a
/// tree, which it iterates in another order. That needs at least 11 names,
/// nine or more of them in one bucket.
fn listed<'a>(names: impl IntoIterator<Item = &'a str>) -> Vec<&'a str> {
let mut seen = HashSet::new();
let mut entries: Vec<(&str, u32)> = Vec::new();
let mut buckets: u32 = 4;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The service's lists follow a java.util.HashMap sized for the names up front, the smallest power of two not below ceil(n / 0.75), not one that starts at 4 and doubles; checked against Java 17 it fits all 67 lists measured, the doubling model 62. The two agree until nine or more names share a bucket. Four lists of 20 and 21 names, with 9 in one bucket, predicted before sending, answer the presized order on the service, twice each, and a different one here; for example qaav qacx qaez qala qanc qape qarg qati qavk h00 h01 h02 h03 h04 h05 h06 h07 h09 h10 h11 lists [h10, h11, h01, h00, ...] on the service and [h10, h01, h00, h11, ...] here. The tree case is reached with 10 names in one bucket among 13, where the comment and body say at least 11. Starting buckets at the presized count matches every non-tree list measured; the tree bucket can be modelled or the stated limit corrected.

for name in names {
if !seen.insert(name) {
continue;
}
let spread = spread_hash(name);
let mask = buckets - 1;
let crowded = buckets < 64
&& entries
.iter()
.filter(|&&(_, s)| s & mask == spread & mask)
.count()
>= 8;
entries.push((name, spread));
if crowded || entries.len() > (buckets / 4 * 3) as usize {
buckets *= 2;
}
}
entries.sort_by_key(|&(_, s)| s & (buckets - 1));
entries.into_iter().map(|(name, _)| name).collect()
}

#[cfg(test)]
mod tests {
use super::*;
use crate::types::ScalarAttributeType;

fn defs(names: &[&str]) -> Vec<AttributeDefinition> {
names
.iter()
.map(|n| AttributeDefinition {
attribute_name: (*n).to_owned(),
attribute_type: ScalarAttributeType::S,
})
.collect()
}

fn ks(hash: &str, range: Option<&str>) -> Vec<KeySchemaElement> {
let mut k = vec![KeySchemaElement {
attribute_name: hash.to_owned(),
key_type: KeyType::Hash,
}];
if let Some(r) = range {
k.push(KeySchemaElement {
attribute_name: r.to_owned(),
key_type: KeyType::Range,
});
}
k
}

fn message(r: Result<(), DynamoDbError>) -> String {
match r {
Err(DynamoDbError::ValidationException(m)) => m,
other => panic!("expected a ValidationException, got {other:?}"),
}
}

#[test]
fn the_first_repeated_name_is_named() {
for (names, repeated) in [
(&["b", "a", "b", "a"][..], "b"),
(&["a", "b", "b", "a"][..], "b"),
(&["a", "b", "a", "b"][..], "a"),
] {
assert_eq!(
message(validate_unique_attribute_definitions(&defs(names))),
format!("Attribute Name is duplicated: {repeated}"),
"{names:?}"
);
}
assert!(validate_unique_attribute_definitions(&defs(&["a", "b"])).is_ok());
}

#[test]
fn fewer_definitions_than_keys_is_the_key_schema_sentence() {
for (schema, names) in [(ks("g", Some("r")), &["pk"][..]), (ks("g", None), &[][..])] {
assert_eq!(
message(validate_definition_count(&schema, &defs(names))),
"Invalid KeySchema: Some index key attribute have no definition"
);
}
assert!(validate_definition_count(&ks("g", Some("r")), &defs(&["pk", "x"])).is_ok());
}

#[test]
fn a_hash_and_a_range_on_one_name_is_refused() {
assert_eq!(
message(validate_hash_and_range_differ(&ks("g", Some("g")))),
"Both the Hash Key and the Range Key element in the KeySchema have the same name"
);
assert!(validate_hash_and_range_differ(&ks("g", Some("r"))).is_ok());
assert!(validate_hash_and_range_differ(&ks("g", None)).is_ok());
}

/// The lists of measured answers (2026-10-25 and 2026-11-25).
#[test]
fn a_missing_key_lists_every_key_and_every_definition_in_the_service_order() {
for (schema, names, expected) in [
(
ks("g", Some("r")),
&["pk", "g"][..],
"Keys: [r, g], AttributeDefinitions: [pk, g]",
),
(
ks("g", Some("r")),
&["pk", "z"][..],
"Keys: [r, g], AttributeDefinitions: [z, pk]",
),
(
ks("pk", Some("sk")),
&["pk", "x"][..],
"Keys: [sk, pk], AttributeDefinitions: [x, pk]",
),
] {
assert_eq!(
message(validate_keys_defined(&schema, &defs(names))),
format!(
"One or more parameter values were invalid: Some index key attributes are \
not defined in AttributeDefinitions. {expected}"
)
);
}
assert!(validate_keys_defined(&ks("g", Some("r")), &defs(&["r", "g"])).is_ok());
}

/// Request order in, the service's order out (measured 2026-11-25). The
/// last two lists put nine and eight names in one bucket of a 16-bucket
/// table: the ninth makes the table double, the eighth does not.
#[test]
fn lists_follow_the_measured_order() {
for (request, service) in [
(
"alpha beta gamma delta epsilon zeta eta theta",
"epsilon zeta eta alpha delta theta beta gamma",
),
("Zed apple Mango kiwi Ünï", "Zed Mango apple kiwi Ünï"),
("pk id userId createdAt", "createdAt pk id userId"),
("gsiPk gsiSk", "gsiSk gsiPk"),
("pk sk g", "sk pk g"),
("pk g h", "h pk g"),
("pk n b", "n b pk"),
(
"kaaa kaaq kabb kabr kacc kacs kadd kadt kaee",
"kaaa kabb kacc kadd kaee kaaq kabr kacs kadt",
),
(
"kaaa kaaq kabb kabr kacc kacs kadd kadt",
"kaaa kaaq kabb kabr kacc kacs kadd kadt",
),
] {
assert_eq!(listed(request.split(' ')).join(" "), service, "{request}");
}
}
}
Loading
Loading