From e670127d5ee139fba9d04c4236fc26959a6bc7f3 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 00:48:38 +0000 Subject: [PATCH 01/21] fix(query): refuse key condition values over the key size limits Closes #435. The service refuses a Query whose key condition values exceed the key size limits before it reads anything; ExtendDB ran the Query. Measured on 2026-10-23, every row repeated with identical answers: - A HASH value over 2048 bytes: "One or more parameter values were invalid: Size of hashkey has exceeded the maximum size limit of2048 bytes" (no space after "of", as the service writes it). 2048 bytes is accepted. - HASH values that each fit but add up to more than 2048 bytes (an index with two HASH attributes): "One or more parameter values were invalid: Aggregated size of all hash keys has exceeded the size limit of 2048 bytes". A sum of exactly 2048 is accepted. A single oversized value gets the single sentence even when the sum is also over. - RANGE values adding up to more than 1024 bytes, one clause or several: "One or more parameter values were invalid: Aggregated size of all range keys has exceeded the size limit of 1024 bytes". 1024 is accepted. Every operator is sized (=, <, <=, >, >=, begins_with); BETWEEN contributes its larger bound, not the sum of both. - The HASH checks are reported before the RANGE check. - Strings are sized by UTF-8 bytes (683 U+20AC characters, 2049 bytes, refused; 682 plus "xx", 2048 bytes, accepted) and binary values by byte length. Base tables, LSIs, GSIs and legacy KeyConditions behave the same. - An undefined #name or :value in the key condition is reported before the size check. Ordering, measured with a 2049-byte value: filter syntax, unused names and values, index name, ConsistentRead on a GSI, missing table, Limit, projection syntax and overlap, the Select conflicts and the filter operand type are all reported first; the ExclusiveStartKey checks after. The check is crates/core/src/validation/key_size.rs, called from handle_query after the expression validations and before the start key checks. The limits come from the configuration and the sentences name them. Tests: unit tests in validation/key_size/tests.rs and the engine; tests/python/test_query_key_size.py, test_query_key_size_values.py and test_query_key_size_order.py (64 rows) pass against the service. On ExtendDB alone, five rows with two or more RANGE clauses on one index skip until the multi-attribute range change in #429 merges (the handler refuses the shape earlier today); they pass on the merged tree. The undefined-name row stays unit level because the undefined-name refusal for a sort key clause arrives with #479. Pre-existing, measured, not changed here: a BETWEEN with the lower bound above the upper bound is refused by the service with a bound-order sentence; two conditions on one key are refused with "KeyConditionExpressions must only contain one condition per key"; a Number with 39 or more digits is refused with "Attempting to store more than 38 significant digits in a Number"; a FilterExpression on a key attribute is refused with "Filter Expression can only contain non-primary key attributes". ExtendDB accepts all four. --- crates/core/src/validation/key_size.rs | 226 ++++++++ crates/core/src/validation/key_size/tests.rs | 523 +++++++++++++++++++ crates/core/src/validation/mod.rs | 34 +- crates/engine/src/lib.rs | 2 + crates/engine/src/query.rs | 16 + crates/engine/src/query_key_size_tests.rs | 324 ++++++++++++ docs/dynamodb-limits.md | 4 +- tests/python/query_key_size_support.py | 221 ++++++++ tests/python/test_query_key_size.py | 423 +++++++++++++++ tests/python/test_query_key_size_order.py | 264 ++++++++++ tests/python/test_query_key_size_values.py | 183 +++++++ 11 files changed, 2192 insertions(+), 28 deletions(-) create mode 100644 crates/core/src/validation/key_size.rs create mode 100644 crates/core/src/validation/key_size/tests.rs create mode 100644 crates/engine/src/query_key_size_tests.rs create mode 100644 tests/python/query_key_size_support.py create mode 100644 tests/python/test_query_key_size.py create mode 100644 tests/python/test_query_key_size_order.py create mode 100644 tests/python/test_query_key_size_values.py diff --git a/crates/core/src/validation/key_size.rs b/crates/core/src/validation/key_size.rs new file mode 100644 index 000000000..1ad77ba4b --- /dev/null +++ b/crates/core/src/validation/key_size.rs @@ -0,0 +1,226 @@ +// 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}; + +/// 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. The service caps a number at 38 significant digits and +/// refuses a longer one on the Query path before any size check (measured +/// 2026-10-23: 39 digits and 2049 digits are both refused with +/// `Attempting to store more than 38 significant digits in a Number`). ExtendDB +/// does not validate a number in a key condition yet, so a long `N` string +/// reaches this function and is sized by its length; the Query path relies on +/// number validation that ExtendDB does not have. +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 key type of the clause's attribute and the bytes it contributes. + Bytes(KeyType, 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. +fn sized_clause( + clause: &Clause<'_>, + key_schema: &[KeySchemaElement], + maps: &ExpressionMaps, +) -> ClauseSize { + let (path, values) = clause; + let Some(first) = path.first() else { + return ClauseSize::Skipped; + }; + let Ok(name) = resolve_element_name(first, maps) else { + return 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 ClauseSize::Unresolved; + }; + size = size.max(key_value_byte_size(value)); + } + let Some(key) = key_schema.iter().find(|ks| ks.attribute_name == name) else { + return ClauseSize::Skipped; + }; + if !placeholders { + return ClauseSize::Skipped; + } + ClauseSize::Bytes(key.key_type, 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 HASH values add up to more +/// than that, the aggregated hash sentence (only an index with several HASH +/// attributes can reach it). +/// - Every RANGE clause contributes the size of its value, whatever its +/// 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. +/// - The HASH checks run before the RANGE check, so the hash sentence wins when +/// both limits are exceeded. +/// - If a `#name` or `:value` of any key clause is not defined, the check +/// returns `Ok` and the request gets the undefined-reference refusal it +/// already has, which the service reports ahead of the size. +/// +/// 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 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. Not measured: a HASH sum of +/// exactly 2048 bytes (treated as within the limit, as the single-value limit +/// is) and which sentence wins when the HASH sum and the RANGE sum are both +/// over (the hash sentence, as for a single HASH value). +/// +/// 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. +pub fn validate_query_key_sizes( + key_condition: &KeyCondition, + key_schema: &[KeySchemaElement], + maps: &ExpressionMaps, + limits: &LimitsConfig, +) -> Result<(), DynamoDbError> { + let mut hash_over = false; + let mut hash_total: usize = 0; + let mut range_total: usize = 0; + for clause in clauses(key_condition) { + match sized_clause(&clause, key_schema, maps) { + ClauseSize::Unresolved => return Ok(()), + ClauseSize::Skipped => {} + ClauseSize::Bytes(KeyType::Hash, size) => { + hash_over |= size > limits.max_partition_key_size_bytes; + hash_total = hash_total.saturating_add(size); + } + ClauseSize::Bytes(KeyType::Range, size) => { + 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..ecbb1b7a1 --- /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:?}"), + } +} + +#[test] +fn hash_value_of_2048_bytes_is_accepted() { + let kc = hash_only("pk", "v"); + assert!(check(&kc, &base_schema(), &maps(&[("v", 2048)])).is_ok()); +} + +#[test] +fn hash_value_of_2049_bytes_is_refused_with_the_service_sentence() { + let kc = hash_only("pk", "v"); + let msg = message(check(&kc, &base_schema(), &maps(&[("v", 2049)]))); + assert_eq!(msg, HASH_MSG_2048); +} + +#[test] +fn hash_sentence_has_no_space_between_of_and_the_number() { + let kc = hash_only("pk", "v"); + let msg = message(check(&kc, &base_schema(), &maps(&[("v", 2049)]))); + assert!(msg.ends_with("limit of2048 bytes"), "got: {msg}"); +} + +#[test] +fn range_value_of_1024_bytes_is_accepted() { + let mut kc = hash_only("pk", "p"); + kc.sk_condition = Some(eq("sk", "v")); + assert!(check(&kc, &base_schema(), &maps(&[("p", 1), ("v", 1024)])).is_ok()); +} + +#[test] +fn range_value_of_1025_bytes_is_refused_with_the_service_sentence() { + let mut kc = hash_only("pk", "p"); + kc.sk_condition = Some(eq("sk", "v")); + let msg = message(check(&kc, &base_schema(), &maps(&[("p", 1), ("v", 1025)]))); + assert_eq!(msg, RANGE_MSG_1024); +} + +#[test] +fn two_range_values_are_added_together() { + // 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. + let mut kc = hash_only("h", "h"); + kc.sk_condition = Some(eq("a", "x")); + kc.extra_sk_conditions = vec![(path("b"), placeholder("y")), (path("c"), placeholder("z"))]; + let m = maps(&[("h", 1), ("x", 600), ("y", 1), ("z", 600)]); + assert_eq!( + message(check(&kc, &multi_range_schema(), &m)), + RANGE_MSG_1024 + ); +} + +#[test] +fn one_600_byte_range_value_on_a_multi_range_index_is_accepted() { + // Measured 2026-10-23 on `idx`. + let mut kc = hash_only("h", "h"); + kc.sk_condition = Some(eq("a", "x")); + let m = maps(&[("h", 1), ("x", 600)]); + assert!(check(&kc, &multi_range_schema(), &m).is_ok()); +} + +#[test] +fn two_range_values_totalling_exactly_1024_are_accepted_and_1025_refused() { + // Measured 2026-10-23 on `idx`: 512 and 512 pass, 512 and 513 are refused. + let mut kc = hash_only("h", "h"); + kc.sk_condition = Some(eq("a", "x")); + kc.extra_sk_conditions = vec![(path("b"), placeholder("y"))]; + let m = maps(&[("h", 1), ("x", 512), ("y", 512)]); + assert!(check(&kc, &multi_range_schema(), &m).is_ok()); + let m = maps(&[("h", 1), ("x", 512), ("y", 513)]); + assert_eq!( + message(check(&kc, &multi_range_schema(), &m)), + RANGE_MSG_1024 + ); +} + +#[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 the_hash_sentence_wins_when_both_limits_are_exceeded() { + let mut kc = hash_only("pk", "p"); + kc.sk_condition = Some(eq("sk", "v")); + let m = maps(&[("p", 2049), ("v", 1025)]); + assert_eq!(message(check(&kc, &base_schema(), &m)), HASH_MSG_2048); +} + +fn two_hash_condition() -> KeyCondition { + let mut kc = hash_only("h1", "x"); + kc.extra_pk_conditions = vec![(path("h2"), placeholder("y"))]; + kc +} + +#[test] +fn one_hash_value_over_the_limit_gets_the_single_sentence() { + // Measured 2026-10-23 on `two-hash`: `h1` of 2049 bytes and `h2` of 1 byte. + let kc = two_hash_condition(); + let m = maps(&[("x", 2049), ("y", 1)]); + assert_eq!(message(check(&kc, &two_hash_schema(), &m)), HASH_MSG_2048); + let m = maps(&[("x", 1), ("y", 2049)]); + assert_eq!(message(check(&kc, &two_hash_schema(), &m)), HASH_MSG_2048); +} + +#[test] +fn hash_values_that_add_up_over_the_limit_get_the_aggregated_sentence() { + // Measured 2026-10-23 on `two-hash`: 1025 and 1024 bytes (sum 2049, neither + // over) and 2048 and 2048 bytes are both refused. + let kc = two_hash_condition(); + for (x, y) in [(1025, 1024), (2048, 2048)] { + let m = maps(&[("x", x), ("y", y)]); + assert_eq!( + message(check(&kc, &two_hash_schema(), &m)), + HASH_TOTAL_MSG_2048, + "{x} + {y}" + ); + } +} + +#[test] +fn hash_values_that_add_up_to_exactly_the_limit_are_accepted() { + // Not measured: a sum of exactly 2048 bytes. Treated as within the limit, + // as a single 2048-byte value is (measured). + let kc = two_hash_condition(); + let m = maps(&[("x", 1024), ("y", 1024)]); + assert!(check(&kc, &two_hash_schema(), &m).is_ok()); +} + +#[test] +fn the_aggregated_hash_sentence_has_a_space_before_the_number() { + let kc = two_hash_condition(); + let m = maps(&[("x", 1025), ("y", 1024)]); + let msg = message(check(&kc, &two_hash_schema(), &m)); + assert!(msg.ends_with("size limit of 2048 bytes"), "got: {msg}"); +} + +#[test] +fn a_hash_sum_over_the_limit_wins_over_the_range_sum() { + // Not measured: both the HASH sum and the RANGE sum over. The hash + // sentences come first, as the single hash sentence does (measured). + let mut kc = two_hash_condition(); + kc.sk_condition = Some(eq("r", "z")); + let m = maps(&[("x", 1025), ("y", 1024), ("z", 1025)]); + assert_eq!( + message(check(&kc, &two_hash_schema(), &m)), + HASH_TOTAL_MSG_2048 + ); +} + +#[test] +fn the_single_hash_sentence_wins_over_the_aggregated_one() { + let kc = two_hash_condition(); + let m = maps(&[("x", 2049), ("y", 2048)]); + assert_eq!(message(check(&kc, &two_hash_schema(), &m)), HASH_MSG_2048); +} + +#[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_value_placeholder_on_the_clause_itself_returns_ok() { + let kc = hash_only("pk", "missing"); + assert!(check(&kc, &base_schema(), &maps(&[("v", 5000)])).is_ok()); +} + +#[test] +fn an_undefined_name_reference_on_the_clause_itself_returns_ok() { + let kc = hash_only("#nope", "v"); + assert!(check(&kc, &base_schema(), &maps(&[("v", 5000)])).is_ok()); +} + +#[test] +fn an_undefined_value_in_another_clause_wins_over_the_size_of_a_defined_one() { + // 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. + let mut kc = hash_only("pk", "v"); + kc.sk_condition = Some(eq("sk", "missing")); + assert!(check(&kc, &base_schema(), &maps(&[("v", 2049)])).is_ok()); +} + +#[test] +fn an_undefined_name_in_another_clause_wins_over_the_size_of_a_defined_one() { + // 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. + let mut kc = hash_only("pk", "v"); + kc.sk_condition = Some(eq("#n", "w")); + assert!(check(&kc, &base_schema(), &maps(&[("v", 2049), ("w", 1)])).is_ok()); +} + +#[test] +fn an_undefined_reference_wins_whatever_its_position() { + // The oversized clause may come before or after the undefined one. + let mut kc = hash_only("pk", "missing"); + kc.sk_condition = Some(eq("sk", "v")); + assert!(check(&kc, &base_schema(), &maps(&[("v", 5000)])).is_ok()); +} + +#[test] +fn an_undefined_bound_of_a_between_returns_ok() { + let mut kc = hash_only("pk", "p"); + kc.sk_condition = Some(between("sk", "l", "missing")); + assert!(check(&kc, &base_schema(), &maps(&[("p", 1), ("l", 5000)])).is_ok()); +} + +#[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_are_sized_by_their_digit_string() { + // The service refuses a number of more than 38 significant digits before + // any size check (measured 2026-10-23). ExtendDB does not validate a + // number in a key condition, so a long digit string reaches the size + // check and is sized by its length. + let kc = hash_only("pk", "v"); + let values = HashMap::from([("v".to_owned(), AttributeValue::N("1".repeat(2049)))]); + let m = ExpressionMaps::new(HashMap::new(), values); + assert_eq!(message(check(&kc, &base_schema(), &m)), HASH_MSG_2048); +} diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index c144b46b6..8ba46af1a 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -1,8 +1,11 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 +mod key_size; pub mod number; pub mod vector_item; +pub use key_size::validate_query_key_sizes; + pub use vector_item::{ MAX_HASH_KEY_SIZE, MAX_INLINE_FILTER_SIZE, validate_vector_write, validate_vector_write_changed, vector_components, vector_norm, @@ -1825,41 +1828,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/engine/src/lib.rs b/crates/engine/src/lib.rs index 74083fbfa..4bf61e5b6 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -27,6 +27,8 @@ mod legacy_filter; mod list_tables; mod put_item; mod query; +#[cfg(test)] +mod query_key_size_tests; mod read_helpers; mod request_limits; mod scan; diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index f45526af8..95d7c9ad1 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -471,6 +471,22 @@ 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 (the type + // check arrives with the multi-attribute range change and belongs above + // this call), 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())?; 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..706216dae --- /dev/null +++ b/crates/engine/src/query_key_size_tests.rs @@ -0,0 +1,324 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Key size limits on a `Query` key condition, driven from the expression +//! text. Each case is a row measured on the service on 2026-10-21 (index with +//! HASH `h` and RANGE `a`, `b`, `c`, `d`), 2026-10-22 (base table with HASH +//! `pk` and RANGE `sk`) or 2026-10-23 (the operator, `BETWEEN`, binary and +//! ordering rows, recorded in the issue's fold file) or 2026-10-23 (the +//! multi-attribute, multi-byte and undefined-reference rows, recorded in +//! `service-435-review.jsonl` and `service-435-440-review-2.jsonl`). 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 HASH_TOTAL_MSG: &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: &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 index_schema() -> Vec { + vec![ + ks("h", KeyType::Hash), + ks("a", KeyType::Range), + ks("b", KeyType::Range), + ks("c", KeyType::Range), + ks("d", 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> { + run_with_names(expr, schema, &[], values) +} + +/// [`run`] with `ExpressionAttributeNames` (`#name` keys are given without the +/// hash). +fn run_with_names( + expr: &str, + schema: &[KeySchemaElement], + names: &[(&str, &str)], + 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 names: HashMap = names + .iter() + .map(|(name, attr)| ((*name).to_owned(), (*attr).to_owned())) + .collect(); + let maps = ExpressionMaps::new(names, 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 index_hash_value_of_2049_bytes_is_refused() { + let result = run("h = :big", &index_schema(), &[("big", s(2049))]); + assert_eq!(refused(result), HASH_MSG); +} + +#[test] +fn index_range_value_of_1025_bytes_is_refused() { + let result = run( + "h = :h AND a = :big", + &index_schema(), + &[("h", s(1)), ("big", s(1025))], + ); + assert_eq!(refused(result), RANGE_MSG); +} + +#[test] +fn index_two_600_byte_range_values_are_refused_together() { + // The wire row is `TestGsiQueryKeySize::test_two_600_byte_range_values_are_refused_together`. + // On a build without the multi-attribute range change the handler refuses + // this shape as `Query condition missed key schema element: h` before it + // reaches this function, so only the wire row, gated on that change, shows + // the end-to-end answer. + let values = [("h", s(1)), ("s", s(600)), ("b", s(1))]; + let result = run( + "h = :h AND a = :s AND b = :b AND c = :s", + &index_schema(), + &values, + ); + assert_eq!(refused(result), RANGE_MSG); +} + +#[test] +fn index_one_600_byte_range_value_is_accepted() { + // Gated wire row: `TestGsiQueryKeySize::test_two_600_byte_range_values_are_refused_together` + // (the same shape with the second 600-byte value removed passes on the + // service). The handler refuses three clauses on one HASH and several + // RANGE attributes before this function on a build without the + // multi-attribute range change. + let values = [("h", s(1)), ("s", s(600)), ("b", s(1))]; + let result = run("h = :h AND a = :s AND b = :b", &index_schema(), &values); + assert!(result.is_ok()); +} + +#[test] +fn base_hash_value_of_2048_bytes_is_accepted() { + assert!(run("pk = :v", &base_schema(), &[("v", s(2048))]).is_ok()); +} + +#[test] +fn base_hash_value_of_2049_bytes_is_refused() { + let result = run("pk = :v", &base_schema(), &[("v", s(2049))]); + assert_eq!(refused(result), HASH_MSG); +} + +#[test] +fn base_range_value_of_1024_bytes_is_accepted() { + let result = run( + "pk = :p AND sk = :v", + &base_schema(), + &[("p", s(1)), ("v", s(1024))], + ); + assert!(result.is_ok()); +} + +#[test] +fn base_range_value_of_1025_bytes_is_refused() { + let result = run( + "pk = :p AND sk = :v", + &base_schema(), + &[("p", s(1)), ("v", s(1025))], + ); + assert_eq!(refused(result), RANGE_MSG); +} + +#[test] +fn base_between_with_two_600_byte_bounds_is_accepted() { + // The bounds are not added together: 600 and 600 pass. + let values = [("p", s(1)), ("l", s(600)), ("u", s(600))]; + let result = run("pk = :p AND sk BETWEEN :l AND :u", &base_schema(), &values); + assert!(result.is_ok()); +} + +#[test] +fn base_between_with_a_1025_byte_bound_is_refused() { + let values = [("p", s(1)), ("l", s(1)), ("u", s(1025))]; + let result = run("pk = :p AND sk BETWEEN :l AND :u", &base_schema(), &values); + assert_eq!(refused(result), RANGE_MSG); +} + +#[test] +fn base_non_equality_operators_and_begins_with_are_sized() { + for expr in [ + "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)", + ] { + let result = run(expr, &base_schema(), &[("p", s(1)), ("v", s(1025))]); + assert_eq!(refused(result), RANGE_MSG, "{expr}"); + let result = run(expr, &base_schema(), &[("p", s(1)), ("v", s(1024))]); + assert!(result.is_ok(), "{expr}"); + } +} + +#[test] +fn binary_values_are_sized_by_byte_length() { + let b = |len: usize| AttributeValue::B(vec![1u8; len]); + assert!(run("pk = :v", &base_schema(), &[("v", b(2048))]).is_ok()); + let result = run("pk = :v", &base_schema(), &[("v", b(2049))]); + assert_eq!(refused(result), HASH_MSG); + let values = [("p", b(1)), ("v", b(1024))]; + assert!(run("pk = :p AND sk = :v", &base_schema(), &values).is_ok()); + let values = [("p", b(1)), ("v", b(1025))]; + let result = run("pk = :p AND sk = :v", &base_schema(), &values); + assert_eq!(refused(result), RANGE_MSG); +} + +#[test] +fn both_limits_exceeded_gives_the_hash_sentence() { + let values = [("p", s(2049)), ("v", s(1025))]; + let result = run("pk = :p AND sk = :v", &base_schema(), &values); + assert_eq!(refused(result), HASH_MSG); +} + +#[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 (rows `6 legacy hash 2049` and `6 legacy range 1025` + // of `service-435-shapes.jsonl`): 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); +} + +fn two_hash_schema() -> Vec { + vec![ + ks("h1", KeyType::Hash), + ks("h2", KeyType::Hash), + ks("r", KeyType::Range), + ] +} + +#[test] +fn two_hash_one_value_over_gets_the_single_sentence() { + let values = [("a", s(2049)), ("b", s(1))]; + let result = run("h1 = :a AND h2 = :b", &two_hash_schema(), &values); + assert_eq!(refused(result), HASH_MSG); +} + +#[test] +fn two_hash_values_adding_up_over_the_limit_get_the_aggregated_sentence() { + for (a, b) in [(1025, 1024), (2048, 2048)] { + let values = [("a", s(a)), ("b", s(b))]; + let result = run("h1 = :a AND h2 = :b", &two_hash_schema(), &values); + assert_eq!(refused(result), HASH_TOTAL_MSG, "{a} + {b}"); + } +} + +#[test] +fn an_undefined_value_in_the_key_condition_wins_over_the_size() { + // Measured 2026-10-23: the undefined attribute value is reported. + let result = run( + "pk = :v AND sk = :missing", + &base_schema(), + &[("v", s(2049))], + ); + assert!(result.is_ok()); +} + +#[test] +fn an_undefined_name_in_the_key_condition_wins_over_the_size() { + // Measured 2026-10-23: the undefined attribute name is reported. + let result = run_with_names( + "pk = :v AND #n = :w", + &base_schema(), + &[], + &[("v", s(2049)), ("w", s(1))], + ); + assert!(result.is_ok()); +} + +#[test] +fn a_defined_name_reference_is_sized() { + let result = run_with_names("#p = :v", &base_schema(), &[("p", "pk")], &[("v", s(2049))]); + assert_eq!(refused(result), HASH_MSG); +} + +#[test] +fn base_between_with_a_1025_byte_ordered_lower_bound_is_refused() { + // Measured 2026-10-23: lower bound `a` x 1025 and upper bound `z`. + let values = [ + ("p", s(1)), + ("l", AttributeValue::S("a".repeat(1025))), + ("u", AttributeValue::S("z".to_owned())), + ]; + let result = run("pk = :p AND sk BETWEEN :l AND :u", &base_schema(), &values); + assert_eq!(refused(result), RANGE_MSG); + let values = [ + ("p", s(1)), + ("l", AttributeValue::S("a".repeat(1024))), + ("u", AttributeValue::S("z".to_owned())), + ]; + assert!(run("pk = :p AND sk BETWEEN :l AND :u", &base_schema(), &values).is_ok()); +} diff --git a/docs/dynamodb-limits.md b/docs/dynamodb-limits.md index 503836958..512a3760e 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`, validated on PutItem and post-UpdateItem | -| 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 value of every sort key clause (any operator; a `BETWEEN` counts its larger bound) and checks the total | | Attribute name size | 1–64 KB (65,535 bytes) | Partial | `validate_attribute_name_sizes`, `LimitsConfig::max_attribute_name_bytes`; top-level names and nested map keys at every depth, on PutItem, BatchWriteItem.PutRequest, TransactWriteItems.Put, and ImportTable. Not enforced on UpdateItem or TransactWriteItems.Update at any level. | | 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..8c5672e80 --- /dev/null +++ b/tests/python/query_key_size_support.py @@ -0,0 +1,221 @@ +# 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 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" +) +MISSING_HASH_MESSAGE = "Query condition missed key schema element: h" + + +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, **query) -> None: + """Run the Query and assert the refusal's code, status and exact text.""" + 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"] == message + + +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"] + + +def require_multi_range(client, **query) -> None: + """Skip unless the server runs a key condition with several RANGE clauses. + + Sends ``query`` with every value cut to its first byte. A server that does + not yet serve several RANGE clauses on one index refuses it as + ``Query condition missed key schema element: h``; the test is then skipped + and passes without an edit once the server serves the shape. + """ + 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 exc.response["Error"]["Message"] == MISSING_HASH_MESSAGE: + pytest.skip("multi-attribute range conditions need the #429 change") + + +@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 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``.""" + with make_table( + dynamodb_client, + "qks-idx", + AttributeDefinitions=[attr(n) for n in ("pk", "sk", "l", "g", "gs")], + 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"}, + } + ], + ) 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..b7407f267 --- /dev/null +++ b/tests/python/test_query_key_size.py @@ -0,0 +1,423 @@ +# 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: 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 (``issues/query-parity/service-435-shapes.jsonl``, +``service-435-review.jsonl`` and ``service-435-440-review-2.jsonl``). Rows that +send several RANGE clauses on one index are skipped on a server that refuses +that shape earlier as ``Query condition missed key schema element: h``. 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_multi_range, + 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): + resp = dynamodb_client.query( + TableName=gsi_table, + **self._query("h = :h AND a = :s600", {":h": S(1, "h"), ":s600": S(600)}), + ) + assert resp["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")}, + ) + require_multi_range(dynamodb_client, TableName=gsi_table, **query) + 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_multi_range(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")}, + ) + require_multi_range(dynamodb_client, TableName=gsi_table, **query) + 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")}, + ) + require_multi_range(dynamodb_client, TableName=gsi_table, **query) + refused(dynamodb_client, RANGE_MESSAGE, TableName=gsi_table, **query) + + def test_between_adds_its_larger_bound_to_the_range_total( + self, dynamodb_client, gsi_table + ): + # a = 600 plus the larger BETWEEN bound: 1 and 600 (1200) is refused, + # 1 and 424 (1024) is accepted. + refusing = 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(600, "b")}, + ) + require_multi_range(dynamodb_client, TableName=gsi_table, **refusing) + refused(dynamodb_client, RANGE_MESSAGE, TableName=gsi_table, **refusing) + accepted = 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(424, "b")}, + ) + 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_isrefused(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_isrefused(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_isrefused(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_isrefused( + 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_isrefused(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_isrefused(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_isrefused(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_isrefused(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_isrefused(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..c65a54d85 --- /dev/null +++ b/tests/python/test_query_key_size_order.py @@ -0,0 +1,264 @@ +# 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 +2026-10-23 (``issues/query-parity/service-435-shapes.jsonl`` rows 8a to 8h and +``service-435-review.jsonl`` rows 7a to 7h): 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. + +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 os + +import boto3 +import botocore.config +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_ending, +) + +BIG = S(2049, "p") + + +@pytest.fixture(scope="module") +def unvalidated_client(endpoint_url): + """A client with botocore parameter validation off, so Limit 0 reaches the server.""" + kwargs: dict = { + "service_name": "dynamodb", + "region_name": os.environ.get("AWS_DEFAULT_REGION", "us-east-1"), + "config": botocore.config.Config( + parameter_validation=False, retries={"max_attempts": 0} + ), + } + if endpoint_url: + kwargs["endpoint_url"] = endpoint_url + if endpoint_url.startswith("https://"): + ca_cert = os.environ.get("EXTENDDB_CA_CERT", "") + kwargs["verify"] = ca_cert if ca_cert else False + return boto3.client(**kwargs) + + +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``.""" + err = _error( + client, + TableName=table, + KeyConditionExpression="pk = :big", + **{ + **query, + "ExpressionAttributeValues": {":big": BIG, **query.get("ExpressionAttributeValues", {})}, + }, + ) + assert err["Code"] == "ValidationException" + assert err["Message"] == message + + +def test_missing_table_is_reported_first(dynamodb_client): + err = _error( + dynamodb_client, + TableName=unique_name("qks-absent"), + KeyConditionExpression="pk = :p", + ExpressionAttributeValues={":p": BIG}, + ) + assert err["Code"] == "ResourceNotFoundException" + assert err["Message"] == "Requested resource not found" + + +def test_wrong_index_name_is_reported_first(dynamodb_client, index_table): + err = _error( + dynamodb_client, + TableName=index_table, + IndexName="nope", + KeyConditionExpression="g = :p", + ExpressionAttributeValues={":p": BIG}, + ) + assert err["Code"] == "ValidationException" + assert err["Message"] == "The table does not have the specified index: nope" + + +def test_consistent_read_on_a_gsi_is_reported_first(dynamodb_client, index_table): + err = _error( + dynamodb_client, + TableName=index_table, + IndexName="gsi", + ConsistentRead=True, + KeyConditionExpression="g = :p", + ExpressionAttributeValues={":p": BIG}, + ) + assert err["Code"] == "ValidationException" + assert err["Message"] == "Consistent reads are not supported on global secondary indexes" + + +def test_limit_zero_is_reported_first(unvalidated_client, index_table): + err = _error( + unvalidated_client, + TableName=index_table, + Limit=0, + KeyConditionExpression="pk = :p", + ExpressionAttributeValues={":p": BIG}, + ) + assert err["Code"] == "ValidationException" + assert err["Message"] == ( + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1" + ) + + +def test_missed_key_schema_element_is_reported_first(dynamodb_client, index_table): + err = _error( + dynamodb_client, + TableName=index_table, + IndexName="gsi", + KeyConditionExpression="gs = :v", + ExpressionAttributeValues={":v": S(1025, "r")}, + ) + assert err["Code"] == "ValidationException" + assert err["Message"] == "Query condition missed key schema element: g" + + +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("Invalid FilterExpression: ") + 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")}, + ) 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..9b6e40b80 --- /dev/null +++ b/tests/python/test_query_key_size_values.py @@ -0,0 +1,183 @@ +# 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 and a GSI. + +Measured on the service on 2026-10-23 (``issues/query-parity/service-435-review.jsonl``, +labels 1 to 4, 6, 10). The main key size rows are in ``test_query_key_size.py``. +""" + +from __future__ import annotations + +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, + 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")}, + ) From 02941062bfcdaddc914bca18721b8fc7aa1c5a47 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 02:22:31 +0000 Subject: [PATCH 02/21] fix(cassandra): pass the bare index name in IndexNotFound so the Query sentence matches the other backends --- crates/storage-cassandra/src/data/index.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/storage-cassandra/src/data/index.rs b/crates/storage-cassandra/src/data/index.rs index 4ebd72dac..3aa353ac6 100644 --- a/crates/storage-cassandra/src/data/index.rs +++ b/crates/storage-cassandra/src/data/index.rs @@ -147,7 +147,7 @@ pub async fn fetch_index_by_name( let row = rows .into_iter() .next() - .ok_or_else(|| StorageError::IndexNotFound(format!("Index {index_name} not found")))?; + .ok_or_else(|| StorageError::IndexNotFound(index_name.to_owned()))?; let index_id: String = get_column(&row, "index_id", "fetch_index_by_name")?; let index_type: String = get_column(&row, "index_type", "fetch_index_by_name")?; From 5c09198d22824b6c2cb1b8d3eca791f79f038998 Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 02:35:58 +0000 Subject: [PATCH 03/21] test(query): skip the idx accept rows on a backend that cannot read a multi-RANGE index The Cassandra backend answers InternalServerError to any Query on an index with several RANGE attributes: its ORDER BY lists sk_* then base_pk and skips the sk2_* to skN_* clustering columns, which Cassandra refuses with "Order by currently only supports the ordering of columns following their declared order in the PRIMARY KEY". require_multi_range now also skips on InternalServerError, so test_one_600_byte_range_value_is_accepted carries the probe like the other idx rows. --- tests/python/query_key_size_support.py | 14 ++++++++++---- tests/python/test_query_key_size.py | 13 +++++++------ 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/tests/python/query_key_size_support.py b/tests/python/query_key_size_support.py index 8c5672e80..2fe5c26a3 100644 --- a/tests/python/query_key_size_support.py +++ b/tests/python/query_key_size_support.py @@ -97,12 +97,15 @@ def refused_ending(client, suffix: str, **query) -> None: def require_multi_range(client, **query) -> None: - """Skip unless the server runs a key condition with several RANGE clauses. + """Skip unless the server runs ``query``'s key condition on a multi-RANGE index. Sends ``query`` with every value cut to its first byte. A server that does not yet serve several RANGE clauses on one index refuses it as - ``Query condition missed key schema element: h``; the test is then skipped - and passes without an edit once the server serves the shape. + ``Query condition missed key schema element: h``; a backend that cannot yet + read an index with several RANGE attributes at all answers + ``InternalServerError`` to any Query on it, whatever the clause count. The + test is then skipped and passes without an edit once the server serves + the shape. """ probe = dict(query) probe["ExpressionAttributeValues"] = { @@ -111,8 +114,11 @@ def require_multi_range(client, **query) -> None: try: client.query(**probe) except ClientError as exc: - if exc.response["Error"]["Message"] == MISSING_HASH_MESSAGE: + err = exc.response["Error"] + if err["Message"] == MISSING_HASH_MESSAGE: pytest.skip("multi-attribute range conditions need the #429 change") + if err["Code"] == "InternalServerError": + pytest.skip("multi-attribute range Query is not supported by this backend yet") @pytest.fixture(scope="module") diff --git a/tests/python/test_query_key_size.py b/tests/python/test_query_key_size.py index b7407f267..fe667ffff 100644 --- a/tests/python/test_query_key_size.py +++ b/tests/python/test_query_key_size.py @@ -19,7 +19,10 @@ rows on 2026-10-23 (``issues/query-parity/service-435-shapes.jsonl``, ``service-435-review.jsonl`` and ``service-435-440-review-2.jsonl``). Rows that send several RANGE clauses on one index are skipped on a server that refuses -that shape earlier as ``Query condition missed key schema element: h``. Multi-byte +that shape earlier as ``Query condition missed key schema element: h``, and the +``idx`` accept rows are skipped on a backend that answers ``InternalServerError`` +to any Query on an index with several RANGE attributes (Cassandra, see +``query_key_size_support.require_multi_range``). 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``. @@ -72,11 +75,9 @@ def test_range_value_of_1025_bytes_is_refused(self, dynamodb_client, gsi_table): ) def test_one_600_byte_range_value_is_accepted(self, dynamodb_client, gsi_table): - resp = dynamodb_client.query( - TableName=gsi_table, - **self._query("h = :h AND a = :s600", {":h": S(1, "h"), ":s600": S(600)}), - ) - assert resp["Count"] == 0 + query = self._query("h = :h AND a = :s600", {":h": S(1, "h"), ":s600": S(600)}) + require_multi_range(dynamodb_client, TableName=gsi_table, **query) + 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 From e05477b8f8fec24f16980454917e5c2269d03dc4 Mon Sep 17 00:00:00 2001 From: Lee <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 5 Nov 2026 02:09:30 +0000 Subject: [PATCH 04/21] test(query): skip later-RANGE accept rows on first-RANGE-only backends Since #429, the MongoDB and Cassandra backends refuse a key condition on a later RANGE attribute of a multi-attribute index with a ValidationException. Two rows of TestGsiQueryKeySize expect such a Query to be served, and they failed on MongoDB. They now skip when a probe gets that refusal, as the multi-range tests on main do. The refusal rows still run on those backends, because the size check answers first. --- tests/python/query_key_size_support.py | 24 ++++++++++++++++++++++++ tests/python/test_query_key_size.py | 10 ++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/tests/python/query_key_size_support.py b/tests/python/query_key_size_support.py index 2fe5c26a3..ec5823f57 100644 --- a/tests/python/query_key_size_support.py +++ b/tests/python/query_key_size_support.py @@ -121,6 +121,30 @@ def require_multi_range(client, **query) -> None: pytest.skip("multi-attribute range Query is not supported by this backend yet") +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, as ``require_multi_range`` + does. + """ + 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``.""" diff --git a/tests/python/test_query_key_size.py b/tests/python/test_query_key_size.py index fe667ffff..02b7ed956 100644 --- a/tests/python/test_query_key_size.py +++ b/tests/python/test_query_key_size.py @@ -21,8 +21,11 @@ send several RANGE clauses on one index are skipped on a server that refuses that shape earlier as ``Query condition missed key schema element: h``, and the ``idx`` accept rows are skipped on a backend that answers ``InternalServerError`` -to any Query on an index with several RANGE attributes (Cassandra, see -``query_key_size_support.require_multi_range``). Multi-byte +to any Query on an index with several RANGE attributes (see +``query_key_size_support.require_multi_range``). The ``idx`` accept rows with a +condition on a later RANGE attribute are also 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``. @@ -44,6 +47,7 @@ index_table, refused, require_multi_range, + require_served, two_hash_table, ) @@ -97,6 +101,7 @@ def test_two_range_values_totalling_1024_bytes_are_accepted( {":h": S(1, "h"), ":a": S(512, "a"), ":b": S(512, "b")}, ) require_multi_range(dynamodb_client, TableName=gsi_table, **query) + 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( @@ -134,6 +139,7 @@ def test_between_adds_its_larger_bound_to_the_range_total( "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(424, "b")}, ) + require_served(dynamodb_client, TableName=gsi_table, **accepted) assert dynamodb_client.query(TableName=gsi_table, **accepted)["Count"] == 0 From d259b6f952b138dc2ccff751a0614934a02e13a5 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:59:34 +0000 Subject: [PATCH 05/21] fix(core): read the key byte size through the key_size module in restorable_item Main added validation/restorable_item.rs, which sizes a backup item's key with key_value_byte_size from the validation module. This branch moved that function into validation/key_size.rs. The call now names the new module, as check_key_size does. --- crates/core/src/validation/restorable_item.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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(), From 001fe2903fc2f1b97e5140a948b97260bb42dacd Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:11:22 +0000 Subject: [PATCH 06/21] fix(core): check the number rules before sizing a Query key value Query sized an N value in a key condition by its digit string, so an invalid number got the key size sentence. The service checks the number first. Measured 2026-11-20 in us-east-1 on a GSI with HASH n (N), each shape twice: - 2049 or 39 digits answer "Attempting to store more than 38 significant digits in a Number", in KeyConditionExpression and in KeyConditions. - 1 followed by 2100 zeros answers "Number overflow. Attempting to store a number with magnitude larger than supported range". - The service serves 2100 zeros followed by 1. validate_query_key_sizes now passes each N value it reads to validate_and_normalize_number and sizes the normalized digits. Query served a 39-digit value before and refuses it now, as the service does. The doc comment of validate_query_key_sizes no longer lists two shapes as not measured. The wire tests assert both, a HASH sum of exactly 2048 bytes and the aggregated hash sentence over an oversized RANGE value. Both pass against the service. The comment also names a request that ExtendDB serves and the service refuses. The request has an undefined #name in a second clause, on a key schema with one HASH attribute and at most one RANGE attribute. --- crates/core/src/validation/key_size.rs | 82 ++++++++++++-------- crates/core/src/validation/key_size/tests.rs | 46 ++++++++--- 2 files changed, 87 insertions(+), 41 deletions(-) diff --git a/crates/core/src/validation/key_size.rs b/crates/core/src/validation/key_size.rs index 1ad77ba4b..6c1a26548 100644 --- a/crates/core/src/validation/key_size.rs +++ b/crates/core/src/validation/key_size.rs @@ -18,17 +18,14 @@ use crate::expression::{ }; use crate::limits::LimitsConfig; use crate::types::{AttributeValue, KeySchemaElement, KeyType}; +use crate::validation::number::validate_and_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. The service caps a number at 38 significant digits and -/// refuses a longer one on the Query path before any size check (measured -/// 2026-10-23: 39 digits and 2049 digits are both refused with -/// `Attempting to store more than 38 significant digits in a Number`). ExtendDB -/// does not validate a number in a key condition yet, so a long `N` string -/// reaches this function and is sized by its length; the Query path relies on -/// number validation that ExtendDB does not have. +/// digit string. A number that passes the number rules is normalized when the +/// request is read; on the Query path a number that breaks them is refused +/// before it is sized (see `sized_clause`). pub(super) fn key_value_byte_size(value: &AttributeValue) -> usize { match value { AttributeValue::S(s) => s.len(), @@ -111,17 +108,30 @@ enum ClauseSize { /// 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, and one that breaks +/// them is refused with the number's own sentence, never 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): 2049 or 39 digits answer `Attempting +/// to store more than 38 significant digits in a Number` in +/// `KeyConditionExpression` and in `KeyConditions`, `1` followed by 2100 zeros +/// answers `Number overflow. ...`, and 2100 zeros followed by `1` is served. +/// +/// # Errors +/// +/// Returns the number rules' `ValidationException` for an `N` value that +/// breaks them. fn sized_clause( clause: &Clause<'_>, key_schema: &[KeySchemaElement], maps: &ExpressionMaps, -) -> ClauseSize { +) -> Result { let (path, values) = clause; let Some(first) = path.first() else { - return ClauseSize::Skipped; + return Ok(ClauseSize::Skipped); }; let Ok(name) = resolve_element_name(first, maps) else { - return ClauseSize::Unresolved; + return Ok(ClauseSize::Unresolved); }; let mut size = 0; let mut placeholders = true; @@ -131,17 +141,21 @@ fn sized_clause( continue; }; let Ok(value) = maps.resolve_value(placeholder) else { - return ClauseSize::Unresolved; + return Ok(ClauseSize::Unresolved); + }; + let bytes = match value { + AttributeValue::N(n) => validate_and_normalize_number(n)?.len(), + other => key_value_byte_size(other), }; - size = size.max(key_value_byte_size(value)); + size = size.max(bytes); } let Some(key) = key_schema.iter().find(|ks| ks.attribute_name == name) else { - return ClauseSize::Skipped; + return Ok(ClauseSize::Skipped); }; if !placeholders { - return ClauseSize::Skipped; + return Ok(ClauseSize::Skipped); } - ClauseSize::Bytes(key.key_type, size) + Ok(ClauseSize::Bytes(key.key_type, size)) } /// Refuse a `Query` whose key condition carries a key value over the key size @@ -158,26 +172,30 @@ fn sized_clause( /// the range sentence. /// - The HASH checks run before the RANGE check, so the hash sentence wins when /// both limits are exceeded. +/// - An `N` value that breaks the number rules is refused with the number's +/// sentence and is not sized (see `sized_clause`). /// - If a `#name` or `:value` of any key clause is not defined, the check -/// returns `Ok` and the request gets the undefined-reference refusal it -/// already has, which the service reports ahead of the size. +/// 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, an undefined +/// `#name` in a second clause (`pk = :h AND #u > :r`) is not refused yet and +/// the Query is served, where the service refuses it. /// /// 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 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. Not measured: a HASH sum of -/// exactly 2048 bytes (treated as within the limit, as the single-value limit -/// is) and which sentence wins when the HASH sum and the RANGE sum are both -/// over (the hash sentence, as for a single HASH value). +/// 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. @@ -185,7 +203,7 @@ fn sized_clause( /// # Errors /// /// Returns `ValidationException` with the service's sentence when a limit is -/// exceeded. +/// exceeded or an `N` value breaks the number rules. pub fn validate_query_key_sizes( key_condition: &KeyCondition, key_schema: &[KeySchemaElement], @@ -196,7 +214,7 @@ pub fn validate_query_key_sizes( let mut hash_total: usize = 0; let mut range_total: usize = 0; for clause in clauses(key_condition) { - match sized_clause(&clause, key_schema, maps) { + match sized_clause(&clause, key_schema, maps)? { ClauseSize::Unresolved => return Ok(()), ClauseSize::Skipped => {} ClauseSize::Bytes(KeyType::Hash, size) => { diff --git a/crates/core/src/validation/key_size/tests.rs b/crates/core/src/validation/key_size/tests.rs index ecbb1b7a1..ef04232eb 100644 --- a/crates/core/src/validation/key_size/tests.rs +++ b/crates/core/src/validation/key_size/tests.rs @@ -511,13 +511,41 @@ fn non_scalar_values_are_skipped() { } #[test] -fn number_values_are_sized_by_their_digit_string() { - // The service refuses a number of more than 38 significant digits before - // any size check (measured 2026-10-23). ExtendDB does not validate a - // number in a key condition, so a long digit string reaches the size - // check and is sized by its length. - let kc = hash_only("pk", "v"); - let values = HashMap::from([("v".to_owned(), AttributeValue::N("1".repeat(2049)))]); - let m = ExpressionMaps::new(HashMap::new(), values); - assert_eq!(message(check(&kc, &base_schema(), &m)), HASH_MSG_2048); +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 + // that breaks the number rules gets the number's sentence, never the size + // sentence, and a valid one is sized by its normalized digits. The RANGE + // rows apply the same rule to a sort key value. + 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"; + let zeros = "0".repeat(2100); + let cases: [(&str, &str, String, Option<&str>); 6] = [ + ("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), + ("range, 1025 digits", "sk", "1".repeat(1025), Some(DIGITS)), + ("range, 2100 zeros and 1", "sk", format!("{zeros}1"), None), + ]; + for (label, attribute, n, expected) in cases { + let mut kc = hash_only("pk", "p"); + let mut values = vec![("p", s_of("p", 1))]; + if attribute == "sk" { + kc.sk_condition = Some(eq("sk", "v")); + values.push(("v", AttributeValue::N(n))); + } else { + values = 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:?}"), + } + } } From 9061b2302533a6825bccadc549d73534dd77130c Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:11:26 +0000 Subject: [PATCH 07/21] fix(query): check Select against the GSI projection after the key size With no ExclusiveStartKey, Query checked Select=ALL_ATTRIBUTES against the index projection before the other request checks. The service makes that check after the key size check. With a start key, it also comes after the start key checks. Measured 2026-11-20 in us-east-1 on a KEYS_ONLY GSI with Select=ALL_ATTRIBUTES, each shape twice: - A 2049-byte key value answers the size sentence, with and without an ExclusiveStartKey. - A 1-byte value answers the Select sentence. - Without a start key, Limit 0 and a parameter mix each answer their own refusal ahead of the Select sentence. So do an empty or invalid KeyConditionExpression, a missed key schema element, a wrong-typed key value and a filter or projection fault. ProjectionExpression with ALL_ATTRIBUTES and an unused name or value also come first. ExtendDB answered the Select sentence for all of them. The check now runs once, after the size and start key checks. The comment above the size check no longer says that the type check is still to come. The type check runs above it, in resolve_key_schema_with. The engine test comments cite the measurement dates and region, not local files. --- crates/engine/src/query.rs | 27 +++++++++++++---------- crates/engine/src/query_key_size_tests.rs | 18 +++++++-------- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 1a646cf3d..30b37aecf 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -131,12 +131,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())?; - } - // Validate Limit >= 1 (REQ-QUERY-001) if let Some(limit) = input.limit && limit < 1 @@ -492,11 +486,11 @@ pub async fn handle_query( // 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 (the type - // check arrives with the multi-attribute range change and belongs above - // this call), 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. + // condition that misses the key schema, a wrong-typed key value (checked + // above, in `resolve_key_schema_with`), 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, @@ -517,9 +511,18 @@ 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 key size and start key checks. + // Measured 2026-11-20 in us-east-1 on a KEYS_ONLY GSI with no + // ExclusiveStartKey: a 2049-byte key value answers the size, and Limit 0, + // a parameter mix, an empty or invalid KeyConditionExpression, a missed key + // schema element, a wrong-typed key value, a filter or projection fault, + // ProjectionExpression with ALL_ATTRIBUTES and an unused name or value + // each answer their own refusal. + 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 index 706216dae..d5dcd6a93 100644 --- a/crates/engine/src/query_key_size_tests.rs +++ b/crates/engine/src/query_key_size_tests.rs @@ -2,12 +2,11 @@ // SPDX-License-Identifier: Apache-2.0 //! Key size limits on a `Query` key condition, driven from the expression -//! text. Each case is a row measured on the service on 2026-10-21 (index with -//! HASH `h` and RANGE `a`, `b`, `c`, `d`), 2026-10-22 (base table with HASH -//! `pk` and RANGE `sk`) or 2026-10-23 (the operator, `BETWEEN`, binary and -//! ordering rows, recorded in the issue's fold file) or 2026-10-23 (the -//! multi-attribute, multi-byte and undefined-reference rows, recorded in -//! `service-435-review.jsonl` and `service-435-440-review-2.jsonl`). The check +//! text. Each case is a row measured on the service in us-east-1 on +//! 2026-10-21 (index with HASH `h` and RANGE `a`, `b`, `c`, `d`), 2026-10-22 +//! (base table with HASH `pk` and RANGE `sk`) or 2026-10-23 (the operator, +//! `BETWEEN`, binary, ordering, multi-attribute, multi-byte and +//! undefined-reference rows). 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. @@ -237,10 +236,9 @@ fn clause_order_does_not_change_the_result() { #[test] fn legacy_key_conditions_are_checked_like_the_expression() { - // Measured 2026-10-23 (rows `6 legacy hash 2049` and `6 legacy range 1025` - // of `service-435-shapes.jsonl`): the service sizes legacy `KeyConditions` - // with the same sentences. Both syntaxes reach the check as one key - // condition. + // 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], From b116a46cabb9417c9d5e7494021b348137f19598 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:11:30 +0000 Subject: [PATCH 08/21] test(query): add the number and Select rows and keep refusal rows visible - test_query_key_size_values.py: rows on a GSI with HASH n (N) for 2049 digits, 39 digits, 1 followed by 2100 zeros and 2100 zeros followed by 1. Each row runs in KeyConditionExpression and in KeyConditions. - test_query_key_size_order.py: rows on a KEYS_ONLY GSI for Select=ALL_ATTRIBUTES with a 2049-byte and a 1-byte value, with and without an ExclusiveStartKey. The Limit 0 row uses the raw_client fixture from conftest.py in place of its own copy. - This commit removes require_multi_range. Neither of its skips fires on any backend at this head. On a refusal row, a 500 or a classifier change turned the row into a skip. - The BETWEEN row is two tests. The refusal half reports its result on MongoDB and Cassandra, where the accept half skips. - The docstrings cite the measurement dates and region, not local files. --- tests/python/query_key_size_support.py | 41 ++++--------- tests/python/test_query_key_size.py | 51 +++++++--------- tests/python/test_query_key_size_order.py | 69 +++++++++++++--------- tests/python/test_query_key_size_values.py | 53 ++++++++++++++++- 4 files changed, 121 insertions(+), 93 deletions(-) diff --git a/tests/python/query_key_size_support.py b/tests/python/query_key_size_support.py index ec5823f57..df2448910 100644 --- a/tests/python/query_key_size_support.py +++ b/tests/python/query_key_size_support.py @@ -31,7 +31,6 @@ "One or more parameter values were invalid: " "Aggregated size of all range keys has exceeded the size limit of 1024 bytes" ) -MISSING_HASH_MESSAGE = "Query condition missed key schema element: h" def S(length: int, fill: str = "x") -> dict: @@ -96,31 +95,6 @@ def refused_ending(client, suffix: str, **query) -> None: assert err["Error"]["Message"].endswith(suffix), err["Error"]["Message"] -def require_multi_range(client, **query) -> None: - """Skip unless the server runs ``query``'s key condition on a multi-RANGE index. - - Sends ``query`` with every value cut to its first byte. A server that does - not yet serve several RANGE clauses on one index refuses it as - ``Query condition missed key schema element: h``; a backend that cannot yet - read an index with several RANGE attributes at all answers - ``InternalServerError`` to any Query on it, whatever the clause count. The - test is then skipped and passes without an edit once the server serves - the shape. - """ - 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: - err = exc.response["Error"] - if err["Message"] == MISSING_HASH_MESSAGE: - pytest.skip("multi-attribute range conditions need the #429 change") - if err["Code"] == "InternalServerError": - pytest.skip("multi-attribute range Query is not supported by this backend yet") - - FIRST_RANGE_ONLY_MARK = "applies a key condition to the first RANGE attribute" @@ -131,8 +105,7 @@ def require_served(client, **query) -> None: 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, as ``require_multi_range`` - does. + ``query`` with every value cut to its first byte. """ probe = dict(query) probe["ExpressionAttributeValues"] = { @@ -227,11 +200,15 @@ def binary_table(dynamodb_client): @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``.""" + """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")], + AttributeDefinitions=[attr(n) for n in ("pk", "sk", "l", "g", "gs")] + [attr("n", "N")], KeySchema=[key("pk", "HASH"), key("sk", "RANGE")], LocalSecondaryIndexes=[ { @@ -245,7 +222,9 @@ def index_table(dynamodb_client): "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 index 02b7ed956..233875936 100644 --- a/tests/python/test_query_key_size.py +++ b/tests/python/test_query_key_size.py @@ -12,19 +12,13 @@ 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: 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 (``issues/query-parity/service-435-shapes.jsonl``, -``service-435-review.jsonl`` and ``service-435-440-review-2.jsonl``). Rows that -send several RANGE clauses on one index are skipped on a server that refuses -that shape earlier as ``Query condition missed key schema element: h``, and the -``idx`` accept rows are skipped on a backend that answers ``InternalServerError`` -to any Query on an index with several RANGE attributes (see -``query_key_size_support.require_multi_range``). The ``idx`` accept rows with a -condition on a later RANGE attribute are also skipped on a backend that applies -a key condition to the first RANGE attribute only (MongoDB and Cassandra, see +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 @@ -46,7 +40,6 @@ gsi_table, index_table, refused, - require_multi_range, require_served, two_hash_table, ) @@ -80,7 +73,6 @@ def test_range_value_of_1025_bytes_is_refused(self, dynamodb_client, gsi_table): 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)}) - require_multi_range(dynamodb_client, TableName=gsi_table, **query) assert dynamodb_client.query(TableName=gsi_table, **query)["Count"] == 0 def test_two_600_byte_range_values_are_refused_together( @@ -90,7 +82,6 @@ def test_two_600_byte_range_values_are_refused_together( "h = :h AND a = :s600 AND b = :b AND c = :s600", {":h": S(1, "h"), ":s600": S(600), ":b": S(1, "b")}, ) - require_multi_range(dynamodb_client, TableName=gsi_table, **query) refused(dynamodb_client, RANGE_MESSAGE, TableName=gsi_table, **query) def test_two_range_values_totalling_1024_bytes_are_accepted( @@ -100,7 +91,6 @@ def test_two_range_values_totalling_1024_bytes_are_accepted( "h = :h AND a = :a AND b = :b", {":h": S(1, "h"), ":a": S(512, "a"), ":b": S(512, "b")}, ) - require_multi_range(dynamodb_client, TableName=gsi_table, **query) require_served(dynamodb_client, TableName=gsi_table, **query) assert dynamodb_client.query(TableName=gsi_table, **query)["Count"] == 0 @@ -111,7 +101,6 @@ def test_two_range_values_totalling_1025_bytes_are_refused( "h = :h AND a = :a AND b = :b", {":h": S(1, "h"), ":a": S(512, "a"), ":b": S(513, "b")}, ) - require_multi_range(dynamodb_client, TableName=gsi_table, **query) refused(dynamodb_client, RANGE_MESSAGE, TableName=gsi_table, **query) def test_a_1025_byte_non_equality_on_a_later_range_attribute_is_refused( @@ -121,24 +110,24 @@ def test_a_1025_byte_non_equality_on_a_later_range_attribute_is_refused( "h = :h AND a = :a AND b > :big", {":h": S(1, "h"), ":a": S(1, "a"), ":big": S(1025, "b")}, ) - require_multi_range(dynamodb_client, TableName=gsi_table, **query) 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: 1 and 600 (1200) is refused, - # 1 and 424 (1024) is accepted. - refusing = 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(600, "b")}, - ) - require_multi_range(dynamodb_client, TableName=gsi_table, **refusing) - refused(dynamodb_client, RANGE_MESSAGE, TableName=gsi_table, **refusing) - accepted = 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(424, "b")}, - ) + # 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 diff --git a/tests/python/test_query_key_size_order.py b/tests/python/test_query_key_size_order.py index c65a54d85..7c0b8257a 100644 --- a/tests/python/test_query_key_size_order.py +++ b/tests/python/test_query_key_size_order.py @@ -4,15 +4,16 @@ """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 -2026-10-23 (``issues/query-parity/service-435-shapes.jsonl`` rows 8a to 8h and -``service-435-review.jsonl`` rows 7a to 7h): a missing table, a wrong +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. +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). 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 @@ -21,10 +22,6 @@ from __future__ import annotations -import os - -import boto3 -import botocore.config import pytest from botocore.exceptions import ClientError @@ -39,24 +36,6 @@ BIG = S(2049, "p") -@pytest.fixture(scope="module") -def unvalidated_client(endpoint_url): - """A client with botocore parameter validation off, so Limit 0 reaches the server.""" - kwargs: dict = { - "service_name": "dynamodb", - "region_name": os.environ.get("AWS_DEFAULT_REGION", "us-east-1"), - "config": botocore.config.Config( - parameter_validation=False, retries={"max_attempts": 0} - ), - } - if endpoint_url: - kwargs["endpoint_url"] = endpoint_url - if endpoint_url.startswith("https://"): - ca_cert = os.environ.get("EXTENDDB_CA_CERT", "") - kwargs["verify"] = ca_cert if ca_cert else False - return boto3.client(**kwargs) - - def _error(client, **query) -> dict: with pytest.raises(ClientError) as exc_info: client.query(**query) @@ -116,9 +95,9 @@ def test_consistent_read_on_a_gsi_is_reported_first(dynamodb_client, index_table assert err["Message"] == "Consistent reads are not supported on global secondary indexes" -def test_limit_zero_is_reported_first(unvalidated_client, index_table): +def test_limit_zero_is_reported_first(raw_client, index_table): err = _error( - unvalidated_client, + raw_client, TableName=index_table, Limit=0, KeyConditionExpression="pk = :p", @@ -262,3 +241,37 @@ def test_exclusive_start_key_of_the_wrong_type_is_reported_after( 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")} + + +@pytest.mark.parametrize( + ("value", "start_key", "message"), + [ + pytest.param(BIG, None, HASH_MESSAGE, id="2049-bytes"), + pytest.param(BIG, START_KEY, HASH_MESSAGE, id="2049-bytes-with-a-start-key"), + pytest.param(S(1, "x"), None, SELECT_ON_KEYS_ONLY_MESSAGE, id="1-byte"), + pytest.param(S(1, "x"), START_KEY, SELECT_ON_KEYS_ONLY_MESSAGE, id="1-byte-with-a-start-key"), + ], +) +def test_select_all_attributes_on_a_keys_only_gsi_is_reported_after( + dynamodb_client, index_table, value, start_key, message +): + # Measured 2026-11-20 in us-east-1, each shape twice. + query = { + "TableName": index_table, + "IndexName": "gko", + "Select": "ALL_ATTRIBUTES", + "KeyConditionExpression": "g = :v", + "ExpressionAttributeValues": {":v": value}, + } + if start_key is not None: + query["ExclusiveStartKey"] = start_key + err = _error(dynamodb_client, **query) + assert err["Code"] == "ValidationException" + assert err["Message"] == message diff --git a/tests/python/test_query_key_size_values.py b/tests/python/test_query_key_size_values.py index 9b6e40b80..7a7829799 100644 --- a/tests/python/test_query_key_size_values.py +++ b/tests/python/test_query_key_size_values.py @@ -2,14 +2,16 @@ # SPDX-License-Identifier: Apache-2.0 """Query key size rows for multi-byte values, ordered BETWEEN bounds, undefined -references, a hash-only table and a GSI. +references, a hash-only table, a GSI and number key values. -Measured on the service on 2026-10-23 (``issues/query-parity/service-435-review.jsonl``, -labels 1 to 4, 6, 10). The main key size rows are in ``test_query_key_size.py``. +Measured on the service in us-east-1 on 2026-10-23, the number rows on +2026-11-20. 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, @@ -181,3 +183,48 @@ def test_an_lsi_begins_with_of_1025_bytes_is_refused( 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" +) + + +class TestNumberKeyValues: + """GSI ``ngsi`` with HASH ``n`` (N), measured 2026-11-20 in us-east-1. + + A number that breaks the number rules gets the number's sentence, not the + size sentence, and a valid number is sized after it is normalized, so 2100 + zeros followed by ``1`` is served. + """ + + @pytest.mark.parametrize("syntax", ["expression", "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"), + ], + ) + def test_a_number_is_checked_before_it_is_sized( + self, dynamodb_client, index_table, number, message, syntax + ): + if syntax == "expression": + condition = { + "KeyConditionExpression": "n = :v", + "ExpressionAttributeValues": {":v": {"N": number}}, + } + else: + condition = { + "KeyConditions": { + "n": {"ComparisonOperator": "EQ", "AttributeValueList": [{"N": number}]} + } + } + query = {"TableName": index_table, "IndexName": "ngsi", **condition} + if message is None: + assert dynamodb_client.query(**query)["Count"] == 0 + else: + refused(dynamodb_client, message, **query) From aa30100c986a4589ff4763a32ee7599f88544a69 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:29:35 +0000 Subject: [PATCH 09/21] docs(core): cite #1214 for the undefined name that Query serves The doc comment of validate_query_key_sizes names one request that ExtendDB serves and the service refuses: an undefined #name in a second key condition clause. #1214 tracks that request. --- crates/core/src/validation/key_size.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/core/src/validation/key_size.rs b/crates/core/src/validation/key_size.rs index 6c1a26548..6d4b7f963 100644 --- a/crates/core/src/validation/key_size.rs +++ b/crates/core/src/validation/key_size.rs @@ -179,7 +179,7 @@ fn sized_clause( /// of the size. ExtendDB refuses most such requests later on. On a key /// schema with one HASH and at most one RANGE attribute, an undefined /// `#name` in a second clause (`pk = :h AND #u > :r`) is not refused yet and -/// the Query is served, where the service refuses it. +/// the Query is served, where the service refuses it (#1214). /// /// All limits are inclusive. `key_schema` is the key schema being queried: the /// index's for an index query, the table's otherwise. From ac99d0a5fb0399c614b2cac7aa42f1f7d407dcae Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:40:43 +0000 Subject: [PATCH 10/21] docs(query): split the long sentences in four new comments Four new comments now use shorter sentences. They are the number rules in sized_clause and its unit test, the undefined #name in validate_query_key_sizes and the Select check in handle_query. They state the same measurements. --- crates/core/src/validation/key_size.rs | 17 +++++++++-------- crates/core/src/validation/key_size/tests.rs | 6 +++--- crates/engine/src/query.rs | 10 +++++----- 3 files changed, 17 insertions(+), 16 deletions(-) diff --git a/crates/core/src/validation/key_size.rs b/crates/core/src/validation/key_size.rs index 6d4b7f963..a1724dd6f 100644 --- a/crates/core/src/validation/key_size.rs +++ b/crates/core/src/validation/key_size.rs @@ -112,10 +112,10 @@ enum ClauseSize { /// An `N` value is checked against the number rules first, and one that breaks /// them is refused with the number's own sentence, never 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): 2049 or 39 digits answer `Attempting -/// to store more than 38 significant digits in a Number` in -/// `KeyConditionExpression` and in `KeyConditions`, `1` followed by 2100 zeros -/// answers `Number overflow. ...`, and 2100 zeros followed by `1` is served. +/// 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`. /// /// # Errors /// @@ -176,10 +176,11 @@ fn sized_clause( /// sentence and is not sized (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, an undefined -/// `#name` in a second clause (`pk = :h AND #u > :r`) is not refused yet and -/// the Query is served, where the service refuses it (#1214). +/// of the size. ExtendDB refuses most such requests later on. One exception +/// remains. ExtendDB does not refuse an undefined `#name` in a second clause +/// when the key schema has one HASH and at most one RANGE attribute. It +/// serves such a Query, for example `pk = :h AND #u > :r`, and the service +/// refuses it (#1214). /// /// All limits are inclusive. `key_schema` is the key schema being queried: the /// index's for an index query, the table's otherwise. diff --git a/crates/core/src/validation/key_size/tests.rs b/crates/core/src/validation/key_size/tests.rs index ef04232eb..015fa55aa 100644 --- a/crates/core/src/validation/key_size/tests.rs +++ b/crates/core/src/validation/key_size/tests.rs @@ -512,10 +512,10 @@ fn non_scalar_values_are_skipped() { #[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 + // Measured 2026-11-20 in us-east-1 on a GSI with HASH `n` (N). A number // that breaks the number rules gets the number's sentence, never the size - // sentence, and a valid one is sized by its normalized digits. The RANGE - // rows apply the same rule to a sort key value. + // sentence. A valid one is sized by its normalized digits. The RANGE rows + // apply the same rule to a sort key value. 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"; diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 30b37aecf..196048b38 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -516,11 +516,11 @@ pub async fn handle_query( // Select=ALL_ATTRIBUTES requires an ALL-projection GSI (shared with Scan). // The service makes this check after the key size and start key checks. // Measured 2026-11-20 in us-east-1 on a KEYS_ONLY GSI with no - // ExclusiveStartKey: a 2049-byte key value answers the size, and Limit 0, - // a parameter mix, an empty or invalid KeyConditionExpression, a missed key - // schema element, a wrong-typed key value, a filter or projection fault, - // ProjectionExpression with ALL_ATTRIBUTES and an unused name or value - // each answer their own refusal. + // ExclusiveStartKey: a 2049-byte key value answers the size. Limit 0, a + // parameter mix and an empty or invalid KeyConditionExpression each answer + // their own refusal. So do a missed key schema element, a wrong-typed key + // value and a filter or projection fault. ProjectionExpression with + // ALL_ATTRIBUTES and an unused name or value come first as well. validate_query_select_index_support(input.select, index_info.as_ref())?; // Determine which key schema to use for LastEvaluatedKey extraction. From 31159a2afde69099afc9364476c0e4933e70309d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:40:38 +0000 Subject: [PATCH 11/21] fix(core): size a Query key number the validator does not read by its text 001fe2903 sized each N value of a key condition after validate_and_normalize_number, so a number written in other Unicode decimal digits got a 400. DynamoDB reads U+FF11 and U+0967 U+0968 as digits. It serves `n = :v` and the KeyConditions form with those values (200, Count 0, measured 2026-11-20 in us-east-1, twice each), and so did the previous head. The size check now calls normalize_number and refuses only the digit count and magnitude faults. A value the validator does not read as a number is sized by its text again, as before 001fe2903. The unit table and TestNumberKeyValues gain the two values, in both syntaxes. The Select test uses the shared refused helper. Its 1-byte row without a start key goes, because test_query_start_key_partition.py sends the same request. Two comments are shorter. --- crates/core/src/validation/key_size.rs | 30 +++++++++++++------- crates/core/src/validation/key_size/tests.rs | 27 +++++++++++------- crates/engine/src/query.rs | 10 ++----- tests/python/test_query_key_size_order.py | 6 ++-- tests/python/test_query_key_size_values.py | 9 ++++-- 5 files changed, 47 insertions(+), 35 deletions(-) diff --git a/crates/core/src/validation/key_size.rs b/crates/core/src/validation/key_size.rs index a1724dd6f..d5ad81f29 100644 --- a/crates/core/src/validation/key_size.rs +++ b/crates/core/src/validation/key_size.rs @@ -18,7 +18,7 @@ use crate::expression::{ }; use crate::limits::LimitsConfig; use crate::types::{AttributeValue, KeySchemaElement, KeyType}; -use crate::validation::number::validate_and_normalize_number; +use crate::validation::number::normalize_number; /// Byte size of a key attribute value. /// @@ -119,8 +119,8 @@ enum ClauseSize { /// /// # Errors /// -/// Returns the number rules' `ValidationException` for an `N` value that -/// breaks them. +/// Returns the number's `ValidationException` for an `N` value with more +/// than 38 significant digits or a magnitude out of range. fn sized_clause( clause: &Clause<'_>, key_schema: &[KeySchemaElement], @@ -144,7 +144,14 @@ fn sized_clause( return Ok(ClauseSize::Unresolved); }; let bytes = match value { - AttributeValue::N(n) => validate_and_normalize_number(n)?.len(), + // The service reads Unicode decimal digits such as U+FF11 as + // digits, and `normalize_number` refuses them, so a value it does + // not read as a number is sized by its text (measured 2026-11-20). + AttributeValue::N(n) => match normalize_number(n) { + Ok(digits) => digits.len(), + Err(fault) if fault.is_not_a_number() => n.len(), + Err(fault) => return Err(fault.error(n)), + }, other => key_value_byte_size(other), }; size = size.max(bytes); @@ -172,15 +179,16 @@ fn sized_clause( /// the range sentence. /// - The HASH checks run before the RANGE check, so the hash sentence wins when /// both limits are exceeded. -/// - An `N` value that breaks the number rules is refused with the number's -/// sentence and is not sized (see `sized_clause`). +/// - An `N` value with more than 38 significant digits or a magnitude out of +/// range is refused with the number's sentence and is not sized. A value +/// the number validator does not read as a number is sized by its text +/// (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. One exception -/// remains. ExtendDB does not refuse an undefined `#name` in a second clause -/// when the key schema has one HASH and at most one RANGE attribute. It -/// serves such a Query, for example `pk = :h AND #u > :r`, and the service -/// refuses it (#1214). +/// 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. diff --git a/crates/core/src/validation/key_size/tests.rs b/crates/core/src/validation/key_size/tests.rs index 015fa55aa..a800da4d8 100644 --- a/crates/core/src/validation/key_size/tests.rs +++ b/crates/core/src/validation/key_size/tests.rs @@ -513,14 +513,15 @@ fn non_scalar_values_are_skipped() { #[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 - // that breaks the number rules gets the number's sentence, never the size - // sentence. A valid one is sized by its normalized digits. The RANGE rows - // apply the same rule to a sort key value. + // 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. 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"; let zeros = "0".repeat(2100); - let cases: [(&str, &str, String, Option<&str>); 6] = [ + let cases: [(&str, &str, String, Option<&str>); 8] = [ ("hash, 2049 digits", "pk", "1".repeat(2049), Some(DIGITS)), ("hash, 39 digits", "pk", "1".repeat(39), Some(DIGITS)), ( @@ -530,18 +531,24 @@ fn number_values_get_the_number_rules_before_any_size() { 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), ]; for (label, attribute, n, expected) in cases { - let mut kc = hash_only("pk", "p"); - let mut values = vec![("p", s_of("p", 1))]; - if attribute == "sk" { + let (kc, values) = if attribute == "sk" { + let mut kc = hash_only("pk", "p"); kc.sk_condition = Some(eq("sk", "v")); - values.push(("v", AttributeValue::N(n))); + (kc, vec![("p", s_of("p", 1)), ("v", AttributeValue::N(n))]) } else { - values = vec![("p", AttributeValue::N(n))]; - } + (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}"), diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 196048b38..9172aaed4 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -514,13 +514,9 @@ pub async fn handle_query( } // Select=ALL_ATTRIBUTES requires an ALL-projection GSI (shared with Scan). - // The service makes this check after the key size and start key checks. - // Measured 2026-11-20 in us-east-1 on a KEYS_ONLY GSI with no - // ExclusiveStartKey: a 2049-byte key value answers the size. Limit 0, a - // parameter mix and an empty or invalid KeyConditionExpression each answer - // their own refusal. So do a missed key schema element, a wrong-typed key - // value and a filter or projection fault. ProjectionExpression with - // ALL_ATTRIBUTES and an unused name or value come first as well. + // 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. diff --git a/tests/python/test_query_key_size_order.py b/tests/python/test_query_key_size_order.py index 7c0b8257a..9368419c6 100644 --- a/tests/python/test_query_key_size_order.py +++ b/tests/python/test_query_key_size_order.py @@ -30,6 +30,7 @@ HASH_MESSAGE, S, index_table, + refused, refused_ending, ) @@ -255,7 +256,6 @@ def test_exclusive_start_key_of_the_wrong_type_is_reported_after( [ pytest.param(BIG, None, HASH_MESSAGE, id="2049-bytes"), pytest.param(BIG, START_KEY, HASH_MESSAGE, id="2049-bytes-with-a-start-key"), - pytest.param(S(1, "x"), None, SELECT_ON_KEYS_ONLY_MESSAGE, id="1-byte"), pytest.param(S(1, "x"), START_KEY, SELECT_ON_KEYS_ONLY_MESSAGE, id="1-byte-with-a-start-key"), ], ) @@ -272,6 +272,4 @@ def test_select_all_attributes_on_a_keys_only_gsi_is_reported_after( } if start_key is not None: query["ExclusiveStartKey"] = start_key - err = _error(dynamodb_client, **query) - assert err["Code"] == "ValidationException" - assert err["Message"] == message + refused(dynamodb_client, message, **query) diff --git a/tests/python/test_query_key_size_values.py b/tests/python/test_query_key_size_values.py index 7a7829799..8dfce815d 100644 --- a/tests/python/test_query_key_size_values.py +++ b/tests/python/test_query_key_size_values.py @@ -194,9 +194,10 @@ def test_an_lsi_begins_with_of_1025_bytes_is_refused( class TestNumberKeyValues: """GSI ``ngsi`` with HASH ``n`` (N), measured 2026-11-20 in us-east-1. - A number that breaks the number rules gets the number's sentence, not the - size sentence, and a valid number is sized after it is normalized, so 2100 - zeros followed by ``1`` is served. + 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. """ @pytest.mark.parametrize("syntax", ["expression", "legacy"]) @@ -207,6 +208,8 @@ class TestNumberKeyValues: 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( From a3f733db956aabdb041c1d828165716f1e62da41 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:41:14 +0000 Subject: [PATCH 12/21] fix(core): do not size a Query key N value that is not a number 31159a2af sized an N value that normalize_number does not read as a number by its text. So 2049 `x` or 2049 U+FF11 in a key condition got the hash size sentence. DynamoDB refuses such a value with a number sentence before it looks up the table (measured 2026-11-24 in us-east-1, twice each). 2049 `x` gets `The parameter cannot be converted to a numeric value: ` and the value, in KeyConditionExpression and in KeyConditions. 39 U+FF11 get `Attempting to store more than 38 significant digits in a Number`. Such a value now adds nothing to the size, and ExtendDB serves the Query as main does. The number check of key condition values is #544's. The unit table gains a 2049 `x` row and a 2049 U+FF11 row. --- crates/core/src/validation/key_size.rs | 36 ++++++++++++-------- crates/core/src/validation/key_size/tests.rs | 11 ++++-- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/crates/core/src/validation/key_size.rs b/crates/core/src/validation/key_size.rs index d5ad81f29..d32c0a668 100644 --- a/crates/core/src/validation/key_size.rs +++ b/crates/core/src/validation/key_size.rs @@ -24,8 +24,8 @@ use crate::validation::number::normalize_number; /// /// `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; on the Query path a number that breaks them is refused -/// before it is sized (see `sized_clause`). +/// 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(), @@ -109,13 +109,22 @@ enum ClauseSize { /// 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, and one that breaks -/// them is refused with the number's own sentence, never 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`. +/// 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`. +/// +/// A value that `normalize_number` does not read as a number adds nothing to +/// the size. The service refuses such a value with a number sentence, not a +/// size sentence (measured 2026-11-24 in us-east-1). `abc` and 2049 `x` +/// answer `The parameter cannot be converted to a numeric value: ` followed +/// by the value, in `KeyConditionExpression` and in `KeyConditions`. The +/// service reads U+FF11 as a digit, and 39 of them answer the 38-digit +/// sentence. /// /// # Errors /// @@ -144,12 +153,9 @@ fn sized_clause( return Ok(ClauseSize::Unresolved); }; let bytes = match value { - // The service reads Unicode decimal digits such as U+FF11 as - // digits, and `normalize_number` refuses them, so a value it does - // not read as a number is sized by its text (measured 2026-11-20). AttributeValue::N(n) => match normalize_number(n) { Ok(digits) => digits.len(), - Err(fault) if fault.is_not_a_number() => n.len(), + Err(fault) if fault.is_not_a_number() => 0, Err(fault) => return Err(fault.error(n)), }, other => key_value_byte_size(other), @@ -181,8 +187,8 @@ fn sized_clause( /// both limits are exceeded. /// - An `N` value with more than 38 significant digits or a magnitude out of /// range is refused with the number's sentence and is not sized. A value -/// the number validator does not read as a number is sized by its text -/// (see `sized_clause`). +/// the number validator does not read as a number 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 diff --git a/crates/core/src/validation/key_size/tests.rs b/crates/core/src/validation/key_size/tests.rs index a800da4d8..7fcb39d0c 100644 --- a/crates/core/src/validation/key_size/tests.rs +++ b/crates/core/src/validation/key_size/tests.rs @@ -516,12 +516,17 @@ fn number_values_get_the_number_rules_before_any_size() { // 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. + // The RANGE rows apply the same rule to a sort key value. The 2049 `x` + // and 2049 U+FF11 rows are values the validator does not read as a + // number: they add nothing, so the size check passes them. The service + // refuses them with a number sentence (measured 2026-11-24: `The parameter + // cannot be converted to a numeric value: xxx...` for 2049 `x`, and the + // digit sentence for 39 U+FF11). 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"; let zeros = "0".repeat(2100); - let cases: [(&str, &str, String, Option<&str>); 8] = [ + let cases: [(&str, &str, String, Option<&str>); 10] = [ ("hash, 2049 digits", "pk", "1".repeat(2049), Some(DIGITS)), ("hash, 39 digits", "pk", "1".repeat(39), Some(DIGITS)), ( @@ -540,6 +545,8 @@ fn number_values_get_the_number_rules_before_any_size() { ), ("range, 1025 digits", "sk", "1".repeat(1025), Some(DIGITS)), ("range, 2100 zeros and 1", "sk", format!("{zeros}1"), None), + ("hash, 2049 x", "pk", "x".repeat(2049), None), + ("hash, 2049 U+FF11", "pk", "\u{ff11}".repeat(2049), None), ]; for (label, attribute, n, expected) in cases { let (kc, values) = if attribute == "sk" { From 762d4a84ae4a756ac45130b82bc34694f8e15dac Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:51:00 +0000 Subject: [PATCH 13/21] test(query): fold the key size rows into two tables query_key_size_tests.rs had 19 tests that sent rows of the core tests through the expression parser. The wire files send the same rows end to end. The file keeps the two tests that add a path: the clause order in the expression, and the KeyConditions desugaring. The comments of two deleted index tests named a gate that b116a46ca took out. In the core tests, one table holds the equality rows on the base table, on `idx` and on `two-hash`. A second table holds the six undefined-reference rows. Each row keeps its measurement comment. Two rows have measurements from 2026-11-20 on `two-hash`, and their comments no longer say "Not measured". They are a HASH sum of exactly 2048 bytes, and the aggregated hash sentence with a 1025-byte RANGE value. Two tests checked the end of a sentence that a table row asserts in full, and they are gone. --- crates/core/src/validation/key_size/tests.rs | 304 +++++++------------ crates/engine/src/query_key_size_tests.rs | 235 +------------- 2 files changed, 118 insertions(+), 421 deletions(-) diff --git a/crates/core/src/validation/key_size/tests.rs b/crates/core/src/validation/key_size/tests.rs index 7fcb39d0c..56d17fbae 100644 --- a/crates/core/src/validation/key_size/tests.rs +++ b/crates/core/src/validation/key_size/tests.rs @@ -116,78 +116,73 @@ fn message(result: Result<(), DynamoDbError>) -> String { } } -#[test] -fn hash_value_of_2048_bytes_is_accepted() { - let kc = hash_only("pk", "v"); - assert!(check(&kc, &base_schema(), &maps(&[("v", 2048)])).is_ok()); -} - -#[test] -fn hash_value_of_2049_bytes_is_refused_with_the_service_sentence() { - let kc = hash_only("pk", "v"); - let msg = message(check(&kc, &base_schema(), &maps(&[("v", 2049)]))); - assert_eq!(msg, HASH_MSG_2048); -} - -#[test] -fn hash_sentence_has_no_space_between_of_and_the_number() { - let kc = hash_only("pk", "v"); - let msg = message(check(&kc, &base_schema(), &maps(&[("v", 2049)]))); - assert!(msg.ends_with("limit of2048 bytes"), "got: {msg}"); -} - -#[test] -fn range_value_of_1024_bytes_is_accepted() { - let mut kc = hash_only("pk", "p"); - kc.sk_condition = Some(eq("sk", "v")); - assert!(check(&kc, &base_schema(), &maps(&[("p", 1), ("v", 1024)])).is_ok()); -} - -#[test] -fn range_value_of_1025_bytes_is_refused_with_the_service_sentence() { - let mut kc = hash_only("pk", "p"); - kc.sk_condition = Some(eq("sk", "v")); - let msg = message(check(&kc, &base_schema(), &maps(&[("p", 1), ("v", 1025)]))); - assert_eq!(msg, RANGE_MSG_1024); -} - -#[test] -fn two_range_values_are_added_together() { - // 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. - let mut kc = hash_only("h", "h"); - kc.sk_condition = Some(eq("a", "x")); - kc.extra_sk_conditions = vec![(path("b"), placeholder("y")), (path("c"), placeholder("z"))]; - let m = maps(&[("h", 1), ("x", 600), ("y", 1), ("z", 600)]); - assert_eq!( - message(check(&kc, &multi_range_schema(), &m)), - RANGE_MSG_1024 - ); -} - -#[test] -fn one_600_byte_range_value_on_a_multi_range_index_is_accepted() { - // Measured 2026-10-23 on `idx`. - let mut kc = hash_only("h", "h"); - kc.sk_condition = Some(eq("a", "x")); - let m = maps(&[("h", 1), ("x", 600)]); - assert!(check(&kc, &multi_range_schema(), &m).is_ok()); -} - -#[test] -fn two_range_values_totalling_exactly_1024_are_accepted_and_1025_refused() { - // Measured 2026-10-23 on `idx`: 512 and 512 pass, 512 and 513 are refused. - let mut kc = hash_only("h", "h"); - kc.sk_condition = Some(eq("a", "x")); - kc.extra_sk_conditions = vec![(path("b"), placeholder("y"))]; - let m = maps(&[("h", 1), ("x", 512), ("y", 512)]); - assert!(check(&kc, &multi_range_schema(), &m).is_ok()); - let m = maps(&[("h", 1), ("x", 512), ("y", 513)]); - assert_eq!( - message(check(&kc, &multi_range_schema(), &m)), - RANGE_MSG_1024 - ); +/// 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() { + 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); + // The key schema, the `attribute = :v` clauses with the bytes of each + // value, and the expected sentence (`None` for `Ok`). + let cases: [(&[KeySchemaElement], &[(&str, usize)], Option<&str>); 16] = [ + // 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), + ]; + 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] @@ -310,82 +305,6 @@ fn every_comparison_operator_and_begins_with_are_sized() { } } -#[test] -fn the_hash_sentence_wins_when_both_limits_are_exceeded() { - let mut kc = hash_only("pk", "p"); - kc.sk_condition = Some(eq("sk", "v")); - let m = maps(&[("p", 2049), ("v", 1025)]); - assert_eq!(message(check(&kc, &base_schema(), &m)), HASH_MSG_2048); -} - -fn two_hash_condition() -> KeyCondition { - let mut kc = hash_only("h1", "x"); - kc.extra_pk_conditions = vec![(path("h2"), placeholder("y"))]; - kc -} - -#[test] -fn one_hash_value_over_the_limit_gets_the_single_sentence() { - // Measured 2026-10-23 on `two-hash`: `h1` of 2049 bytes and `h2` of 1 byte. - let kc = two_hash_condition(); - let m = maps(&[("x", 2049), ("y", 1)]); - assert_eq!(message(check(&kc, &two_hash_schema(), &m)), HASH_MSG_2048); - let m = maps(&[("x", 1), ("y", 2049)]); - assert_eq!(message(check(&kc, &two_hash_schema(), &m)), HASH_MSG_2048); -} - -#[test] -fn hash_values_that_add_up_over_the_limit_get_the_aggregated_sentence() { - // Measured 2026-10-23 on `two-hash`: 1025 and 1024 bytes (sum 2049, neither - // over) and 2048 and 2048 bytes are both refused. - let kc = two_hash_condition(); - for (x, y) in [(1025, 1024), (2048, 2048)] { - let m = maps(&[("x", x), ("y", y)]); - assert_eq!( - message(check(&kc, &two_hash_schema(), &m)), - HASH_TOTAL_MSG_2048, - "{x} + {y}" - ); - } -} - -#[test] -fn hash_values_that_add_up_to_exactly_the_limit_are_accepted() { - // Not measured: a sum of exactly 2048 bytes. Treated as within the limit, - // as a single 2048-byte value is (measured). - let kc = two_hash_condition(); - let m = maps(&[("x", 1024), ("y", 1024)]); - assert!(check(&kc, &two_hash_schema(), &m).is_ok()); -} - -#[test] -fn the_aggregated_hash_sentence_has_a_space_before_the_number() { - let kc = two_hash_condition(); - let m = maps(&[("x", 1025), ("y", 1024)]); - let msg = message(check(&kc, &two_hash_schema(), &m)); - assert!(msg.ends_with("size limit of 2048 bytes"), "got: {msg}"); -} - -#[test] -fn a_hash_sum_over_the_limit_wins_over_the_range_sum() { - // Not measured: both the HASH sum and the RANGE sum over. The hash - // sentences come first, as the single hash sentence does (measured). - let mut kc = two_hash_condition(); - kc.sk_condition = Some(eq("r", "z")); - let m = maps(&[("x", 1025), ("y", 1024), ("z", 1025)]); - assert_eq!( - message(check(&kc, &two_hash_schema(), &m)), - HASH_TOTAL_MSG_2048 - ); -} - -#[test] -fn the_single_hash_sentence_wins_over_the_aggregated_one() { - let kc = two_hash_condition(); - let m = maps(&[("x", 2049), ("y", 2048)]); - assert_eq!(message(check(&kc, &two_hash_schema(), &m)), HASH_MSG_2048); -} - #[test] fn binary_values_count_their_bytes() { let kc = hash_only("pk", "v"); @@ -455,48 +374,53 @@ fn a_clause_on_an_attribute_outside_the_key_schema_adds_nothing() { } #[test] -fn an_undefined_value_placeholder_on_the_clause_itself_returns_ok() { - let kc = hash_only("pk", "missing"); - assert!(check(&kc, &base_schema(), &maps(&[("v", 5000)])).is_ok()); -} - -#[test] -fn an_undefined_name_reference_on_the_clause_itself_returns_ok() { - let kc = hash_only("#nope", "v"); - assert!(check(&kc, &base_schema(), &maps(&[("v", 5000)])).is_ok()); -} - -#[test] -fn an_undefined_value_in_another_clause_wins_over_the_size_of_a_defined_one() { - // 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. - let mut kc = hash_only("pk", "v"); - kc.sk_condition = Some(eq("sk", "missing")); - assert!(check(&kc, &base_schema(), &maps(&[("v", 2049)])).is_ok()); -} - -#[test] -fn an_undefined_name_in_another_clause_wins_over_the_size_of_a_defined_one() { - // 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. - let mut kc = hash_only("pk", "v"); - kc.sk_condition = Some(eq("#n", "w")); - assert!(check(&kc, &base_schema(), &maps(&[("v", 2049), ("w", 1)])).is_ok()); -} - -#[test] -fn an_undefined_reference_wins_whatever_its_position() { - // The oversized clause may come before or after the undefined one. - let mut kc = hash_only("pk", "missing"); - kc.sk_condition = Some(eq("sk", "v")); - assert!(check(&kc, &base_schema(), &maps(&[("v", 5000)])).is_ok()); -} - -#[test] -fn an_undefined_bound_of_a_between_returns_ok() { - let mut kc = hash_only("pk", "p"); - kc.sk_condition = Some(between("sk", "l", "missing")); - assert!(check(&kc, &base_schema(), &maps(&[("p", 1), ("l", 5000)])).is_ok()); +fn an_undefined_reference_returns_ok_whatever_the_sizes() { + let with_sort = |pk_value: &str, sk: SortKeyCondition| KeyCondition { + sk_condition: Some(sk), + ..hash_only("pk", pk_value) + }; + let cases: [(&str, KeyCondition, &[(&str, usize)]); 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] diff --git a/crates/engine/src/query_key_size_tests.rs b/crates/engine/src/query_key_size_tests.rs index d5dcd6a93..3b9b35ac7 100644 --- a/crates/engine/src/query_key_size_tests.rs +++ b/crates/engine/src/query_key_size_tests.rs @@ -1,12 +1,9 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! Key size limits on a `Query` key condition, driven from the expression -//! text. Each case is a row measured on the service in us-east-1 on -//! 2026-10-21 (index with HASH `h` and RANGE `a`, `b`, `c`, `d`), 2026-10-22 -//! (base table with HASH `pk` and RANGE `sk`) or 2026-10-23 (the operator, -//! `BETWEEN`, binary, ordering, multi-attribute, multi-byte and -//! undefined-reference rows). The check +//! 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. @@ -23,8 +20,6 @@ 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 HASH_TOTAL_MSG: &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: &str = "One or more parameter values were invalid: \ Aggregated size of all range keys has exceeded the size limit of 1024 bytes"; @@ -39,16 +34,6 @@ fn base_schema() -> Vec { vec![ks("pk", KeyType::Hash), ks("sk", KeyType::Range)] } -fn index_schema() -> Vec { - vec![ - ks("h", KeyType::Hash), - ks("a", KeyType::Range), - ks("b", KeyType::Range), - ks("c", KeyType::Range), - ks("d", KeyType::Range), - ] -} - fn s(len: usize) -> AttributeValue { AttributeValue::S("x".repeat(len)) } @@ -59,17 +44,6 @@ fn run( expr: &str, schema: &[KeySchemaElement], values: &[(&str, AttributeValue)], -) -> Result<(), DynamoDbError> { - run_with_names(expr, schema, &[], values) -} - -/// [`run`] with `ExpressionAttributeNames` (`#name` keys are given without the -/// hash). -fn run_with_names( - expr: &str, - schema: &[KeySchemaElement], - names: &[(&str, &str)], - values: &[(&str, AttributeValue)], ) -> Result<(), DynamoDbError> { let limits = LimitsConfig::default(); let key_condition = parse_key_condition_expr(expr, &limits).expect("expression parses"); @@ -77,11 +51,7 @@ fn run_with_names( .iter() .map(|(name, value)| ((*name).to_owned(), value.clone())) .collect(); - let names: HashMap = names - .iter() - .map(|(name, attr)| ((*name).to_owned(), (*attr).to_owned())) - .collect(); - let maps = ExpressionMaps::new(names, values); + let maps = ExpressionMaps::new(HashMap::new(), values); validate_query_key_sizes(&key_condition, schema, &maps, &limits) } @@ -92,132 +62,6 @@ fn refused(result: Result<(), DynamoDbError>) -> String { } } -#[test] -fn index_hash_value_of_2049_bytes_is_refused() { - let result = run("h = :big", &index_schema(), &[("big", s(2049))]); - assert_eq!(refused(result), HASH_MSG); -} - -#[test] -fn index_range_value_of_1025_bytes_is_refused() { - let result = run( - "h = :h AND a = :big", - &index_schema(), - &[("h", s(1)), ("big", s(1025))], - ); - assert_eq!(refused(result), RANGE_MSG); -} - -#[test] -fn index_two_600_byte_range_values_are_refused_together() { - // The wire row is `TestGsiQueryKeySize::test_two_600_byte_range_values_are_refused_together`. - // On a build without the multi-attribute range change the handler refuses - // this shape as `Query condition missed key schema element: h` before it - // reaches this function, so only the wire row, gated on that change, shows - // the end-to-end answer. - let values = [("h", s(1)), ("s", s(600)), ("b", s(1))]; - let result = run( - "h = :h AND a = :s AND b = :b AND c = :s", - &index_schema(), - &values, - ); - assert_eq!(refused(result), RANGE_MSG); -} - -#[test] -fn index_one_600_byte_range_value_is_accepted() { - // Gated wire row: `TestGsiQueryKeySize::test_two_600_byte_range_values_are_refused_together` - // (the same shape with the second 600-byte value removed passes on the - // service). The handler refuses three clauses on one HASH and several - // RANGE attributes before this function on a build without the - // multi-attribute range change. - let values = [("h", s(1)), ("s", s(600)), ("b", s(1))]; - let result = run("h = :h AND a = :s AND b = :b", &index_schema(), &values); - assert!(result.is_ok()); -} - -#[test] -fn base_hash_value_of_2048_bytes_is_accepted() { - assert!(run("pk = :v", &base_schema(), &[("v", s(2048))]).is_ok()); -} - -#[test] -fn base_hash_value_of_2049_bytes_is_refused() { - let result = run("pk = :v", &base_schema(), &[("v", s(2049))]); - assert_eq!(refused(result), HASH_MSG); -} - -#[test] -fn base_range_value_of_1024_bytes_is_accepted() { - let result = run( - "pk = :p AND sk = :v", - &base_schema(), - &[("p", s(1)), ("v", s(1024))], - ); - assert!(result.is_ok()); -} - -#[test] -fn base_range_value_of_1025_bytes_is_refused() { - let result = run( - "pk = :p AND sk = :v", - &base_schema(), - &[("p", s(1)), ("v", s(1025))], - ); - assert_eq!(refused(result), RANGE_MSG); -} - -#[test] -fn base_between_with_two_600_byte_bounds_is_accepted() { - // The bounds are not added together: 600 and 600 pass. - let values = [("p", s(1)), ("l", s(600)), ("u", s(600))]; - let result = run("pk = :p AND sk BETWEEN :l AND :u", &base_schema(), &values); - assert!(result.is_ok()); -} - -#[test] -fn base_between_with_a_1025_byte_bound_is_refused() { - let values = [("p", s(1)), ("l", s(1)), ("u", s(1025))]; - let result = run("pk = :p AND sk BETWEEN :l AND :u", &base_schema(), &values); - assert_eq!(refused(result), RANGE_MSG); -} - -#[test] -fn base_non_equality_operators_and_begins_with_are_sized() { - for expr in [ - "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)", - ] { - let result = run(expr, &base_schema(), &[("p", s(1)), ("v", s(1025))]); - assert_eq!(refused(result), RANGE_MSG, "{expr}"); - let result = run(expr, &base_schema(), &[("p", s(1)), ("v", s(1024))]); - assert!(result.is_ok(), "{expr}"); - } -} - -#[test] -fn binary_values_are_sized_by_byte_length() { - let b = |len: usize| AttributeValue::B(vec![1u8; len]); - assert!(run("pk = :v", &base_schema(), &[("v", b(2048))]).is_ok()); - let result = run("pk = :v", &base_schema(), &[("v", b(2049))]); - assert_eq!(refused(result), HASH_MSG); - let values = [("p", b(1)), ("v", b(1024))]; - assert!(run("pk = :p AND sk = :v", &base_schema(), &values).is_ok()); - let values = [("p", b(1)), ("v", b(1025))]; - let result = run("pk = :p AND sk = :v", &base_schema(), &values); - assert_eq!(refused(result), RANGE_MSG); -} - -#[test] -fn both_limits_exceeded_gives_the_hash_sentence() { - let values = [("p", s(2049)), ("v", s(1025))]; - let result = run("pk = :p AND sk = :v", &base_schema(), &values); - assert_eq!(refused(result), HASH_MSG); -} - #[test] fn clause_order_does_not_change_the_result() { let result = run( @@ -249,74 +93,3 @@ fn legacy_key_conditions_are_checked_like_the_expression() { let result = validate_query_key_sizes(&kc, &base_schema(), &maps, &LimitsConfig::default()); assert_eq!(refused(result), RANGE_MSG); } - -fn two_hash_schema() -> Vec { - vec![ - ks("h1", KeyType::Hash), - ks("h2", KeyType::Hash), - ks("r", KeyType::Range), - ] -} - -#[test] -fn two_hash_one_value_over_gets_the_single_sentence() { - let values = [("a", s(2049)), ("b", s(1))]; - let result = run("h1 = :a AND h2 = :b", &two_hash_schema(), &values); - assert_eq!(refused(result), HASH_MSG); -} - -#[test] -fn two_hash_values_adding_up_over_the_limit_get_the_aggregated_sentence() { - for (a, b) in [(1025, 1024), (2048, 2048)] { - let values = [("a", s(a)), ("b", s(b))]; - let result = run("h1 = :a AND h2 = :b", &two_hash_schema(), &values); - assert_eq!(refused(result), HASH_TOTAL_MSG, "{a} + {b}"); - } -} - -#[test] -fn an_undefined_value_in_the_key_condition_wins_over_the_size() { - // Measured 2026-10-23: the undefined attribute value is reported. - let result = run( - "pk = :v AND sk = :missing", - &base_schema(), - &[("v", s(2049))], - ); - assert!(result.is_ok()); -} - -#[test] -fn an_undefined_name_in_the_key_condition_wins_over_the_size() { - // Measured 2026-10-23: the undefined attribute name is reported. - let result = run_with_names( - "pk = :v AND #n = :w", - &base_schema(), - &[], - &[("v", s(2049)), ("w", s(1))], - ); - assert!(result.is_ok()); -} - -#[test] -fn a_defined_name_reference_is_sized() { - let result = run_with_names("#p = :v", &base_schema(), &[("p", "pk")], &[("v", s(2049))]); - assert_eq!(refused(result), HASH_MSG); -} - -#[test] -fn base_between_with_a_1025_byte_ordered_lower_bound_is_refused() { - // Measured 2026-10-23: lower bound `a` x 1025 and upper bound `z`. - let values = [ - ("p", s(1)), - ("l", AttributeValue::S("a".repeat(1025))), - ("u", AttributeValue::S("z".to_owned())), - ]; - let result = run("pk = :p AND sk BETWEEN :l AND :u", &base_schema(), &values); - assert_eq!(refused(result), RANGE_MSG); - let values = [ - ("p", s(1)), - ("l", AttributeValue::S("a".repeat(1024))), - ("u", AttributeValue::S("z".to_owned())), - ]; - assert!(run("pk = :p AND sk BETWEEN :l AND :u", &base_schema(), &values).is_ok()); -} From 482bf8a1e9ee22f672636fab6fcc9429ce86d2b6 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:54:10 +0000 Subject: [PATCH 14/21] fix(core): count each key attribute once in the Query key size The size check added every clause into the HASH or RANGE total, including a second clause on one key attribute. `pk = :a AND pk = :b` with 1025 bytes in each value got the aggregated hash sentence. `pk = :p AND sk = :a AND sk = :b` with 600 bytes in each got the range sentence. Main serves both. DynamoDB refuses both with `Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key`. The `pk` shape is from a measurement on 2026-11-24 in us-east-1 (sent twice), and #489 records the `sk` shape. Each key attribute now contributes its largest value once, and the single hash check reads that value. The one-condition-per-key refusal is #484's. Two rows join the equality table. --- crates/core/src/validation/key_size.rs | 49 ++++++++++++-------- crates/core/src/validation/key_size/tests.rs | 9 +++- 2 files changed, 38 insertions(+), 20 deletions(-) diff --git a/crates/core/src/validation/key_size.rs b/crates/core/src/validation/key_size.rs index d32c0a668..52477efb9 100644 --- a/crates/core/src/validation/key_size.rs +++ b/crates/core/src/validation/key_size.rs @@ -101,8 +101,9 @@ enum ClauseSize { /// The clause names an attribute outside the key schema, or is not a /// placeholder, and adds nothing. Skipped, - /// The key type of the clause's attribute and the bytes it contributes. - Bytes(KeyType, usize), + /// 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 @@ -162,27 +163,33 @@ fn sized_clause( }; size = size.max(bytes); } - let Some(key) = key_schema.iter().find(|ks| ks.attribute_name == name) else { + 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.key_type, size)) + 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 HASH values add up to more -/// than that, the aggregated hash sentence (only an index with several HASH -/// attributes can reach it). -/// - Every RANGE clause contributes the size of its value, whatever its -/// 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. +/// 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 with more than 38 significant digits or a magnitude out of @@ -225,20 +232,24 @@ pub fn validate_query_key_sizes( maps: &ExpressionMaps, limits: &LimitsConfig, ) -> Result<(), DynamoDbError> { - let mut hash_over = false; - let mut hash_total: usize = 0; - let mut range_total: usize = 0; + 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(KeyType::Hash, size) => { + 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); } - ClauseSize::Bytes(KeyType::Range, size) => { - range_total = range_total.saturating_add(size); - } + KeyType::Range => range_total = range_total.saturating_add(size), } } if hash_over { diff --git a/crates/core/src/validation/key_size/tests.rs b/crates/core/src/validation/key_size/tests.rs index 56d17fbae..1eb4f882a 100644 --- a/crates/core/src/validation/key_size/tests.rs +++ b/crates/core/src/validation/key_size/tests.rs @@ -144,7 +144,7 @@ fn equality_clauses_are_checked_against_the_limits() { let range = Some(RANGE_MSG_1024); // The key schema, the `attribute = :v` clauses with the bytes of each // value, and the expected sentence (`None` for `Ok`). - let cases: [(&[KeySchemaElement], &[(&str, usize)], Option<&str>); 16] = [ + let cases: [(&[KeySchemaElement], &[(&str, usize)], Option<&str>); 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), @@ -174,6 +174,13 @@ fn equality_clauses_are_checked_against_the_limits() { (&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); From 5d10fd08cab860fed58ea56640ac4bc684b0aa52 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:00:18 +0000 Subject: [PATCH 15/21] style(core): clear the clippy warnings in the Query key size code The pedantic clippy run flagged `ExtendDB` without backticks in the doc comment of validate_query_key_sizes (doc_markdown). The two tables of 762d4a84a tripped type_complexity, a default lint that CI's `-D warnings` refuses. Each table now names its row type. After this commit, clippy with `-W clippy::pedantic` and `--all-targets` on extenddb-core and extenddb-engine reports no warning on a line this PR adds. --- crates/core/src/validation/key_size.rs | 2 +- crates/core/src/validation/key_size/tests.rs | 15 +++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/core/src/validation/key_size.rs b/crates/core/src/validation/key_size.rs index 52477efb9..65ad78019 100644 --- a/crates/core/src/validation/key_size.rs +++ b/crates/core/src/validation/key_size.rs @@ -198,7 +198,7 @@ fn sized_clause( /// `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 +/// 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). diff --git a/crates/core/src/validation/key_size/tests.rs b/crates/core/src/validation/key_size/tests.rs index 1eb4f882a..893431606 100644 --- a/crates/core/src/validation/key_size/tests.rs +++ b/crates/core/src/validation/key_size/tests.rs @@ -138,13 +138,18 @@ fn equalities(clauses: &[(&str, usize)]) -> (KeyCondition, ExpressionMaps) { #[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); - // The key schema, the `attribute = :v` clauses with the bytes of each - // value, and the expected sentence (`None` for `Ok`). - let cases: [(&[KeySchemaElement], &[(&str, usize)], Option<&str>); 18] = [ + 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), @@ -382,11 +387,13 @@ fn a_clause_on_an_attribute_outside_the_key_schema_adds_nothing() { #[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: [(&str, KeyCondition, &[(&str, usize)]); 6] = [ + let cases: [Row<'_>; 6] = [ ( "undefined value on the clause", hash_only("pk", "missing"), From 6a89a56cb71455b2c3eabc4f7a3d7a8728cdfed9 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:04:36 +0000 Subject: [PATCH 16/21] test(query): rename the isrefused tests and reuse assert_validation Nine test names in test_query_key_size.py read `isrefused`, and they now read `is_refused`. `refused` in query_key_size_support.py repeated the three asserts of helpers.assert_validation. It now calls that helper and takes its `code` argument. In test_query_key_size_order.py, `_first` and five tests made the same three asserts after `_error`, and they now call `refused`. `_error` stays for the two syntax error tests, which check the start of the message. --- tests/python/query_key_size_support.py | 11 +++---- tests/python/test_query_key_size.py | 18 ++++++------ tests/python/test_query_key_size_order.py | 35 +++++++++-------------- 3 files changed, 27 insertions(+), 37 deletions(-) diff --git a/tests/python/query_key_size_support.py b/tests/python/query_key_size_support.py index df2448910..4ee792964 100644 --- a/tests/python/query_key_size_support.py +++ b/tests/python/query_key_size_support.py @@ -17,7 +17,7 @@ import pytest from botocore.exceptions import ClientError -from helpers import unique_name, wait_for_active, wait_for_deleted +from helpers import assert_validation, unique_name, wait_for_active, wait_for_deleted HASH_MESSAGE = ( "One or more parameter values were invalid: " @@ -71,14 +71,11 @@ def make_table(client, prefix: str, **create_args): drop_table(client, name) -def refused(client, message: str, **query) -> None: - """Run the Query and assert the refusal's code, status and exact text.""" +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) - err = exc_info.value.response - assert err["Error"]["Code"] == "ValidationException", err["Error"]["Message"] - assert err["ResponseMetadata"]["HTTPStatusCode"] == 400 - assert err["Error"]["Message"] == message + assert_validation(exc_info.value, message, code) def refused_ending(client, suffix: str, **query) -> None: diff --git a/tests/python/test_query_key_size.py b/tests/python/test_query_key_size.py index 233875936..80d1ee894 100644 --- a/tests/python/test_query_key_size.py +++ b/tests/python/test_query_key_size.py @@ -234,7 +234,7 @@ def test_hash_value_of_2048_bytes_is_accepted(self, dynamodb_client, base_table) ) assert resp["Count"] == 1 - def test_hash_value_of_2049_bytes_isrefused(self, dynamodb_client, base_table): + def test_hash_value_of_2049_bytes_is_refused(self, dynamodb_client, base_table): refused( dynamodb_client, HASH_MESSAGE, @@ -256,7 +256,7 @@ def test_range_value_of_1024_bytes_is_accepted(self, dynamodb_client, base_table ) assert resp["Count"] == 1 - def test_range_value_of_1025_bytes_isrefused(self, dynamodb_client, base_table): + def test_range_value_of_1025_bytes_is_refused(self, dynamodb_client, base_table): refused( dynamodb_client, RANGE_MESSAGE, @@ -295,7 +295,7 @@ class TestRangeOperatorsAreSized: "pk = :p AND begins_with(sk, :v)", ], ) - def test_1025_byte_value_isrefused(self, dynamodb_client, base_table, expression): + def test_1025_byte_value_is_refused(self, dynamodb_client, base_table, expression): refused( dynamodb_client, RANGE_MESSAGE, @@ -304,7 +304,7 @@ def test_1025_byte_value_isrefused(self, dynamodb_client, base_table, expression ExpressionAttributeValues={":p": {"S": "p"}, ":v": S(1025, "s")}, ) - def test_between_with_a_1025_byte_upper_bound_isrefused( + def test_between_with_a_1025_byte_upper_bound_is_refused( self, dynamodb_client, base_table ): refused( @@ -331,7 +331,7 @@ def test_hash_value_of_2048_bytes_is_accepted(self, dynamodb_client, binary_tabl ) assert resp["Count"] == 0 - def test_hash_value_of_2049_bytes_isrefused(self, dynamodb_client, binary_table): + def test_hash_value_of_2049_bytes_is_refused(self, dynamodb_client, binary_table): refused( dynamodb_client, HASH_MESSAGE, @@ -348,7 +348,7 @@ def test_range_value_of_1024_bytes_is_accepted(self, dynamodb_client, binary_tab ) assert resp["Count"] == 0 - def test_range_value_of_1025_bytes_isrefused(self, dynamodb_client, binary_table): + def test_range_value_of_1025_bytes_is_refused(self, dynamodb_client, binary_table): refused( dynamodb_client, RANGE_MESSAGE, @@ -370,7 +370,7 @@ def test_range_value_of_1024_bytes_is_accepted(self, dynamodb_client, index_tabl ) assert resp["Count"] == 0 - def test_range_value_of_1025_bytes_isrefused(self, dynamodb_client, index_table): + def test_range_value_of_1025_bytes_is_refused(self, dynamodb_client, index_table): refused( dynamodb_client, RANGE_MESSAGE, @@ -384,7 +384,7 @@ def test_range_value_of_1025_bytes_isrefused(self, dynamodb_client, index_table) class TestLegacyKeyConditionsKeySize: """Measured 2026-10-23 with the legacy KeyConditions parameter.""" - def test_hash_value_of_2049_bytes_isrefused(self, dynamodb_client, base_table): + def test_hash_value_of_2049_bytes_is_refused(self, dynamodb_client, base_table): refused( dynamodb_client, HASH_MESSAGE, @@ -394,7 +394,7 @@ def test_hash_value_of_2049_bytes_isrefused(self, dynamodb_client, base_table): }, ) - def test_range_value_of_1025_bytes_isrefused(self, dynamodb_client, base_table): + def test_range_value_of_1025_bytes_is_refused(self, dynamodb_client, base_table): refused( dynamodb_client, RANGE_MESSAGE, diff --git a/tests/python/test_query_key_size_order.py b/tests/python/test_query_key_size_order.py index 9368419c6..b359e3af7 100644 --- a/tests/python/test_query_key_size_order.py +++ b/tests/python/test_query_key_size_order.py @@ -47,8 +47,9 @@ def _error(client, **query) -> dict: def _first(client, table: str, message: str, **query) -> None: """The query on ``table`` with a 2049-byte ``pk`` reports ``message``.""" - err = _error( + refused( client, + message, TableName=table, KeyConditionExpression="pk = :big", **{ @@ -56,71 +57,63 @@ def _first(client, table: str, message: str, **query) -> None: "ExpressionAttributeValues": {":big": BIG, **query.get("ExpressionAttributeValues", {})}, }, ) - assert err["Code"] == "ValidationException" - assert err["Message"] == message def test_missing_table_is_reported_first(dynamodb_client): - err = _error( + refused( dynamodb_client, + "Requested resource not found", + code="ResourceNotFoundException", TableName=unique_name("qks-absent"), KeyConditionExpression="pk = :p", ExpressionAttributeValues={":p": BIG}, ) - assert err["Code"] == "ResourceNotFoundException" - assert err["Message"] == "Requested resource not found" def test_wrong_index_name_is_reported_first(dynamodb_client, index_table): - err = _error( + refused( dynamodb_client, + "The table does not have the specified index: nope", TableName=index_table, IndexName="nope", KeyConditionExpression="g = :p", ExpressionAttributeValues={":p": BIG}, ) - assert err["Code"] == "ValidationException" - assert err["Message"] == "The table does not have the specified index: nope" def test_consistent_read_on_a_gsi_is_reported_first(dynamodb_client, index_table): - err = _error( + 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}, ) - assert err["Code"] == "ValidationException" - assert err["Message"] == "Consistent reads are not supported on global secondary indexes" def test_limit_zero_is_reported_first(raw_client, index_table): - err = _error( + refused( raw_client, + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1", TableName=index_table, Limit=0, KeyConditionExpression="pk = :p", ExpressionAttributeValues={":p": BIG}, ) - assert err["Code"] == "ValidationException" - assert err["Message"] == ( - "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " - "Member must have value greater than or equal to 1" - ) def test_missed_key_schema_element_is_reported_first(dynamodb_client, index_table): - err = _error( + refused( dynamodb_client, + "Query condition missed key schema element: g", TableName=index_table, IndexName="gsi", KeyConditionExpression="gs = :v", ExpressionAttributeValues={":v": S(1025, "r")}, ) - assert err["Code"] == "ValidationException" - assert err["Message"] == "Query condition missed key schema element: g" def test_projection_syntax_error_is_reported_first(dynamodb_client, index_table): From 1e5f4bc144eddc58f7f34515ba18ff3d4d2c9f83 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:17:35 +0000 Subject: [PATCH 17/21] docs(query): count one sort key value per attribute in the limits table 482bf8a1e counts the largest value of each key attribute once. The sort key row of docs/dynamodb-limits.md said that the Query check adds up every sort key clause. It now says that the check adds up the sort key values of the key condition, one per attribute. --- docs/dynamodb-limits.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dynamodb-limits.md b/docs/dynamodb-limits.md index 252eb0750..98121a123 100755 --- a/docs/dynamodb-limits.md +++ b/docs/dynamodb-limits.md @@ -40,7 +40,7 @@ Source: [AWS DynamoDB Service Quotas](https://docs.aws.amazon.com/amazondynamodb |-------|---------------|--------|-------------------------------------------------------------------------------| | 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 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 value of every sort key clause (any operator; a `BETWEEN` counts its larger bound) and checks the total | +| 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 | From 1fe3f0cfee56f7f7fde079ea1427ad2409acb631 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:09:30 +0000 Subject: [PATCH 18/21] fix(core): refuse a Query key N value that is not a number a3f733db9 sized an N value that normalize_number does not read as a number as 0 bytes, so the Query went on to storage. On SQLite at 1e5f4bc14, `abc`, 2049 `x`, `" 1"` and the empty value answered HTTP 200 with Count 0. That was the answer on a GSI keyed on an N attribute, in KeyConditions and on the base table's N partition key. On the base table's N sort key they answered InternalServerError, and the server log shows `invalid numeric sort key: invalid digit found in string`. DynamoDB refuses each of these values with `The parameter cannot be converted to a numeric value: ` followed by the value as sent. The empty value gets the colon too (measured 2026-11-24 in us-east-1, twice each, in KeyConditionExpression and in KeyConditions). sized_clause now refuses such a value with that text when the value holds ASCII characters only. NumberFault::Empty has no colon, so the refusal uses the text of NumberFault::Malformed. A value with a character outside ASCII still adds nothing to the size. The service reads Unicode decimal digits as digits, and the number rules do not (#565). A refusal here would refuse one U+FF11, which the service reads as the number 1. The unit table now expects the sentence for 2049 `x`. It gains rows for `abc`, `" 1"`, the empty value, and `1e-131` as a partition key value and as a sort key value. --- crates/core/src/validation/key_size.rs | 43 ++++++++++++-------- crates/core/src/validation/key_size/tests.rs | 36 ++++++++++++---- 2 files changed, 55 insertions(+), 24 deletions(-) diff --git a/crates/core/src/validation/key_size.rs b/crates/core/src/validation/key_size.rs index 65ad78019..2ad1c0fa6 100644 --- a/crates/core/src/validation/key_size.rs +++ b/crates/core/src/validation/key_size.rs @@ -18,7 +18,7 @@ use crate::expression::{ }; use crate::limits::LimitsConfig; use crate::types::{AttributeValue, KeySchemaElement, KeyType}; -use crate::validation::number::normalize_number; +use crate::validation::number::{NumberFault, normalize_number}; /// Byte size of a key attribute value. /// @@ -117,20 +117,28 @@ enum ClauseSize { /// 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`. +/// 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). /// -/// A value that `normalize_number` does not read as a number adds nothing to -/// the size. The service refuses such a value with a number sentence, not a -/// size sentence (measured 2026-11-24 in us-east-1). `abc` and 2049 `x` -/// answer `The parameter cannot be converted to a numeric value: ` followed -/// by the value, in `KeyConditionExpression` and in `KeyConditions`. The -/// service reads U+FF11 as a digit, and 39 of them answer the 38-digit -/// sentence. +/// 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 with more -/// than 38 significant digits or a magnitude out of range. +/// 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], @@ -156,7 +164,10 @@ fn sized_clause( let bytes = match value { AttributeValue::N(n) => match normalize_number(n) { Ok(digits) => digits.len(), - Err(fault) if fault.is_not_a_number() => 0, + 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), @@ -192,10 +203,10 @@ fn sized_clause( /// 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 with more than 38 significant digits or a magnitude out of -/// range is refused with the number's sentence and is not sized. A value -/// the number validator does not read as a number adds nothing (see -/// `sized_clause`). +/// - 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 diff --git a/crates/core/src/validation/key_size/tests.rs b/crates/core/src/validation/key_size/tests.rs index 893431606..14bd51b4b 100644 --- a/crates/core/src/validation/key_size/tests.rs +++ b/crates/core/src/validation/key_size/tests.rs @@ -454,17 +454,27 @@ fn number_values_get_the_number_rules_before_any_size() { // 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. The 2049 `x` - // and 2049 U+FF11 rows are values the validator does not read as a - // number: they add nothing, so the size check passes them. The service - // refuses them with a number sentence (measured 2026-11-24: `The parameter - // cannot be converted to a numeric value: xxx...` for 2049 `x`, and the - // digit sentence for 39 U+FF11). + // 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 cases: [(&str, &str, String, Option<&str>); 10] = [ + 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)), ( @@ -483,7 +493,17 @@ fn number_values_get_the_number_rules_before_any_size() { ), ("range, 1025 digits", "sk", "1".repeat(1025), Some(DIGITS)), ("range, 2100 zeros and 1", "sk", format!("{zeros}1"), None), - ("hash, 2049 x", "pk", "x".repeat(2049), 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 { From b255fe578749588bf0702a267589ac24f26b0f9d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:18:46 +0000 Subject: [PATCH 19/21] test(query): pin the number sentences in each Query key position test_query_key_size_values.py gains a table for N values that the service refuses as numbers: `abc`, 2049 `x`, `" 1"`, the empty value and `1e-131`. Each row runs in four forms. Two are on a GSI keyed on an N attribute, in KeyConditionExpression and in KeyConditions. The other two use the N partition key and the N sort key of a new `number_table` fixture. Each row asserts status, code and message by equality. The service gives these answers before the table lookup (measured 2026-11-24 in us-east-1, twice each, on a table that does not exist). Two more rows, 39 and 683 U+FF11, assert the service's 38-digit sentence. They are expected failures on ExtendDB, because the number rules do not read U+FF11 as a digit (#565). The mark is not strict, so a check that reads these digits makes the rows of its form pass. The existing number test now builds its Query with the same helper. On a server built from 1e5f4bc14, the 16 rows for `abc`, 2049 `x`, `" 1"` and the empty value fail. 12 of them get HTTP 200, and the 4 on the sort key get InternalServerError. The 4 underflow rows pass there too. With 1fe3f0cfe, the three wire files pass on SQLite: 99 passed and 8 expected failures. --- tests/python/query_key_size_support.py | 12 +++ tests/python/test_query_key_size_values.py | 96 +++++++++++++++++----- 2 files changed, 87 insertions(+), 21 deletions(-) diff --git a/tests/python/query_key_size_support.py b/tests/python/query_key_size_support.py index 4ee792964..18d76ef78 100644 --- a/tests/python/query_key_size_support.py +++ b/tests/python/query_key_size_support.py @@ -183,6 +183,18 @@ def hash_only_table(dynamodb_client): 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.""" diff --git a/tests/python/test_query_key_size_values.py b/tests/python/test_query_key_size_values.py index 8dfce815d..fdab87bae 100644 --- a/tests/python/test_query_key_size_values.py +++ b/tests/python/test_query_key_size_values.py @@ -5,11 +5,14 @@ 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. The main key size rows are in ``test_query_key_size.py``. +2026-11-20 and 2026-11-24. The main key size rows are in +``test_query_key_size.py``. """ from __future__ import annotations +import os + import pytest from query_key_size_support import ( # noqa: F401 (fixtures are used by name) @@ -19,6 +22,7 @@ base_table, hash_only_table, index_table, + number_table, refused, refused_ending, ) @@ -189,18 +193,59 @@ def test_an_lsi_begins_with_of_1025_bytes_is_refused( 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: " + +# The service reads U+FF11 as the digit 1. ExtendDB's number rules do not +# (#565), so on ExtendDB these rows are expected to fail. Not strict: a check +# that reads these digits in one of the forms makes the rows of that form pass. +FULLWIDTH_DIGITS = pytest.mark.xfail( + bool(os.environ.get("DYNAMODB_ENDPOINT", "").strip()), + reason="#565: the number rules do not read U+FF11 as a digit", + strict=False, +) -class TestNumberKeyValues: - """GSI ``ngsi`` with HASH ``n`` (N), measured 2026-11-20 in us-east-1. +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``. - 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. + ``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, ``1e-131`` gets the underflow sentence, and 39 or 683 U+FF11 get + the 38-digit sentence. 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("syntax", ["expression", "legacy"]) + @pytest.mark.parametrize("form", ["gsi", "gsi-legacy"]) @pytest.mark.parametrize( ("number", "message"), [ @@ -213,21 +258,30 @@ class TestNumberKeyValues: ], ) def test_a_number_is_checked_before_it_is_sized( - self, dynamodb_client, index_table, number, message, syntax + self, dynamodb_client, index_table, number_table, number, message, form ): - if syntax == "expression": - condition = { - "KeyConditionExpression": "n = :v", - "ExpressionAttributeValues": {":v": {"N": number}}, - } - else: - condition = { - "KeyConditions": { - "n": {"ComparisonOperator": "EQ", "AttributeValueList": [{"N": number}]} - } - } - query = {"TableName": index_table, "IndexName": "ngsi", **condition} + 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"), + pytest.param("\uff11" * 39, DIGITS_MESSAGE, id="39-fullwidth", marks=FULLWIDTH_DIGITS), + pytest.param( + "\uff11" * 683, DIGITS_MESSAGE, id="683-fullwidth", marks=FULLWIDTH_DIGITS + ), + ], + ) + 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)) From ee588273f7a652857bacb4153b6a7401fb77f049 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:46:21 +0000 Subject: [PATCH 20/21] test(query): leave the U+FF11 rows to #565 The files in tests/python hold no expected failures (tests/python/README.md, Design Principles). The rows for 39 and 683 U+FF11 assert the service's 38-digit sentence. ExtendDB gives that sentence only once its number rules read Unicode decimal digits, which is #565, so the rows and their mark go. The measurements of 2026-11-24 are on #565. --- tests/python/test_query_key_size_values.py | 23 ++++------------------ 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/tests/python/test_query_key_size_values.py b/tests/python/test_query_key_size_values.py index fdab87bae..b1c6b6807 100644 --- a/tests/python/test_query_key_size_values.py +++ b/tests/python/test_query_key_size_values.py @@ -11,8 +11,6 @@ from __future__ import annotations -import os - import pytest from query_key_size_support import ( # noqa: F401 (fixtures are used by name) @@ -198,15 +196,6 @@ def test_an_lsi_begins_with_of_1025_bytes_is_refused( ) NOT_A_NUMBER = "The parameter cannot be converted to a numeric value: " -# The service reads U+FF11 as the digit 1. ExtendDB's number rules do not -# (#565), so on ExtendDB these rows are expected to fail. Not strict: a check -# that reads these digits in one of the forms makes the rows of that form pass. -FULLWIDTH_DIGITS = pytest.mark.xfail( - bool(os.environ.get("DYNAMODB_ENDPOINT", "").strip()), - reason="#565: the number rules do not read U+FF11 as a digit", - strict=False, -) - 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``. @@ -239,10 +228,10 @@ class TestNumberKeyValues: 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, ``1e-131`` gets the underflow sentence, and 39 or 683 U+FF11 get - the 38-digit sentence. 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. + 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"]) @@ -275,10 +264,6 @@ def test_a_number_is_checked_before_it_is_sized( 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"), - pytest.param("\uff11" * 39, DIGITS_MESSAGE, id="39-fullwidth", marks=FULLWIDTH_DIGITS), - pytest.param( - "\uff11" * 683, DIGITS_MESSAGE, id="683-fullwidth", marks=FULLWIDTH_DIGITS - ), ], ) def test_each_key_position_gets_the_number_sentence( From 66b82ec5a9a8878817dd9ad30cd2be2518cfafc1 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:40:04 +0000 Subject: [PATCH 21/21] test(query): pin the Select order on a KEYS_ONLY GSI without a start key On a KEYS_ONLY GSI with Select ALL_ATTRIBUTES and no ExclusiveStartKey, DynamoDB answers each of these refusals before the Select sentence: - 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 - FilterExpression `#` A reviewer measured each shape twice on 2026-11-24. These shapes are now rows of test_select_all_attributes_on_a_keys_only_gsi_is_reported_after. Each row asserts status, code and message by equality, except the `#` row. ExtendDB words that syntax error in its own way (#1419), so the row checks the `Invalid FilterExpression: ` label. The table now sends its requests through raw_client, because the SDK refuses Limit 0. FILTER_LABEL, LIMIT_MESSAGE and MISSED_G_MESSAGE hold the three texts that a new row shares with an existing test. With the Select check moved above the Limit check, the six new rows fail. The two 2049-byte rows of the table and two start key rows in test_query_start_key_partition.py fail too. On SQLite, the three wire files and test_query_start_key_partition.py give 136 passed. --- tests/python/test_query_key_size_order.py | 90 +++++++++++++++++++---- 1 file changed, 75 insertions(+), 15 deletions(-) diff --git a/tests/python/test_query_key_size_order.py b/tests/python/test_query_key_size_order.py index b359e3af7..62443cb62 100644 --- a/tests/python/test_query_key_size_order.py +++ b/tests/python/test_query_key_size_order.py @@ -13,7 +13,11 @@ 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 (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 @@ -35,6 +39,12 @@ ) 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: @@ -96,8 +106,7 @@ def test_consistent_read_on_a_gsi_is_reported_first(dynamodb_client, index_table def test_limit_zero_is_reported_first(raw_client, index_table): refused( raw_client, - "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " - "Member must have value greater than or equal to 1", + LIMIT_MESSAGE, TableName=index_table, Limit=0, KeyConditionExpression="pk = :p", @@ -108,7 +117,7 @@ def test_limit_zero_is_reported_first(raw_client, index_table): def test_missed_key_schema_element_is_reported_first(dynamodb_client, index_table): refused( dynamodb_client, - "Query condition missed key schema element: g", + MISSED_G_MESSAGE, TableName=index_table, IndexName="gsi", KeyConditionExpression="gs = :v", @@ -204,7 +213,7 @@ def test_filter_expression_syntax_is_reported_first(dynamodb_client, index_table ExpressionAttributeValues={":p": BIG}, ) assert err["Code"] == "ValidationException" - assert err["Message"].startswith("Invalid FilterExpression: ") + assert err["Message"].startswith(FILTER_LABEL) assert err["Message"] != HASH_MESSAGE @@ -242,27 +251,78 @@ def test_exclusive_start_key_of_the_wrong_type_is_reported_after( "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( - ("value", "start_key", "message"), + ("values", "changes", "message"), [ - pytest.param(BIG, None, HASH_MESSAGE, id="2049-bytes"), - pytest.param(BIG, START_KEY, HASH_MESSAGE, id="2049-bytes-with-a-start-key"), - pytest.param(S(1, "x"), START_KEY, SELECT_ON_KEYS_ONLY_MESSAGE, id="1-byte-with-a-start-key"), + 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( - dynamodb_client, index_table, value, start_key, message + raw_client, index_table, values, changes, message ): - # Measured 2026-11-20 in us-east-1, each shape twice. + # 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": {":v": value}, + "ExpressionAttributeValues": values, + **changes, } - if start_key is not None: - query["ExclusiveStartKey"] = start_key - refused(dynamodb_client, message, **query) + 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)