From 75a783b3544b2f8496cbe340b72b13b4de7829c2 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:43:45 +0000 Subject: [PATCH 01/14] fix(expression): refuse a document path of more than 32 elements Amazon DynamoDB refuses a document path of more than 32 elements, each attribute name and each list index counting as one, in every expression kind, with `Invalid : The document path has too many nesting levels; nesting levels: ` (measured 2026-10-26 at 02:26, 02:29, 03:38 and 03:39 UTC, each request twice). It checks each path's `#name` references and then its length, path by path in text order. ExtendDB had no limit: a 33-element path was evaluated, and an ADD on one created the missing maps. The check runs where each path's names are resolved: in the semantic walk's `check_path_refs` for update and condition expressions, in `resolve_paths` for projections, and in the key condition parser before the nested-attribute refusal. The grammar pass still runs first, so a syntax error is reported before the length. Two checks move to the service's position so the new refusal does not answer ahead of them (measured 2026-10-26 at 04:40, 04:41 and 04:43 UTC): - The BETWEEN bounds check (both bounds placeholders of different types, or the lower above the upper) runs in the semantic walk, so it answers at request time on a missing key, after a false AND and on an empty Query, as the service does; it ran only while evaluating an item. - UpdateItem and PutItem check the nesting depth of ExpressionAttributeValues right after the table name, before the expressions, the table lookup and the key, as DeleteItem already did. --- crates/core/src/expression/evaluator.rs | 63 +++++---- crates/core/src/expression/key_condition.rs | 7 + crates/core/src/expression/mod.rs | 2 + crates/core/src/expression/path_length.rs | 129 ++++++++++++++++++ crates/core/src/expression/projection.rs | 4 + .../expression/semantics/condition_rules.rs | 8 +- crates/core/src/expression/semantics/refs.rs | 10 +- crates/engine/src/put_item.rs | 24 ++-- crates/engine/src/update_item.rs | 27 ++-- docs/dynamodb-limits.md | 1 + 10 files changed, 225 insertions(+), 50 deletions(-) create mode 100644 crates/core/src/expression/path_length.rs diff --git a/crates/core/src/expression/evaluator.rs b/crates/core/src/expression/evaluator.rs index cee1186ea..2aa2cff79 100755 --- a/crates/core/src/expression/evaluator.rs +++ b/crates/core/src/expression/evaluator.rs @@ -53,29 +53,10 @@ pub fn evaluate_condition( let val = resolve_to_value(operand, item, maps)?; let lo = resolve_to_value(low, item, maps)?; let hi = resolve_to_value(high, item, maps)?; - // DynamoDB validates bounds when both are literal placeholders - if matches!(low.as_ref(), Expr::Placeholder(_)) - && matches!(high.as_ref(), Expr::Placeholder(_)) - && let (Some(l), Some(h)) = (lo.as_deref(), hi.as_deref()) - { - let l_type = attribute_type_code(l); - let h_type = attribute_type_code(h); - if l_type != h_type { - return Err(DynamoDbError::ValidationException(format!( - "Invalid ConditionExpression: The BETWEEN operator requires same data type for lower and upper bounds; lower bound operand: AttributeValue: {{{}}}, upper bound operand: AttributeValue: {{{}}}", - format_attribute_value(l), - format_attribute_value(h) - ))); - } - let lpn = placeholder_numeric(low, maps); - let hpn = placeholder_numeric(high, maps); - if compare_values(l, h, CompareOp::Gt, lpn, hpn) { - return Err(DynamoDbError::ValidationException(format!( - "Invalid ConditionExpression: The BETWEEN operator requires upper bound to be greater than or equal to lower bound; lower bound operand: AttributeValue: {{{}}}, upper bound operand: AttributeValue: {{{}}}", - format_attribute_value(l), - format_attribute_value(h) - ))); - } + if let Some(msg) = between_bounds_fault(low, high, maps) { + return Err(DynamoDbError::ValidationException(format!( + "Invalid ConditionExpression: {msg}" + ))); } match (&val, &lo, &hi) { (Some(v), Some(l), Some(h)) => { @@ -127,6 +108,42 @@ fn resolve_to_value<'a>( } } +/// The service's sentence when both BETWEEN bounds are placeholders and they +/// differ in type or the lower is above the upper, without the `Invalid +/// : ` label. The service checks this at request time, whatever the +/// item (measured 2026-10-26). +pub(crate) fn between_bounds_fault( + low: &Expr, + high: &Expr, + maps: &ExpressionMaps, +) -> Option { + let (Expr::Placeholder(l_name), Expr::Placeholder(h_name)) = (low, high) else { + return None; + }; + let (Some(l), Some(h)) = (maps.values.get(l_name), maps.values.get(h_name)) else { + return None; + }; + let bounds = format!( + "lower bound operand: AttributeValue: {{{}}}, upper bound operand: AttributeValue: {{{}}}", + format_attribute_value(l), + format_attribute_value(h) + ); + if attribute_type_code(l) != attribute_type_code(h) { + return Some(format!( + "The BETWEEN operator requires same data type for lower and upper bounds; {bounds}" + )); + } + let (lpn, hpn) = ( + placeholder_numeric(low, maps), + placeholder_numeric(high, maps), + ); + compare_values(l, h, CompareOp::Gt, lpn, hpn).then(|| { + format!( + "The BETWEEN operator requires upper bound to be greater than or equal to lower bound; {bounds}" + ) + }) +} + /// Look up a pre-parsed `BigDecimal` for a placeholder expression. /// /// Returns `None` if the expression is not a placeholder or has no pre-parsed value. diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index d8fb7122d..54c2dd8a7 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -628,6 +628,13 @@ fn parse_clauses(tokens: &[Token]) -> Result, DynamoDbError> { // A key condition may only reference a top-level key attribute. Any document // path (`attr.sub` or `attr[i]`) on a key is rejected, matching Amazon // DynamoDB. Runs after the reserved-word check and before key-schema checks. + for clause in &clauses { + if let Some(msg) = super::path_length::too_many_levels(raw_clause_path(clause)) { + return Err(validation_err(&format!( + "Invalid KeyConditionExpression: {msg}" + ))); + } + } for clause in &clauses { reject_nested_key_path(raw_clause_path(clause))?; } diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 86eef4d1b..6aa980ebf 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -14,6 +14,7 @@ mod key_condition; mod kind; mod parser; mod parser_common; +mod path_length; mod projection; mod reserved_words; mod resolver; @@ -31,6 +32,7 @@ pub use key_condition::{ }; pub use kind::ExpressionKind; pub use parser::{parse_condition, parse_condition_with_depth_limit}; +pub use path_length::MAX_DOCUMENT_PATH_ELEMENTS; pub use projection::{Projection, parse_projection}; pub use reserved_words::validate_no_reserved_words; pub use resolver::{ diff --git a/crates/core/src/expression/path_length.rs b/crates/core/src/expression/path_length.rs new file mode 100644 index 000000000..bfa33aff1 --- /dev/null +++ b/crates/core/src/expression/path_length.rs @@ -0,0 +1,129 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Length limit of a document path in an expression. +//! +//! Amazon `DynamoDB` refuses a document path of more than 32 elements, each +//! attribute name and each list index counting as one, in every expression +//! kind: `Invalid : The document path has too many nesting levels; +//! nesting levels: `. It checks a path's `#name` references first and then +//! its length, path by path in the order the paths appear, so an undefined +//! `#name` in an earlier path or inside the long path is reported instead +//! (measured 2026-10-26, us-east-1). The callers run the check where they +//! resolve each path's names. + +use super::ast::PathElement; + +/// Most elements a document path may have. +pub const MAX_DOCUMENT_PATH_ELEMENTS: usize = 32; + +/// The service's sentence for `path` when it is too long, without the +/// `Invalid : ` label the caller adds. +pub(crate) fn too_many_levels(path: &[PathElement]) -> Option { + (path.len() > MAX_DOCUMENT_PATH_ELEMENTS).then(|| { + format!( + "The document path has too many nesting levels; nesting levels: {}", + path.len() + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn names(n: usize) -> Vec { + (0..n) + .map(|_| PathElement::Attribute("k".to_owned())) + .collect() + } + + #[test] + fn thirty_two_elements_pass_and_thirty_three_are_refused() { + assert_eq!(too_many_levels(&names(32)), None); + assert_eq!( + too_many_levels(&names(33)).as_deref(), + Some("The document path has too many nesting levels; nesting levels: 33") + ); + } + + #[test] + fn a_list_index_counts_as_an_element() { + let mut path = names(1); + path.extend((0..32).map(PathElement::Index)); + assert_eq!(path.len(), 33); + assert!(too_many_levels(&path).is_some()); + path.pop(); + assert_eq!(too_many_levels(&path), None); + } + + fn path_text(first: &str, n: usize) -> String { + format!("{first}{}", ".k".repeat(n - 1)) + } + + fn message(result: Result<(), crate::error::DynamoDbError>) -> String { + match result { + Err(crate::error::DynamoDbError::ValidationException(m)) => m, + other => panic!("{other:?}"), + } + } + + fn maps() -> crate::expression::ExpressionMaps { + crate::expression::ExpressionMaps::new( + std::collections::HashMap::from([("m".to_owned(), "m".to_owned())]), + std::collections::HashMap::from([( + "v".to_owned(), + crate::types::AttributeValue::S("v".to_owned()), + )]), + ) + } + + const LEVELS_33: &str = "The document path has too many nesting levels; nesting levels: 33"; + + #[test] + fn a_key_condition_path_is_checked_before_the_nested_refusal() { + let parse = |n: usize| { + let expr = format!("pk = :v AND {} = :v", path_text("m", n)); + crate::expression::parse_key_condition(&crate::expression::tokenize(&expr).unwrap()) + .map(|_| ()) + }; + assert_eq!( + message(parse(33)), + format!("Invalid KeyConditionExpression: {LEVELS_33}") + ); + assert!(message(parse(32)).contains("cannot have conditions on nested attributes")); + } + + #[test] + fn a_projection_path_is_checked_after_its_names() { + let compile = |text: &str| { + let paths = + crate::expression::parse_projection(&crate::expression::tokenize(text).unwrap()) + .unwrap(); + crate::expression::Projection::compile(&paths, &maps(), true).map(|_| ()) + }; + assert_eq!( + message(compile(&path_text("#m", 33))), + format!("Invalid ProjectionExpression: {LEVELS_33}") + ); + assert!(message(compile(&path_text("#zz", 33))).contains("attribute name: #zz")); + assert!(compile(&path_text("#m", 32)).is_ok()); + } + + #[test] + fn an_update_path_is_checked_after_its_names_in_text_order() { + let check = |text: &str| { + let tokens = crate::expression::tokenize(text).unwrap(); + let parsed = crate::expression::parse_update_sections(&tokens, Some(text)).unwrap(); + crate::expression::validate_update_semantics(&parsed, &maps()) + }; + let long = path_text("#m", 33); + assert_eq!( + message(check(&format!("SET {long} = :v"))), + format!("Invalid UpdateExpression: {LEVELS_33}") + ); + assert!(message(check(&format!("SET #zz = :v, {long} = :v"))).contains("#zz")); + assert!(message(check(&format!("SET {} = :v", path_text("#zz", 33)))).contains("#zz")); + assert!(message(check(&format!("SET {long} = :v, #zz = :v"))).contains("33")); + } +} diff --git a/crates/core/src/expression/projection.rs b/crates/core/src/expression/projection.rs index ee90d5201..5c918598c 100755 --- a/crates/core/src/expression/projection.rs +++ b/crates/core/src/expression/projection.rs @@ -158,6 +158,10 @@ pub(crate) fn resolve_paths( } } } + // The length after the path's names, as the service checks it. + if let Some(msg) = super::path_length::too_many_levels(path) { + return Err(DynamoDbError::ValidationException(msg)); + } resolved.push(elems); } Ok(resolved) diff --git a/crates/core/src/expression/semantics/condition_rules.rs b/crates/core/src/expression/semantics/condition_rules.rs index a7a55ce93..f53ffa62a 100644 --- a/crates/core/src/expression/semantics/condition_rules.rs +++ b/crates/core/src/expression/semantics/condition_rules.rs @@ -57,7 +57,13 @@ fn walk_condition( walk_condition_operand(operand, maps, kind)?; walk_condition_operand(low, maps, kind)?; walk_condition_operand(high, maps, kind)?; - validate_ordering_operand_types(expr, maps).map_err(|e| with_kind(e, kind)) + validate_ordering_operand_types(expr, maps).map_err(|e| with_kind(e, kind))?; + // The bounds are checked at request time, so a condition that + // fails them is refused before the other expressions are checked. + match super::super::evaluator::between_bounds_fault(low, high, maps) { + Some(msg) => Err(validation(kind, &msg)), + None => Ok(()), + } } Expr::In { operand, list } => { walk_condition_operand(operand, maps, kind)?; diff --git a/crates/core/src/expression/semantics/refs.rs b/crates/core/src/expression/semantics/refs.rs index 157e60573..e3f7a4433 100644 --- a/crates/core/src/expression/semantics/refs.rs +++ b/crates/core/src/expression/semantics/refs.rs @@ -2,7 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 //! The name and value usage checks shared by both passes: every `#name` -//! element of a document path, and every `:value` placeholder, is defined. +//! element of a document path, and every `:value` placeholder, is defined, +//! and a document path has at most 32 elements. use super::super::ast::PathElement; use super::super::kind::ExpressionKind; @@ -28,7 +29,12 @@ pub(super) fn check_path_refs( )); } } - Ok(()) + // The service checks the length after the path's names (measured + // 2026-10-26). + match super::super::path_length::too_many_levels(path) { + Some(msg) => Err(validation(kind, &msg)), + None => Ok(()), + } } pub(super) fn check_value_defined( diff --git a/crates/engine/src/put_item.rs b/crates/engine/src/put_item.rs index b51d54729..1d9991876 100755 --- a/crates/engine/src/put_item.rs +++ b/crates/engine/src/put_item.rs @@ -131,6 +131,19 @@ pub async fn handle_put_item( extenddb_core::validation::validate_table_name(&input.table_name, &ctx.limits)?; + // The nesting-depth limit applies to every ExpressionAttributeValue on the + // single-item write paths, condition-only placeholders included: measured + // 2026-08-24 (us-east-1), a 32-level value referenced solely by a + // ConditionExpression is rejected on PutItem, DeleteItem, and UpdateItem + // alike, while 31 levels is accepted. TransactWriteItems deliberately does + // NOT get this check: the same 32-level condition-only value is accepted + // inside a transaction on every sub-op shape (also measured). It comes + // before the ConditionExpression and the table lookup (measured + // 2026-10-26). + if let Some(values) = &input.expression_attribute_values { + extenddb_core::validation::validate_attribute_values_nesting_depth(values.values())?; + } + // Validate expressions/`Expected` before the existence check, // so a malformed request to a missing table returns ValidationException, // not ResourceNotFoundException. Key/item-content checks stay after. @@ -177,17 +190,6 @@ pub async fn handle_put_item( &key_info.attribute_definitions, )?; - // The nesting-depth limit applies to every ExpressionAttributeValue on the - // single-item write paths, condition-only placeholders included: measured - // 2026-08-24 (us-east-1), a 32-level value referenced solely by a - // ConditionExpression is rejected on PutItem, DeleteItem, and UpdateItem - // alike, while 31 levels is accepted. TransactWriteItems deliberately does - // NOT get this check: the same 32-level condition-only value is accepted - // inside a transaction on every sub-op shape (also measured). - if let Some(values) = &input.expression_attribute_values { - extenddb_core::validation::validate_attribute_values_nesting_depth(values.values())?; - } - extenddb_core::validation::validate_vector_write( &input.item, &key_info.vector_indexes, diff --git a/crates/engine/src/update_item.rs b/crates/engine/src/update_item.rs index 298a9948d..91a090e01 100755 --- a/crates/engine/src/update_item.rs +++ b/crates/engine/src/update_item.rs @@ -62,6 +62,20 @@ pub async fn handle_update_item( extenddb_core::validation::validate_table_name(&input.table_name, &ctx.limits)?; + // Amazon DynamoDB enforces the nesting-depth limit on EVERY + // ExpressionAttributeValue, condition-only placeholders included: a + // 32-level value referenced solely by a ConditionExpression answers the + // nesting ValidationException rather than evaluating the condition. + // An earlier measurement had condition-only values exempt, and some + // regions did behave that way; re-measured 2026-08-24, both us-east-1 and + // eu-west-2 apply the limit to the whole map, so the per-placeholder walk + // this replaced is gone. A 31-level value still passes and the condition + // evaluates normally. It comes before every expression check, the unused + // names and values, the table lookup and the key (measured 2026-10-26). + if let Some(values) = &input.expression_attribute_values { + extenddb_core::validation::validate_attribute_values_nesting_depth(values.values())?; + } + // Validate Update/Condition expressions (and AttributeUpdates // desugaring) before the existence check; key, item-content nesting, and // the no-key-update checks stay after (post-existence on Amazon DynamoDB). @@ -209,19 +223,6 @@ pub async fn handle_update_item( // `expression::apply_update_validated`, which every backend applies to the // evaluated image and which no expression form can bypass. - // Amazon DynamoDB enforces the nesting-depth limit on EVERY - // ExpressionAttributeValue, condition-only placeholders included: a - // 32-level value referenced solely by a ConditionExpression answers the - // nesting ValidationException rather than evaluating the condition. - // An earlier measurement had condition-only values exempt, and some - // regions did behave that way; re-measured 2026-08-24, both us-east-1 and - // eu-west-2 apply the limit to the whole map, so the per-placeholder walk - // this replaced is gone. A 31-level value still passes and the condition - // evaluates normally. - if let Some(values) = &input.expression_attribute_values { - extenddb_core::validation::validate_attribute_values_nesting_depth(values.values())?; - } - // Validate that no update action targets a key attribute (REQ-DATA-003) validate_no_key_updates(&actions, &key_info, &maps)?; diff --git a/docs/dynamodb-limits.md b/docs/dynamodb-limits.md index 2b37b9023..b693e40c1 100755 --- a/docs/dynamodb-limits.md +++ b/docs/dynamodb-limits.md @@ -67,6 +67,7 @@ Source: [AWS DynamoDB Service Quotas](https://docs.aws.amazon.com/amazondynamodb | Condition expression size | 4 KB | Enforced | `check_expression_size`, `LimitsConfig::max_expression_length_bytes` | | Update expression size | 4 KB | Enforced | `check_expression_size`, `LimitsConfig::max_expression_length_bytes` | | Key condition expression size | 4 KB | Enforced | `check_expression_size`, `LimitsConfig::max_expression_length_bytes` | +| Document path length in an expression | 32 elements (each attribute name and list index counts as one) | Enforced | Every expression kind: `Invalid : The document path has too many nesting levels; nesting levels: `. Checked path by path in the order the paths appear, after each path's `#name` references, so an undefined `#name` in an earlier path or inside the long path is reported first, as on the service. A syntax error anywhere in the expression is reported first. ExtendDB checks reserved words on the whole expression before any path, where the service checks them in the same walk, so a long path followed by a reserved word answers the reserved word error | | Expression attribute names | 2 MB total | Not enforced | Per-entry key/value validated (`serde_helpers`); no aggregate size validation | | Expression attribute values | 2 MB total | Not enforced | Per-entry key/value validated (`serde_helpers`); no aggregate size validation | From 5b64ffde00ed91c38404e40c1910741ff5209d50 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:43:46 +0000 Subject: [PATCH 02/14] test(expression): document path length limit and its order Dual-target wire tests from the 2026-10-26 measurements: 32 elements accepted and 33 or more refused in every expression kind and operation; an undefined `#name` before or inside a long path, and a filter or condition fault, reported before the length; a value nested too deep reported before a long path or a syntax error; BETWEEN bounds refused on a missing key, after a false AND and on an empty Query. The at-the-limit condition uses `size()` of the 32-element path. PutItem, UpdateItem and DeleteItem prefix expression errors with `1 validation error detected: `, so those tests accept the message either way. --- tests/test_document_path_length.py | 361 +++++++++++++++++++++++++++++ 1 file changed, 361 insertions(+) create mode 100644 tests/test_document_path_length.py diff --git a/tests/test_document_path_length.py b/tests/test_document_path_length.py new file mode 100644 index 000000000..d857b9407 --- /dev/null +++ b/tests/test_document_path_length.py @@ -0,0 +1,361 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Length limit of a document path in an expression. + +Amazon DynamoDB refuses a document path of more than 32 elements (each +attribute name and each list index counts as one) in every expression kind, +with ValidationException ``Invalid : The document path has too many +nesting levels; nesting levels: ``, naming the first such path in the +expression. A syntax error anywhere in the expression is reported instead. +The service checks a path's ``#name`` references before its length, path by +path in the order the paths appear, and finishes the checks of the +FilterExpression before the ProjectionExpression and of the +ConditionExpression before the UpdateExpression. Measured on 2026-10-26 at +02:26, 02:29, 03:38, 03:39, 04:21, 04:40, 04:41 and 04:43 UTC (us-east-1), each case +twice. + +PutItem, UpdateItem and DeleteItem prefix every expression error with +``1 validation error detected: ``; the other operations do not. That prefix +is a separate change, so for those three operations the tests accept the +message with or without it. + +Dual-target against Amazon DynamoDB and extenddb. +""" + +from __future__ import annotations + +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table + +N = {"#m": "m", "#k": "k"} +S = {":s": {"S": "s"}} +PREFIX = "1 validation error detected: " + + +def too_long(kind: str, n: int) -> str: + return f"Invalid {kind}: The document path has too many nesting levels; nesting levels: {n}" + + +def p(n: int) -> str: + """A path of n elements: #m then n - 1 times .#k.""" + return "#m" + ".#k" * (n - 1) + + +def nmap(wrappers: int) -> dict: + value = {"S": "leaf"} + for _ in range(wrappers): + value = {"M": {"k": value}} + return value + + +def _error(call) -> tuple[str, str]: + with pytest.raises(ClientError) as exc_info: + call() + err = exc_info.value.response["Error"] + return err["Code"], err["Message"] + + +def _single_item_error(call) -> tuple[str, str]: + code, message = _error(call) + return code, message.removeprefix(PREFIX) + + +@pytest.fixture(scope="module") +def table(dynamodb_client): + with scoped_table( + dynamodb_client, + attribute_definitions=[ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"}, + ], + key_schema=[ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"}, + ], + ) as name: + yield name + + +@pytest.fixture +def key(dynamodb_client, table, request): + k = {"pk": {"S": "plen"}, "sk": {"S": request.node.name}} + dynamodb_client.put_item(TableName=table, Item={**k, "x": {"S": "x"}, "m": nmap(31)}) + return k + + +def _stored(client, table, key): + return client.get_item(TableName=table, Key=key, ConsistentRead=True)["Item"] + + +def _update(client, table, key, expr, names=N, values=S, **kw): + args = {"TableName": table, "Key": key, "UpdateExpression": expr, **kw} + if names: + args["ExpressionAttributeNames"] = names + if values: + args["ExpressionAttributeValues"] = values + return client.update_item(**args) + + +# (case, update expression, names, values, elements reported) +UPDATE_REFUSED = [ + ("set_33", f"SET {p(33)} = :s", N, S, 33), + ("set_34", f"SET {p(34)} = :s", N, S, 34), + ("set_40", f"SET {p(40)} = :s", N, S, 40), + ("set_index_33", "SET #m" + "[0]" * 32 + " = :s", {"#m": "m"}, S, 33), + ("set_mixed_33", "SET #m" + ".#k[0]" * 16 + " = :s", N, S, 33), + ("first_of_33_and_40", f"SET {p(33)} = :s, {p(40)} = :s", N, S, 33), + ("first_of_40_and_33", f"SET {p(40)} = :s, {p(33)} = :s", N, S, 40), + ("value_side", f"SET #x = {p(33)}", {**N, "#x": "x"}, None, 33), + ("if_not_exists", f"SET #x = if_not_exists({p(33)}, :s)", {**N, "#x": "x"}, S, 33), + ("list_append", f"SET #x = list_append({p(33)}, :l)", {**N, "#x": "x"}, {":l": {"L": []}}, 33), + ("remove", f"REMOVE {p(33)}", N, None, 33), + ("delete", f"DELETE {p(33)} :ss", N, {":ss": {"SS": ["a"]}}, 33), + ("add", f"ADD {p(33)} :one", N, {":one": {"N": "1"}}, 33), + ("undefined_name_after", f"SET {p(33)} = :s, #zz = :s", N, S, 33), + ("undefined_value", f"SET {p(33)} = :nope", N, S, 33), + ("unused_value", f"SET {p(33)} = :s", N, {**S, ":unused": {"S": "u"}}, 33), + ("unused_name", f"SET {p(33)} = :s", {**N, "#unused": "u"}, S, 33), + ("overlapping_paths", f"SET {p(33)} = :s, {p(33)} = :s", N, S, 33), +] + + +@pytest.mark.parametrize(("case", "expr", "names", "values", "n"), UPDATE_REFUSED, + ids=[c[0] for c in UPDATE_REFUSED]) +def test_update_expression_path_past_the_limit(dynamodb_client, table, key, case, expr, names, values, n): + assert _single_item_error(lambda: _update(dynamodb_client, table, key, expr, names, values)) == ( + "ValidationException", too_long("UpdateExpression", n)) + assert _stored(dynamodb_client, table, key)["x"] == {"S": "x"} + + +def test_update_expression_path_at_the_limit(dynamodb_client, table, key): + _update(dynamodb_client, table, key, f"SET {p(32)} = :s") + item = _stored(dynamodb_client, table, key) + leaf = item["m"] + for _ in range(31): + leaf = leaf["M"]["k"] + assert leaf == {"S": "s"} + + +def test_a_syntax_error_after_a_long_path_comes_first(dynamodb_client, table, key): + # The service answers `Syntax error; token: "", near: ","`; ExtendDB + # words its syntax errors differently, so only the kind of error is compared. + code, message = _single_item_error(lambda: _update(dynamodb_client, table, key, f"SET {p(33)} = :s,")) + assert code == "ValidationException" + assert message.startswith("Invalid UpdateExpression: "), message + assert "nesting levels" not in message, message + + +def test_condition_expression_on_update_item(dynamodb_client, table, key): + assert _single_item_error(lambda: _update( + dynamodb_client, table, key, "SET #x = :s", names={**N, "#x": "x"}, + values={**S, ":z": {"N": "0"}}, ConditionExpression=f"size({p(33)}) > :z", + )) == ("ValidationException", too_long("ConditionExpression", 33)) + + +def test_condition_expression_on_put_item(dynamodb_client, table, key): + assert _single_item_error(lambda: dynamodb_client.put_item( + TableName=table, Item={**key, "x": {"S": "y"}}, + ConditionExpression=f"attribute_not_exists({p(33)})", ExpressionAttributeNames=N, + )) == ("ValidationException", too_long("ConditionExpression", 33)) + assert _stored(dynamodb_client, table, key)["x"] == {"S": "x"} + + +def test_condition_expression_on_delete_item(dynamodb_client, table, key): + assert _single_item_error(lambda: dynamodb_client.delete_item( + TableName=table, Key=key, ConditionExpression=f"attribute_exists({p(33)})", ExpressionAttributeNames=N, + )) == ("ValidationException", too_long("ConditionExpression", 33)) + assert "Item" in dynamodb_client.get_item(TableName=table, Key=key, ConsistentRead=True) + + +def test_condition_expression_at_the_limit(dynamodb_client, table, key): + # size() of the 32-element path is the 4 characters of the leaf string. + _update(dynamodb_client, table, key, "SET #x = :s", names={**N, "#x": "x"}, + values={**S, ":four": {"N": "4"}}, + ConditionExpression=f"attribute_exists(#x) AND size({p(32)}) = :four") + assert _stored(dynamodb_client, table, key)["x"] == {"S": "s"} + + +UNDEFINED_NAME = "An expression attribute name used in the document path is not defined; attribute name: #zz" +UNDEFINED_VALUE = "An expression attribute value used in expression is not defined; attribute value: :nope" +X = {**N, "#x": "x"} + + +# (case, update expression, names, values, condition, the message without its prefix) +SINGLE_ITEM_ORDER = [ + ("name_in_earlier_path", f"SET #zz = :s, {p(33)} = :s", N, S, None, f"Invalid UpdateExpression: {UNDEFINED_NAME}"), + ("name_first_in_long_path", "SET #zz" + ".#k" * 32 + " = :s", N, S, None, + f"Invalid UpdateExpression: {UNDEFINED_NAME}"), + ("name_last_in_long_path", f"SET {p(32)}.#zz = :s", N, S, None, f"Invalid UpdateExpression: {UNDEFINED_NAME}"), + ("condition_name_before_update", f"SET {p(33)} = :s", N, S, "attribute_exists(#zz)", + f"Invalid ConditionExpression: {UNDEFINED_NAME}"), + ("condition_value_before_update", f"SET {p(33)} = :s", X, S, "#x = :nope", + f"Invalid ConditionExpression: {UNDEFINED_VALUE}"), + ("condition_between_before_update", f"SET {p(33)} = :s", X, {**S, ":hi": {"N": "5"}, ":lo": {"N": "1"}}, + "#x BETWEEN :hi AND :lo", + "Invalid ConditionExpression: The BETWEEN operator requires upper bound to be greater than or equal to " + "lower bound; lower bound operand: AttributeValue: {N:5}, upper bound operand: AttributeValue: {N:1}"), + ("condition_operand_before_update", f"SET {p(33)} = :s", X, {**S, ":n": {"N": "1"}}, "begins_with(#x, :n)", + "Invalid ConditionExpression: Incorrect operand type for operator or function; operator or function: " + "begins_with, operand type: N"), +] + + +@pytest.mark.parametrize(("case", "expr", "names", "values", "condition", "message"), SINGLE_ITEM_ORDER, + ids=[c[0] for c in SINGLE_ITEM_ORDER]) +def test_update_item_reports_an_earlier_fault_first(dynamodb_client, table, key, case, expr, names, values, + condition, message): + kw = {"ConditionExpression": condition} if condition else {} + assert _single_item_error(lambda: _update(dynamodb_client, table, key, expr, names, values, **kw)) == ( + "ValidationException", message) + + +NESTING = "Nesting Levels have exceeded supported limits: Attributes in the item have nested levels beyond supported limit" +BETWEEN = ("The BETWEEN operator requires upper bound to be greater than or equal to lower bound; " + "lower bound operand: AttributeValue: {N:5}, upper bound operand: AttributeValue: {N:1}") + + +def deep_value() -> dict: + return nmap(32) + + +def test_a_value_nested_too_deep_is_reported_first(dynamodb_client, table, key): + assert _single_item_error(lambda: _update(dynamodb_client, table, key, f"SET {p(33)} = :d", + values={":d": deep_value()})) == ("ValidationException", NESTING) + assert _single_item_error(lambda: dynamodb_client.put_item( + TableName=table, Item={**key, "x": {"S": "y"}}, + ConditionExpression=f"attribute_exists({p(33)}) OR #m <> :d", ExpressionAttributeNames=N, + ExpressionAttributeValues={":d": deep_value()}, + )) == ("ValidationException", NESTING) + assert _single_item_error(lambda: _update(dynamodb_client, table, key, "SET #m = :d,", names={"#m": "m"}, + values={":d": deep_value()})) == ("ValidationException", NESTING) + + +def test_between_bounds_are_checked_whatever_the_item(dynamodb_client, table, key): + bounds = {":hi": {"N": "5"}, ":lo": {"N": "1"}, ":s": {"S": "s"}} + missing = {"pk": {"S": "plen"}, "sk": {"S": "between-no-item"}} + for k, cond in ((missing, "#x BETWEEN :hi AND :lo"), (key, "attribute_exists(#n) AND #x BETWEEN :hi AND :lo")): + names = {"#x": "x", "#n": "nope"} if "#n" in cond else {"#x": "x"} + assert _single_item_error(lambda: _update(dynamodb_client, table, k, "SET #x = :s", names=names, + values=bounds, ConditionExpression=cond)) == ( + "ValidationException", f"Invalid ConditionExpression: {BETWEEN}"), cond + assert "Item" not in dynamodb_client.get_item(TableName=table, Key=missing, ConsistentRead=True) + assert _error(lambda: dynamodb_client.query( + TableName=table, KeyConditionExpression="pk = :p", FilterExpression="#x BETWEEN :hi AND :lo", + ExpressionAttributeNames={"#x": "x"}, + ExpressionAttributeValues={":p": {"S": "plen-empty"}, ":hi": bounds[":hi"], ":lo": bounds[":lo"]}, + )) == ("ValidationException", f"Invalid FilterExpression: {BETWEEN}") + + +def test_projection_names_come_before_the_length(dynamodb_client, table, key): + for projection in (f"#zz, {p(33)}", "#zz" + ".#k" * 32, f"{p(32)}.#zz"): + assert _error(lambda: dynamodb_client.get_item( + TableName=table, Key=key, ProjectionExpression=projection, ExpressionAttributeNames=N, + )) == ("ValidationException", f"Invalid ProjectionExpression: {UNDEFINED_NAME}"), projection + assert _error(lambda: dynamodb_client.transact_get_items(TransactItems=[ + {"Get": {"TableName": table, "Key": key, "ProjectionExpression": "#zz"}}, + {"Get": {"TableName": table, "Key": key, "ProjectionExpression": p(33), "ExpressionAttributeNames": N}}, + ])) == ("ValidationException", f"Invalid ProjectionExpression: {UNDEFINED_NAME}") + + +def test_transact_write_items_update(dynamodb_client, table, key): + assert _error(lambda: dynamodb_client.transact_write_items(TransactItems=[{"Update": { + "TableName": table, "Key": key, "UpdateExpression": f"SET {p(33)} = :s", + "ExpressionAttributeNames": N, "ExpressionAttributeValues": S, + }}])) == ("ValidationException", too_long("UpdateExpression", 33)) + + +def test_transact_write_items_condition_check(dynamodb_client, table, key): + assert _error(lambda: dynamodb_client.transact_write_items(TransactItems=[{"ConditionCheck": { + "TableName": table, "Key": key, "ConditionExpression": f"attribute_exists({p(33)})", + "ExpressionAttributeNames": N, + }}])) == ("ValidationException", too_long("ConditionExpression", 33)) + + +def test_transact_write_items_put_condition(dynamodb_client, table, key): + assert _error(lambda: dynamodb_client.transact_write_items(TransactItems=[{"Put": { + "TableName": table, "Item": {**key, "x": {"S": "y"}}, + "ConditionExpression": f"attribute_not_exists({p(33)})", "ExpressionAttributeNames": N, + }}])) == ("ValidationException", too_long("ConditionExpression", 33)) + assert _stored(dynamodb_client, table, key)["x"] == {"S": "x"} + + +def test_get_item_projection(dynamodb_client, table, key): + assert _error(lambda: dynamodb_client.get_item( + TableName=table, Key=key, ProjectionExpression=p(33), ExpressionAttributeNames=N, + )) == ("ValidationException", too_long("ProjectionExpression", 33)) + assert _error(lambda: dynamodb_client.get_item( + TableName=table, Key=key, ProjectionExpression="#m" + "[0]" * 32, ExpressionAttributeNames={"#m": "m"}, + )) == ("ValidationException", too_long("ProjectionExpression", 33)) + + +def test_get_item_projection_at_the_limit(dynamodb_client, table, key): + item = dynamodb_client.get_item(TableName=table, Key=key, ProjectionExpression=p(32), + ExpressionAttributeNames=N)["Item"] + assert set(item) == {"m"} + + +def test_batch_get_item_projection(dynamodb_client, table, key): + assert _error(lambda: dynamodb_client.batch_get_item(RequestItems={table: { + "Keys": [key], "ProjectionExpression": p(33), "ExpressionAttributeNames": N, + }})) == ("ValidationException", too_long("ProjectionExpression", 33)) + + +def test_transact_get_items_projection(dynamodb_client, table, key): + assert _error(lambda: dynamodb_client.transact_get_items(TransactItems=[{"Get": { + "TableName": table, "Key": key, "ProjectionExpression": p(33), "ExpressionAttributeNames": N, + }}])) == ("ValidationException", too_long("ProjectionExpression", 33)) + + +def _query(client, table, **kw): + values = {":p": {"S": "plen"}, **kw.pop("values", {})} + return client.query(TableName=table, KeyConditionExpression=kw.pop("key", "pk = :p"), + ExpressionAttributeNames=N, ExpressionAttributeValues=values, **kw) + + +def test_query_filter(dynamodb_client, table, key): + assert _error(lambda: _query(dynamodb_client, table, FilterExpression=f"attribute_exists({p(33)})")) == ( + "ValidationException", too_long("FilterExpression", 33)) + assert _query(dynamodb_client, table, FilterExpression=f"attribute_exists({p(32)})")["Count"] >= 1 + + +def test_query_projection(dynamodb_client, table, key): + assert _error(lambda: _query(dynamodb_client, table, ProjectionExpression=p(33))) == ( + "ValidationException", too_long("ProjectionExpression", 33)) + + +def test_query_key_condition(dynamodb_client, table, key): + assert _error(lambda: _query(dynamodb_client, table, key=f"pk = :p AND {p(33)} = :s", values=S)) == ( + "ValidationException", too_long("KeyConditionExpression", 33)) + assert _error(lambda: _query(dynamodb_client, table, key=f"pk = :p AND {p(32)} = :s", values=S)) == ( + "ValidationException", + "Invalid KeyConditionExpression: KeyConditionExpressions cannot have conditions on nested attributes") + + +def test_query_filter_is_checked_before_the_projection(dynamodb_client, table, key): + assert _error(lambda: _query(dynamodb_client, table, + FilterExpression=f"attribute_exists(#zz) OR attribute_exists({p(33)})")) == ( + "ValidationException", f"Invalid FilterExpression: {UNDEFINED_NAME}") + assert _error(lambda: _query(dynamodb_client, table, ProjectionExpression=p(33), + FilterExpression="attribute_exists(#zz)")) == ( + "ValidationException", f"Invalid FilterExpression: {UNDEFINED_NAME}") + + +def test_scan_filter_is_checked_before_the_projection(dynamodb_client, table, key): + for flt, names, message in (("attribute_exists(#zz)", N, UNDEFINED_NAME), ("#x = :nope", X, UNDEFINED_VALUE)): + assert _error(lambda: dynamodb_client.scan( + TableName=table, Limit=1, ProjectionExpression=p(33), FilterExpression=flt, + ExpressionAttributeNames=names, + )) == ("ValidationException", f"Invalid FilterExpression: {message}"), flt + + +def test_scan_filter_and_projection(dynamodb_client, table, key): + assert _error(lambda: dynamodb_client.scan( + TableName=table, Limit=1, FilterExpression=f"{p(33)} = :s", + ExpressionAttributeNames=N, ExpressionAttributeValues=S, + )) == ("ValidationException", too_long("FilterExpression", 33)) + assert _error(lambda: dynamodb_client.scan( + TableName=table, Limit=1, ProjectionExpression=p(33), ExpressionAttributeNames=N, + )) == ("ValidationException", too_long("ProjectionExpression", 33)) From ea464eba6d6d6141dd611557707eb37b38419791 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:43:46 +0000 Subject: [PATCH 03/14] fix(expression): value nesting after mixed parameters and Item numbers The service reports an invalid number in the Item or the Key, then legacy and expression parameters used together, before an ExpressionAttributeValue nested more than 32 levels (measured 2026-10-26 at 05:15 and 05:20 UTC, each request twice). The earlier move put the nesting check ahead of both: UpdateItem now runs it right after the check for mixed parameters, and PutItem checks the Item's numbers just before it. DeleteItem already ran it after the mixed-parameter check. The path_length module comment now says the key condition parser checks the length before the names are checked, and a unit test covers the BETWEEN bounds in the semantic walk. --- crates/core/src/expression/path_length.rs | 6 ++-- crates/core/src/expression/semantics/tests.rs | 22 ++++++++++++++ crates/engine/src/put_item.rs | 6 ++-- crates/engine/src/update_item.rs | 29 ++++++++++--------- 4 files changed, 45 insertions(+), 18 deletions(-) diff --git a/crates/core/src/expression/path_length.rs b/crates/core/src/expression/path_length.rs index bfa33aff1..1db4d21c1 100644 --- a/crates/core/src/expression/path_length.rs +++ b/crates/core/src/expression/path_length.rs @@ -9,8 +9,10 @@ //! nesting levels: `. It checks a path's `#name` references first and then //! its length, path by path in the order the paths appear, so an undefined //! `#name` in an earlier path or inside the long path is reported instead -//! (measured 2026-10-26, us-east-1). The callers run the check where they -//! resolve each path's names. +//! (measured 2026-10-26, us-east-1). The semantic walk and the projection +//! resolution run the check right after each path's names; the key condition +//! parser runs it before the names are checked, ahead of its nested-attribute +//! refusal. use super::ast::PathElement; diff --git a/crates/core/src/expression/semantics/tests.rs b/crates/core/src/expression/semantics/tests.rs index 52aae7b06..a39f64f49 100644 --- a/crates/core/src/expression/semantics/tests.rs +++ b/crates/core/src/expression/semantics/tests.rs @@ -432,3 +432,25 @@ fn key_condition_function_names() { } assert_eq!(key_condition_err("pk = :p AND begins_with(sk, :v)"), "OK"); } + +/// The BETWEEN bounds are checked at request time (measured 2026-10-26, +/// HBTW-1: refused on a missing key and after a false AND). +#[test] +fn between_bounds_are_checked_in_the_walk() { + let m = maps( + &[], + &[ + (":hi", AttributeValue::N("5".to_owned())), + (":lo", AttributeValue::N("1".to_owned())), + ], + ); + assert_eq!( + condition_err("a BETWEEN :hi AND :lo", &m), + format!( + "{C}The BETWEEN operator requires upper bound to be greater than or equal to lower \ + bound; lower bound operand: AttributeValue: {{N:5}}, upper bound operand: \ + AttributeValue: {{N:1}}" + ) + ); + assert!(condition_err("attribute_exists(b) AND a BETWEEN :hi AND :lo", &m).contains("BETWEEN")); +} diff --git a/crates/engine/src/put_item.rs b/crates/engine/src/put_item.rs index 1d9991876..82c2f758f 100755 --- a/crates/engine/src/put_item.rs +++ b/crates/engine/src/put_item.rs @@ -138,9 +138,11 @@ pub async fn handle_put_item( // alike, while 31 levels is accepted. TransactWriteItems deliberately does // NOT get this check: the same 32-level condition-only value is accepted // inside a transaction on every sub-op shape (also measured). It comes - // before the ConditionExpression and the table lookup (measured - // 2026-10-26). + // after an invalid number in the Item and before the ConditionExpression + // and the table lookup (measured 2026-10-26), so the Item's numbers are + // checked here first; `validate_put_item` checks them again later. if let Some(values) = &input.expression_attribute_values { + extenddb_core::validation::validate_item_numbers(&input.item)?; extenddb_core::validation::validate_attribute_values_nesting_depth(values.values())?; } diff --git a/crates/engine/src/update_item.rs b/crates/engine/src/update_item.rs index 91a090e01..e6576c2f2 100755 --- a/crates/engine/src/update_item.rs +++ b/crates/engine/src/update_item.rs @@ -62,20 +62,6 @@ pub async fn handle_update_item( extenddb_core::validation::validate_table_name(&input.table_name, &ctx.limits)?; - // Amazon DynamoDB enforces the nesting-depth limit on EVERY - // ExpressionAttributeValue, condition-only placeholders included: a - // 32-level value referenced solely by a ConditionExpression answers the - // nesting ValidationException rather than evaluating the condition. - // An earlier measurement had condition-only values exempt, and some - // regions did behave that way; re-measured 2026-08-24, both us-east-1 and - // eu-west-2 apply the limit to the whole map, so the per-placeholder walk - // this replaced is gone. A 31-level value still passes and the condition - // evaluates normally. It comes before every expression check, the unused - // names and values, the table lookup and the key (measured 2026-10-26). - if let Some(values) = &input.expression_attribute_values { - extenddb_core::validation::validate_attribute_values_nesting_depth(values.values())?; - } - // Validate Update/Condition expressions (and AttributeUpdates // desugaring) before the existence check; key, item-content nesting, and // the no-key-update checks stay after (post-existence on Amazon DynamoDB). @@ -103,6 +89,21 @@ pub async fn handle_update_item( ], )?; + // Amazon DynamoDB enforces the nesting-depth limit on EVERY + // ExpressionAttributeValue, condition-only placeholders included: a + // 32-level value referenced solely by a ConditionExpression answers the + // nesting ValidationException rather than evaluating the condition. + // An earlier measurement had condition-only values exempt, and some + // regions did behave that way; re-measured 2026-08-24, both us-east-1 and + // eu-west-2 apply the limit to the whole map, so the per-placeholder walk + // this replaced is gone. A 31-level value still passes and the condition + // evaluates normally. It comes after the check for legacy and expression + // parameters used together and before the unused names and values, every + // expression check, the table lookup and the key (measured 2026-10-26). + if let Some(values) = &input.expression_attribute_values { + extenddb_core::validation::validate_attribute_values_nesting_depth(values.values())?; + } + // Desugar legacy AttributeUpdates into UpdateExpression if present. let (effective_update_expr, extra_expr_values, extra_expr_names) = if let Some(attr_updates) = &input.attribute_updates { From 8549bc023a608e3695f09c7b71038f1021610df5 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:43:46 +0000 Subject: [PATCH 04/14] test(expression): mixed parameters and Item numbers before value nesting UpdateItem with `AttributeUpdates`, `Expected` or `ConditionalOperator` beside an expression and a 32-level value answers the mixed-parameter error, and PutItem with `{N: abc}` in the Item, at the top level or nested, answers the number error (measured 2026-10-26 at 05:15 and 05:20 UTC). --- tests/test_document_path_length.py | 41 ++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/tests/test_document_path_length.py b/tests/test_document_path_length.py index d857b9407..c993407e1 100644 --- a/tests/test_document_path_length.py +++ b/tests/test_document_path_length.py @@ -12,8 +12,8 @@ path in the order the paths appear, and finishes the checks of the FilterExpression before the ProjectionExpression and of the ConditionExpression before the UpdateExpression. Measured on 2026-10-26 at -02:26, 02:29, 03:38, 03:39, 04:21, 04:40, 04:41 and 04:43 UTC (us-east-1), each case -twice. +02:26, 02:29, 03:38, 03:39, 04:21, 04:40, 04:41, 04:43, 05:15 and 05:20 UTC +(us-east-1), each case twice. PutItem, UpdateItem and DeleteItem prefix every expression error with ``1 validation error detected: ``; the other operations do not. That prefix @@ -233,6 +233,43 @@ def test_a_value_nested_too_deep_is_reported_first(dynamodb_client, table, key): values={":d": deep_value()})) == ("ValidationException", NESTING) +MIXING = "Can not use both expression and non-expression parameters in the same request: " +BAD_NUMBER = "The parameter cannot be converted to a numeric value: abc" + + +# (case, extra UpdateItem arguments, non-expression and expression parameters named) +MIXED = [ + ("attribute_updates", {"UpdateExpression": "SET #m = :d", + "AttributeUpdates": {"y": {"Action": "PUT", "Value": {"S": "v"}}}}, + "{AttributeUpdates}", "{UpdateExpression}"), + ("expected", {"UpdateExpression": "SET #m = :d", "Expected": {"x": {"Exists": False}}}, + "{Expected}", "{UpdateExpression}"), + ("conditional_operator", {"UpdateExpression": "SET #m = :d", "ConditionalOperator": "AND"}, + "{ConditionalOperator}", "{UpdateExpression}"), + ("attribute_updates_and_condition", {"ConditionExpression": "#m <> :d", + "AttributeUpdates": {"y": {"Action": "PUT", "Value": {"S": "v"}}}}, + "{AttributeUpdates}", "{ConditionExpression}"), +] + + +@pytest.mark.parametrize(("case", "args", "legacy", "expression"), MIXED, ids=[c[0] for c in MIXED]) +def test_mixed_parameters_come_before_a_value_nested_too_deep(dynamodb_client, table, key, case, args, legacy, + expression): + assert _single_item_error(lambda: dynamodb_client.update_item( + TableName=table, Key=key, ExpressionAttributeNames={"#m": "m"}, + ExpressionAttributeValues={":d": deep_value()}, **args, + )) == ("ValidationException", + f"{MIXING}Non-expression parameters: {legacy} Expression parameters: {expression}") + + +@pytest.mark.parametrize("bad", [{"N": "abc"}, {"M": {"z": {"N": "abc"}}}], ids=["top_level", "nested"]) +def test_an_invalid_number_in_the_item_comes_before_a_value_nested_too_deep(dynamodb_client, table, key, bad): + assert _single_item_error(lambda: dynamodb_client.put_item( + TableName=table, Item={**key, "y": bad}, ConditionExpression="#m <> :d", + ExpressionAttributeNames={"#m": "m"}, ExpressionAttributeValues={":d": deep_value()}, + )) == ("ValidationException", BAD_NUMBER) + + def test_between_bounds_are_checked_whatever_the_item(dynamodb_client, table, key): bounds = {":hi": {"N": "5"}, ":lo": {"N": "1"}, ":s": {"S": "s"}} missing = {"pk": {"S": "plen"}, "sk": {"S": "between-no-item"}} From d508588c925d04398a6d95747dd2d100d4208697 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:50:07 +0000 Subject: [PATCH 05/14] fix(expression): check a projection path's overlap before the next path The service checks projection paths one after another in text order. It checks a path's names, then its length, then its overlap with an earlier path. GetItem, Scan, Query, BatchGetItem and TransactGetItems with `#k, #k, <33 elements>` answer the overlap of the two `#k` paths. `#k, <33 elements>, #k` and `#m, <33 elements>` answer the length. Measured 2026-11-12 in us-east-1, each request twice. ExtendDB checked the length in `resolve_paths` and the overlap after it resolved every path, so the first request answered the length. `resolve_paths` now checks each path against the earlier paths right after its length, and the separate overlap pass is gone. The update overlap check uses the same loop. Both now name the first path that overlaps an earlier one. On the service, `a, b, b.y, a.x` answers `[b]` and `[b, y]` for a projection and for an UpdateExpression. ExtendDB named `[a]` and `[a, x]`. --- crates/core/src/expression/path_length.rs | 21 +++++-- crates/core/src/expression/projection.rs | 62 +++++++++---------- crates/core/src/expression/resolver.rs | 9 +-- crates/core/src/expression/semantics/tests.rs | 7 +++ tests/test_document_path_length.py | 37 +++++++++++ 5 files changed, 94 insertions(+), 42 deletions(-) diff --git a/crates/core/src/expression/path_length.rs b/crates/core/src/expression/path_length.rs index 1db4d21c1..72c386674 100644 --- a/crates/core/src/expression/path_length.rs +++ b/crates/core/src/expression/path_length.rs @@ -97,17 +97,28 @@ mod tests { } #[test] - fn a_projection_path_is_checked_after_its_names() { + fn a_projection_path_is_checked_after_its_names_and_before_its_overlap() { let compile = |text: &str| { let paths = crate::expression::parse_projection(&crate::expression::tokenize(text).unwrap()) .unwrap(); crate::expression::Projection::compile(&paths, &maps(), true).map(|_| ()) }; - assert_eq!( - message(compile(&path_text("#m", 33))), - format!("Invalid ProjectionExpression: {LEVELS_33}") - ); + let long = path_text("#m", 33); + let length = format!("Invalid ProjectionExpression: {LEVELS_33}"); + let overlap = "Invalid ProjectionExpression: Two document paths overlap with each other; \ + must remove or rewrite one of these paths; path one: [k], path two: [k]"; + // Measured 2026-11-12 (us-east-1), each request twice. + for (text, want) in [ + (long.clone(), length.as_str()), + (format!("k, k, {long}"), overlap), + (format!("{long}, k, k"), length.as_str()), + (format!("k, {long}, k"), length.as_str()), + (format!("#m, {long}"), length.as_str()), + (format!("{}, k, k", path_text("#m", 32)), overlap), + ] { + assert_eq!(message(compile(&text)), want, "{text}"); + } assert!(message(compile(&path_text("#zz", 33))).contains("attribute name: #zz")); assert!(compile(&path_text("#m", 32)).is_ok()); } diff --git a/crates/core/src/expression/projection.rs b/crates/core/src/expression/projection.rs index 5c918598c..bc80cf9f8 100755 --- a/crates/core/src/expression/projection.rs +++ b/crates/core/src/expression/projection.rs @@ -70,10 +70,8 @@ impl Projection { maps: &ExpressionMaps, reject_overlap: bool, ) -> Result { - let resolved = resolve_paths(paths, maps).map_err(prefix_projection_error)?; - if reject_overlap { - check_overlap(&resolved)?; - } + let overlap = reject_overlap.then_some(super::ExpressionKind::Projection); + let resolved = resolve_paths(paths, maps, overlap).map_err(prefix_projection_error)?; Ok(Self { root: build_trie(resolved), }) @@ -131,11 +129,18 @@ pub(crate) enum ResolvedElement { } /// Resolve `#name` references in parsed paths, rejecting index-start paths. +/// +/// The service checks the paths one after another in text order: a path's +/// names, then its length, then, when `overlap` names the expression kind, +/// whether it overlaps an earlier path (one is a prefix of the other). So +/// `#k, #k, <33 elements>` answers the overlap, and `#m, <33 elements>` and +/// `#k, <33 elements>, #k` the length (measured 2026-11-12, us-east-1). pub(crate) fn resolve_paths( paths: &[Vec], maps: &ExpressionMaps, + overlap: Option, ) -> Result>, DynamoDbError> { - let mut resolved = Vec::with_capacity(paths.len()); + let mut resolved: Vec> = Vec::with_capacity(paths.len()); for path in paths { if path.is_empty() { continue; @@ -158,42 +163,27 @@ pub(crate) fn resolve_paths( } } } - // The length after the path's names, as the service checks it. if let Some(msg) = super::path_length::too_many_levels(path) { return Err(DynamoDbError::ValidationException(msg)); } + // Siblings are fine; the message names the earlier path first. + if let Some(kind) = overlap + && let Some(earlier) = resolved + .iter() + .find(|e| is_prefix(e, &elems) || is_prefix(&elems, e)) + { + return Err(DynamoDbError::ValidationException(format!( + "Invalid {kind}: Two document paths overlap with each other; \ + must remove or rewrite one of these paths; path one: {}, path two: {}", + render_path(earlier), + render_path(&elems), + ))); + } resolved.push(elems); } Ok(resolved) } -/// Reject paths where one is a prefix of another (DynamoDB's overlap rule), -/// reporting the first offending pair in expression order. Siblings are fine. -fn check_overlap(resolved: &[Vec]) -> Result<(), DynamoDbError> { - check_overlap_for(resolved, super::ExpressionKind::Projection) -} - -/// The overlap rule for any expression kind that names document paths; the -/// message carries the kind's `Invalid :` prefix. -pub(crate) fn check_overlap_for( - resolved: &[Vec], - kind: super::ExpressionKind, -) -> Result<(), DynamoDbError> { - for i in 0..resolved.len() { - for j in (i + 1)..resolved.len() { - if is_prefix(&resolved[i], &resolved[j]) || is_prefix(&resolved[j], &resolved[i]) { - return Err(DynamoDbError::ValidationException(format!( - "Invalid {kind}: Two document paths overlap with each other; \ - must remove or rewrite one of these paths; path one: {}, path two: {}", - render_path(&resolved[i]), - render_path(&resolved[j]), - ))); - } - } - } - Ok(()) -} - /// Return true when `a` is a prefix of `b` (equal paths included). fn is_prefix(a: &[ResolvedElement], b: &[ResolvedElement]) -> bool { a.len() <= b.len() && a == &b[..a.len()] @@ -640,6 +630,12 @@ mod tests { "Invalid ProjectionExpression: Two document paths overlap with each other; \ must remove or rewrite one of these paths; path one: [a, b], path two: [a]" ); + // The first path that overlaps an earlier one (measured 2026-11-12). + assert_eq!( + overlap_msg("a, b, b.y, a.x"), + "Invalid ProjectionExpression: Two document paths overlap with each other; \ + must remove or rewrite one of these paths; path one: [b], path two: [b, y]" + ); } #[test] diff --git a/crates/core/src/expression/resolver.rs b/crates/core/src/expression/resolver.rs index 6d1e11401..0acd688f5 100755 --- a/crates/core/src/expression/resolver.rs +++ b/crates/core/src/expression/resolver.rs @@ -332,8 +332,10 @@ pub fn validate_unused_attributes( /// prefix of the other, across all four sections, after `#name` resolution: /// `SET a = :v, a = :w`, `SET m = :v, m.x = :w`, `SET a.b = :v REMOVE a`, and /// `SET #l[1] = :v, #l[1].x = :w` with `#l` bound to `lst` all fail. Siblings -/// (`m.x` and `m.y`) are fine. The first offending pair in expression order is -/// named, rendered as the service renders it: `[lst, [1]]`. +/// (`m.x` and `m.y`) are fine. The first path in expression order that +/// overlaps an earlier one is named after that earlier path, rendered as the +/// service renders it: `[lst, [1]]` (`SET a = :v, b = :v, b.y = :v, a.x = :v` +/// names `[b]` and `[b, y]`, measured 2026-11-12). /// /// # Errors /// @@ -353,8 +355,7 @@ pub fn validate_update_paths_disjoint( | UpdateAction::Delete { path, .. } => path.clone(), }) .collect(); - let resolved = super::projection::resolve_paths(&paths, maps)?; - super::projection::check_overlap_for(&resolved, super::ExpressionKind::Update) + super::projection::resolve_paths(&paths, maps, Some(super::ExpressionKind::Update)).map(|_| ()) } fn collect_expr_refs( diff --git a/crates/core/src/expression/semantics/tests.rs b/crates/core/src/expression/semantics/tests.rs index a39f64f49..cdefe7e86 100644 --- a/crates/core/src/expression/semantics/tests.rs +++ b/crates/core/src/expression/semantics/tests.rs @@ -251,6 +251,13 @@ fn overlap_after_the_walk() { "{U}Two document paths overlap with each other; must remove or rewrite one of these paths; path one: [a], path two: [a, b]" ) ); + // The first path that overlaps an earlier one (measured 2026-11-12). + assert_eq!( + update_err("SET a = :v, b = :v, b.y = :v, a.x = :v", &m), + format!( + "{U}Two document paths overlap with each other; must remove or rewrite one of these paths; path one: [b], path two: [b, y]" + ) + ); } #[test] diff --git a/tests/test_document_path_length.py b/tests/test_document_path_length.py index c993407e1..f384a6fee 100644 --- a/tests/test_document_path_length.py +++ b/tests/test_document_path_length.py @@ -297,6 +297,43 @@ def test_projection_names_come_before_the_length(dynamodb_client, table, key): ])) == ("ValidationException", f"Invalid ProjectionExpression: {UNDEFINED_NAME}") +OVERLAP_K = ("Invalid ProjectionExpression: Two document paths overlap with each other; must remove or rewrite " + "one of these paths; path one: [k], path two: [k]") + +# (case, projection, message): the service checks the paths one after another, +# each path's length before its overlap with an earlier path (measured +# 2026-11-12, each request twice). +PROJECTION_ORDER = [ + ("overlap_before_a_later_length", f"#k, #k, {p(33)}", OVERLAP_K), + ("length_before_a_later_overlap", f"{p(33)}, #k, #k", too_long("ProjectionExpression", 33)), + ("length_between_overlapping_paths", f"#k, {p(33)}, #k", too_long("ProjectionExpression", 33)), + ("length_before_its_own_overlap", f"#m, {p(33)}", too_long("ProjectionExpression", 33)), + ("overlap_after_a_path_at_the_limit", f"{p(32)}, #k, #k", OVERLAP_K), +] + + +@pytest.mark.parametrize(("case", "projection", "message"), PROJECTION_ORDER, ids=[c[0] for c in PROJECTION_ORDER]) +def test_projection_paths_are_checked_one_after_another(dynamodb_client, table, key, case, projection, message): + assert _error(lambda: dynamodb_client.get_item( + TableName=table, Key=key, ProjectionExpression=projection, ExpressionAttributeNames=N, + )) == ("ValidationException", message) + + +def test_projection_overlap_before_a_later_length_on_every_read(dynamodb_client, table, key): + projection = f"#k, #k, {p(33)}" + reads = { + "scan": lambda: dynamodb_client.scan( + TableName=table, Limit=1, ProjectionExpression=projection, ExpressionAttributeNames=N), + "query": lambda: _query(dynamodb_client, table, ProjectionExpression=projection), + "batch_get_item": lambda: dynamodb_client.batch_get_item(RequestItems={table: { + "Keys": [key], "ProjectionExpression": projection, "ExpressionAttributeNames": N}}), + "transact_get_items": lambda: dynamodb_client.transact_get_items(TransactItems=[{"Get": { + "TableName": table, "Key": key, "ProjectionExpression": projection, "ExpressionAttributeNames": N}}]), + } + for operation, read in reads.items(): + assert _error(read) == ("ValidationException", OVERLAP_K), operation + + def test_transact_write_items_update(dynamodb_client, table, key): assert _error(lambda: dynamodb_client.transact_write_items(TransactItems=[{"Update": { "TableName": table, "Key": key, "UpdateExpression": f"SET {p(33)} = :s", From 617ab86e403cd2c3b5c18c7bf05767a0012274ff Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:51:52 +0000 Subject: [PATCH 06/14] fix(transact): check an Update's condition before its UpdateExpression On the service, a TransactWriteItems Update whose ConditionExpression names an undefined `#zz` answers the undefined-name error for `#zz` first. That error comes before each of these UpdateExpression defects: - a path of 33 elements - a syntax error - an undefined name or an undefined value - overlapping paths - a reserved word - an ADD of a string With BETWEEN bounds out of order in the condition and a 33-element SET path, the service answers the bounds error. Measured 2026-11-12 in us-east-1, each request two or six times. On 2026-10-14 the service answered the UpdateExpression first, and the transaction path kept that order. With the new path length check, a long SET path beside an undefined name in the condition answered the length. Before the check, it answered the condition's error. The transaction path now checks the condition first, as UpdateItem does. test_expression_semantics.py expected the old order, and its transaction rows now expect the condition's error. --- crates/engine/src/transact_write_items.rs | 30 ++++++++++--------- tests/test_document_path_length.py | 35 +++++++++++++++++++++++ tests/test_expression_semantics.py | 21 +++++++------- 3 files changed, 63 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/transact_write_items.rs b/crates/engine/src/transact_write_items.rs index e64f7ecf1..c979887ff 100755 --- a/crates/engine/src/transact_write_items.rs +++ b/crates/engine/src/transact_write_items.rs @@ -491,20 +491,18 @@ fn parse_write_expressions( validate_value_map_nesting(values)?; // Inside a transaction the service checks an Update item's - // UpdateExpression (syntax, the ordered semantic walk, overlapping paths) - // before its ConditionExpression, the reverse of UpdateItem; then the - // unused names and values; then, for a Put, the item's size and the - // item's nesting (measured: an oversize Put with an unused value reports - // the value, an oversize item one reports its size ahead of the next - // item's defects, and one item with a long attribute name, an oversize - // item and a deep item reports the name first and the nesting last). + // ConditionExpression before its UpdateExpression, as UpdateItem does: + // a condition with an undefined name or BETWEEN bounds out of order beats + // an UpdateExpression syntax error, undefined name or value, overlap, + // reserved word, operand type and path length (measured 2026-11-12, each + // request twice; on 2026-10-14 the service answered the UpdateExpression + // first). Then come the unused names and values; then, for a Put, the + // item's size and the item's nesting (measured: an oversize Put with an + // unused value reports the value, an oversize item one reports its size + // ahead of the next item's defects, and one item with a long attribute + // name, an oversize item and a deep item reports the name first and the + // nesting last). let maps = build_expression_maps(names, values); - let actions = match update_expression { - Some(expr) => Some(crate::expression_helpers::parse_update_expr_checked( - expr, &maps, limits, - )?), - None => None, - }; let condition = match condition_expression { // A ConditionCheck's expression is required, so an empty string is // parsed and refused as empty (measured 2026-10-27: `Invalid @@ -521,6 +519,12 @@ fn parse_write_expressions( } _ => None, }; + let actions = match update_expression { + Some(expr) => Some(crate::expression_helpers::parse_update_expr_checked( + expr, &maps, limits, + )?), + None => None, + }; // Transactions accept names/values with no expression (unlike single-item // APIs); only check for unused refs when some expression is present. if condition.is_some() || actions.is_some() { diff --git a/tests/test_document_path_length.py b/tests/test_document_path_length.py index f384a6fee..0fa93585b 100644 --- a/tests/test_document_path_length.py +++ b/tests/test_document_path_length.py @@ -341,6 +341,41 @@ def test_transact_write_items_update(dynamodb_client, table, key): }}])) == ("ValidationException", too_long("UpdateExpression", 33)) +# (case, update expression, names, values): one UpdateExpression defect each, +# beside a condition with an undefined name. The service answers the +# condition first, in a transaction as in UpdateItem (measured 2026-11-12, +# each request twice). +TRANSACTION_UPDATE_DEFECTS = [ + ("length", f"SET {p(33)} = :s", N, S), + ("syntax", "SET a = = :s", None, S), + ("undefined_name", "SET #nope = :s", None, S), + ("undefined_value", "SET a = :nope", None, None), + ("overlap", "SET a = :s, a.b = :s", None, S), + ("reserved_word", "SET name = :s", None, S), +] + + +@pytest.mark.parametrize(("case", "expr", "names", "values"), TRANSACTION_UPDATE_DEFECTS, + ids=[c[0] for c in TRANSACTION_UPDATE_DEFECTS]) +def test_transact_write_items_update_checks_the_condition_first(dynamodb_client, table, key, case, expr, names, + values): + update = {"TableName": table, "Key": key, "UpdateExpression": expr, "ConditionExpression": "attribute_exists(#zz)"} + if names: + update["ExpressionAttributeNames"] = names + if values: + update["ExpressionAttributeValues"] = values + assert _error(lambda: dynamodb_client.transact_write_items(TransactItems=[{"Update": update}])) == ( + "ValidationException", f"Invalid ConditionExpression: {UNDEFINED_NAME}") + + +def test_transact_write_items_update_checks_the_between_bounds_first(dynamodb_client, table, key): + assert _error(lambda: dynamodb_client.transact_write_items(TransactItems=[{"Update": { + "TableName": table, "Key": key, "UpdateExpression": f"SET {p(33)} = :s", + "ConditionExpression": "#x BETWEEN :hi AND :lo", "ExpressionAttributeNames": X, + "ExpressionAttributeValues": {**S, ":hi": {"N": "5"}, ":lo": {"N": "1"}}, + }}])) == ("ValidationException", f"Invalid ConditionExpression: {BETWEEN}") + + def test_transact_write_items_condition_check(dynamodb_client, table, key): assert _error(lambda: dynamodb_client.transact_write_items(TransactItems=[{"ConditionCheck": { "TableName": table, "Key": key, "ConditionExpression": f"attribute_exists({p(33)})", diff --git a/tests/test_expression_semantics.py b/tests/test_expression_semantics.py index e06872f70..f1927451b 100644 --- a/tests/test_expression_semantics.py +++ b/tests/test_expression_semantics.py @@ -21,8 +21,9 @@ `SET a = :v SET b = :q` reports `:q` and `SET a = :v SET b = :v ADD n :s` reports the repeated `SET`. - Every unused name or value is listed in one set. - - UpdateItem checks the ConditionExpression before the UpdateExpression; - inside TransactWriteItems the UpdateExpression comes first. + - UpdateItem checks the ConditionExpression before the UpdateExpression, + and so does TransactWriteItems (re-measured 2026-11-12; on 2026-10-14 + the transaction answered the UpdateExpression first). ConditionExpression and FilterExpression: - the six condition functions are matched as written; `if_not_exists` and @@ -74,7 +75,6 @@ OPERAND_COUNT = "Incorrect number of operands for operator or function; operator or function: {}, number of operands: {}" NEEDS_PATH = "Operator or function requires a document path; operator or function: {}" SECTION_ONCE = 'The "{}" section can only be used once in an update expression;' -OVERLAP_A_AB = "Two document paths overlap with each other; must remove or rewrite one of these paths; path one: [a], path two: [a, b]" EVAL_TYPE = "An operand in the update expression has an incorrect data type" KEY_SCHEMA = "The provided key element does not match the schema" EMPTY_ARGS_SYNTAX = 'Syntax error; token: ")", near: "()"' @@ -407,16 +407,17 @@ def test_update_item_checks_the_condition_first(self, dynamodb_client, table): P + C + UNDEF_NAME.format("#b")) _expect_prefix(_update(dynamodb_client, table, "SET #a = :v", {":v": N}, condition="attribute_exists("), P + C) - def test_transaction_checks_the_update_first(self, dynamodb_client, table): + def test_transaction_checks_the_condition_first(self, dynamodb_client, table): _expect(_transact_update(dynamodb_client, table, "SET #a = :v", {":v": N}, condition="attribute_exists(#b)"), - U + UNDEF_NAME.format("#a")) - _expect(_transact_update(dynamodb_client, table, "SET #a = :v", {":v": N}, condition="attribute_exists("), - U + UNDEF_NAME.format("#a")) + C + UNDEF_NAME.format("#b")) + _expect_prefix(_transact_update(dynamodb_client, table, "SET #a = :v", {":v": N}, condition="attribute_exists("), + C) _expect(_transact_update(dynamodb_client, table, "SET a = :v, a.b = :v", {":v": N}, condition="attribute_exists(#b)"), - U + OVERLAP_A_AB) + C + UNDEF_NAME.format("#b")) _expect(_transact_update(dynamodb_client, table, "ADD n :s", {":s": S}, condition="attribute_exists(#b)"), - U + ADD_DELETE_TYPE.format("ADD", "STRING")) - _expect_prefix(_transact_update(dynamodb_client, table, "SET a = ", condition="attribute_exists(#b)"), U) + C + UNDEF_NAME.format("#b")) + _expect(_transact_update(dynamodb_client, table, "SET a = ", condition="attribute_exists(#b)"), + C + UNDEF_NAME.format("#b")) class TestUnusedKeysAreListedTogether: From 91060d07fb739ad24eaf14285b0b279a3242fa31 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:55:26 +0000 Subject: [PATCH 07/14] fix(put): check the Item's numbers and nesting before the condition On the service, PutItem with `n: {N: "abc"}` in the Item and the condition `attribute_exists(<33 elements>)` answers the number error. This holds with no ExpressionAttributeValues in the request. The answer is `1 validation error detected: The parameter cannot be converted to a numeric value: abc`. An Item attribute 33 maps deep answers the nesting error beside the same condition. It also answers the nesting error beside `a BETWEEN :hi AND :lo` with 5 and 1. A TransactWriteItems Put with that Item answers the nesting error too. The Item's numbers and nesting also come before these condition faults: - a syntax error - an undefined name or value - an unused value - a reserved word The nesting also comes before the item size. A Put whose Item nests 32, 33 or 40 lists, or 32, 33 or 40 maps, answers the nesting error. It does so beside a condition with an undefined value and beside an item over 400 KB. Measured 2026-11-12 in us-east-1, each request twice. PutItem checked the Item's numbers early only when the request carried ExpressionAttributeValues. It checked the nesting after the table lookup. So the new path length check and the BETWEEN bounds check answered first. PutItem now checks both right after the table name, with or without values. A TransactWriteItems Put now checks its Item's nesting before the item's expressions instead of after its size. test_transact_write_phase_order.py expected the earlier order (measured 2026-10-27) in two rows. Both rows now expect the nesting error. A comment said that TransactWriteItems does not check the nesting of its values. The comment now points at `validate_value_map_nesting`. On the service, a TransactWriteItems Put or ConditionCheck refuses a value 32 maps deep that only the condition reads, and accepts 31 maps. Measured 2026-11-12. --- crates/engine/src/put_item.rs | 21 ++++++++----- crates/engine/src/transact_write_items.rs | 28 ++++++++++------- tests/test_document_path_length.py | 38 +++++++++++++++++++++++ tests/test_transact_write_phase_order.py | 25 ++++++--------- 4 files changed, 79 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/put_item.rs b/crates/engine/src/put_item.rs index 8ff373b7e..a391976be 100755 --- a/crates/engine/src/put_item.rs +++ b/crates/engine/src/put_item.rs @@ -147,18 +147,25 @@ pub async fn handle_put_item( extenddb_core::validation::validate_table_name(&input.table_name, &ctx.limits)?; + // The Item's numbers and nesting come before every expression check, with + // or without ExpressionAttributeValues: an Item holding `{N: abc}` or an + // attribute 33 maps deep answers the number or the nesting error beside a + // condition with a syntax error, an undefined name or value, an unused + // value, a reserved word, a path of 33 elements or BETWEEN bounds out of + // order (measured 2026-11-12). `validate_put_item` checks them again + // after the table lookup. + extenddb_core::validation::validate_item_numbers(&input.item)?; + extenddb_core::validation::validate_item_nesting_depth(&input.item)?; + // The nesting-depth limit applies to every ExpressionAttributeValue on the // single-item write paths, condition-only placeholders included: measured // 2026-08-24 (us-east-1), a 32-level value referenced solely by a // ConditionExpression is rejected on PutItem, DeleteItem, and UpdateItem - // alike, while 31 levels is accepted. TransactWriteItems deliberately does - // NOT get this check: the same 32-level condition-only value is accepted - // inside a transaction on every sub-op shape (also measured). It comes - // after an invalid number in the Item and before the ConditionExpression - // and the table lookup (measured 2026-10-26), so the Item's numbers are - // checked here first; `validate_put_item` checks them again later. + // alike, while 31 levels is accepted. TransactWriteItems checks its values + // separately, in `validate_value_map_nesting`. It comes after an invalid + // number in the Item and before the ConditionExpression and the table + // lookup (measured 2026-10-26). if let Some(values) = &input.expression_attribute_values { - extenddb_core::validation::validate_item_numbers(&input.item)?; extenddb_core::validation::validate_attribute_values_nesting_depth(values.values())?; } diff --git a/crates/engine/src/transact_write_items.rs b/crates/engine/src/transact_write_items.rs index c979887ff..0478b77a5 100755 --- a/crates/engine/src/transact_write_items.rs +++ b/crates/engine/src/transact_write_items.rs @@ -81,11 +81,10 @@ pub async fn handle_transact_write_items( // Validation runs in the order the service applies it, each phase over // every item before the next phase starts: // 1. per item, in order, with no table needed: the attribute name sizes - // of the item's expression maps and, for a Put, of its item, the - // nesting of the item's ExpressionAttributeValues, expression - // grammar, the semantic walk, unused names and values, then for a - // Put the item size and the item nesting (top-level - // ValidationException), + // of the item's expression maps and, for a Put, of its item, a Put's + // item nesting, the nesting of the item's ExpressionAttributeValues, + // expression grammar, the semantic walk, unused names and values, + // then for a Put the item size (top-level ValidationException), // 2. table lookup (ResourceNotFoundException), // 3. the 4 MB request total (top-level ValidationException), // 4. the key pass, per item in order: a key that does not fit the schema @@ -483,6 +482,16 @@ fn parse_write_expressions( )); }; + // A Put's Item nesting comes before every check of the item's expressions + // and before the item's size: an Item attribute 33 maps deep answers the + // nesting error beside a condition with a syntax error, an undefined name + // or value, an unused value, a reserved word, a path of 33 elements or + // BETWEEN bounds out of order, and beside an item over the size limit + // (measured 2026-11-12). + if let Some(put) = &twi.put { + validate_item_nesting_depth(&put.item)?; + } + // The nesting of every ExpressionAttributeValues value, used or not, is // the first thing the service checks about an item's expressions // (measured: it beats the same item's syntax error, undefined reference @@ -497,11 +506,9 @@ fn parse_write_expressions( // reserved word, operand type and path length (measured 2026-11-12, each // request twice; on 2026-10-14 the service answered the UpdateExpression // first). Then come the unused names and values; then, for a Put, the - // item's size and the item's nesting (measured: an oversize Put with an - // unused value reports the value, an oversize item one reports its size - // ahead of the next item's defects, and one item with a long attribute - // name, an oversize item and a deep item reports the name first and the - // nesting last). + // item's size (measured: an oversize Put with an unused value reports the + // value, and an oversize item reports its size ahead of the next item's + // defects). let maps = build_expression_maps(names, values); let condition = match condition_expression { // A ConditionCheck's expression is required, so an empty string is @@ -541,7 +548,6 @@ fn parse_write_expressions( } if let Some(put) = &twi.put { validate_item_size(&put.item, limits.max_item_size_bytes)?; - validate_item_nesting_depth(&put.item)?; } Ok(ParsedExpressions { maps, diff --git a/tests/test_document_path_length.py b/tests/test_document_path_length.py index 0fa93585b..aeb8462a3 100644 --- a/tests/test_document_path_length.py +++ b/tests/test_document_path_length.py @@ -270,6 +270,44 @@ def test_an_invalid_number_in_the_item_comes_before_a_value_nested_too_deep(dyna )) == ("ValidationException", BAD_NUMBER) +REVERSED = {":hi": {"N": "5"}, ":lo": {"N": "1"}} + +# (case, Item attributes, condition, names, values, message): the Item's +# numbers and nesting come before the condition, with or without +# ExpressionAttributeValues (measured 2026-11-12, each request twice). +ITEM_BEFORE_CONDITION = [ + ("number_before_the_length", {"n": {"N": "abc"}}, f"attribute_exists({p(33)})", N, None, BAD_NUMBER), + ("nesting_before_the_length", {"d": nmap(33)}, f"attribute_exists({p(33)})", N, None, NESTING), + ("nesting_before_the_between_bounds", {"d": nmap(33)}, "a BETWEEN :hi AND :lo", None, REVERSED, NESTING), +] + + +def _put_body(table, key, attrs, condition, names, values): + body = {"TableName": table, "Item": {**key, **attrs}, "ConditionExpression": condition} + if names: + body["ExpressionAttributeNames"] = names + if values: + body["ExpressionAttributeValues"] = values + return body + + +@pytest.mark.parametrize(("case", "attrs", "condition", "names", "values", "message"), ITEM_BEFORE_CONDITION, + ids=[c[0] for c in ITEM_BEFORE_CONDITION]) +def test_put_item_checks_the_item_before_the_condition(dynamodb_client, table, key, case, attrs, condition, names, + values, message): + body = _put_body(table, key, attrs, condition, names, values) + assert _single_item_error(lambda: dynamodb_client.put_item(**body)) == ("ValidationException", message) + + +@pytest.mark.parametrize(("case", "attrs", "condition", "names", "values", "message"), ITEM_BEFORE_CONDITION[1:], + ids=[c[0] for c in ITEM_BEFORE_CONDITION[1:]]) +def test_transact_write_items_put_checks_the_item_nesting_before_the_condition( + dynamodb_client, table, key, case, attrs, condition, names, values, message): + body = _put_body(table, key, attrs, condition, names, values) + assert _error(lambda: dynamodb_client.transact_write_items(TransactItems=[{"Put": body}])) == ( + "ValidationException", message) + + def test_between_bounds_are_checked_whatever_the_item(dynamodb_client, table, key): bounds = {":hi": {"N": "5"}, ":lo": {"N": "1"}, ":s": {"S": "s"}} missing = {"pk": {"S": "plen"}, "sk": {"S": "between-no-item"}} diff --git a/tests/test_transact_write_phase_order.py b/tests/test_transact_write_phase_order.py index fcc7686f5..0081b7b56 100644 --- a/tests/test_transact_write_phase_order.py +++ b/tests/test_transact_write_phase_order.py @@ -3,12 +3,14 @@ """Where four per-item checks sit in TransactWriteItems validation. -Amazon DynamoDB reports them in two places (measured 2026-10-27): +Amazon DynamoDB reports them in two places (measured 2026-10-27; the order of +a Put's item nesting re-measured 2026-11-12): * before any table is looked up, one item after another, in the pass that - also checks the expressions: the nesting of every ExpressionAttributeValues - value of the item, and for a Put the attribute name size, then the item - size, then the item nesting; + also checks the expressions: for a Put the attribute name size and the + item nesting, ahead of the item's expressions, then the nesting of every + ExpressionAttributeValues value of the item, and for a Put the item size + after the expressions; * after every table is looked up and after the 4 MB total, in the key pass, one item after another: a key that does not fit the schema, then a key attribute named in an Update (both a ValidationError cancellation reason @@ -46,7 +48,6 @@ class and the words "attribute name" are compared. KEY_UPDATE_SK = KEY_UPDATE.replace("attribute pk.", "attribute sk.") KEY_MISMATCH = "The provided key element does not match the schema" PUT_MISMATCH_SK = "One or more parameter values were invalid: Type mismatch for key sk expected: S actual: N" -ITEM_SIZE = "Item size has exceeded the maximum allowed size" UNDEFINED_VALUE = ( "Invalid ConditionExpression: An expression attribute value used in " "expression is not defined; attribute value: :q" @@ -182,24 +183,18 @@ def test_the_checks_follow_item_order_against_an_expression_error(self, dynamodb check(dynamodb_client, [defect, undefined]) _top(dynamodb_client, [undefined, defect], UNDEFINED_VALUE) - def test_a_put_reports_name_size_then_item_size_then_nesting(self, dynamodb_client, table): + def test_a_put_reports_name_size_then_nesting_then_item_size(self, dynamodb_client, table): pad = {"S": "x" * 410_000} name_and_size = {"pk": {"S": "w"}, "sk": {"S": "a"}, "a" * 65536: {"S": "v"}, "pad": pad} nesting_and_size = {"pk": {"S": "w"}, "sk": {"S": "a"}, "d": _deep(40), "pad": pad} nesting_and_name = {"pk": {"S": "w"}, "sk": {"S": "a"}, "d": _deep(40), "a" * 65536: {"S": "v"}} _attribute_name_error(dynamodb_client, [_put(table, name_and_size)]) - _top(dynamodb_client, [_put(table, nesting_and_size)], ITEM_SIZE) + _top(dynamodb_client, [_put(table, nesting_and_size)], NESTING) _attribute_name_error(dynamodb_client, [_put(table, nesting_and_name)]) - def test_inside_one_item_the_expressions_come_first_and_the_value_nesting_before_them( - self, dynamodb_client, table - ): + def test_inside_one_item_the_nesting_comes_before_the_expressions(self, dynamodb_client, table): deep_item = {"pk": {"S": "w"}, "sk": {"S": "a"}, "d": _deep(40)} - _top( - dynamodb_client, - [_put(table, deep_item, ConditionExpression="note = :q")], - UNDEFINED_VALUE, - ) + _top(dynamodb_client, [_put(table, deep_item, ConditionExpression="note = :q")], NESTING) _top(dynamodb_client, [_update(table, GOOD_KEY, "SET d = ", {":v": _deep(40)})], VALUE_NESTING) _top( dynamodb_client, From d98748b5d0164c3585ca2a2db2b698a6aa871deb Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:01:30 +0000 Subject: [PATCH 08/14] fix(query): check key condition references and path lengths in one pass The service checks a KeyConditionExpression's `#name` and `:value` references and each document path's length in one pass in text order. Then it refuses a nested attribute, and then the clause shapes. Measured 2026-11-12 in us-east-1, each request twice: - `pk = :p AND #zz.#k... = :s` (33 elements, `#zz` undefined) and `#zz = :p AND <33 elements> = :s` answer the undefined `#zz`. - `pk = :nope AND <33 elements> = :s` answers the undefined `:nope`. - `<33 elements> = :s AND pk = :nope`, `<33 elements> = :s AND #zz = :p` and `pk = :p AND <33 elements> = :nope` answer the length. - `#zz = :p AND <32 elements> = :s`, `<32 elements> = :s AND pk = :nope` and `#m.#k = :s AND #zz = :p` answer the undefined reference ahead of the nested-attribute refusal. - `pk < :nope` and `begins_with(pk, :nope)` answer the undefined `:nope` ahead of the clause shape. ExtendDB's parser checked the length of every path, then the nested attributes and the shapes. The references ran after the whole parse. The key condition parse now takes the request's maps and walks the tokens once. It checks each path's names, then its length, and each value. The walk is the engine's former `check_key_condition_refs` with the length added. It moves into `parse_key_condition_with_maps` in core, so it can run before the nested-attribute refusal. `parse_key_condition` without maps, which authorization reads, refuses a long path as a nested attribute. --- crates/core/src/expression/key_condition.rs | 87 ++++++++++++++++++--- crates/core/src/expression/mod.rs | 2 +- crates/core/src/expression/path_length.rs | 55 ++++++++++--- crates/engine/src/expression_helpers.rs | 54 ++++--------- tests/test_document_path_length.py | 30 +++++++ 5 files changed, 168 insertions(+), 60 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 54c2dd8a7..47cfbb79e 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -15,6 +15,7 @@ use super::ast::{CompareOp, Expr, PathElement}; use super::parser_common; +use super::resolver::ExpressionMaps; use super::tokenizer::Token; use crate::error::DynamoDbError; use crate::types::{ @@ -530,8 +531,31 @@ impl SortKeyCondition { /// /// Returns `ValidationException` for syntax errors or unsupported constructs. pub fn parse_key_condition(tokens: &[Token]) -> Result { - let mut clauses = parse_clauses(tokens)?; + classify_clauses(parse_clauses(tokens, None)?) +} + +/// [`parse_key_condition`] for a request: once the expression parses, every +/// `#name` and `:value` reference is checked against `maps` and every document +/// path's length, in one pass in the order the expression is written, before +/// the nested-attribute refusal and the clause shapes. +/// +/// Measured 2026-11-12 (us-east-1): `pk = :nope AND <33 elements> = :s` +/// answers the undefined `:nope`, `<33 elements> = :s AND pk = :nope` and +/// `pk = :p AND <33 elements> = :nope` the length, `#m.#k = :s AND #zz = :p` +/// the undefined `#zz`, and `pk < :nope` the undefined `:nope`. +/// +/// # Errors +/// +/// Returns `ValidationException` for the errors of [`parse_key_condition`], +/// an undefined reference and a path of more than 32 elements. +pub fn parse_key_condition_with_maps( + tokens: &[Token], + maps: &ExpressionMaps, +) -> Result { + classify_clauses(parse_clauses(tokens, Some(maps))?) +} +fn classify_clauses(mut clauses: Vec) -> Result { match clauses.len() { 1 => classify_single(clauses.remove(0)), 2 => classify_pair(clauses.remove(0), clauses.remove(0)), @@ -555,7 +579,7 @@ pub fn parse_key_condition(tokens: &[Token]) -> Result Result, DynamoDbError> { - Ok(parse_clauses(tokens)? + Ok(parse_clauses(tokens, None)? .into_iter() .filter_map(|clause| match clause { RawClause::Eq(path, value) => Some(KeyClauseOperand { @@ -589,7 +613,12 @@ pub struct KeyClauseOperand { /// Parse a `KeyConditionExpression` token stream into its AND-ed clauses, /// before any of them is read as the partition or the sort key condition. -fn parse_clauses(tokens: &[Token]) -> Result, DynamoDbError> { +/// With `maps`, the references and path lengths are checked once the clauses +/// parse (see [`check_references`]). +fn parse_clauses( + tokens: &[Token], + maps: Option<&ExpressionMaps>, +) -> Result, DynamoDbError> { parser_common::check_redundant_parens(tokens) .map_err(|body| validation_err(&format!("Invalid KeyConditionExpression: {body}")))?; @@ -625,16 +654,14 @@ fn parse_clauses(tokens: &[Token]) -> Result, DynamoDbError> { )); } + if let Some(maps) = maps { + check_references(tokens, maps)?; + } + // A key condition may only reference a top-level key attribute. Any document // path (`attr.sub` or `attr[i]`) on a key is rejected, matching Amazon - // DynamoDB. Runs after the reserved-word check and before key-schema checks. - for clause in &clauses { - if let Some(msg) = super::path_length::too_many_levels(raw_clause_path(clause)) { - return Err(validation_err(&format!( - "Invalid KeyConditionExpression: {msg}" - ))); - } - } + // DynamoDB. Runs after the reserved-word check, the references and the + // path lengths, and before key-schema checks. for clause in &clauses { reject_nested_key_path(raw_clause_path(clause))?; } @@ -642,6 +669,44 @@ fn parse_clauses(tokens: &[Token]) -> Result, DynamoDbError> { Ok(clauses) } +/// Refuse the first `#name` or `:value` reference that `maps` does not define +/// and the first document path of more than 32 elements, in one pass in the +/// order the expression is written: each path's names, then its length. +fn check_references(tokens: &[Token], maps: &ExpressionMaps) -> Result<(), DynamoDbError> { + let mut pos = 0; + while pos < tokens.len() { + match &tokens[pos] { + Token::Placeholder(value) if !maps.values.contains_key(value) => { + return Err(validation_err(&format!( + "Invalid KeyConditionExpression: An expression attribute value used in expression is not defined; attribute value: :{value}" + ))); + } + // A function name such as `begins_with` is not a path. + Token::Ident(_) if tokens.get(pos + 1) == Some(&Token::LParen) => pos += 1, + Token::Ident(_) | Token::NameRef(_) => { + let path = parser_common::parse_path(tokens, &mut pos)?; + for element in &path { + if let PathElement::Attribute(name) = element + && let Some(reference) = name.strip_prefix('#') + && !maps.names.contains_key(reference) + { + return Err(validation_err(&format!( + "Invalid KeyConditionExpression: An expression attribute name used in the document path is not defined; attribute name: #{reference}" + ))); + } + } + if let Some(msg) = super::path_length::too_many_levels(&path) { + return Err(validation_err(&format!( + "Invalid KeyConditionExpression: {msg}" + ))); + } + } + _ => pos += 1, + } + } + Ok(()) +} + /// The attribute-side path of a raw clause. fn raw_clause_path(clause: &RawClause) -> &[PathElement] { match clause { diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index bdc3192db..d5042b9b8 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -28,7 +28,7 @@ pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only} pub use evaluator::{compare_orderable, evaluate_condition}; pub use key_condition::{ KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands, - parse_key_condition, + parse_key_condition, parse_key_condition_with_maps, }; pub use kind::ExpressionKind; pub use parser::{parse_condition, parse_condition_with_depth_limit}; diff --git a/crates/core/src/expression/path_length.rs b/crates/core/src/expression/path_length.rs index 72c386674..7523495dc 100644 --- a/crates/core/src/expression/path_length.rs +++ b/crates/core/src/expression/path_length.rs @@ -83,17 +83,52 @@ mod tests { const LEVELS_33: &str = "The document path has too many nesting levels; nesting levels: 33"; #[test] - fn a_key_condition_path_is_checked_before_the_nested_refusal() { - let parse = |n: usize| { - let expr = format!("pk = :v AND {} = :v", path_text("m", n)); - crate::expression::parse_key_condition(&crate::expression::tokenize(&expr).unwrap()) - .map(|_| ()) - }; - assert_eq!( - message(parse(33)), - format!("Invalid KeyConditionExpression: {LEVELS_33}") + fn a_key_condition_checks_names_values_and_lengths_in_text_order() { + let maps = crate::expression::ExpressionMaps::new( + std::collections::HashMap::from([("m".to_owned(), "m".to_owned())]), + ["p", "s"] + .into_iter() + .map(|k| { + ( + k.to_owned(), + crate::types::AttributeValue::S("v".to_owned()), + ) + }) + .collect(), ); - assert!(message(parse(32)).contains("cannot have conditions on nested attributes")); + let parse = |expr: &str| { + let tokens = crate::expression::tokenize(expr).unwrap(); + crate::expression::parse_key_condition_with_maps(&tokens, &maps).map(|_| ()) + }; + let (long, at_limit) = (path_text("#m", 33), path_text("#m", 32)); + let length = format!("Invalid KeyConditionExpression: {LEVELS_33}"); + let name = "Invalid KeyConditionExpression: An expression attribute name used in the \ + document path is not defined; attribute name: #zz"; + let value = "Invalid KeyConditionExpression: An expression attribute value used in \ + expression is not defined; attribute value: :nope"; + let nested = "Invalid KeyConditionExpression: KeyConditionExpressions cannot have \ + conditions on nested attributes"; + // Measured 2026-11-12 (us-east-1), each request twice. + for (expr, want) in [ + (format!("pk = :p AND {long} = :s"), length.as_str()), + (format!("pk = :p AND {} = :s", path_text("#zz", 33)), name), + (format!("pk = :nope AND {long} = :s"), value), + (format!("{long} = :s AND pk = :nope"), length.as_str()), + (format!("#zz = :p AND {long} = :s"), name), + (format!("{long} = :s AND #zz = :p"), length.as_str()), + (format!("pk = :p AND {long} = :nope"), length.as_str()), + ( + format!("pk = :p AND begins_with({long}, :nope)"), + length.as_str(), + ), + (format!("pk = :p AND {at_limit}.#zz = :s"), name), + (format!("pk = :p AND {at_limit} = :s"), nested), + (format!("#zz = :p AND {at_limit} = :s"), name), + (format!("{at_limit} = :s AND pk = :nope"), value), + ("pk < :nope".to_owned(), value), + ] { + assert_eq!(message(parse(&expr)), want, "{expr}"); + } } #[test] diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index f27e1af37..3a56c2e75 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -8,9 +8,9 @@ use std::collections::HashMap; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ Expr, ExpressionKind, ExpressionMaps, KeyCondition, PathElement, Token, UpdateAction, - parse_condition_with_depth_limit, parse_key_condition, parse_projection, parse_update_from, - parse_update_sections, tokenize_for, tokenize_with_limit, validate_condition_semantics, - validate_no_reserved_words, validate_update_semantics, + parse_condition_with_depth_limit, parse_key_condition_with_maps, parse_projection, + parse_update_from, parse_update_sections, tokenize_for, tokenize_with_limit, + validate_condition_semantics, validate_no_reserved_words, validate_update_semantics, }; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{AttributeValue, ConditionalOperator, ExpectedAttributeValue}; @@ -380,27 +380,29 @@ pub fn parse_projection_expr( /// Size-check, tokenize, reserved-word check, and parse a /// `KeyConditionExpression`, then reject a `#name` or `:value` the request -/// does not define. +/// does not define and a document path of more than 32 elements. /// /// Errors carry the `KeyConditionExpression` prefix, matching Amazon -/// `DynamoDB`. The references are checked once the whole expression parses, -/// in the order they stand in the text, names and values alike (measured -/// 2026-10-27: `pk = :q AND #n = :v` names `:q`, `#b = :p AND #a > :q` names -/// `#b`). The check runs before the key schema is consulted, so an undefined -/// `#n` is reported as such rather than as a key schema mismatch (measured -/// 2026-10-14). +/// `DynamoDB`. The references and the path lengths are checked once the whole +/// expression parses, in one pass in the order they stand in the text, names +/// and values alike (measured 2026-10-27: `pk = :q AND #n = :v` names `:q`, +/// `#b = :p AND #a > :q` names `#b`; see +/// `extenddb_core::expression::parse_key_condition_with_maps` for the +/// lengths). The check runs before the key schema is consulted, so an +/// undefined `#n` is reported as such rather than as a key schema mismatch +/// (measured 2026-10-14). /// /// # Errors /// /// Returns `DynamoDbError::ValidationException` for over-size, syntax, -/// reserved-word, or undefined-reference errors. +/// reserved-word, undefined-reference or path-length errors. pub fn parse_key_condition_expr( expr: &str, maps: &ExpressionMaps, limits: &LimitsConfig, ) -> Result { check_expression_size(expr, ExpressionKind::KeyCondition, limits)?; - let (tokens, parsed) = tokenize_for( + tokenize_for( expr, limits.max_expression_tokens, ExpressionKind::KeyCondition, @@ -409,33 +411,9 @@ pub fn parse_key_condition_expr( if limits.enforce_reserved_keywords { validate_no_reserved_words(&tokens)?; } - let parsed = parse_key_condition(&tokens)?; - Ok((tokens, parsed)) + parse_key_condition_with_maps(&tokens, maps) }) - .map_err(|e| prefix_expression_error(e, ExpressionKind::KeyCondition))?; - check_key_condition_refs(&tokens, maps)?; - Ok(parsed) -} - -/// The first `#name` or `:value` token, in text order, that `maps` does not -/// define. -fn check_key_condition_refs(tokens: &[Token], maps: &ExpressionMaps) -> Result<(), DynamoDbError> { - for token in tokens { - match token { - Token::NameRef(name) if !maps.names.contains_key(name) => { - return Err(DynamoDbError::ValidationException(format!( - "Invalid KeyConditionExpression: An expression attribute name used in the document path is not defined; attribute name: #{name}" - ))); - } - Token::Placeholder(value) if !maps.values.contains_key(value) => { - return Err(DynamoDbError::ValidationException(format!( - "Invalid KeyConditionExpression: An expression attribute value used in expression is not defined; attribute value: :{value}" - ))); - } - _ => {} - } - } - Ok(()) + .map_err(|e| prefix_expression_error(e, ExpressionKind::KeyCondition)) } /// Prefix an expression error with the expression type, matching `DynamoDB`'s format. diff --git a/tests/test_document_path_length.py b/tests/test_document_path_length.py index aeb8462a3..05b301395 100644 --- a/tests/test_document_path_length.py +++ b/tests/test_document_path_length.py @@ -481,6 +481,36 @@ def test_query_key_condition(dynamodb_client, table, key): "Invalid KeyConditionExpression: KeyConditionExpressions cannot have conditions on nested attributes") +KEY_NAME = f"Invalid KeyConditionExpression: {UNDEFINED_NAME}" +KEY_VALUE = f"Invalid KeyConditionExpression: {UNDEFINED_VALUE}" +KEY_LENGTH = too_long("KeyConditionExpression", 33) + +# (case, key condition, names, values defined, message): the names, the +# values and each path's length in one pass in text order, then the +# nested-attribute refusal (measured 2026-11-12, each request twice). +KEY_CONDITION_ORDER = [ + ("name_inside_the_long_path", "pk = :p AND #zz" + ".#k" * 32 + " = :s", {"#k": "k"}, (":p", ":s"), KEY_NAME), + ("value_in_an_earlier_clause", f"pk = :nope AND {p(33)} = :s", N, (":s",), KEY_VALUE), + ("length_before_a_later_value", f"{p(33)} = :s AND pk = :nope", N, (":s",), KEY_LENGTH), + ("name_in_an_earlier_clause", f"#zz = :p AND {p(33)} = :s", N, (":p", ":s"), KEY_NAME), + ("length_before_a_later_name", f"{p(33)} = :s AND #zz = :p", N, (":p", ":s"), KEY_LENGTH), + ("length_before_its_value", f"pk = :p AND {p(33)} = :nope", N, (":p",), KEY_LENGTH), + ("name_at_the_end_of_the_long_path", f"pk = :p AND {p(32)}.#zz = :s", N, (":p", ":s"), KEY_NAME), + ("name_before_the_nested_refusal", f"#zz = :p AND {p(32)} = :s", N, (":p", ":s"), KEY_NAME), + ("value_before_the_nested_refusal", f"{p(32)} = :s AND pk = :nope", N, (":s",), KEY_VALUE), +] + + +@pytest.mark.parametrize(("case", "condition", "names", "values", "message"), KEY_CONDITION_ORDER, + ids=[c[0] for c in KEY_CONDITION_ORDER]) +def test_key_condition_checks_names_values_and_lengths_in_text_order(dynamodb_client, table, case, condition, + names, values, message): + assert _error(lambda: dynamodb_client.query( + TableName=table, KeyConditionExpression=condition, ExpressionAttributeNames=names, + ExpressionAttributeValues={v: {"S": "plen"} for v in values}, + )) == ("ValidationException", message) + + def test_query_filter_is_checked_before_the_projection(dynamodb_client, table, key): assert _error(lambda: _query(dynamodb_client, table, FilterExpression=f"attribute_exists(#zz) OR attribute_exists({p(33)})")) == ( From 4cacd55e1e1b96d406a755f87ff66dab1b962e72 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:04:18 +0000 Subject: [PATCH 09/14] fix(expression): build the BETWEEN bounds sentence only for a fault `between_bounds_fault` formatted both bounds into the sentence before it checked them. The evaluator calls it for every item a condition or filter reads. A Scan of 6,000 items with `#x BETWEEN :lo AND :hi` and two 380,000-character bounds in order took 0.45 s on a SQLite debug build. The same Scan with `#x >= :lo AND #x <= :hi` took 0.23 s (median of five runs). The function now finds the fault first. It builds the sentence only when the bounds differ in type or the lower is above the upper. After the change the BETWEEN Scan takes 0.26 s, and the `>=` and `<=` Scan takes 0.26 s. New tests cover the evaluator's own call and the type branch, which no test reached: - `evaluate_condition` refuses bounds out of order and bounds of different types, on an item with the attribute and on an empty item. - The wire tests send both faults through UpdateItem on a missing item, on an existing item and after a false AND. - They send both through a Query FilterExpression, on an empty partition and on one with items. - They send bounds out of order through a legacy `Expected` on PutItem. On the service each of these answers ValidationException (measured 2026-11-12 in us-east-1, each request twice). The `Expected` row compares the class and the operator only, because the service gives `Expected` its own sentence. --- crates/core/src/expression/evaluator.rs | 36 ++++++++--------- crates/core/src/expression/evaluator_tests.rs | 38 ++++++++++++++++++ tests/test_document_path_length.py | 40 ++++++++++++++----- 3 files changed, 87 insertions(+), 27 deletions(-) diff --git a/crates/core/src/expression/evaluator.rs b/crates/core/src/expression/evaluator.rs index 2aa2cff79..607d08bb0 100755 --- a/crates/core/src/expression/evaluator.rs +++ b/crates/core/src/expression/evaluator.rs @@ -111,7 +111,8 @@ fn resolve_to_value<'a>( /// The service's sentence when both BETWEEN bounds are placeholders and they /// differ in type or the lower is above the upper, without the `Invalid /// : ` label. The service checks this at request time, whatever the -/// item (measured 2026-10-26). +/// item (measured 2026-10-26). The evaluator calls this for every item, so +/// the sentence is built only when the bounds are at fault. pub(crate) fn between_bounds_fault( low: &Expr, high: &Expr, @@ -123,25 +124,24 @@ pub(crate) fn between_bounds_fault( let (Some(l), Some(h)) = (maps.values.get(l_name), maps.values.get(h_name)) else { return None; }; - let bounds = format!( - "lower bound operand: AttributeValue: {{{}}}, upper bound operand: AttributeValue: {{{}}}", - format_attribute_value(l), - format_attribute_value(h) - ); - if attribute_type_code(l) != attribute_type_code(h) { - return Some(format!( - "The BETWEEN operator requires same data type for lower and upper bounds; {bounds}" - )); - } - let (lpn, hpn) = ( + let requirement = if attribute_type_code(l) != attribute_type_code(h) { + "same data type for lower and upper bounds" + } else if compare_values( + l, + h, + CompareOp::Gt, placeholder_numeric(low, maps), placeholder_numeric(high, maps), - ); - compare_values(l, h, CompareOp::Gt, lpn, hpn).then(|| { - format!( - "The BETWEEN operator requires upper bound to be greater than or equal to lower bound; {bounds}" - ) - }) + ) { + "upper bound to be greater than or equal to lower bound" + } else { + return None; + }; + Some(format!( + "The BETWEEN operator requires {requirement}; lower bound operand: AttributeValue: {{{}}}, upper bound operand: AttributeValue: {{{}}}", + format_attribute_value(l), + format_attribute_value(h) + )) } /// Look up a pre-parsed `BigDecimal` for a placeholder expression. diff --git a/crates/core/src/expression/evaluator_tests.rs b/crates/core/src/expression/evaluator_tests.rs index 2eb32b0c0..0e7ab7950 100755 --- a/crates/core/src/expression/evaluator_tests.rs +++ b/crates/core/src/expression/evaluator_tests.rs @@ -227,6 +227,44 @@ fn between_out_of_range() { assert!(!eval("age BETWEEN :lo AND :hi", &item, HashMap::new(), values).unwrap()); } +/// Bounds of different types or with the lower above the upper are refused +/// whatever the item holds. A legacy `Expected` condition reaches the +/// evaluator without the semantic walk, so this is its only bounds check +/// (measured 2026-11-12: PutItem with `Expected` `n BETWEEN [5, 1]` answers +/// ValidationException on a missing and on an existing item). +#[test] +fn between_bounds_at_fault_are_refused_for_every_item() { + let bounds = |lo: AttributeValue, hi: AttributeValue| { + HashMap::from([("lo".to_owned(), lo), ("hi".to_owned(), hi)]) + }; + for (values, want) in [ + ( + bounds(AttributeValue::N("5".into()), AttributeValue::N("1".into())), + "Invalid ConditionExpression: The BETWEEN operator requires upper bound to be \ + greater than or equal to lower bound; lower bound operand: AttributeValue: {N:5}, \ + upper bound operand: AttributeValue: {N:1}", + ), + ( + bounds(AttributeValue::N("1".into()), AttributeValue::S("a".into())), + "Invalid ConditionExpression: The BETWEEN operator requires same data type for \ + lower and upper bounds; lower bound operand: AttributeValue: {N:1}, upper bound \ + operand: AttributeValue: {S:a}", + ), + ] { + for item in [simple_item(), BTreeMap::new()] { + match eval( + "age BETWEEN :lo AND :hi", + &item, + HashMap::new(), + values.clone(), + ) { + Err(DynamoDbError::ValidationException(msg)) => assert_eq!(msg, want), + other => panic!("{want}: {other:?}"), + } + } + } +} + #[test] fn in_expression_match() { let item = simple_item(); diff --git a/tests/test_document_path_length.py b/tests/test_document_path_length.py index 05b301395..867820e01 100644 --- a/tests/test_document_path_length.py +++ b/tests/test_document_path_length.py @@ -215,6 +215,8 @@ def test_update_item_reports_an_earlier_fault_first(dynamodb_client, table, key, NESTING = "Nesting Levels have exceeded supported limits: Attributes in the item have nested levels beyond supported limit" BETWEEN = ("The BETWEEN operator requires upper bound to be greater than or equal to lower bound; " "lower bound operand: AttributeValue: {N:5}, upper bound operand: AttributeValue: {N:1}") +BETWEEN_TYPES = ("The BETWEEN operator requires same data type for lower and upper bounds; " + "lower bound operand: AttributeValue: {N:1}, upper bound operand: AttributeValue: {S:a}") def deep_value() -> dict: @@ -308,20 +310,40 @@ def test_transact_write_items_put_checks_the_item_nesting_before_the_condition( "ValidationException", message) -def test_between_bounds_are_checked_whatever_the_item(dynamodb_client, table, key): - bounds = {":hi": {"N": "5"}, ":lo": {"N": "1"}, ":s": {"S": "s"}} +@pytest.mark.parametrize(("lower", "upper", "message"), [ + ({"N": "5"}, {"N": "1"}, BETWEEN), + ({"N": "1"}, {"S": "a"}, BETWEEN_TYPES), +], ids=["lower_above_upper", "different_types"]) +def test_between_bounds_are_checked_whatever_the_item(dynamodb_client, table, key, lower, upper, message): + bounds = {":a": lower, ":b": upper, ":s": {"S": "s"}} missing = {"pk": {"S": "plen"}, "sk": {"S": "between-no-item"}} - for k, cond in ((missing, "#x BETWEEN :hi AND :lo"), (key, "attribute_exists(#n) AND #x BETWEEN :hi AND :lo")): + for k, cond in ((missing, "#x BETWEEN :a AND :b"), (key, "#x BETWEEN :a AND :b"), + (key, "attribute_exists(#n) AND #x BETWEEN :a AND :b")): names = {"#x": "x", "#n": "nope"} if "#n" in cond else {"#x": "x"} assert _single_item_error(lambda: _update(dynamodb_client, table, k, "SET #x = :s", names=names, values=bounds, ConditionExpression=cond)) == ( - "ValidationException", f"Invalid ConditionExpression: {BETWEEN}"), cond + "ValidationException", f"Invalid ConditionExpression: {message}"), cond assert "Item" not in dynamodb_client.get_item(TableName=table, Key=missing, ConsistentRead=True) - assert _error(lambda: dynamodb_client.query( - TableName=table, KeyConditionExpression="pk = :p", FilterExpression="#x BETWEEN :hi AND :lo", - ExpressionAttributeNames={"#x": "x"}, - ExpressionAttributeValues={":p": {"S": "plen-empty"}, ":hi": bounds[":hi"], ":lo": bounds[":lo"]}, - )) == ("ValidationException", f"Invalid FilterExpression: {BETWEEN}") + for partition in ("plen-empty", "plen"): + assert _error(lambda: dynamodb_client.query( + TableName=table, KeyConditionExpression="pk = :p", FilterExpression="#x BETWEEN :a AND :b", + ExpressionAttributeNames={"#x": "x"}, + ExpressionAttributeValues={":p": {"S": partition}, ":a": lower, ":b": upper}, + )) == ("ValidationException", f"Invalid FilterExpression: {message}"), partition + + +def test_legacy_expected_between_bounds_out_of_order_are_refused(dynamodb_client, table, key): + # The service words this `One or more parameter values were invalid: The + # BETWEEN condition was provided a range where the lower bound is greater + # than the upper bound` (measured 2026-11-12); ExtendDB answers with the + # ConditionExpression sentence, so only the class and the operator are + # compared. + expected = {"n": {"ComparisonOperator": "BETWEEN", "AttributeValueList": [{"N": "5"}, {"N": "1"}]}} + missing = {"pk": {"S": "plen"}, "sk": {"S": "between-expected-no-item"}} + for k in (missing, key): + code, message = _single_item_error(lambda: dynamodb_client.put_item( + TableName=table, Item={**k, "n": {"N": "3"}}, Expected=expected)) + assert (code, "BETWEEN" in message) == ("ValidationException", True), message def test_projection_names_come_before_the_length(dynamodb_client, table, key): From ad681858acfb0abbd1ac3bef4b5a66d65f0ad978 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:04:46 +0000 Subject: [PATCH 10/14] docs(expression): state the key condition order and drop a run label The limits row and the path_length module comment now say that a KeyConditionExpression checks its names before the length. They also say that it checks its values in the same pass. The key condition change made both statements true. The BETWEEN walk test no longer carries the label of the run it came from. --- crates/core/src/expression/path_length.rs | 8 ++++---- crates/core/src/expression/semantics/tests.rs | 4 ++-- docs/dynamodb-limits.md | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/core/src/expression/path_length.rs b/crates/core/src/expression/path_length.rs index 7523495dc..aa0ef7875 100644 --- a/crates/core/src/expression/path_length.rs +++ b/crates/core/src/expression/path_length.rs @@ -9,10 +9,10 @@ //! nesting levels: `. It checks a path's `#name` references first and then //! its length, path by path in the order the paths appear, so an undefined //! `#name` in an earlier path or inside the long path is reported instead -//! (measured 2026-10-26, us-east-1). The semantic walk and the projection -//! resolution run the check right after each path's names; the key condition -//! parser runs it before the names are checked, ahead of its nested-attribute -//! refusal. +//! (measured 2026-10-26 and 2026-11-12, us-east-1). The semantic walk, the +//! projection resolution and the key condition's reference pass run the check +//! right after each path's names; the key condition's pass also checks each +//! `:value` in text order, and runs before the nested-attribute refusal. use super::ast::PathElement; diff --git a/crates/core/src/expression/semantics/tests.rs b/crates/core/src/expression/semantics/tests.rs index cdefe7e86..859b4c488 100644 --- a/crates/core/src/expression/semantics/tests.rs +++ b/crates/core/src/expression/semantics/tests.rs @@ -440,8 +440,8 @@ fn key_condition_function_names() { assert_eq!(key_condition_err("pk = :p AND begins_with(sk, :v)"), "OK"); } -/// The BETWEEN bounds are checked at request time (measured 2026-10-26, -/// HBTW-1: refused on a missing key and after a false AND). +/// The BETWEEN bounds are checked at request time (measured 2026-10-26: +/// refused on a missing key and after a false AND). #[test] fn between_bounds_are_checked_in_the_walk() { let m = maps( diff --git a/docs/dynamodb-limits.md b/docs/dynamodb-limits.md index 30f748a68..41bc531bf 100755 --- a/docs/dynamodb-limits.md +++ b/docs/dynamodb-limits.md @@ -67,7 +67,7 @@ Source: [AWS DynamoDB Service Quotas](https://docs.aws.amazon.com/amazondynamodb | Condition expression size | 4 KB | Enforced | `check_expression_size`, `LimitsConfig::max_expression_length_bytes` | | Update expression size | 4 KB | Enforced | `check_expression_size`, `LimitsConfig::max_expression_length_bytes` | | Key condition expression size | 4 KB | Enforced | `check_expression_size`, `LimitsConfig::max_expression_length_bytes` | -| Document path length in an expression | 32 elements (each attribute name and list index counts as one) | Enforced | Every expression kind: `Invalid : The document path has too many nesting levels; nesting levels: `. Checked path by path in the order the paths appear, after each path's `#name` references, so an undefined `#name` in an earlier path or inside the long path is reported first, as on the service. A syntax error anywhere in the expression is reported first. ExtendDB checks reserved words on the whole expression before any path, where the service checks them in the same walk, so a long path followed by a reserved word answers the reserved word error | +| Document path length in an expression | 32 elements (each attribute name and list index counts as one) | Enforced | Every expression kind: `Invalid : The document path has too many nesting levels; nesting levels: `. Checked path by path in the order the paths appear, after each path's `#name` references, so an undefined `#name` in an earlier path or inside the long path is reported first, as on the service; a KeyConditionExpression checks its `:value` references in the same pass. A syntax error anywhere in the expression is reported first. ExtendDB checks reserved words on the whole expression before any path, where the service checks them in the same walk, so a long path followed by a reserved word answers the reserved word error | | Expression attribute names | 2 MB total | Not enforced | Per-entry key/value validated (`serde_helpers`); no aggregate size validation | | Expression attribute values | 2 MB total | Not enforced | Per-entry key/value validated (`serde_helpers`); no aggregate size validation | From 3626544161fb45c0583f01f51e5a8f2746ca0699 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:28:59 +0000 Subject: [PATCH 11/14] refactor(query): reuse the semantic walk's reference checks for keys The key condition pass restated the undefined-name and undefined-value messages and the path length call. It now calls `check_path_refs` and `check_value_defined`, the checks the update and condition walk uses, with the KeyConditionExpression kind. ExtendDB answers the 78 measured requests the same way before and after the change. --- crates/core/src/expression/key_condition.rs | 29 ++++++-------------- crates/core/src/expression/semantics/mod.rs | 1 + crates/core/src/expression/semantics/refs.rs | 4 +-- 3 files changed, 11 insertions(+), 23 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 47cfbb79e..da4023a40 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -671,35 +671,22 @@ fn parse_clauses( /// Refuse the first `#name` or `:value` reference that `maps` does not define /// and the first document path of more than 32 elements, in one pass in the -/// order the expression is written: each path's names, then its length. +/// order the expression is written: each path's names, then its length, with +/// the semantic walk's checks. fn check_references(tokens: &[Token], maps: &ExpressionMaps) -> Result<(), DynamoDbError> { + use super::semantics::{check_path_refs, check_value_defined}; + let kind = super::ExpressionKind::KeyCondition; let mut pos = 0; while pos < tokens.len() { match &tokens[pos] { - Token::Placeholder(value) if !maps.values.contains_key(value) => { - return Err(validation_err(&format!( - "Invalid KeyConditionExpression: An expression attribute value used in expression is not defined; attribute value: :{value}" - ))); + Token::Placeholder(value) => { + check_value_defined(value, maps, kind)?; + pos += 1; } // A function name such as `begins_with` is not a path. Token::Ident(_) if tokens.get(pos + 1) == Some(&Token::LParen) => pos += 1, Token::Ident(_) | Token::NameRef(_) => { - let path = parser_common::parse_path(tokens, &mut pos)?; - for element in &path { - if let PathElement::Attribute(name) = element - && let Some(reference) = name.strip_prefix('#') - && !maps.names.contains_key(reference) - { - return Err(validation_err(&format!( - "Invalid KeyConditionExpression: An expression attribute name used in the document path is not defined; attribute name: #{reference}" - ))); - } - } - if let Some(msg) = super::path_length::too_many_levels(&path) { - return Err(validation_err(&format!( - "Invalid KeyConditionExpression: {msg}" - ))); - } + check_path_refs(&parser_common::parse_path(tokens, &mut pos)?, maps, kind)?; } _ => pos += 1, } diff --git a/crates/core/src/expression/semantics/mod.rs b/crates/core/src/expression/semantics/mod.rs index 07b4fd5aa..b779f3f07 100644 --- a/crates/core/src/expression/semantics/mod.rs +++ b/crates/core/src/expression/semantics/mod.rs @@ -76,4 +76,5 @@ mod tests; mod update_rules; pub use condition_rules::validate_condition_semantics; +pub(in crate::expression) use refs::{check_path_refs, check_value_defined}; pub use update_rules::validate_update_semantics; diff --git a/crates/core/src/expression/semantics/refs.rs b/crates/core/src/expression/semantics/refs.rs index e3f7a4433..d6afe9fa5 100644 --- a/crates/core/src/expression/semantics/refs.rs +++ b/crates/core/src/expression/semantics/refs.rs @@ -11,7 +11,7 @@ use super::super::resolver::ExpressionMaps; use super::errors::validation; use crate::error::DynamoDbError; -pub(super) fn check_path_refs( +pub(in crate::expression) fn check_path_refs( path: &[PathElement], maps: &ExpressionMaps, kind: ExpressionKind, @@ -37,7 +37,7 @@ pub(super) fn check_path_refs( } } -pub(super) fn check_value_defined( +pub(in crate::expression) fn check_value_defined( name: &str, maps: &ExpressionMaps, kind: ExpressionKind, From 375c1ad1b870b49caffe5f6c8fbf51660806dd46 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:53:20 +0000 Subject: [PATCH 12/14] docs(expression): split the long sentences in the new comments The comments and doc comments that this change adds now use sentences of 25 words or fewer and no semicolons. The code is unchanged. --- crates/core/src/expression/evaluator_tests.rs | 6 ++-- crates/core/src/expression/key_condition.rs | 21 ++++++------- crates/core/src/expression/path_length.rs | 4 +-- crates/core/src/expression/projection.rs | 13 ++++---- crates/core/src/expression/resolver.rs | 8 ++--- crates/engine/src/expression_helpers.rs | 10 +++---- crates/engine/src/put_item.rs | 13 ++++---- crates/engine/src/transact_write_items.rs | 30 ++++++++++--------- docs/dynamodb-limits.md | 2 +- tests/test_document_path_length.py | 19 ++++++------ 10 files changed, 66 insertions(+), 60 deletions(-) diff --git a/crates/core/src/expression/evaluator_tests.rs b/crates/core/src/expression/evaluator_tests.rs index 0e7ab7950..bf13ee8fa 100755 --- a/crates/core/src/expression/evaluator_tests.rs +++ b/crates/core/src/expression/evaluator_tests.rs @@ -229,9 +229,9 @@ fn between_out_of_range() { /// Bounds of different types or with the lower above the upper are refused /// whatever the item holds. A legacy `Expected` condition reaches the -/// evaluator without the semantic walk, so this is its only bounds check -/// (measured 2026-11-12: PutItem with `Expected` `n BETWEEN [5, 1]` answers -/// ValidationException on a missing and on an existing item). +/// evaluator without the semantic walk, so this is its only bounds check. +/// Measured 2026-11-12: PutItem with `Expected` `n BETWEEN [5, 1]` answers +/// ValidationException on a missing and on an existing item. #[test] fn between_bounds_at_fault_are_refused_for_every_item() { let bounds = |lo: AttributeValue, hi: AttributeValue| { diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index da4023a40..5029f0ff1 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -534,15 +534,16 @@ pub fn parse_key_condition(tokens: &[Token]) -> Result = :s` -/// answers the undefined `:nope`, `<33 elements> = :s AND pk = :nope` and -/// `pk = :p AND <33 elements> = :nope` the length, `#m.#k = :s AND #zz = :p` -/// the undefined `#zz`, and `pk < :nope` the undefined `:nope`. +/// answers the undefined `:nope`. `<33 elements> = :s AND pk = :nope` and +/// `pk = :p AND <33 elements> = :nope` answer the length. +/// `#m.#k = :s AND #zz = :p` answers the undefined `#zz`, and `pk < :nope` +/// the undefined `:nope`. /// /// # Errors /// @@ -670,9 +671,9 @@ fn parse_clauses( } /// Refuse the first `#name` or `:value` reference that `maps` does not define -/// and the first document path of more than 32 elements, in one pass in the -/// order the expression is written: each path's names, then its length, with -/// the semantic walk's checks. +/// and the first document path of more than 32 elements. One pass in text +/// order checks each path's names, then its length, with the semantic walk's +/// checks. fn check_references(tokens: &[Token], maps: &ExpressionMaps) -> Result<(), DynamoDbError> { use super::semantics::{check_path_refs, check_value_defined}; let kind = super::ExpressionKind::KeyCondition; diff --git a/crates/core/src/expression/path_length.rs b/crates/core/src/expression/path_length.rs index aa0ef7875..fe0769435 100644 --- a/crates/core/src/expression/path_length.rs +++ b/crates/core/src/expression/path_length.rs @@ -11,8 +11,8 @@ //! `#name` in an earlier path or inside the long path is reported instead //! (measured 2026-10-26 and 2026-11-12, us-east-1). The semantic walk, the //! projection resolution and the key condition's reference pass run the check -//! right after each path's names; the key condition's pass also checks each -//! `:value` in text order, and runs before the nested-attribute refusal. +//! right after each path's names. The key condition's pass also checks each +//! `:value` in text order, and it runs before the nested-attribute refusal. use super::ast::PathElement; diff --git a/crates/core/src/expression/projection.rs b/crates/core/src/expression/projection.rs index bc80cf9f8..41103fd76 100755 --- a/crates/core/src/expression/projection.rs +++ b/crates/core/src/expression/projection.rs @@ -130,11 +130,12 @@ pub(crate) enum ResolvedElement { /// Resolve `#name` references in parsed paths, rejecting index-start paths. /// -/// The service checks the paths one after another in text order: a path's -/// names, then its length, then, when `overlap` names the expression kind, -/// whether it overlaps an earlier path (one is a prefix of the other). So -/// `#k, #k, <33 elements>` answers the overlap, and `#m, <33 elements>` and -/// `#k, <33 elements>, #k` the length (measured 2026-11-12, us-east-1). +/// The service checks the paths one after another in text order. It checks a +/// path's names, then its length. When `overlap` names the expression kind, +/// it then checks whether the path overlaps an earlier path (one is a prefix +/// of the other). So `#k, #k, <33 elements>` answers the overlap. Both +/// `#m, <33 elements>` and `#k, <33 elements>, #k` answer the length +/// (measured 2026-11-12, us-east-1). pub(crate) fn resolve_paths( paths: &[Vec], maps: &ExpressionMaps, @@ -166,7 +167,7 @@ pub(crate) fn resolve_paths( if let Some(msg) = super::path_length::too_many_levels(path) { return Err(DynamoDbError::ValidationException(msg)); } - // Siblings are fine; the message names the earlier path first. + // Siblings are fine. The message names the earlier path first. if let Some(kind) = overlap && let Some(earlier) = resolved .iter() diff --git a/crates/core/src/expression/resolver.rs b/crates/core/src/expression/resolver.rs index 0acd688f5..4e22f82a1 100755 --- a/crates/core/src/expression/resolver.rs +++ b/crates/core/src/expression/resolver.rs @@ -332,10 +332,10 @@ pub fn validate_unused_attributes( /// prefix of the other, across all four sections, after `#name` resolution: /// `SET a = :v, a = :w`, `SET m = :v, m.x = :w`, `SET a.b = :v REMOVE a`, and /// `SET #l[1] = :v, #l[1].x = :w` with `#l` bound to `lst` all fail. Siblings -/// (`m.x` and `m.y`) are fine. The first path in expression order that -/// overlaps an earlier one is named after that earlier path, rendered as the -/// service renders it: `[lst, [1]]` (`SET a = :v, b = :v, b.y = :v, a.x = :v` -/// names `[b]` and `[b, y]`, measured 2026-11-12). +/// (`m.x` and `m.y`) are fine. The message names the first path in expression +/// order that overlaps an earlier one, after that earlier path. It renders the +/// paths as the service renders them: `[lst, [1]]`. Measured 2026-11-12: +/// `SET a = :v, b = :v, b.y = :v, a.x = :v` names `[b]` and `[b, y]`. /// /// # Errors /// diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 3a56c2e75..ae602f33f 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -383,12 +383,12 @@ pub fn parse_projection_expr( /// does not define and a document path of more than 32 elements. /// /// Errors carry the `KeyConditionExpression` prefix, matching Amazon -/// `DynamoDB`. The references and the path lengths are checked once the whole -/// expression parses, in one pass in the order they stand in the text, names -/// and values alike (measured 2026-10-27: `pk = :q AND #n = :v` names `:q`, -/// `#b = :p AND #a > :q` names `#b`; see +/// `DynamoDB`. Once the whole expression parses, the references and the path +/// lengths are checked in one pass in text order, names and values alike. +/// Measured 2026-10-27: `pk = :q AND #n = :v` names `:q`, and +/// `#b = :p AND #a > :q` names `#b`. See /// `extenddb_core::expression::parse_key_condition_with_maps` for the -/// lengths). The check runs before the key schema is consulted, so an +/// lengths. The check runs before the key schema is consulted, so an /// undefined `#n` is reported as such rather than as a key schema mismatch /// (measured 2026-10-14). /// diff --git a/crates/engine/src/put_item.rs b/crates/engine/src/put_item.rs index a391976be..9c1c288d7 100755 --- a/crates/engine/src/put_item.rs +++ b/crates/engine/src/put_item.rs @@ -148,12 +148,13 @@ pub async fn handle_put_item( extenddb_core::validation::validate_table_name(&input.table_name, &ctx.limits)?; // The Item's numbers and nesting come before every expression check, with - // or without ExpressionAttributeValues: an Item holding `{N: abc}` or an - // attribute 33 maps deep answers the number or the nesting error beside a - // condition with a syntax error, an undefined name or value, an unused - // value, a reserved word, a path of 33 elements or BETWEEN bounds out of - // order (measured 2026-11-12). `validate_put_item` checks them again - // after the table lookup. + // or without ExpressionAttributeValues (measured 2026-11-12). An Item + // holding `{N: abc}` or an attribute 33 maps deep answers the number or + // the nesting error beside a condition fault. The faults measured are a + // syntax error, an undefined name or value, an unused value and a + // reserved word. They also include a path of 33 elements and BETWEEN + // bounds out of order. + // `validate_put_item` checks them again after the table lookup. extenddb_core::validation::validate_item_numbers(&input.item)?; extenddb_core::validation::validate_item_nesting_depth(&input.item)?; diff --git a/crates/engine/src/transact_write_items.rs b/crates/engine/src/transact_write_items.rs index 0478b77a5..27e1ad650 100755 --- a/crates/engine/src/transact_write_items.rs +++ b/crates/engine/src/transact_write_items.rs @@ -483,11 +483,12 @@ fn parse_write_expressions( }; // A Put's Item nesting comes before every check of the item's expressions - // and before the item's size: an Item attribute 33 maps deep answers the - // nesting error beside a condition with a syntax error, an undefined name - // or value, an unused value, a reserved word, a path of 33 elements or - // BETWEEN bounds out of order, and beside an item over the size limit - // (measured 2026-11-12). + // and before the item's size (measured 2026-11-12). An Item attribute 33 + // maps deep answers the nesting error beside a condition fault. The + // faults measured are a syntax error, an undefined name or value, an + // unused value and a reserved word. They also include a path of 33 + // elements and BETWEEN bounds out of order. The Item also answers the + // nesting error beside an item over the size limit. if let Some(put) = &twi.put { validate_item_nesting_depth(&put.item)?; } @@ -500,15 +501,16 @@ fn parse_write_expressions( validate_value_map_nesting(values)?; // Inside a transaction the service checks an Update item's - // ConditionExpression before its UpdateExpression, as UpdateItem does: - // a condition with an undefined name or BETWEEN bounds out of order beats - // an UpdateExpression syntax error, undefined name or value, overlap, - // reserved word, operand type and path length (measured 2026-11-12, each - // request twice; on 2026-10-14 the service answered the UpdateExpression - // first). Then come the unused names and values; then, for a Put, the - // item's size (measured: an oversize Put with an unused value reports the - // value, and an oversize item reports its size ahead of the next item's - // defects). + // ConditionExpression before its UpdateExpression, as UpdateItem does + // (measured 2026-11-12, each request twice). A condition with an + // undefined name or BETWEEN bounds out of order beats an UpdateExpression + // fault. The faults measured are a syntax error, an undefined name or + // value and an overlap. They also include a reserved word, an operand + // type and the path length. On 2026-10-14 the service answered the + // UpdateExpression first. The unused names and values come next. Then, + // for a Put, comes the item's size. Measured: an oversize Put with an + // unused value reports the value. An oversize item reports its size + // ahead of the next item's defects. let maps = build_expression_maps(names, values); let condition = match condition_expression { // A ConditionCheck's expression is required, so an empty string is diff --git a/docs/dynamodb-limits.md b/docs/dynamodb-limits.md index 41bc531bf..ccfe08b78 100755 --- a/docs/dynamodb-limits.md +++ b/docs/dynamodb-limits.md @@ -67,7 +67,7 @@ Source: [AWS DynamoDB Service Quotas](https://docs.aws.amazon.com/amazondynamodb | Condition expression size | 4 KB | Enforced | `check_expression_size`, `LimitsConfig::max_expression_length_bytes` | | Update expression size | 4 KB | Enforced | `check_expression_size`, `LimitsConfig::max_expression_length_bytes` | | Key condition expression size | 4 KB | Enforced | `check_expression_size`, `LimitsConfig::max_expression_length_bytes` | -| Document path length in an expression | 32 elements (each attribute name and list index counts as one) | Enforced | Every expression kind: `Invalid : The document path has too many nesting levels; nesting levels: `. Checked path by path in the order the paths appear, after each path's `#name` references, so an undefined `#name` in an earlier path or inside the long path is reported first, as on the service; a KeyConditionExpression checks its `:value` references in the same pass. A syntax error anywhere in the expression is reported first. ExtendDB checks reserved words on the whole expression before any path, where the service checks them in the same walk, so a long path followed by a reserved word answers the reserved word error | +| Document path length in an expression | 32 elements (each attribute name and list index counts as one) | Enforced | Every expression kind: `Invalid : The document path has too many nesting levels; nesting levels: `. Checked path by path in the order the paths appear, after each path's `#name` references, so an undefined `#name` in an earlier path or inside the long path is reported first, as on the service. A KeyConditionExpression checks its `:value` references in the same pass. A syntax error anywhere in the expression is reported first. ExtendDB checks reserved words on the whole expression before any path, where the service checks them in the same walk, so a long path followed by a reserved word answers the reserved word error | | Expression attribute names | 2 MB total | Not enforced | Per-entry key/value validated (`serde_helpers`); no aggregate size validation | | Expression attribute values | 2 MB total | Not enforced | Per-entry key/value validated (`serde_helpers`); no aggregate size validation | diff --git a/tests/test_document_path_length.py b/tests/test_document_path_length.py index 867820e01..1c1cbd48a 100644 --- a/tests/test_document_path_length.py +++ b/tests/test_document_path_length.py @@ -335,9 +335,9 @@ def test_between_bounds_are_checked_whatever_the_item(dynamodb_client, table, ke def test_legacy_expected_between_bounds_out_of_order_are_refused(dynamodb_client, table, key): # The service words this `One or more parameter values were invalid: The # BETWEEN condition was provided a range where the lower bound is greater - # than the upper bound` (measured 2026-11-12); ExtendDB answers with the - # ConditionExpression sentence, so only the class and the operator are - # compared. + # than the upper bound` (measured 2026-11-12). ExtendDB answers with the + # ConditionExpression sentence, so the test compares only the class and + # the operator. expected = {"n": {"ComparisonOperator": "BETWEEN", "AttributeValueList": [{"N": "5"}, {"N": "1"}]}} missing = {"pk": {"S": "plen"}, "sk": {"S": "between-expected-no-item"}} for k in (missing, key): @@ -360,9 +360,9 @@ def test_projection_names_come_before_the_length(dynamodb_client, table, key): OVERLAP_K = ("Invalid ProjectionExpression: Two document paths overlap with each other; must remove or rewrite " "one of these paths; path one: [k], path two: [k]") -# (case, projection, message): the service checks the paths one after another, -# each path's length before its overlap with an earlier path (measured -# 2026-11-12, each request twice). +# (case, projection, message): the service checks the paths one after +# another. It checks each path's length before its overlap with an earlier +# path (measured 2026-11-12, each request twice). PROJECTION_ORDER = [ ("overlap_before_a_later_length", f"#k, #k, {p(33)}", OVERLAP_K), ("length_before_a_later_overlap", f"{p(33)}, #k, #k", too_long("ProjectionExpression", 33)), @@ -507,9 +507,10 @@ def test_query_key_condition(dynamodb_client, table, key): KEY_VALUE = f"Invalid KeyConditionExpression: {UNDEFINED_VALUE}" KEY_LENGTH = too_long("KeyConditionExpression", 33) -# (case, key condition, names, values defined, message): the names, the -# values and each path's length in one pass in text order, then the -# nested-attribute refusal (measured 2026-11-12, each request twice). +# (case, key condition, names, values defined, message): the service checks +# the names, the values and each path's length in one pass in text order. +# Then it refuses a nested attribute (measured 2026-11-12, each request +# twice). KEY_CONDITION_ORDER = [ ("name_inside_the_long_path", "pk = :p AND #zz" + ".#k" * 32 + " = :s", {"#k": "k"}, (":p", ":s"), KEY_NAME), ("value_in_an_earlier_clause", f"pk = :nope AND {p(33)} = :s", N, (":s",), KEY_VALUE), From 519f2006292860729be2e01c0cfe55aa0d297829 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:59:38 +0000 Subject: [PATCH 13/14] refactor(put): check the Item's numbers and nesting once `handle_put_item` checks the Item's numbers and nesting right after the table name, before the condition and the table lookup. `validate_put_item` then checked both again on the same Item. `handle_put_item` is the only caller of `validate_put_item`, so the second pair of checks could not fail. `validate_put_item` no longer runs them, and the handler comment no longer says that it does. The comment on the ExpressionAttributeValues nesting check said "It comes after an invalid number in the Item". The pronoun read as `validate_value_map_nesting`, the function that the sentence before names. The comment now starts with "This check". It also says that the check comes after the Item's nesting as well as its numbers. --- crates/core/src/validation/mod.rs | 2 -- crates/engine/src/put_item.rs | 7 +++---- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index 6e131d5ab..9e9f689af 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -1092,8 +1092,6 @@ pub fn validate_put_item( // The attribute-name size check is not here: the service reports it // ahead of the table lookup, so the handler runs it before this. validate_item_keys(&input.item, key_schema, attr_defs)?; - validate_item_numbers(&input.item)?; - validate_item_nesting_depth(&input.item)?; let size = item_size_bytes(&input.item); if size > limits.max_item_size_bytes { diff --git a/crates/engine/src/put_item.rs b/crates/engine/src/put_item.rs index 9c1c288d7..84cb55926 100755 --- a/crates/engine/src/put_item.rs +++ b/crates/engine/src/put_item.rs @@ -154,7 +154,6 @@ pub async fn handle_put_item( // syntax error, an undefined name or value, an unused value and a // reserved word. They also include a path of 33 elements and BETWEEN // bounds out of order. - // `validate_put_item` checks them again after the table lookup. extenddb_core::validation::validate_item_numbers(&input.item)?; extenddb_core::validation::validate_item_nesting_depth(&input.item)?; @@ -163,9 +162,9 @@ pub async fn handle_put_item( // 2026-08-24 (us-east-1), a 32-level value referenced solely by a // ConditionExpression is rejected on PutItem, DeleteItem, and UpdateItem // alike, while 31 levels is accepted. TransactWriteItems checks its values - // separately, in `validate_value_map_nesting`. It comes after an invalid - // number in the Item and before the ConditionExpression and the table - // lookup (measured 2026-10-26). + // separately, in `validate_value_map_nesting`. This check comes after the + // Item's numbers and nesting and before the ConditionExpression and the + // table lookup (measured 2026-10-26). if let Some(values) = &input.expression_attribute_values { extenddb_core::validation::validate_attribute_values_nesting_depth(values.values())?; } From 70292427ad7e90ff5ba48d18bb58a3322b9b3936 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:57:53 +0000 Subject: [PATCH 14/14] fix(put): run the Item and value checks once, at their position from main Main (#620) checks a PutItem Item's numbers and nesting in put_item_item, ahead of the mixed-parameter check. It checks the ExpressionAttributeValues nesting and numbers in put_item_values, after that check. This branch ran the same three checks again after validate_table_name. The second copies could not fail after the first ones. They are gone. The behaviour this branch added, the Item's error ahead of every condition fault, holds through main's checks. The two comments from main said that validate_put_item and a later nesting check repeat these checks. This branch removed both repeats, so the comments now say that the checks run once. They also carry the measurements this branch recorded. The Item's error comes beside a condition fault, with or without ExpressionAttributeValues. TransactWriteItems checks its values in validate_value_map_nesting. --- crates/engine/src/put_item.rs | 36 ++++++++++------------------------- 1 file changed, 10 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/put_item.rs b/crates/engine/src/put_item.rs index d33e8bd71..34bb85ab0 100755 --- a/crates/engine/src/put_item.rs +++ b/crates/engine/src/put_item.rs @@ -116,8 +116,12 @@ pub async fn handle_put_item( // Numbers come first, as before this check; the service's order follows // the request body, which `Item` does not keep. An attribute name over // the size limit comes before both: the service answered either fault for - // one item holding both (measured 2026-11-11). - // The later `validate_put_item` repeats both and cannot fail after this. + // one item holding both (measured 2026-11-11). Beside a condition fault + // the Item's error comes first, with or without ExpressionAttributeValues + // (measured 2026-11-12). The faults measured are a syntax error, an + // undefined name or value, an unused value and a reserved word. They also + // include a path of 33 elements and BETWEEN bounds out of order. This is + // the one run of the two checks: `validate_put_item` does not repeat them. extenddb_core::validation::number::operations::put_item_item(&input)?; // Reject mixing legacy and expression parameters, then EAN/EAV supplied @@ -138,8 +142,10 @@ pub async fn handle_put_item( // The ExpressionAttributeValues follow the mixed-parameter check and // precede the other expression checks and the table lookup (measured // 2026-10-27). A value nested too deep comes ahead of a malformed number, - // as before this check; the service answered either on two sends. - // The later nesting check repeats this one and cannot fail after it. + // as before this check; the service answered either on two sends. The + // nesting limit applies to every value, condition-only placeholders + // included (measured 2026-08-24). TransactWriteItems checks its values + // separately, in `validate_value_map_nesting`. extenddb_core::validation::number::operations::put_item_values(&input)?; // A legacy Expected value's number is read ahead of the condition // (measured 2026-11-11). @@ -166,28 +172,6 @@ pub async fn handle_put_item( extenddb_core::validation::validate_table_name(&input.table_name, &ctx.limits)?; - // The Item's numbers and nesting come before every expression check, with - // or without ExpressionAttributeValues (measured 2026-11-12). An Item - // holding `{N: abc}` or an attribute 33 maps deep answers the number or - // the nesting error beside a condition fault. The faults measured are a - // syntax error, an undefined name or value, an unused value and a - // reserved word. They also include a path of 33 elements and BETWEEN - // bounds out of order. - extenddb_core::validation::validate_item_numbers(&input.item)?; - extenddb_core::validation::validate_item_nesting_depth(&input.item)?; - - // The nesting-depth limit applies to every ExpressionAttributeValue on the - // single-item write paths, condition-only placeholders included: measured - // 2026-08-24 (us-east-1), a 32-level value referenced solely by a - // ConditionExpression is rejected on PutItem, DeleteItem, and UpdateItem - // alike, while 31 levels is accepted. TransactWriteItems checks its values - // separately, in `validate_value_map_nesting`. This check comes after the - // Item's numbers and nesting and before the ConditionExpression and the - // table lookup (measured 2026-10-26). - if let Some(values) = &input.expression_attribute_values { - extenddb_core::validation::validate_attribute_values_nesting_depth(values.values())?; - } - // Validate expressions/`Expected` before the existence check, // so a malformed request to a missing table returns ValidationException, // not ResourceNotFoundException. Key/item-content checks stay after.