diff --git a/crates/core/src/validation/key_size.rs b/crates/core/src/validation/key_size.rs new file mode 100644 index 000000000..2ad1c0fa6 --- /dev/null +++ b/crates/core/src/validation/key_size.rs @@ -0,0 +1,281 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Key value size limits. +//! +//! The write path checks the key values of an item against these limits (see +//! `validate_key_sizes`). `Query` applies the same limits to the values in its +//! key condition: a partition key value may not exceed +//! `max_partition_key_size_bytes` (2048), the partition key values of an index +//! with several HASH attributes may not exceed it together, and the values of +//! all range key attributes together may not exceed `max_sort_key_size_bytes` +//! (1024). All limits are inclusive. The three sentences are the service's +//! own; the single hash sentence has no space between `of` and the number. + +use crate::error::DynamoDbError; +use crate::expression::{ + Expr, ExpressionMaps, KeyCondition, PathElement, SortKeyCondition, resolve_element_name, +}; +use crate::limits::LimitsConfig; +use crate::types::{AttributeValue, KeySchemaElement, KeyType}; +use crate::validation::number::{NumberFault, normalize_number}; + +/// Byte size of a key attribute value. +/// +/// `S` is sized by its UTF-8 bytes, `B` by its decoded bytes and `N` by its +/// digit string. A number that passes the number rules is normalized when the +/// request is read. The Query path sizes an `N` value in `sized_clause` and +/// does not call this function for it. +pub(super) fn key_value_byte_size(value: &AttributeValue) -> usize { + match value { + AttributeValue::S(s) => s.len(), + AttributeValue::N(n) => n.len(), + AttributeValue::B(b) => b.len(), + _ => 0, + } +} + +/// The refusal for a partition key value over `max` bytes. +pub(super) fn hash_key_too_large(max: usize) -> DynamoDbError { + DynamoDbError::ValidationException(format!( + "One or more parameter values were invalid: \ + Size of hashkey has exceeded the maximum size limit of{max} bytes" + )) +} + +/// The refusal for partition key values that are each within `max` bytes but +/// add up to more than `max`. Measured 2026-10-23 on an index with HASH `h1` +/// and `h2`. +pub(super) fn hash_keys_too_large_in_total(max: usize) -> DynamoDbError { + DynamoDbError::ValidationException(format!( + "One or more parameter values were invalid: \ + Aggregated size of all hash keys has exceeded the size limit of {max} bytes" + )) +} + +/// The refusal for range key values over `max` bytes in total. +pub(super) fn range_keys_too_large(max: usize) -> DynamoDbError { + DynamoDbError::ValidationException(format!( + "One or more parameter values were invalid: \ + Aggregated size of all range keys has exceeded the size limit of {max} bytes" + )) +} + +/// One clause of a key condition: the attribute path and the value +/// expressions it carries (one for every form but `BETWEEN`, which has two). +type Clause<'a> = (&'a [PathElement], Vec<&'a Expr>); + +/// Every clause of `kc`, whichever field the parser or the schema classifier +/// left it in. A clause is assigned to HASH or RANGE by its attribute name +/// against the key schema, not by its field, so the result does not depend on +/// how a multi-attribute key condition was arranged. +fn clauses(kc: &KeyCondition) -> Vec> { + let mut clauses: Vec> = Vec::new(); + clauses.push((kc.pk_path.as_slice(), vec![&kc.pk_value])); + for (path, value) in &kc.extra_pk_conditions { + clauses.push((path.as_slice(), vec![value])); + } + match &kc.sk_condition { + Some(SortKeyCondition::Compare { path, value, .. }) => { + clauses.push((path.as_slice(), vec![value])); + } + Some(SortKeyCondition::Between { path, low, high }) => { + clauses.push((path.as_slice(), vec![low, high])); + } + Some(SortKeyCondition::BeginsWith { path, prefix }) => { + clauses.push((path.as_slice(), vec![prefix])); + } + None => {} + } + for (path, value) in &kc.extra_sk_conditions { + clauses.push((path.as_slice(), vec![value])); + } + clauses +} + +/// What one clause contributes to the size check. +enum ClauseSize { + /// A `#name` or `:value` of the clause is not defined. The request keeps + /// the undefined-reference refusal it gets downstream, ahead of any size. + Unresolved, + /// The clause names an attribute outside the key schema, or is not a + /// placeholder, and adds nothing. + Skipped, + /// The position of the clause's attribute in the key schema and the bytes + /// the clause contributes. + Bytes(usize, usize), +} + +/// Size one clause. A clause with two values (`BETWEEN`) contributes the +/// larger of the two. Measured 2026-10-23: bounds of 600 and 600 bytes pass (a +/// sum would be 1200), bounds of 1 and 1025 bytes are refused. +/// +/// An `N` value is checked against the number rules first. One with more than +/// 38 significant digits or a magnitude out of range is refused with the +/// number's own sentence and is not sized. One that passes is sized by its +/// normalized digit string. Measured 2026-11-20 in us-east-1 on a GSI with +/// HASH `n` (N). In `KeyConditionExpression` and in `KeyConditions`, 2049 or +/// 39 digits answer `Attempting to store more than 38 significant digits in a +/// Number`. `1` followed by 2100 zeros answers `Number overflow. ...`, and the +/// service serves 2100 zeros followed by `1`. `1e-131` answers `Number +/// underflow. ...` as a partition and as a sort key value (measured +/// 2026-11-24). +/// +/// An ASCII value that `normalize_number` does not read as a number is refused +/// with `The parameter cannot be converted to a numeric value: ` followed by +/// the value as sent. Measured 2026-11-24 in us-east-1, in +/// `KeyConditionExpression` and in `KeyConditions`: `abc`, 2049 `x`, ` 1` +/// and the empty value. An empty value keeps the colon, which the text of +/// `NumberFault::Empty` does not have. +/// +/// A value that is not a number to these rules and holds a character outside +/// ASCII adds nothing to the size. The service reads Unicode decimal digits as +/// digits and these rules do not (#565). It serves a Query with one U+FF11, +/// read as the number 1, and answers the 38-digit sentence for 39, 683 or +/// 2049 of them. Refusing such a value here would refuse the one U+FF11. +/// +/// # Errors +/// +/// Returns the number's `ValidationException` for an `N` value that is not a +/// number and holds ASCII characters only, has more than 38 significant +/// digits or has a magnitude out of range. +fn sized_clause( + clause: &Clause<'_>, + key_schema: &[KeySchemaElement], + maps: &ExpressionMaps, +) -> Result { + let (path, values) = clause; + let Some(first) = path.first() else { + return Ok(ClauseSize::Skipped); + }; + let Ok(name) = resolve_element_name(first, maps) else { + return Ok(ClauseSize::Unresolved); + }; + let mut size = 0; + let mut placeholders = true; + for value in values { + let Expr::Placeholder(placeholder) = value else { + placeholders = false; + continue; + }; + let Ok(value) = maps.resolve_value(placeholder) else { + return Ok(ClauseSize::Unresolved); + }; + let bytes = match value { + AttributeValue::N(n) => match normalize_number(n) { + Ok(digits) => digits.len(), + Err(fault) if fault.is_not_a_number() && !n.is_ascii() => 0, + Err(fault) if fault.is_not_a_number() => { + return Err(NumberFault::Malformed.error(n)); + } + Err(fault) => return Err(fault.error(n)), + }, + other => key_value_byte_size(other), + }; + size = size.max(bytes); + } + let Some(key) = key_schema.iter().position(|ks| ks.attribute_name == name) else { + return Ok(ClauseSize::Skipped); + }; + if !placeholders { + return Ok(ClauseSize::Skipped); + } + Ok(ClauseSize::Bytes(key, size)) +} + +/// Refuse a `Query` whose key condition carries a key value over the key size +/// limits. +/// +/// - If any single HASH value is over `max_partition_key_size_bytes` (2048), +/// the single hash sentence. Otherwise, if the values of the HASH +/// attributes add up to more than that, the aggregated hash sentence (only +/// an index with several HASH attributes can reach it). +/// - Every RANGE attribute contributes the size of its clause's value, +/// whatever the operator (`=`, `<`, `<=`, `>`, `>=`, `begins_with`); a +/// `BETWEEN` contributes the larger of its two bounds. The contributions are +/// added up, and a total over `max_sort_key_size_bytes` (1024) is refused +/// with the range sentence. +/// - A key attribute with more than one clause contributes its largest value +/// once, so a second clause on `pk` does not reach the aggregated hash +/// sentence. The service refuses that key condition with `Invalid +/// KeyConditionExpression: KeyConditionExpressions must only contain one +/// condition per key` (measured 2026-11-24 with 1025 bytes in each `pk` +/// value). This check does not make that refusal. +/// - The HASH checks run before the RANGE check, so the hash sentence wins when +/// both limits are exceeded. +/// - An `N` value that is not a number, has more than 38 significant digits or +/// has a magnitude out of range is refused with the number's sentence and is +/// not sized. A value that is not a number and holds a character outside +/// ASCII adds nothing (see `sized_clause`). +/// - If a `#name` or `:value` of any key clause is not defined, the check +/// returns `Ok`, because the service reports the undefined reference ahead +/// of the size. `ExtendDB` refuses most such requests later on. On a key +/// schema with one HASH and at most one RANGE attribute it serves +/// `pk = :h AND #u > :r` with `#u` undefined, which the service refuses +/// (#1214). +/// +/// All limits are inclusive. `key_schema` is the key schema being queried: the +/// index's for an index query, the table's otherwise. +/// +/// Measured on the service in us-east-1 2026-10-21 to 2026-10-23: the limits +/// and the sentences on a base table, an LSI and a GSI; string and binary +/// values sized by byte length; every operator above at 1025 bytes refused; +/// `BETWEEN` as described; the hash sentence when both limits are exceeded; on +/// an index with HASH `h1`, `h2`: `h1` of 2049 bytes and `h2` of 1 byte gives +/// the single sentence, 1025 and 1024 bytes (sum 2049) and 2048 and 2048 bytes +/// give the aggregated sentence; on an index with HASH `h` and RANGE `a`, `b`, +/// `c`, `d`: `a` of 600 and `c` of 600 bytes (with `b` of 1) refused, 512 and +/// 512 passes, 512 and 513 refused, `b > 1025` refused, `a` of 600 with `b +/// BETWEEN` 1 and 600 refused and with 1 and 424 passes. Measured 2026-11-20 on +/// the `h1`, `h2` index: 1024 and 1024 bytes (sum 2048) pass, and 1025 and 1024 +/// bytes with a 1025-byte RANGE value give the aggregated hash sentence. +/// +/// A clause that names an attribute outside the key schema, or that is not a +/// placeholder, adds nothing, so the refusal it already gets stays unchanged. +/// +/// # Errors +/// +/// Returns `ValidationException` with the service's sentence when a limit is +/// exceeded or an `N` value breaks the number rules. +pub fn validate_query_key_sizes( + key_condition: &KeyCondition, + key_schema: &[KeySchemaElement], + maps: &ExpressionMaps, + limits: &LimitsConfig, +) -> Result<(), DynamoDbError> { + let mut sizes = vec![0; key_schema.len()]; + for clause in clauses(key_condition) { + match sized_clause(&clause, key_schema, maps)? { + ClauseSize::Unresolved => return Ok(()), + ClauseSize::Skipped => {} + ClauseSize::Bytes(key, size) => sizes[key] = sizes[key].max(size), + } + } + let mut hash_over = false; + let mut hash_total: usize = 0; + let mut range_total: usize = 0; + for (key, size) in key_schema.iter().zip(sizes) { + match key.key_type { + KeyType::Hash => { + hash_over |= size > limits.max_partition_key_size_bytes; + hash_total = hash_total.saturating_add(size); + } + KeyType::Range => range_total = range_total.saturating_add(size), + } + } + if hash_over { + return Err(hash_key_too_large(limits.max_partition_key_size_bytes)); + } + if hash_total > limits.max_partition_key_size_bytes { + return Err(hash_keys_too_large_in_total( + limits.max_partition_key_size_bytes, + )); + } + if range_total > limits.max_sort_key_size_bytes { + return Err(range_keys_too_large(limits.max_sort_key_size_bytes)); + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/validation/key_size/tests.rs b/crates/core/src/validation/key_size/tests.rs new file mode 100644 index 000000000..14bd51b4b --- /dev/null +++ b/crates/core/src/validation/key_size/tests.rs @@ -0,0 +1,523 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use std::collections::HashMap; + +use super::*; +use crate::expression::CompareOp; + +const HASH_MSG_2048: &str = "One or more parameter values were invalid: \ + Size of hashkey has exceeded the maximum size limit of2048 bytes"; +const HASH_TOTAL_MSG_2048: &str = "One or more parameter values were invalid: \ + Aggregated size of all hash keys has exceeded the size limit of 2048 bytes"; +const RANGE_MSG_1024: &str = "One or more parameter values were invalid: \ + Aggregated size of all range keys has exceeded the size limit of 1024 bytes"; + +fn ks(name: &str, key_type: KeyType) -> KeySchemaElement { + KeySchemaElement { + attribute_name: name.to_owned(), + key_type, + } +} + +fn path(name: &str) -> Vec { + vec![PathElement::Attribute(name.to_owned())] +} + +fn placeholder(name: &str) -> Expr { + Expr::Placeholder(name.to_owned()) +} + +fn eq(name: &str, value: &str) -> SortKeyCondition { + SortKeyCondition::Compare { + path: path(name), + op: CompareOp::Eq, + value: placeholder(value), + } +} + +fn compare(name: &str, op: CompareOp, value: &str) -> SortKeyCondition { + SortKeyCondition::Compare { + path: path(name), + op, + value: placeholder(value), + } +} + +fn maps(values: &[(&str, usize)]) -> ExpressionMaps { + let values: HashMap = values + .iter() + .map(|(name, len)| ((*name).to_owned(), AttributeValue::S("x".repeat(*len)))) + .collect(); + ExpressionMaps::new(HashMap::new(), values) +} + +/// Placeholder values with their content, for tests where the bytes matter. +fn maps_with(values: Vec<(&str, AttributeValue)>) -> ExpressionMaps { + let values: HashMap = values + .into_iter() + .map(|(name, value)| (name.to_owned(), value)) + .collect(); + ExpressionMaps::new(HashMap::new(), values) +} + +fn s_of(fill: &str, len: usize) -> AttributeValue { + AttributeValue::S(fill.repeat(len)) +} + +fn base_schema() -> Vec { + vec![ks("pk", KeyType::Hash), ks("sk", KeyType::Range)] +} + +/// `h` plus RANGE `a`, `b`, `c`, `d`: the index `idx` of the measured rows +/// (service, 2026-10-21 and 2026-10-23). +fn multi_range_schema() -> Vec { + vec![ + ks("h", KeyType::Hash), + ks("a", KeyType::Range), + ks("b", KeyType::Range), + ks("c", KeyType::Range), + ks("d", KeyType::Range), + ] +} + +/// HASH `h1`, `h2` plus RANGE `r`: the index `two-hash` of the measured rows +/// (service, 2026-10-23). +fn two_hash_schema() -> Vec { + vec![ + ks("h1", KeyType::Hash), + ks("h2", KeyType::Hash), + ks("r", KeyType::Range), + ] +} + +fn hash_only(name: &str, value: &str) -> KeyCondition { + KeyCondition { + pk_path: path(name), + pk_value: placeholder(value), + extra_pk_conditions: Vec::new(), + sk_condition: None, + extra_sk_conditions: Vec::new(), + } +} + +fn check( + kc: &KeyCondition, + schema: &[KeySchemaElement], + maps: &ExpressionMaps, +) -> Result<(), DynamoDbError> { + validate_query_key_sizes(kc, schema, maps, &LimitsConfig::default()) +} + +fn message(result: Result<(), DynamoDbError>) -> String { + match result { + Err(DynamoDbError::ValidationException(msg)) => msg, + other => panic!("expected ValidationException, got {other:?}"), + } +} + +/// A key condition of `attribute = :vN` clauses, each `:vN` an S value of the +/// given length. The first clause is in `pk_path` and the others in +/// `extra_pk_conditions`: the check assigns a clause by its attribute name, +/// not by its field. +fn equalities(clauses: &[(&str, usize)]) -> (KeyCondition, ExpressionMaps) { + let names: Vec = (0..clauses.len()).map(|i| format!("v{i}")).collect(); + let mut kc = hash_only(clauses[0].0, &names[0]); + kc.extra_pk_conditions = clauses[1..] + .iter() + .zip(&names[1..]) + .map(|((attribute, _), name)| (path(attribute), placeholder(name))) + .collect(); + let values: Vec<(&str, usize)> = names + .iter() + .zip(clauses) + .map(|(name, (_, len))| (name.as_str(), *len)) + .collect(); + (kc, maps(&values)) +} + +#[test] +fn equality_clauses_are_checked_against_the_limits() { + // The key schema, the `attribute = :v` clauses with the bytes of each + // value, and the expected sentence (`None` for `Ok`). + type Row<'a> = ( + &'a [KeySchemaElement], + &'a [(&'a str, usize)], + Option<&'a str>, + ); + let (base, idx, two) = (base_schema(), multi_range_schema(), two_hash_schema()); + let hash = Some(HASH_MSG_2048); + let total = Some(HASH_TOTAL_MSG_2048); + let range = Some(RANGE_MSG_1024); + let cases: [Row<'_>; 18] = [ + // Measured 2026-10-23 on a base table with HASH `pk` and RANGE `sk`: + // the limits, and the hash sentence when both limits are exceeded. + (&base, &[("pk", 2048)], None), + (&base, &[("pk", 2049)], hash), + (&base, &[("pk", 1), ("sk", 1024)], None), + (&base, &[("pk", 1), ("sk", 1025)], range), + (&base, &[("pk", 2049), ("sk", 1025)], hash), + // Measured 2026-10-23 on `idx`: `a` and `c` of 600 bytes with `b` of 1 + // byte is refused, `a` of 600 bytes alone passes. Each value is under + // the limit alone; together they are not. 512 and 512 pass, 512 and + // 513 are refused. + (&idx, &[("h", 1), ("a", 600), ("b", 1), ("c", 600)], range), + (&idx, &[("h", 1), ("a", 600)], None), + (&idx, &[("h", 1), ("a", 512), ("b", 512)], None), + (&idx, &[("h", 1), ("a", 512), ("b", 513)], range), + // Measured 2026-10-23 on `two-hash`: `h1` of 2049 bytes and `h2` of 1 + // byte get the single sentence. 1025 and 1024 bytes (sum 2049, neither + // over) and 2048 and 2048 bytes get the aggregated sentence. + (&two, &[("h1", 2049), ("h2", 1)], hash), + (&two, &[("h1", 1), ("h2", 2049)], hash), + (&two, &[("h1", 1025), ("h2", 1024)], total), + (&two, &[("h1", 2048), ("h2", 2048)], total), + // Measured 2026-11-20 on `two-hash`: a sum of exactly 2048 bytes + // passes, and with the HASH sum and a 1025-byte RANGE value both over, + // the aggregated hash sentence comes back. + (&two, &[("h1", 1024), ("h2", 1024)], None), + (&two, &[("h1", 1025), ("h2", 1024), ("r", 1025)], total), + // Not measured: the single hash check runs before the sum. + (&two, &[("h1", 2049), ("h2", 2048)], hash), + // Two clauses on one attribute: the attribute counts its larger value + // once. The service refuses both with `Invalid KeyConditionExpression: + // KeyConditionExpressions must only contain one condition per key` + // (measured 2026-11-24 with 1025 bytes in each `pk` value; #489 + // records the `sk` shape), a refusal this check does not make. + (&base, &[("pk", 1025), ("pk", 1025)], None), + (&base, &[("pk", 1), ("sk", 600), ("sk", 600)], None), + ]; + for (schema, clauses, expected) in cases { + let (kc, m) = equalities(clauses); + let result = check(&kc, schema, &m); + match expected { + Some(sentence) => assert_eq!(message(result), sentence, "{clauses:?}"), + None => assert!(result.is_ok(), "{clauses:?}: {result:?}"), + } + } +} + +#[test] +fn a_non_equality_on_a_later_range_attribute_is_added_to_the_total() { + // Measured 2026-10-23 on `idx`: `a` of 1 byte with `b > :v` of 1025 bytes + // is refused. + let mut kc = hash_only("h", "h"); + kc.extra_sk_conditions = vec![(path("a"), placeholder("x"))]; + kc.sk_condition = Some(compare("b", CompareOp::Gt, "v")); + let m = maps(&[("h", 1), ("x", 1), ("v", 1025)]); + assert_eq!( + message(check(&kc, &multi_range_schema(), &m)), + RANGE_MSG_1024 + ); +} + +#[test] +fn clauses_are_assigned_by_attribute_name_not_by_field() { + // The parser leaves RANGE equalities in extra_pk_conditions until the + // schema classifier moves them. The sizes still add up by name, so the + // measured `idx` rows hold whether or not the classifier has run. + let mut kc = hash_only("h", "h"); + kc.extra_pk_conditions = vec![(path("a"), placeholder("x"))]; + kc.sk_condition = Some(eq("b", "y")); + let m = maps(&[("h", 1), ("x", 600), ("y", 600)]); + assert_eq!( + message(check(&kc, &multi_range_schema(), &m)), + RANGE_MSG_1024 + ); +} + +fn between(name: &str, low: &str, high: &str) -> SortKeyCondition { + SortKeyCondition::Between { + path: path(name), + low: placeholder(low), + high: placeholder(high), + } +} + +#[test] +fn between_contributes_its_larger_bound_not_the_sum() { + // Measured 2026-10-23: 600 and 600 (sum 1200) pass. + let mut kc = hash_only("pk", "p"); + kc.sk_condition = Some(between("sk", "l", "u")); + let m = maps(&[("p", 1), ("l", 600), ("u", 600)]); + assert!(check(&kc, &base_schema(), &m).is_ok()); +} + +#[test] +fn between_with_a_1025_byte_upper_bound_is_refused() { + // Measured 2026-10-23: bounds of 1 and 1025 bytes. + let mut kc = hash_only("pk", "p"); + kc.sk_condition = Some(between("sk", "l", "u")); + let m = maps(&[("p", 1), ("l", 1), ("u", 1025)]); + assert_eq!(message(check(&kc, &base_schema(), &m)), RANGE_MSG_1024); +} + +#[test] +fn between_with_a_1025_byte_lower_bound_is_refused() { + // Measured 2026-10-23: lower bound `a` x 1025, upper bound `z` (an ordered + // pair) is refused with the range sentence, and `a` x 1024 passes. The + // reversed pair, a 1025-byte lower bound above a 1-byte upper bound, is + // refused by the service with a bound-order sentence ahead of the size + // check; ExtendDB has no bound-order check yet, and this test pins only + // the sizing of the ordered pair. + let mut kc = hash_only("pk", "p"); + kc.sk_condition = Some(between("sk", "l", "u")); + let m = maps_with(vec![ + ("p", s_of("p", 1)), + ("l", s_of("a", 1025)), + ("u", s_of("z", 1)), + ]); + assert_eq!(message(check(&kc, &base_schema(), &m)), RANGE_MSG_1024); + let m = maps_with(vec![ + ("p", s_of("p", 1)), + ("l", s_of("a", 1024)), + ("u", s_of("z", 1)), + ]); + assert!(check(&kc, &base_schema(), &m).is_ok()); +} + +#[test] +fn a_between_adds_its_larger_bound_to_the_range_total() { + // Measured 2026-10-23 on `idx`: `a` of 600 bytes with `b BETWEEN` 1 and + // 424 bytes (total 1024) passes, with 1 and 600 bytes (total 1200) is + // refused. + let mut kc = hash_only("h", "h"); + kc.extra_sk_conditions = vec![(path("a"), placeholder("x"))]; + kc.sk_condition = Some(between("b", "l", "u")); + let m = maps(&[("h", 1), ("x", 600), ("l", 1), ("u", 424)]); + assert!(check(&kc, &multi_range_schema(), &m).is_ok()); + let m = maps(&[("h", 1), ("x", 600), ("l", 1), ("u", 600)]); + assert_eq!( + message(check(&kc, &multi_range_schema(), &m)), + RANGE_MSG_1024 + ); +} + +#[test] +fn every_comparison_operator_and_begins_with_are_sized() { + // Measured 2026-10-23: a 1025-byte value on each form is refused and a + // 1024-byte value passes. + let forms: Vec SortKeyCondition> = vec![ + |v| compare("sk", CompareOp::Gt, v), + |v| compare("sk", CompareOp::Ge, v), + |v| compare("sk", CompareOp::Lt, v), + |v| compare("sk", CompareOp::Le, v), + |v| SortKeyCondition::BeginsWith { + path: path("sk"), + prefix: placeholder(v), + }, + ]; + for form in forms { + let mut kc = hash_only("pk", "p"); + kc.sk_condition = Some(form("v")); + let m = maps(&[("p", 1), ("v", 1025)]); + assert_eq!(message(check(&kc, &base_schema(), &m)), RANGE_MSG_1024); + let m = maps(&[("p", 1), ("v", 1024)]); + assert!(check(&kc, &base_schema(), &m).is_ok()); + } +} + +#[test] +fn binary_values_count_their_bytes() { + let kc = hash_only("pk", "v"); + let values = HashMap::from([("v".to_owned(), AttributeValue::B(vec![0u8; 2049]))]); + let m = ExpressionMaps::new(HashMap::new(), values); + assert_eq!(message(check(&kc, &base_schema(), &m)), HASH_MSG_2048); +} + +#[test] +fn multibyte_strings_count_utf8_bytes_not_characters() { + // Measured 2026-10-23: 683 U+20AC (3 bytes each, 2049 bytes) in the hash + // value is refused; 682 of them plus `xx` (2048 bytes) passes. In a range + // value, 342 of them (1026 bytes) is refused and 341 plus `x` (1024 bytes) + // passes. + let euro = "\u{20ac}"; + let hash = |value: String| { + let kc = hash_only("pk", "v"); + let m = maps_with(vec![("v", AttributeValue::S(value))]); + check(&kc, &base_schema(), &m) + }; + assert_eq!(message(hash(euro.repeat(683))), HASH_MSG_2048); + assert!(hash(format!("{}xx", euro.repeat(682))).is_ok()); + let range = |value: String| { + let mut kc = hash_only("pk", "p"); + kc.sk_condition = Some(eq("sk", "v")); + let m = maps_with(vec![ + ("p", AttributeValue::S("p".to_owned())), + ("v", AttributeValue::S(value)), + ]); + check(&kc, &base_schema(), &m) + }; + assert_eq!(message(range(euro.repeat(342))), RANGE_MSG_1024); + assert!(range(format!("{}x", euro.repeat(341))).is_ok()); +} + +#[test] +fn name_references_resolve_through_expression_attribute_names() { + let kc = hash_only("#p", "v"); + let m = ExpressionMaps::new( + HashMap::from([("p".to_owned(), "pk".to_owned())]), + HashMap::from([("v".to_owned(), AttributeValue::S("x".repeat(2049)))]), + ); + assert_eq!(message(check(&kc, &base_schema(), &m)), HASH_MSG_2048); +} + +#[test] +fn limits_come_from_the_configuration_and_the_sentence_names_them() { + let limits = LimitsConfig { + max_partition_key_size_bytes: 10, + max_sort_key_size_bytes: 20, + ..LimitsConfig::default() + }; + let mut kc = hash_only("pk", "p"); + kc.sk_condition = Some(eq("sk", "v")); + let hash = + validate_query_key_sizes(&kc, &base_schema(), &maps(&[("p", 11), ("v", 1)]), &limits); + assert!(message(hash).ends_with("limit of10 bytes")); + let range = + validate_query_key_sizes(&kc, &base_schema(), &maps(&[("p", 10), ("v", 21)]), &limits); + assert!(message(range).ends_with("limit of 20 bytes")); +} + +#[test] +fn a_clause_on_an_attribute_outside_the_key_schema_adds_nothing() { + let kc = hash_only("other", "v"); + assert!(check(&kc, &base_schema(), &maps(&[("v", 5000)])).is_ok()); +} + +#[test] +fn an_undefined_reference_returns_ok_whatever_the_sizes() { + // A label, the key condition, and the bytes of each defined value. + type Row<'a> = (&'a str, KeyCondition, &'a [(&'a str, usize)]); + let with_sort = |pk_value: &str, sk: SortKeyCondition| KeyCondition { + sk_condition: Some(sk), + ..hash_only("pk", pk_value) + }; + let cases: [Row<'_>; 6] = [ + ( + "undefined value on the clause", + hash_only("pk", "missing"), + &[("v", 5000)], + ), + ( + "undefined name on the clause", + hash_only("#nope", "v"), + &[("v", 5000)], + ), + // Measured 2026-10-23: `pk = :v AND sk = :missing` with `:v` of 2049 + // bytes is refused as an undefined attribute value, not as a size. + ( + "undefined value in another clause", + with_sort("v", eq("sk", "missing")), + &[("v", 2049)], + ), + // Measured 2026-10-23: `pk = :v AND #n = :w` with `#n` undefined and + // `:v` of 2049 bytes is refused as an undefined attribute name, not as + // a size. + ( + "undefined name in another clause", + with_sort("v", eq("#n", "w")), + &[("v", 2049), ("w", 1)], + ), + // The oversized clause may come before or after the undefined one. + ( + "oversized clause after the undefined one", + with_sort("missing", eq("sk", "v")), + &[("v", 5000)], + ), + ( + "undefined bound of a BETWEEN", + with_sort("p", between("sk", "l", "missing")), + &[("p", 1), ("l", 5000)], + ), + ]; + for (label, kc, values) in cases { + let result = check(&kc, &base_schema(), &maps(values)); + assert!(result.is_ok(), "{label}: {result:?}"); + } +} + +#[test] +fn non_scalar_values_are_skipped() { + let kc = hash_only("pk", "v"); + let values = HashMap::from([( + "v".to_owned(), + AttributeValue::L(vec![AttributeValue::S("x".repeat(5000))]), + )]); + let m = ExpressionMaps::new(HashMap::new(), values); + assert!(check(&kc, &base_schema(), &m).is_ok()); +} + +#[test] +fn number_values_get_the_number_rules_before_any_size() { + // Measured 2026-11-20 in us-east-1 on a GSI with HASH `n` (N). A number + // with more than 38 significant digits or out of range gets the number's + // sentence, never the size sentence. A valid one is sized by its + // normalized digits. A number in other Unicode decimal digits is served. + // The RANGE rows apply the same rule to a sort key value. Measured + // 2026-11-24: an ASCII value that is not a number gets the not-a-number + // sentence with the value after the colon, the empty value too, and + // `1e-131` gets the underflow sentence. 2049 U+FF11 is not a number to + // these rules and adds nothing, so the size check passes it. The service + // answers the 38-digit sentence for it (#565). + const DIGITS: &str = "Attempting to store more than 38 significant digits in a Number"; + const OVERFLOW: &str = + "Number overflow. Attempting to store a number with magnitude larger than supported range"; + const UNDERFLOW: &str = "Number underflow. Attempting to store a number with magnitude smaller than supported range"; + let not_a_number = + |n: &str| format!("The parameter cannot be converted to a numeric value: {n}"); + let zeros = "0".repeat(2100); + let x2049 = "x".repeat(2049); + let (x, abc, space, empty) = ( + not_a_number(&x2049), + not_a_number("abc"), + not_a_number(" 1"), + not_a_number(""), + ); + let cases: [(&str, &str, String, Option<&str>); 15] = [ + ("hash, 2049 digits", "pk", "1".repeat(2049), Some(DIGITS)), + ("hash, 39 digits", "pk", "1".repeat(39), Some(DIGITS)), + ( + "hash, 1 and 2100 zeros", + "pk", + format!("1{zeros}"), + Some(OVERFLOW), + ), + ("hash, 2100 zeros and 1", "pk", format!("{zeros}1"), None), + ("hash, U+FF11", "pk", "\u{ff11}".to_owned(), None), + ( + "hash, U+0967 U+0968", + "pk", + "\u{967}\u{968}".to_owned(), + None, + ), + ("range, 1025 digits", "sk", "1".repeat(1025), Some(DIGITS)), + ("range, 2100 zeros and 1", "sk", format!("{zeros}1"), None), + ("hash, 2049 x", "pk", x2049, Some(x.as_str())), + ("hash, abc", "pk", "abc".to_owned(), Some(abc.as_str())), + ( + "hash, space and 1", + "pk", + " 1".to_owned(), + Some(space.as_str()), + ), + ("hash, empty", "pk", String::new(), Some(empty.as_str())), + ("hash, 1e-131", "pk", "1e-131".to_owned(), Some(UNDERFLOW)), + ("range, 1e-131", "sk", "1e-131".to_owned(), Some(UNDERFLOW)), + ("hash, 2049 U+FF11", "pk", "\u{ff11}".repeat(2049), None), + ]; + for (label, attribute, n, expected) in cases { + let (kc, values) = if attribute == "sk" { + let mut kc = hash_only("pk", "p"); + kc.sk_condition = Some(eq("sk", "v")); + (kc, vec![("p", s_of("p", 1)), ("v", AttributeValue::N(n))]) + } else { + (hash_only("pk", "p"), vec![("p", AttributeValue::N(n))]) + }; + let result = check(&kc, &base_schema(), &maps_with(values)); + match expected { + Some(sentence) => assert_eq!(message(result), sentence, "{label}"), + None => assert!(result.is_ok(), "{label}: {result:?}"), + } + } +} diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index 9c1bcbb21..50c9ccd1c 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -1,10 +1,12 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 +mod key_size; pub mod number; pub mod restorable_item; pub mod vector_item; pub mod warm_throughput; +pub use key_size::validate_query_key_sizes; pub use restorable_item::{ RestorableItemError, RestorableItemReason, RestorableKeySchema, RestorableLimits, SHOWN_VALUE_BYTES, validate_restorable_item, @@ -2150,41 +2152,20 @@ fn check_key_size( value: &AttributeValue, limits: &LimitsConfig, ) -> Result<(), DynamoDbError> { - let size = key_value_byte_size(value); + let size = key_size::key_value_byte_size(value); let max_size = match ks.key_type { KeyType::Hash => limits.max_partition_key_size_bytes, KeyType::Range => limits.max_sort_key_size_bytes, }; if size > max_size { - let msg = match ks.key_type { - KeyType::Hash => format!( - "One or more parameter values were invalid: \ - Size of hashkey has exceeded the maximum size limit of{max_size} bytes" - ), - KeyType::Range => format!( - "One or more parameter values were invalid: \ - Aggregated size of all range keys has exceeded the size limit of {max_size} bytes" - ), - }; - return Err(DynamoDbError::ValidationException(msg)); + return Err(match ks.key_type { + KeyType::Hash => key_size::hash_key_too_large(max_size), + KeyType::Range => key_size::range_keys_too_large(max_size), + }); } Ok(()) } -/// Get the byte size of a key attribute value. -/// -/// For `N` keys this uses the digit-string length. Amazon DynamoDB caps a -/// number at 38 significant digits, so the string length is always far below -/// the key-size limit and the proxy is exact for the rejection decision. -fn key_value_byte_size(value: &AttributeValue) -> usize { - match value { - AttributeValue::S(s) => s.len(), - AttributeValue::N(n) => n.len(), - AttributeValue::B(b) => b.len(), - _ => 0, - } -} - /// Validate that an item does not exceed the maximum allowed size. /// /// Called by the storage layer after applying update expressions to ensure diff --git a/crates/core/src/validation/restorable_item.rs b/crates/core/src/validation/restorable_item.rs index 5d2b4f671..720c88f36 100644 --- a/crates/core/src/validation/restorable_item.rs +++ b/crates/core/src/validation/restorable_item.rs @@ -440,7 +440,7 @@ pub fn validate_restorable_item( KeyType::Hash => (limits.max_partition_key_size_bytes, "hash"), KeyType::Range => (limits.max_sort_key_size_bytes, "range"), }; - let size = super::key_value_byte_size(value); + let size = super::key_size::key_value_byte_size(value); if size > max { return Err(refuse( path(), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4fe89b969..54bc39b0e 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -59,6 +59,8 @@ pub use pre_dispatch::{ParsedRequest, parse_request}; pub mod private_fs; mod put_item; mod query; +#[cfg(test)] +mod query_key_size_tests; pub mod query_key_values; mod read_helpers; mod request_limits; diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index ce1cb2cdc..1ad0e97dd 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -108,12 +108,6 @@ pub async fn handle_query( )); } - // Select=ALL_ATTRIBUTES requires an ALL-projection GSI (shared with Scan). - // With an ExclusiveStartKey this runs after the start key checks below. - if input.exclusive_start_key.is_none() { - validate_query_select_index_support(input.select, index_info.as_ref())?; - } - // Limit >= 1 is checked at request time in validate_query_request_body. // For index queries, build a key_info that reflects the index's key schema @@ -459,6 +453,21 @@ pub async fn handle_query( )?; } + // Refuse key values over the key size limits (hash 2048 bytes, all range + // values together 1024 bytes) before any storage read. Order measured + // 2026-10-23 with a 2049-byte hash value plus one other fault: a missing + // table, a wrong IndexName, ConsistentRead on a GSI, Limit 0, a key + // condition that misses the key schema, a wrong-typed key value (checked + // above), a FilterExpression syntax error and an unused expression value + // are all reported ahead of the size; an invalid ExclusiveStartKey is + // reported after it. KeyConditions is checked like the expression. + extenddb_core::validation::validate_query_key_sizes( + &key_condition, + &query_key_info.key_schema, + effective_maps, + &ctx.limits, + )?; + // Validate ExclusiveStartKey matches the key schema if let Some(ref start_key) = input.exclusive_start_key { validate_query_exclusive_start_key(start_key, &key_info, index_info.as_ref())?; @@ -472,9 +481,14 @@ pub async fn handle_query( forward: input.scan_index_forward, }, )?; - validate_query_select_index_support(input.select, index_info.as_ref())?; } + // Select=ALL_ATTRIBUTES requires an ALL-projection GSI (shared with Scan). + // The service makes this check after the other request checks, the key + // size and start key checks included (measured 2026-11-20 in us-east-1 on + // a KEYS_ONLY GSI). + validate_query_select_index_support(input.select, index_info.as_ref())?; + // Determine which key schema to use for LastEvaluatedKey extraction. // For index queries, the LEK includes both the index key and the base table key, // and the same shape addresses each chunk read from storage. diff --git a/crates/engine/src/query_key_size_tests.rs b/crates/engine/src/query_key_size_tests.rs new file mode 100644 index 000000000..3b9b35ac7 --- /dev/null +++ b/crates/engine/src/query_key_size_tests.rs @@ -0,0 +1,95 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Key size limits on a `Query` key condition, reached through the +//! expression parser and through the `KeyConditions` desugaring. The rows of +//! the limits are in `extenddb_core`'s `validation::key_size` tests. The check +//! does not depend on how the key condition is arranged, so it runs on the +//! parser's output without the schema classification step. + +use std::collections::HashMap; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::expression::ExpressionMaps; +use extenddb_core::limits::LimitsConfig; +use extenddb_core::types::{AttributeValue, Condition, KeySchemaElement, KeyType}; +use extenddb_core::validation::validate_query_key_sizes; + +use crate::expression_helpers::parse_key_condition_expr; +use crate::legacy_filter::desugar_key_conditions; + +const HASH_MSG: &str = "One or more parameter values were invalid: \ + Size of hashkey has exceeded the maximum size limit of2048 bytes"; +const RANGE_MSG: &str = "One or more parameter values were invalid: \ + Aggregated size of all range keys has exceeded the size limit of 1024 bytes"; + +fn ks(name: &str, key_type: KeyType) -> KeySchemaElement { + KeySchemaElement { + attribute_name: name.to_owned(), + key_type, + } +} + +fn base_schema() -> Vec { + vec![ks("pk", KeyType::Hash), ks("sk", KeyType::Range)] +} + +fn s(len: usize) -> AttributeValue { + AttributeValue::S("x".repeat(len)) +} + +/// Parse `expr` and check it against `schema` with the given placeholder +/// values (`:name` keys are given without the colon). +fn run( + expr: &str, + schema: &[KeySchemaElement], + values: &[(&str, AttributeValue)], +) -> Result<(), DynamoDbError> { + let limits = LimitsConfig::default(); + let key_condition = parse_key_condition_expr(expr, &limits).expect("expression parses"); + let values: HashMap = values + .iter() + .map(|(name, value)| ((*name).to_owned(), value.clone())) + .collect(); + let maps = ExpressionMaps::new(HashMap::new(), values); + validate_query_key_sizes(&key_condition, schema, &maps, &limits) +} + +fn refused(result: Result<(), DynamoDbError>) -> String { + match result { + Err(DynamoDbError::ValidationException(msg)) => msg, + other => panic!("expected ValidationException, got {other:?}"), + } +} + +#[test] +fn clause_order_does_not_change_the_result() { + let result = run( + "sk = :v AND pk = :p", + &base_schema(), + &[("p", s(1)), ("v", s(1025))], + ); + assert_eq!(refused(result), RANGE_MSG); + let result = run( + "sk = :v AND pk = :p", + &base_schema(), + &[("p", s(2049)), ("v", s(1))], + ); + assert_eq!(refused(result), HASH_MSG); +} + +#[test] +fn legacy_key_conditions_are_checked_like_the_expression() { + // Measured 2026-10-23 in us-east-1, with a 2049-byte hash value and with a + // 1025-byte range value: the service sizes legacy `KeyConditions` with the + // same sentences. Both syntaxes reach the check as one key condition. + let eq = |value: AttributeValue| Condition { + comparison_operator: "EQ".to_owned(), + attribute_value_list: vec![value], + }; + let schema = [("pk".to_owned(), true), ("sk".to_owned(), false)]; + let conditions = HashMap::from([("pk".to_owned(), eq(s(1))), ("sk".to_owned(), eq(s(1025)))]); + let (kc, maps) = desugar_key_conditions(&conditions, &schema).expect("desugars"); + let result = validate_query_key_sizes(&kc, &base_schema(), &maps, &LimitsConfig::default()); + assert_eq!(refused(result), RANGE_MSG); +} diff --git a/docs/dynamodb-limits.md b/docs/dynamodb-limits.md index 92bfc362c..98121a123 100755 --- a/docs/dynamodb-limits.md +++ b/docs/dynamodb-limits.md @@ -39,8 +39,8 @@ Source: [AWS DynamoDB Service Quotas](https://docs.aws.amazon.com/amazondynamodb | Limit | DynamoDB Value | Status | Notes | |-------|---------------|--------|-------------------------------------------------------------------------------| | Maximum item size | 400 KB (409,600 bytes) | Enforced | `LimitsConfig::max_item_size_bytes`. The engine enforces it on PutItem, BatchWriteItem, the transaction Put path and ImportTable; the PostgreSQL and SQLite storage layers enforce it on UpdateItem and the transaction Update path. Cassandra applies a fixed 409,600 to the finished item of an update with the put wording; MongoDB applies no limit on updates. The sizing calculation (item bytes, number cost, and the statement-based UpdateItem rule) lives in [differences-from-dynamodb.md](differences-from-dynamodb.md#item-size). | -| Partition key size | 1–2,048 bytes | Enforced | `validate_key_sizes`, `LimitsConfig::max_partition_key_size_bytes` | -| Sort key size | 1–1,024 bytes | Enforced | `validate_key_sizes`, `LimitsConfig::max_sort_key_size_bytes` | +| Partition key size | 1 to 2,048 bytes | Enforced | `validate_key_sizes`, `LimitsConfig::max_partition_key_size_bytes`; on Query, `validate_query_key_sizes` checks each partition key value in the key condition, and the sum of the partition key values of an index with several HASH attributes | +| Sort key size | 1 to 1,024 bytes | Enforced | `validate_key_sizes`, `LimitsConfig::max_sort_key_size_bytes`; on Query, `validate_query_key_sizes` adds up the sort key values of the key condition, one per attribute (any operator; a `BETWEEN` counts its larger bound), and checks the total | | Attribute name size | 1 to 65,535 bytes (64 KB) | Enforced | `validate_attribute_name_sizes`, `validate_expression_attribute_name_sizes`, `validate_attribute_updates_name_sizes`, `LimitsConfig::max_attribute_name_bytes`; UTF-8 bytes, top-level names and map keys at every depth. PutItem, BatchWriteItem.PutRequest, TransactWriteItems.Put and ImportTable check the item. PutItem, UpdateItem, DeleteItem and every TransactWriteItems member (Put, Update, Delete, ConditionCheck) check every `ExpressionAttributeNames` value and every map key inside every `ExpressionAttributeValues` value; UpdateItem also checks the names and values of `AttributeUpdates`. PutItem and UpdateItem report the name ahead of the table lookup; UpdateItem also reports it ahead of the condition and the index-key checks. TransactWriteItems checks every member, and BatchWriteItem every PutRequest, before any table lookup, so neither a missing table (in any member) nor a PutRequest item missing its key is reported first; a transaction fails as a whole with a top-level ValidationException. With an over-limit name in both expression maps, UpdateItem reports the `ExpressionAttributeNames` placeholder and a transacted Update or Put reports the `ExpressionAttributeValues` placeholder; a transacted Put with a long item name and a long `ExpressionAttributeNames` value reports the placeholder, a standalone PutItem the item. The message depends on the request form (`AttributeNameRequestForm`): PutItem, UpdateItem and DeleteItem answer `1 validation error detected: Attribute name is too large, must be less than 65536 bytes`, followed by ` for key #n` when the name came through `ExpressionAttributeNames`; a TransactWriteItems member answers `ExpressionAttributeNames contains invalid value: Attribute name is too large, must be less than 65536 bytes for key #n`, or `ExpressionAttributeValues contains invalid value: ... for key :v` for a map key inside a value; TransactWriteItems.Put and BatchWriteItem.PutRequest answer `Attribute name is too large, must be less than 65536 bytes` for a name in the item. | | Attribute nesting depth | 32 levels | Enforced | `validate_item_nesting_depth`, applied on PutItem, UpdateItem, BatchWriteItem.PutRequest, TransactWriteItems.Put, ImportTable | | Number of attributes per item | No practical limit | Enforced | ExtendDB has no per-item attribute count limit | diff --git a/tests/python/query_key_size_support.py b/tests/python/query_key_size_support.py new file mode 100644 index 000000000..18d76ef78 --- /dev/null +++ b/tests/python/query_key_size_support.py @@ -0,0 +1,239 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Constants, helpers and table fixtures shared by the Query key size wire files. + +The wire files are ``test_query_key_size.py`` (the key size rows), +``test_query_key_size_values.py`` (multi-byte values, ordered BETWEEN bounds, +undefined references, a hash-only table) and ``test_query_key_size_order.py`` +(where the size refusal sits among the other Query refusals). Fixtures are +imported by name into each file so each file gets its own module-scoped tables. +""" + +from __future__ import annotations + +from contextlib import contextmanager + +import pytest +from botocore.exceptions import ClientError + +from helpers import assert_validation, unique_name, wait_for_active, wait_for_deleted + +HASH_MESSAGE = ( + "One or more parameter values were invalid: " + "Size of hashkey has exceeded the maximum size limit of2048 bytes" +) +HASH_TOTAL_MESSAGE = ( + "One or more parameter values were invalid: " + "Aggregated size of all hash keys has exceeded the size limit of 2048 bytes" +) +RANGE_MESSAGE = ( + "One or more parameter values were invalid: " + "Aggregated size of all range keys has exceeded the size limit of 1024 bytes" +) + + +def S(length: int, fill: str = "x") -> dict: + """A string AttributeValue of exactly ``length`` bytes (ASCII fill).""" + return {"S": fill * length} + + +def B(length: int) -> dict: + """A binary AttributeValue of exactly ``length`` bytes.""" + return {"B": b"\x01" * length} + + +def attr(name: str, attribute_type: str = "S") -> dict: + return {"AttributeName": name, "AttributeType": attribute_type} + + +def key(name: str, key_type: str) -> dict: + return {"AttributeName": name, "KeyType": key_type} + + +def drop_table(client, name: str) -> None: + try: + client.delete_table(TableName=name) + except client.exceptions.ResourceNotFoundException: + return + wait_for_deleted(client, name) + + +@contextmanager +def make_table(client, prefix: str, **create_args): + """Create an ACTIVE pay-per-request table, yield its name, drop it on exit.""" + name = unique_name(prefix) + client.create_table(TableName=name, BillingMode="PAY_PER_REQUEST", **create_args) + try: + wait_for_active(client, name) + yield name + finally: + drop_table(client, name) + + +def refused(client, message: str, code: str = "ValidationException", **query) -> None: + """Run the Query and assert a 400 with ``code`` and exactly ``message``.""" + with pytest.raises(ClientError) as exc_info: + client.query(**query) + assert_validation(exc_info.value, message, code) + + +def refused_ending(client, suffix: str, **query) -> None: + """Run the Query and assert a 400 ValidationException whose text ends with ``suffix``. + + For refusals whose leading label differs between the service and ExtendDB + (a pre-existing wording gap); the size sentences never come back. + """ + with pytest.raises(ClientError) as exc_info: + client.query(**query) + err = exc_info.value.response + assert err["Error"]["Code"] == "ValidationException", err["Error"]["Message"] + assert err["ResponseMetadata"]["HTTPStatusCode"] == 400 + assert err["Error"]["Message"].endswith(suffix), err["Error"]["Message"] + + +FIRST_RANGE_ONLY_MARK = "applies a key condition to the first RANGE attribute" + + +def require_served(client, **query) -> None: + """Skip unless the backend serves ``query``'s condition on a later RANGE attribute. + + The MongoDB and Cassandra backends apply a key condition to the first RANGE + attribute of a multi-attribute index only, and refuse a condition on a later + one with a ValidationException that says so. The size checks run before that + refusal, so only the rows that expect a Query to be served call this. Sends + ``query`` with every value cut to its first byte. + """ + probe = dict(query) + probe["ExpressionAttributeValues"] = { + name: {"S": value["S"][:1]} for name, value in query["ExpressionAttributeValues"].items() + } + try: + client.query(**probe) + except ClientError as exc: + if FIRST_RANGE_ONLY_MARK in exc.response["Error"]["Message"]: + pytest.skip("this backend applies key conditions to the first RANGE attribute only") + + +@pytest.fixture(scope="module") +def gsi_table(dynamodb_client): + """Base HASH ``pk``; index ``idx`` on HASH ``h`` and RANGE ``a``, ``b``, ``c``, ``d``.""" + with make_table( + dynamodb_client, + "qks-gsi", + AttributeDefinitions=[attr(n) for n in ("pk", "h", "a", "b", "c", "d")], + KeySchema=[key("pk", "HASH")], + GlobalSecondaryIndexes=[ + { + "IndexName": "idx", + "KeySchema": [ + key("h", "HASH"), + key("a", "RANGE"), + key("b", "RANGE"), + key("c", "RANGE"), + key("d", "RANGE"), + ], + "Projection": {"ProjectionType": "ALL"}, + } + ], + ) as name: + yield name + + +@pytest.fixture(scope="module") +def two_hash_table(dynamodb_client): + """Base HASH ``pk``; index ``two-hash`` on HASH ``h1``, ``h2`` and RANGE ``a``.""" + with make_table( + dynamodb_client, + "qks-2h", + AttributeDefinitions=[attr(n) for n in ("pk", "h1", "h2", "a")], + KeySchema=[key("pk", "HASH")], + GlobalSecondaryIndexes=[ + { + "IndexName": "two-hash", + "KeySchema": [key("h1", "HASH"), key("h2", "HASH"), key("a", "RANGE")], + "Projection": {"ProjectionType": "ALL"}, + } + ], + ) as name: + yield name + + +@pytest.fixture(scope="module") +def base_table(dynamodb_client): + """HASH ``pk`` and RANGE ``sk``, both S.""" + with make_table( + dynamodb_client, + "qks-base", + AttributeDefinitions=[attr("pk"), attr("sk")], + KeySchema=[key("pk", "HASH"), key("sk", "RANGE")], + ) as name: + yield name + + +@pytest.fixture(scope="module") +def hash_only_table(dynamodb_client): + """HASH ``pk`` only.""" + with make_table( + dynamodb_client, + "qks-hash", + AttributeDefinitions=[attr("pk")], + KeySchema=[key("pk", "HASH")], + ) as name: + yield name + + +@pytest.fixture(scope="module") +def number_table(dynamodb_client): + """HASH ``pk`` and RANGE ``sk``, both N.""" + with make_table( + dynamodb_client, + "qks-num", + AttributeDefinitions=[attr("pk", "N"), attr("sk", "N")], + KeySchema=[key("pk", "HASH"), key("sk", "RANGE")], + ) as name: + yield name + + +@pytest.fixture(scope="module") +def binary_table(dynamodb_client): + """HASH ``pk`` and RANGE ``sk``, both B.""" + with make_table( + dynamodb_client, + "qks-bin", + AttributeDefinitions=[attr("pk", "B"), attr("sk", "B")], + KeySchema=[key("pk", "HASH"), key("sk", "RANGE")], + ) as name: + yield name + + +@pytest.fixture(scope="module") +def index_table(dynamodb_client): + """HASH ``pk`` and RANGE ``sk``; LSI ``lsi`` on RANGE ``l``; GSI ``gsi`` on ``g`` and ``gs``. + + Two KEYS_ONLY GSIs as well: ``gko`` on HASH ``g`` and ``ngsi`` on HASH ``n`` (N). + """ + keys_only = {"ProjectionType": "KEYS_ONLY"} + with make_table( + dynamodb_client, + "qks-idx", + AttributeDefinitions=[attr(n) for n in ("pk", "sk", "l", "g", "gs")] + [attr("n", "N")], + KeySchema=[key("pk", "HASH"), key("sk", "RANGE")], + LocalSecondaryIndexes=[ + { + "IndexName": "lsi", + "KeySchema": [key("pk", "HASH"), key("l", "RANGE")], + "Projection": {"ProjectionType": "ALL"}, + } + ], + GlobalSecondaryIndexes=[ + { + "IndexName": "gsi", + "KeySchema": [key("g", "HASH"), key("gs", "RANGE")], + "Projection": {"ProjectionType": "ALL"}, + }, + {"IndexName": "gko", "KeySchema": [key("g", "HASH")], "Projection": keys_only}, + {"IndexName": "ngsi", "KeySchema": [key("n", "HASH")], "Projection": keys_only}, + ], + ) as name: + yield name diff --git a/tests/python/test_query_key_size.py b/tests/python/test_query_key_size.py new file mode 100644 index 000000000..80d1ee894 --- /dev/null +++ b/tests/python/test_query_key_size.py @@ -0,0 +1,419 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Query key value size limits. + +A Query whose key condition carries a partition key value over 2048 bytes, +partition key values (on an index with several HASH attributes) that add up to +more than 2048 bytes, or range key values that add up to more than 1024 bytes, +is refused with a ValidationException. All limits are inclusive. The single +hash sentence has no space between ``of`` and ``2048``; the aggregated hash +sentence is its own. Every RANGE clause counts whatever its operator; a BETWEEN +counts the larger of its two bounds, so two 600-byte bounds pass and bounds of +1 and 1025 bytes are refused. + +Every row below was measured on the service in us-east-1: the GSI hash and range +rows on 2026-10-21 (index ``idx`` with HASH ``h`` and RANGE ``a``, ``b``, ``c``, +``d``, all S), the base table rows on 2026-10-22 (HASH ``pk``, RANGE ``sk``, +both S), and the operator, BETWEEN, binary, LSI, legacy, multi-attribute and +two-HASH rows on 2026-10-23. The ``idx`` accept rows with a condition on a later +RANGE attribute are skipped on a backend that applies a key condition to the +first RANGE attribute only (MongoDB and Cassandra, see +``query_key_size_support.require_served``). Multi-byte +values, ordered BETWEEN bounds, undefined references and a hash-only table are in +``test_query_key_size_values.py``; the order against other refusals is in +``test_query_key_size_order.py``. +""" + +from __future__ import annotations + +import pytest + +from query_key_size_support import ( # noqa: F401 (fixtures are used by name) + HASH_MESSAGE, + HASH_TOTAL_MESSAGE, + RANGE_MESSAGE, + B, + S, + base_table, + binary_table, + gsi_table, + index_table, + refused, + require_served, + two_hash_table, +) + + +class TestGsiQueryKeySize: + """Index ``idx`` with HASH h and RANGE a, b, c, d (service, 2026-10-21 and 2026-10-23).""" + + def _query(self, expression: str, values: dict) -> dict: + return { + "IndexName": "idx", + "KeyConditionExpression": expression, + "ExpressionAttributeValues": values, + } + + def test_hash_value_of_2049_bytes_is_refused(self, dynamodb_client, gsi_table): + refused( + dynamodb_client, + HASH_MESSAGE, + TableName=gsi_table, + **self._query("h = :big", {":big": S(2049)}), + ) + + def test_range_value_of_1025_bytes_is_refused(self, dynamodb_client, gsi_table): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=gsi_table, + **self._query("h = :h AND a = :big", {":h": S(1, "h"), ":big": S(1025)}), + ) + + def test_one_600_byte_range_value_is_accepted(self, dynamodb_client, gsi_table): + query = self._query("h = :h AND a = :s600", {":h": S(1, "h"), ":s600": S(600)}) + assert dynamodb_client.query(TableName=gsi_table, **query)["Count"] == 0 + + def test_two_600_byte_range_values_are_refused_together( + self, dynamodb_client, gsi_table + ): + query = self._query( + "h = :h AND a = :s600 AND b = :b AND c = :s600", + {":h": S(1, "h"), ":s600": S(600), ":b": S(1, "b")}, + ) + refused(dynamodb_client, RANGE_MESSAGE, TableName=gsi_table, **query) + + def test_two_range_values_totalling_1024_bytes_are_accepted( + self, dynamodb_client, gsi_table + ): + query = self._query( + "h = :h AND a = :a AND b = :b", + {":h": S(1, "h"), ":a": S(512, "a"), ":b": S(512, "b")}, + ) + require_served(dynamodb_client, TableName=gsi_table, **query) + assert dynamodb_client.query(TableName=gsi_table, **query)["Count"] == 0 + + def test_two_range_values_totalling_1025_bytes_are_refused( + self, dynamodb_client, gsi_table + ): + query = self._query( + "h = :h AND a = :a AND b = :b", + {":h": S(1, "h"), ":a": S(512, "a"), ":b": S(513, "b")}, + ) + refused(dynamodb_client, RANGE_MESSAGE, TableName=gsi_table, **query) + + def test_a_1025_byte_non_equality_on_a_later_range_attribute_is_refused( + self, dynamodb_client, gsi_table + ): + query = self._query( + "h = :h AND a = :a AND b > :big", + {":h": S(1, "h"), ":a": S(1, "a"), ":big": S(1025, "b")}, + ) + refused(dynamodb_client, RANGE_MESSAGE, TableName=gsi_table, **query) + + def _between(self, upper: int) -> dict: + """``a`` of 600 bytes and ``b BETWEEN`` a 1-byte and an ``upper``-byte bound.""" + return self._query( + "h = :h AND a = :a AND b BETWEEN :l AND :u", + {":h": S(1, "h"), ":a": S(600, "a"), ":l": S(1, "b"), ":u": S(upper, "b")}, + ) + + def test_between_adds_its_larger_bound_to_the_range_total( + self, dynamodb_client, gsi_table + ): + # a = 600 plus the larger BETWEEN bound, 600: 1200 is refused. + refused(dynamodb_client, RANGE_MESSAGE, TableName=gsi_table, **self._between(600)) + + def test_between_within_the_range_total_is_accepted(self, dynamodb_client, gsi_table): + # a = 600 plus the larger BETWEEN bound, 424: 1024 is accepted. + accepted = self._between(424) + require_served(dynamodb_client, TableName=gsi_table, **accepted) + assert dynamodb_client.query(TableName=gsi_table, **accepted)["Count"] == 0 + + +class TestTwoHashQueryKeySize: + """Index ``two-hash`` with HASH h1, h2 and RANGE a (service, 2026-10-23).""" + + def _query(self, h1: dict, h2: dict) -> dict: + return { + "IndexName": "two-hash", + "KeyConditionExpression": "h1 = :a AND h2 = :b", + "ExpressionAttributeValues": {":a": h1, ":b": h2}, + } + + def test_one_value_over_2048_bytes_gets_the_single_sentence( + self, dynamodb_client, two_hash_table + ): + refused( + dynamodb_client, + HASH_MESSAGE, + TableName=two_hash_table, + **self._query(S(2049, "a"), S(1, "b")), + ) + + def test_values_adding_up_to_2049_bytes_get_the_aggregated_sentence( + self, dynamodb_client, two_hash_table + ): + refused( + dynamodb_client, + HASH_TOTAL_MESSAGE, + TableName=two_hash_table, + **self._query(S(1025, "a"), S(1024, "b")), + ) + + def test_two_2048_byte_values_get_the_aggregated_sentence( + self, dynamodb_client, two_hash_table + ): + refused( + dynamodb_client, + HASH_TOTAL_MESSAGE, + TableName=two_hash_table, + **self._query(S(2048, "a"), S(2048, "b")), + ) + + def test_values_adding_up_to_exactly_2048_bytes_are_accepted( + self, dynamodb_client, two_hash_table + ): + resp = dynamodb_client.query( + TableName=two_hash_table, **self._query(S(1024, "a"), S(1024, "b")) + ) + assert resp["Count"] == 0 + + def _query_with_range(self, h1: dict, h2: dict, a: dict) -> dict: + return { + "IndexName": "two-hash", + "KeyConditionExpression": "h1 = :a AND h2 = :b AND a = :r", + "ExpressionAttributeValues": {":a": h1, ":b": h2, ":r": a}, + } + + def test_hash_total_wins_over_an_oversized_range_value( + self, dynamodb_client, two_hash_table + ): + refused( + dynamodb_client, + HASH_TOTAL_MESSAGE, + TableName=two_hash_table, + **self._query_with_range(S(1025, "a"), S(1024, "b"), S(1025, "z")), + ) + + def test_single_hash_sentence_wins_over_an_oversized_range_value( + self, dynamodb_client, two_hash_table + ): + refused( + dynamodb_client, + HASH_MESSAGE, + TableName=two_hash_table, + **self._query_with_range(S(2049, "a"), S(1, "b"), S(1025, "z")), + ) + + def test_range_sentence_when_the_hash_total_is_within_the_limit( + self, dynamodb_client, two_hash_table + ): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=two_hash_table, + **self._query_with_range(S(1024, "a"), S(1024, "b"), S(1025, "z")), + ) + + +class TestBaseTableQueryKeySize: + """Measured 2026-10-22 against a base table with HASH pk and RANGE sk.""" + + def test_hash_value_of_2048_bytes_is_accepted(self, dynamodb_client, base_table): + pk = S(2048, "p") + dynamodb_client.put_item( + TableName=base_table, Item={"pk": pk, "sk": {"S": "s"}} + ) + resp = dynamodb_client.query( + TableName=base_table, + ConsistentRead=True, + KeyConditionExpression="pk = :v", + ExpressionAttributeValues={":v": pk}, + ) + assert resp["Count"] == 1 + + def test_hash_value_of_2049_bytes_is_refused(self, dynamodb_client, base_table): + refused( + dynamodb_client, + HASH_MESSAGE, + TableName=base_table, + KeyConditionExpression="pk = :v", + ExpressionAttributeValues={":v": S(2049, "p")}, + ) + + def test_range_value_of_1024_bytes_is_accepted(self, dynamodb_client, base_table): + sk = S(1024, "s") + dynamodb_client.put_item( + TableName=base_table, Item={"pk": {"S": "range-at-limit"}, "sk": sk} + ) + resp = dynamodb_client.query( + TableName=base_table, + ConsistentRead=True, + KeyConditionExpression="pk = :p AND sk = :v", + ExpressionAttributeValues={":p": {"S": "range-at-limit"}, ":v": sk}, + ) + assert resp["Count"] == 1 + + def test_range_value_of_1025_bytes_is_refused(self, dynamodb_client, base_table): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=base_table, + KeyConditionExpression="pk = :p AND sk = :v", + ExpressionAttributeValues={":p": {"S": "p"}, ":v": S(1025, "s")}, + ) + + def test_between_bounds_are_not_added_together(self, dynamodb_client, base_table): + dynamodb_client.put_item( + TableName=base_table, Item={"pk": {"S": "between"}, "sk": {"S": "m"}} + ) + resp = dynamodb_client.query( + TableName=base_table, + ConsistentRead=True, + KeyConditionExpression="pk = :p AND sk BETWEEN :l AND :h", + ExpressionAttributeValues={ + ":p": {"S": "between"}, + ":l": S(600, "a"), + ":h": S(600, "z"), + }, + ) + assert resp["Count"] == 1 + + +class TestRangeOperatorsAreSized: + """Measured 2026-10-23: every RANGE operator counts its value.""" + + @pytest.mark.parametrize( + "expression", + [ + "pk = :p AND sk > :v", + "pk = :p AND sk >= :v", + "pk = :p AND sk < :v", + "pk = :p AND sk <= :v", + "pk = :p AND begins_with(sk, :v)", + ], + ) + def test_1025_byte_value_is_refused(self, dynamodb_client, base_table, expression): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=base_table, + KeyConditionExpression=expression, + ExpressionAttributeValues={":p": {"S": "p"}, ":v": S(1025, "s")}, + ) + + def test_between_with_a_1025_byte_upper_bound_is_refused( + self, dynamodb_client, base_table + ): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=base_table, + KeyConditionExpression="pk = :p AND sk BETWEEN :l AND :h", + ExpressionAttributeValues={ + ":p": {"S": "p"}, + ":l": S(1, "a"), + ":h": S(1025, "z"), + }, + ) + + +class TestBinaryKeySize: + """Measured 2026-10-23: binary key values are sized by byte length.""" + + def test_hash_value_of_2048_bytes_is_accepted(self, dynamodb_client, binary_table): + resp = dynamodb_client.query( + TableName=binary_table, + KeyConditionExpression="pk = :v", + ExpressionAttributeValues={":v": B(2048)}, + ) + assert resp["Count"] == 0 + + def test_hash_value_of_2049_bytes_is_refused(self, dynamodb_client, binary_table): + refused( + dynamodb_client, + HASH_MESSAGE, + TableName=binary_table, + KeyConditionExpression="pk = :v", + ExpressionAttributeValues={":v": B(2049)}, + ) + + def test_range_value_of_1024_bytes_is_accepted(self, dynamodb_client, binary_table): + resp = dynamodb_client.query( + TableName=binary_table, + KeyConditionExpression="pk = :p AND sk = :v", + ExpressionAttributeValues={":p": B(1), ":v": B(1024)}, + ) + assert resp["Count"] == 0 + + def test_range_value_of_1025_bytes_is_refused(self, dynamodb_client, binary_table): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=binary_table, + KeyConditionExpression="pk = :p AND sk = :v", + ExpressionAttributeValues={":p": B(1), ":v": B(1025)}, + ) + + +class TestLsiQueryKeySize: + """Measured 2026-10-23: the index's RANGE key is sized on an LSI query.""" + + def test_range_value_of_1024_bytes_is_accepted(self, dynamodb_client, index_table): + resp = dynamodb_client.query( + TableName=index_table, + IndexName="lsi", + KeyConditionExpression="pk = :p AND l = :v", + ExpressionAttributeValues={":p": {"S": "p"}, ":v": S(1024, "l")}, + ) + assert resp["Count"] == 0 + + def test_range_value_of_1025_bytes_is_refused(self, dynamodb_client, index_table): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=index_table, + IndexName="lsi", + KeyConditionExpression="pk = :p AND l = :v", + ExpressionAttributeValues={":p": {"S": "p"}, ":v": S(1025, "l")}, + ) + + +class TestLegacyKeyConditionsKeySize: + """Measured 2026-10-23 with the legacy KeyConditions parameter.""" + + def test_hash_value_of_2049_bytes_is_refused(self, dynamodb_client, base_table): + refused( + dynamodb_client, + HASH_MESSAGE, + TableName=base_table, + KeyConditions={ + "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [S(2049, "p")]} + }, + ) + + def test_range_value_of_1025_bytes_is_refused(self, dynamodb_client, base_table): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=base_table, + KeyConditions={ + "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "p"}]}, + "sk": {"ComparisonOperator": "EQ", "AttributeValueList": [S(1025, "s")]}, + }, + ) + + +class TestBothLimitsExceeded: + """Measured 2026-10-23: the hash sentence wins.""" + + def test_hash_sentence_wins(self, dynamodb_client, base_table): + refused( + dynamodb_client, + HASH_MESSAGE, + TableName=base_table, + KeyConditionExpression="pk = :p AND sk = :v", + ExpressionAttributeValues={":p": S(2049, "p"), ":v": S(1025, "s")}, + ) diff --git a/tests/python/test_query_key_size_order.py b/tests/python/test_query_key_size_order.py new file mode 100644 index 000000000..62443cb62 --- /dev/null +++ b/tests/python/test_query_key_size_order.py @@ -0,0 +1,328 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Where the Query key size refusal sits among the other Query refusals. + +Each test sends a 2049-byte partition key value together with one other +fault and asserts which refusal comes back. Measured on the service in +us-east-1 on 2026-10-23: a missing table, a wrong +IndexName, ConsistentRead on a GSI, Limit 0, a key condition that misses the +key schema, a projection syntax error, Select against a projection, an +undefined filter name, a filter operand type, Select ALL_PROJECTED_ATTRIBUTES +on a base table, overlapping projection paths, an unused expression name, a +FilterExpression syntax error and an unused expression value are all reported +ahead of the size; an invalid ExclusiveStartKey is reported after it. On a +KEYS_ONLY GSI, Select ALL_ATTRIBUTES is reported after the size, with and +without an ExclusiveStartKey (measured 2026-11-20). Without an +ExclusiveStartKey it is also reported after Limit 0, a key condition on the +base table's partition key, an N value on the S key, an unused expression +value, an empty KeyConditionExpression and a FilterExpression syntax error +(measured 2026-11-24, in the review of #481). + +Where ExtendDB words a syntax error differently from the service, the test +checks the label that precedes the wording and that the size refusal did not +come back. +""" + +from __future__ import annotations + +import pytest +from botocore.exceptions import ClientError + +from helpers import unique_name +from query_key_size_support import ( # noqa: F401 (fixtures are used by name) + HASH_MESSAGE, + S, + index_table, + refused, + refused_ending, +) + +BIG = S(2049, "p") +FILTER_LABEL = "Invalid FilterExpression: " +LIMIT_MESSAGE = ( + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1" +) +MISSED_G_MESSAGE = "Query condition missed key schema element: g" + + +def _error(client, **query) -> dict: + with pytest.raises(ClientError) as exc_info: + client.query(**query) + err = exc_info.value.response + assert err["ResponseMetadata"]["HTTPStatusCode"] == 400 + return err["Error"] + + +def _first(client, table: str, message: str, **query) -> None: + """The query on ``table`` with a 2049-byte ``pk`` reports ``message``.""" + refused( + client, + message, + TableName=table, + KeyConditionExpression="pk = :big", + **{ + **query, + "ExpressionAttributeValues": {":big": BIG, **query.get("ExpressionAttributeValues", {})}, + }, + ) + + +def test_missing_table_is_reported_first(dynamodb_client): + refused( + dynamodb_client, + "Requested resource not found", + code="ResourceNotFoundException", + TableName=unique_name("qks-absent"), + KeyConditionExpression="pk = :p", + ExpressionAttributeValues={":p": BIG}, + ) + + +def test_wrong_index_name_is_reported_first(dynamodb_client, index_table): + refused( + dynamodb_client, + "The table does not have the specified index: nope", + TableName=index_table, + IndexName="nope", + KeyConditionExpression="g = :p", + ExpressionAttributeValues={":p": BIG}, + ) + + +def test_consistent_read_on_a_gsi_is_reported_first(dynamodb_client, index_table): + refused( + dynamodb_client, + "Consistent reads are not supported on global secondary indexes", + TableName=index_table, + IndexName="gsi", + ConsistentRead=True, + KeyConditionExpression="g = :p", + ExpressionAttributeValues={":p": BIG}, + ) + + +def test_limit_zero_is_reported_first(raw_client, index_table): + refused( + raw_client, + LIMIT_MESSAGE, + TableName=index_table, + Limit=0, + KeyConditionExpression="pk = :p", + ExpressionAttributeValues={":p": BIG}, + ) + + +def test_missed_key_schema_element_is_reported_first(dynamodb_client, index_table): + refused( + dynamodb_client, + MISSED_G_MESSAGE, + TableName=index_table, + IndexName="gsi", + KeyConditionExpression="gs = :v", + ExpressionAttributeValues={":v": S(1025, "r")}, + ) + + +def test_projection_syntax_error_is_reported_first(dynamodb_client, index_table): + err = _error( + dynamodb_client, + TableName=index_table, + KeyConditionExpression="pk = :big", + ProjectionExpression="a,,b", + ExpressionAttributeValues={":big": BIG}, + ) + assert err["Code"] == "ValidationException" + assert err["Message"].startswith("Invalid ProjectionExpression: ") + assert err["Message"] != HASH_MESSAGE + + +def test_select_count_with_a_projection_is_reported_first(dynamodb_client, index_table): + _first( + dynamodb_client, + index_table, + "1 validation error detected: Cannot specify the ProjectionExpression " + "when choosing to get only the Count", + Select="COUNT", + ProjectionExpression="sk", + ) + + +def test_undefined_filter_name_is_reported_first(dynamodb_client, index_table): + _first( + dynamodb_client, + index_table, + "Invalid FilterExpression: An expression attribute name used in the " + "document path is not defined; attribute name: #z", + FilterExpression="#z = :big", + ) + + +def test_filter_operand_type_is_reported_first(dynamodb_client, index_table): + _first( + dynamodb_client, + index_table, + "Invalid FilterExpression: Incorrect operand type for operator or function; " + "operator or function: begins_with, operand type: N", + FilterExpression="begins_with(a, :n)", + ExpressionAttributeValues={":n": {"N": "1"}}, + ) + + +def test_select_all_projected_attributes_on_a_base_table_is_reported_first( + dynamodb_client, index_table +): + # The service prefixes this with `1 validation error detected: `; ExtendDB + # omits that label (a wording gap that exists without the size check). + refused_ending( + dynamodb_client, + "ALL_PROJECTED_ATTRIBUTES can be used only when Querying using an IndexName", + TableName=index_table, + KeyConditionExpression="pk = :big", + Select="ALL_PROJECTED_ATTRIBUTES", + ExpressionAttributeValues={":big": BIG}, + ) + + +def test_overlapping_projection_paths_are_reported_first(dynamodb_client, index_table): + _first( + dynamodb_client, + index_table, + "Invalid ProjectionExpression: Two document paths overlap with each other; " + "must remove or rewrite one of these paths; path one: [a], path two: [a, b]", + ProjectionExpression="a, a.b", + ) + + +def test_unused_expression_name_is_reported_first(dynamodb_client, index_table): + _first( + dynamodb_client, + index_table, + "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}", + ExpressionAttributeNames={"#u": "a"}, + ) + + +def test_filter_expression_syntax_is_reported_first(dynamodb_client, index_table): + err = _error( + dynamodb_client, + TableName=index_table, + KeyConditionExpression="pk = :p", + FilterExpression="nope(", + ExpressionAttributeValues={":p": BIG}, + ) + assert err["Code"] == "ValidationException" + assert err["Message"].startswith(FILTER_LABEL) + assert err["Message"] != HASH_MESSAGE + + +def test_unused_expression_value_is_reported_first(dynamodb_client, index_table): + _first( + dynamodb_client, + index_table, + "Value provided in ExpressionAttributeValues unused in expressions: keys: {:z}", + ExpressionAttributeValues={":z": S(1, "z")}, + ) + + +def test_invalid_exclusive_start_key_is_reported_after(dynamodb_client, index_table): + _first( + dynamodb_client, + index_table, + HASH_MESSAGE, + ExclusiveStartKey={"pk": BIG}, + ) + + +def test_exclusive_start_key_of_the_wrong_type_is_reported_after( + dynamodb_client, index_table +): + _first( + dynamodb_client, + index_table, + HASH_MESSAGE, + ExclusiveStartKey={"pk": {"N": "1"}, "sk": S(1, "s")}, + ) + + +SELECT_ON_KEYS_ONLY_MESSAGE = ( + "One or more parameter values were invalid: Select type ALL_ATTRIBUTES is not " + "supported for global secondary index gko because its projection type is not ALL" +) +START_KEY = {"g": S(1, "x"), "pk": S(1, "a"), "sk": S(1, "b")} +ONE_BYTE = S(1, "x") + + +@pytest.mark.parametrize( + ("values", "changes", "message"), + [ + pytest.param({":v": BIG}, {}, HASH_MESSAGE, id="2049-bytes"), + pytest.param( + {":v": BIG}, + {"ExclusiveStartKey": START_KEY}, + HASH_MESSAGE, + id="2049-bytes-with-a-start-key", + ), + pytest.param( + {":v": ONE_BYTE}, + {"ExclusiveStartKey": START_KEY}, + SELECT_ON_KEYS_ONLY_MESSAGE, + id="1-byte-with-a-start-key", + ), + pytest.param({":v": ONE_BYTE}, {"Limit": 0}, LIMIT_MESSAGE, id="limit-0"), + pytest.param( + {":v": ONE_BYTE}, + {"KeyConditionExpression": "pk = :v"}, + MISSED_G_MESSAGE, + id="base-partition-key", + ), + pytest.param( + {":v": {"N": "1"}}, + {}, + "One or more parameter values were invalid: " + "Condition parameter type does not match schema type", + id="n-value-on-the-s-key", + ), + pytest.param( + {":v": ONE_BYTE, ":w": ONE_BYTE}, + {}, + "Value provided in ExpressionAttributeValues unused in expressions: keys: {:w}", + id="unused-value", + ), + pytest.param( + {":v": ONE_BYTE}, + {"KeyConditionExpression": ""}, + "Invalid KeyConditionExpression: The expression can not be empty;", + id="empty-key-condition", + ), + # The service answers `Invalid FilterExpression: Syntax error; token: + # "#", near: "#"`, and ExtendDB answers `Invalid FilterExpression: empty + # name reference '#'` (#1419), so this row checks the label only. + pytest.param( + {":v": ONE_BYTE}, + {"FilterExpression": "#"}, + FILTER_LABEL, + id="filter-syntax-error", + ), + ], +) +def test_select_all_attributes_on_a_keys_only_gsi_is_reported_after( + raw_client, index_table, values, changes, message +): + # Each shape measured twice: the first three rows on 2026-11-20 in + # us-east-1, the other six on 2026-11-24 (review of #481). + query = { + "TableName": index_table, + "IndexName": "gko", + "Select": "ALL_ATTRIBUTES", + "KeyConditionExpression": "g = :v", + "ExpressionAttributeValues": values, + **changes, + } + if message == FILTER_LABEL: + err = _error(raw_client, **query) + assert err["Code"] == "ValidationException", err["Message"] + assert err["Message"].startswith(FILTER_LABEL), err["Message"] + else: + refused(raw_client, message, **query) diff --git a/tests/python/test_query_key_size_values.py b/tests/python/test_query_key_size_values.py new file mode 100644 index 000000000..b1c6b6807 --- /dev/null +++ b/tests/python/test_query_key_size_values.py @@ -0,0 +1,272 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Query key size rows for multi-byte values, ordered BETWEEN bounds, undefined +references, a hash-only table, a GSI and number key values. + +Measured on the service in us-east-1 on 2026-10-23, the number rows on +2026-11-20 and 2026-11-24. The main key size rows are in +``test_query_key_size.py``. +""" + +from __future__ import annotations + +import pytest + +from query_key_size_support import ( # noqa: F401 (fixtures are used by name) + HASH_MESSAGE, + RANGE_MESSAGE, + S, + base_table, + hash_only_table, + index_table, + number_table, + refused, + refused_ending, +) + +EURO = "\u20ac" # three bytes in UTF-8 + + +class TestMultiByteKeySize: + """Strings are sized by their UTF-8 bytes, not their characters.""" + + def test_683_three_byte_characters_in_a_hash_value_are_refused( + self, dynamodb_client, base_table + ): + refused( + dynamodb_client, + HASH_MESSAGE, + TableName=base_table, + KeyConditionExpression="pk = :v", + ExpressionAttributeValues={":v": {"S": EURO * 683}}, + ) + + def test_a_hash_value_of_2048_bytes_with_multi_byte_characters_is_accepted( + self, dynamodb_client, base_table + ): + resp = dynamodb_client.query( + TableName=base_table, + KeyConditionExpression="pk = :v", + ExpressionAttributeValues={":v": {"S": EURO * 682 + "xx"}}, + ) + assert resp["Count"] == 0 + + def test_342_three_byte_characters_in_a_range_value_are_refused( + self, dynamodb_client, base_table + ): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=base_table, + KeyConditionExpression="pk = :p AND sk = :v", + ExpressionAttributeValues={":p": S(1, "p"), ":v": {"S": EURO * 342}}, + ) + + def test_a_range_value_of_1024_bytes_with_multi_byte_characters_is_accepted( + self, dynamodb_client, base_table + ): + resp = dynamodb_client.query( + TableName=base_table, + KeyConditionExpression="pk = :p AND sk = :v", + ExpressionAttributeValues={":p": S(1, "p"), ":v": {"S": EURO * 341 + "x"}}, + ) + assert resp["Count"] == 0 + + +class TestBetweenLowerBound: + """An ordered BETWEEN is sized by its larger bound, which may be the lower one.""" + + def test_a_1025_byte_lower_bound_is_refused(self, dynamodb_client, base_table): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=base_table, + KeyConditionExpression="pk = :p AND sk BETWEEN :l AND :u", + ExpressionAttributeValues={ + ":p": S(1, "p"), + ":l": S(1025, "a"), + ":u": S(1, "z"), + }, + ) + + def test_a_1024_byte_lower_bound_is_accepted(self, dynamodb_client, base_table): + resp = dynamodb_client.query( + TableName=base_table, + KeyConditionExpression="pk = :p AND sk BETWEEN :l AND :u", + ExpressionAttributeValues={ + ":p": S(1, "p"), + ":l": S(1024, "a"), + ":u": S(1, "z"), + }, + ) + assert resp["Count"] == 0 + + +class TestUndefinedReferencesWin: + """An undefined value in the key condition is reported, not the size. + + The service words it ``Invalid KeyConditionExpression: An expression + attribute value used in expression is not defined; attribute value: + :missing``. ExtendDB omits the leading label (a wording gap that exists + without this check), so the row compares the text after it. + """ + + def test_an_undefined_value_is_reported_ahead_of_a_2049_byte_hash( + self, dynamodb_client, base_table + ): + refused_ending( + dynamodb_client, + "An expression attribute value used in expression is not defined; " + "attribute value: :missing", + TableName=base_table, + KeyConditionExpression="pk = :v AND sk = :missing", + ExpressionAttributeValues={":v": S(2049, "p")}, + ) + + +class TestHashOnlyTable: + def test_a_2049_byte_hash_value_is_refused(self, dynamodb_client, hash_only_table): + refused( + dynamodb_client, + HASH_MESSAGE, + TableName=hash_only_table, + KeyConditionExpression="pk = :v", + ExpressionAttributeValues={":v": S(2049, "p")}, + ) + + def test_a_2048_byte_hash_value_is_accepted(self, dynamodb_client, hash_only_table): + resp = dynamodb_client.query( + TableName=hash_only_table, + KeyConditionExpression="pk = :v", + ExpressionAttributeValues={":v": S(2048, "p")}, + ) + assert resp["Count"] == 0 + + +class TestIndexRangeClauses: + """The index's own RANGE key is sized: a GSI with one RANGE attribute and an LSI.""" + + def test_a_gsi_non_equality_of_1025_bytes_is_refused( + self, dynamodb_client, index_table + ): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=index_table, + IndexName="gsi", + KeyConditionExpression="g = :g AND gs > :v", + ExpressionAttributeValues={":g": S(1, "g"), ":v": S(1025, "s")}, + ) + + def test_a_gsi_between_with_two_600_byte_bounds_is_accepted( + self, dynamodb_client, index_table + ): + resp = dynamodb_client.query( + TableName=index_table, + IndexName="gsi", + KeyConditionExpression="g = :g AND gs BETWEEN :l AND :u", + ExpressionAttributeValues={ + ":g": S(1, "g"), + ":l": S(600, "a"), + ":u": S(600, "z"), + }, + ) + assert resp["Count"] == 0 + + def test_an_lsi_begins_with_of_1025_bytes_is_refused( + self, dynamodb_client, index_table + ): + refused( + dynamodb_client, + RANGE_MESSAGE, + TableName=index_table, + IndexName="lsi", + KeyConditionExpression="pk = :p AND begins_with(l, :v)", + ExpressionAttributeValues={":p": S(1, "p"), ":v": S(1025, "l")}, + ) + + +DIGITS_MESSAGE = "Attempting to store more than 38 significant digits in a Number" +OVERFLOW_MESSAGE = ( + "Number overflow. Attempting to store a number with magnitude larger than supported range" +) +UNDERFLOW_MESSAGE = ( + "Number underflow. Attempting to store a number with magnitude smaller than supported range" +) +NOT_A_NUMBER = "The parameter cannot be converted to a numeric value: " + + +def number_query(form: str, index_table: str, number_table: str, number: str) -> dict: + """A Query with the N value ``number`` in the key position ``form``. + + ``gsi`` and ``gsi-legacy``: HASH ``n`` of the GSI ``ngsi``, in + ``KeyConditionExpression`` and in ``KeyConditions``. ``partition`` and + ``sort``: HASH ``pk`` and RANGE ``sk`` of a table with N keys. + """ + value = {"N": number} + if form == "gsi-legacy": + condition = {"n": {"ComparisonOperator": "EQ", "AttributeValueList": [value]}} + return {"TableName": index_table, "IndexName": "ngsi", "KeyConditions": condition} + sort_values = {":p": {"N": "1"}, ":v": value} + target, expression, values = { + "gsi": ({"TableName": index_table, "IndexName": "ngsi"}, "n = :v", {":v": value}), + "partition": ({"TableName": number_table}, "pk = :v", {":v": value}), + "sort": ({"TableName": number_table}, "pk = :p AND sk = :v", sort_values), + }[form] + return {**target, "KeyConditionExpression": expression, "ExpressionAttributeValues": values} + + +class TestNumberKeyValues: + """Number key values on the GSI ``ngsi`` (HASH ``n``, N) and a table with N keys. + + Measured 2026-11-20 on ``ngsi``: a number with more than 38 significant + digits or out of range gets the number's sentence, not the size sentence. + A valid number is sized after it is normalized, so 2100 zeros followed by + ``1`` is served. A number in other Unicode decimal digits (U+FF11, U+0967 + U+0968) is served too. + + Measured 2026-11-24: an ASCII value that is not a number gets ``The + parameter cannot be converted to a numeric value: `` followed by the + value, and ``1e-131`` gets the underflow sentence. 39 or 683 U+FF11 get + the 38-digit sentence, which #565 covers, so no row here holds them. The + service gives these answers before the table lookup, on a table that + does not exist too, so the rows run in each key position. + """ + + @pytest.mark.parametrize("form", ["gsi", "gsi-legacy"]) + @pytest.mark.parametrize( + ("number", "message"), + [ + pytest.param("1" * 2049, DIGITS_MESSAGE, id="2049-digits"), + pytest.param("1" * 39, DIGITS_MESSAGE, id="39-digits"), + pytest.param("1" + "0" * 2100, OVERFLOW_MESSAGE, id="1-then-2100-zeros"), + pytest.param("0" * 2100 + "1", None, id="2100-zeros-then-1"), + pytest.param("\uff11", None, id="fullwidth-1"), + pytest.param("\u0967\u0968", None, id="devanagari-12"), + ], + ) + def test_a_number_is_checked_before_it_is_sized( + self, dynamodb_client, index_table, number_table, number, message, form + ): + query = number_query(form, index_table, number_table, number) + if message is None: + assert dynamodb_client.query(**query)["Count"] == 0 + else: + refused(dynamodb_client, message, **query) + + @pytest.mark.parametrize("form", ["gsi", "gsi-legacy", "partition", "sort"]) + @pytest.mark.parametrize( + ("number", "message"), + [ + pytest.param("abc", NOT_A_NUMBER + "abc", id="abc"), + pytest.param("x" * 2049, NOT_A_NUMBER + "x" * 2049, id="2049-x"), + pytest.param(" 1", NOT_A_NUMBER + " 1", id="space-1"), + pytest.param("", NOT_A_NUMBER, id="empty"), + pytest.param("1e-131", UNDERFLOW_MESSAGE, id="underflow"), + ], + ) + def test_each_key_position_gets_the_number_sentence( + self, dynamodb_client, index_table, number_table, number, message, form + ): + refused(dynamodb_client, message, **number_query(form, index_table, number_table, number))