diff --git a/crates/core/src/expression/evaluator.rs b/crates/core/src/expression/evaluator.rs index 84ebe12a7..943b9d33e 100755 --- a/crates/core/src/expression/evaluator.rs +++ b/crates/core/src/expression/evaluator.rs @@ -55,29 +55,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)) => { @@ -129,6 +110,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). 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, + 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 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), + ) { + "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 number for a placeholder expression. /// /// Returns `None` if the expression is not a placeholder or has no pre-parsed diff --git a/crates/core/src/expression/evaluator_tests.rs b/crates/core/src/expression/evaluator_tests.rs index e3f88a634..123bd9630 100755 --- a/crates/core/src/expression/evaluator_tests.rs +++ b/crates/core/src/expression/evaluator_tests.rs @@ -228,6 +228,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/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index d8fb7122d..5029f0ff1 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,32 @@ 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, one pass +/// in text order checks every `#name` and `:value` reference against `maps` +/// and every document path's length. The pass runs 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` answer the length. +/// `#m.#k = :s AND #zz = :p` answers 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 +580,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 +614,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,9 +655,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. + // 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))?; } @@ -635,6 +670,31 @@ 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. 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; + let mut pos = 0; + while pos < tokens.len() { + match &tokens[pos] { + 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(_) => { + check_path_refs(&parser_common::parse_path(tokens, &mut pos)?, maps, kind)?; + } + _ => 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 d327acacc..2f2e2811f 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; @@ -29,10 +30,11 @@ 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}; +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..fe0769435 --- /dev/null +++ b/crates/core/src/expression/path_length.rs @@ -0,0 +1,177 @@ +// 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 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 it runs before the nested-attribute refusal. + +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_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(), + ); + 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] + 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(|_| ()) + }; + 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()); + } + + #[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..41103fd76 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,19 @@ 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. 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, + 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,38 +164,27 @@ 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. + 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()] @@ -636,6 +631,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 44927e09e..54a814644 100755 --- a/crates/core/src/expression/resolver.rs +++ b/crates/core/src/expression/resolver.rs @@ -361,8 +361,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 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 /// @@ -382,8 +384,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/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/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 157e60573..d6afe9fa5 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; @@ -10,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, @@ -28,10 +29,15 @@ 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( +pub(in crate::expression) fn check_value_defined( name: &str, maps: &ExpressionMaps, kind: ExpressionKind, diff --git a/crates/core/src/expression/semantics/tests.rs b/crates/core/src/expression/semantics/tests.rs index 52aae7b06..859b4c488 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] @@ -432,3 +439,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: +/// 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/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index 8cf47154c..738c948de 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -1109,8 +1109,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/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index f27e1af37..ae602f33f 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`. 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 +/// 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/crates/engine/src/put_item.rs b/crates/engine/src/put_item.rs index 0f65921b7..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). @@ -212,17 +218,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/transact_write_items.rs b/crates/engine/src/transact_write_items.rs index af0bb038d..a7cc59bc0 100755 --- a/crates/engine/src/transact_write_items.rs +++ b/crates/engine/src/transact_write_items.rs @@ -92,10 +92,10 @@ pub async fn handle_transact_write_items( // 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 // numbers of the item's ExpressionAttributeValues (for a Put or - // Delete, only with a ConditionExpression) and of its key or 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 + // Delete, only with a ConditionExpression) and of its key or 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), @@ -503,6 +503,17 @@ fn parse_write_expressions( )); }; + // A Put's Item nesting comes before every check of the item's expressions + // 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)?; + } + // 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 @@ -511,20 +522,17 @@ 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 + // (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 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 @@ -541,6 +549,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() { @@ -557,7 +571,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/crates/engine/src/update_item.rs b/crates/engine/src/update_item.rs index 042cb4420..cf0d43b1e 100755 --- a/crates/engine/src/update_item.rs +++ b/crates/engine/src/update_item.rs @@ -120,6 +120,21 @@ pub(crate) async fn handle_update_item_with( // (measured 2026-11-11). extenddb_core::validation::number::operations::expected_values(input.expected.as_ref())?; + // 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 { @@ -244,19 +259,6 @@ pub(crate) async fn handle_update_item_with( // `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 92bfc362c..42c204e4a 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 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 new file mode 100644 index 000000000..1c1cbd48a --- /dev/null +++ b/tests/test_document_path_length.py @@ -0,0 +1,561 @@ +# 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, 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 +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}") +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: + 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) + + +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) + + +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) + + +@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 :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: {message}"), cond + assert "Item" not in dynamodb_client.get_item(TableName=table, Key=missing, ConsistentRead=True) + 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 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): + 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): + 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}") + + +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. 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)), + ("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", + "ExpressionAttributeNames": N, "ExpressionAttributeValues": S, + }}])) == ("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)})", + "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") + + +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 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), + ("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)})")) == ( + "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)) 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: 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,