From 597ef700018ba58dac2b67e0b65ca62fac2f35f8 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:39:42 +0000 Subject: [PATCH 01/37] fix(expression): cap operators at 300, word syntax errors as the service does, and classify too-long map keys on PutItem Condition, filter and key condition expressions now count operators the way Amazon DynamoDB does: every comparison, AND, OR, NOT, BETWEEN, IN and function call (size included) counts one; parentheses, paths, placeholders and list elements count zero. A count above 300 is refused with "Invalid : The expression contains too many operators; operator count: ". On the write paths the count runs after the ordering operand type check and before the unused name and value check and the table lookup; on Query it runs ahead of the key grammar. TransactWriteItems is unchanged. A repeated or misplaced operator or keyword now answers "Syntax error; token: \"\", near: \"\"" on condition, filter, key condition, update and projection expressions. The window runs from the token before the offending one to the token after it, with the source whitespace kept; at the end of input the token is and the window is the last token. Other syntax error texts are unchanged. PutItem classified deserializer errors itself and answered a too-long key in ExpressionAttributeNames or ExpressionAttributeValues as SerializationException. It now uses the shared classifier, which answers the ValidationException. The ExpressionAttributeValues text carries the "; size of key: " suffix, as the service answers on PutItem, Scan and Query. Measured on 2026-10-25 between 10:39 and 10:52 UTC, each case twice. Fixes #501 --- crates/core/src/expression/key_condition.rs | 198 +++++++++++++--- crates/core/src/expression/mod.rs | 10 +- crates/core/src/expression/operator_count.rs | 129 +++++++++++ crates/core/src/expression/parser.rs | 102 +++++--- crates/core/src/expression/projection.rs | 74 +++++- crates/core/src/expression/syntax_error.rs | 232 +++++++++++++++++++ crates/core/src/expression/update_parser.rs | 230 +++++++++--------- crates/core/src/serde_helpers.rs | 44 ++-- crates/engine/src/expression_helpers.rs | 107 ++++++++- crates/engine/src/put_item.rs | 24 +- crates/engine/src/query.rs | 3 + crates/engine/src/scan.rs | 7 + 12 files changed, 929 insertions(+), 231 deletions(-) create mode 100644 crates/core/src/expression/operator_count.rs create mode 100644 crates/core/src/expression/syntax_error.rs diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index edaa1f8e5..787382c68 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -14,7 +14,9 @@ //! - No OR, NOT, nested conditions, or other functions use super::ast::{CompareOp, Expr, PathElement}; +use super::kind::ExpressionKind; use super::parser_common; +use super::syntax_error::{is_operator_or_keyword, syntax_error}; use super::tokenizer::Token; use crate::error::DynamoDbError; use crate::types::{ @@ -530,7 +532,23 @@ impl SortKeyCondition { /// /// Returns `ValidationException` for syntax errors or unsupported constructs. pub fn parse_key_condition(tokens: &[Token]) -> Result { - let mut clauses = parse_clauses(tokens)?; + parse_key_condition_from(tokens, "") +} + +/// Parse a `KeyConditionExpression` whose tokens came from `source`, so a +/// syntax error can quote the source window around the offending token as +/// Amazon `DynamoDB` does (`pk = = :v` answers `Syntax error; token: "=", +/// near: "= = :v"`; `pk = :v AND` answers `token: "", near: "AND"`, +/// measured 2026-10-25). An empty `source` joins the token texts instead. +/// +/// # Errors +/// +/// Returns `ValidationException` for syntax errors or unsupported constructs. +pub fn parse_key_condition_from( + tokens: &[Token], + source: &str, +) -> Result { + let mut clauses = parse_clauses(tokens, source)?; match clauses.len() { 1 => classify_single(clauses.remove(0)), @@ -555,7 +573,7 @@ pub fn parse_key_condition(tokens: &[Token]) -> Result Result, DynamoDbError> { - Ok(parse_clauses(tokens)? + Ok(parse_clauses(tokens, "")? .into_iter() .filter_map(|clause| match clause { RawClause::Eq(path, value) => Some(KeyClauseOperand { @@ -589,25 +607,35 @@ 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> { +/// A syntax error quotes `source`, the text the tokens came from; an empty +/// `source` joins the token texts instead. +fn parse_clauses(tokens: &[Token], source: &str) -> Result, DynamoDbError> { parser_common::check_redundant_parens(tokens) .map_err(|body| validation_err(&format!("Invalid KeyConditionExpression: {body}")))?; // Strip outer parentheses: "(pk = :pk AND sk > :sk)" → "pk = :pk AND sk > :sk" - let tokens = if tokens.len() >= 2 + let all = tokens; + let (tokens, offset) = if tokens.len() >= 2 && tokens[0] == Token::LParen && tokens[tokens.len() - 1] == Token::RParen && outer_parens_match(tokens) { - &tokens[1..tokens.len() - 1] + (&tokens[1..tokens.len() - 1], 1) } else { - tokens + (tokens, 0) + }; + // Syntax errors quote the window from the full token list, so a position + // inside the stripped slice is shifted back by the stripped parenthesis. + let src = Source { + text: source, + all, + offset, }; let mut pos = 0; let mut clauses = Vec::new(); - clauses.push(parse_key_clause(tokens, &mut pos)?); + clauses.push(parse_key_clause(tokens, &src, &mut pos)?); while pos < tokens.len() { if tokens[pos] != Token::And { @@ -616,7 +644,7 @@ fn parse_clauses(tokens: &[Token]) -> Result, DynamoDbError> { )); } pos += 1; - clauses.push(parse_key_clause(tokens, &mut pos)?); + clauses.push(parse_key_clause(tokens, &src, &mut pos)?); } if pos < tokens.len() { @@ -635,6 +663,27 @@ fn parse_clauses(tokens: &[Token]) -> Result, DynamoDbError> { Ok(clauses) } +/// The expression text and full token list a clause parser reports syntax +/// errors against; `offset` is the number of tokens stripped before the slice +/// being parsed. +struct Source<'a> { + text: &'a str, + all: &'a [Token], + offset: usize, +} + +impl Source<'_> { + /// The service's syntax error for the token at `pos` of the parsed slice. + fn syntax_error(&self, pos: usize) -> DynamoDbError { + syntax_error( + ExpressionKind::KeyCondition, + self.text, + self.all, + pos + self.offset, + ) + } +} + /// The attribute-side path of a raw clause. fn raw_clause_path(clause: &RawClause) -> &[PathElement] { match clause { @@ -777,17 +826,25 @@ fn raw_to_sk(clause: RawClause) -> SortKeyCondition { } } -fn parse_key_clause(tokens: &[Token], pos: &mut usize) -> Result { +fn parse_key_clause( + tokens: &[Token], + src: &Source<'_>, + pos: &mut usize, +) -> Result { if *pos >= tokens.len() { - return Err(validation_err( - "Invalid KeyConditionExpression: unexpected end of expression", - )); + if tokens.is_empty() { + return Err(validation_err( + "Invalid KeyConditionExpression: unexpected end of expression", + )); + } + // Input ends where a clause is required (`pk = :v AND`). + return Err(src.syntax_error(*pos)); } // Allow one level of parentheses around a single clause if tokens[*pos] == Token::LParen { *pos += 1; - let clause = parse_key_clause_inner(tokens, pos)?; + let clause = parse_key_clause_inner(tokens, src, pos)?; if *pos < tokens.len() && tokens[*pos] == Token::RParen { *pos += 1; return Ok(clause); @@ -797,14 +854,16 @@ fn parse_key_clause(tokens: &[Token], pos: &mut usize) -> Result Result { +fn parse_key_clause_inner( + tokens: &[Token], + src: &Source<'_>, + pos: &mut usize, +) -> Result { if *pos >= tokens.len() { - return Err(validation_err( - "Invalid KeyConditionExpression: unexpected end of expression", - )); + return Err(src.syntax_error(*pos)); } // begins_with(path, :val) @@ -815,15 +874,15 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result= tokens.len() { return Err(validation_err( @@ -846,7 +905,7 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result Result Result Result Result { +fn parse_key_operand( + tokens: &[Token], + src: &Source<'_>, + pos: &mut usize, +) -> Result { if *pos >= tokens.len() { - return Err(validation_err( - "Invalid KeyConditionExpression: unexpected end of expression", - )); + return Err(src.syntax_error(*pos)); } match &tokens[*pos] { @@ -903,9 +964,11 @@ fn parse_key_operand(tokens: &[Token], pos: &mut usize) -> Result { - let value = parse_key_value(tokens, pos)?; + let value = parse_key_value(tokens, src, pos)?; Ok(KeyOperand::Value(value)) } + // An operator or keyword where an operand is required (`AND pk = :v`). + token if is_operator_or_keyword(token) => Err(src.syntax_error(*pos)), _ => Err(validation_err( "Invalid KeyConditionExpression: expected attribute path or value placeholder", )), @@ -914,27 +977,30 @@ fn parse_key_operand(tokens: &[Token], pos: &mut usize) -> Result, pos: &mut usize, ) -> Result, DynamoDbError> { if *pos >= tokens.len() { - return Err(validation_err( - "Invalid KeyConditionExpression: expected attribute path", - )); + return Err(src.syntax_error(*pos)); } match &tokens[*pos] { Token::Ident(_) | Token::NameRef(_) => parser_common::parse_path(tokens, pos), + token if is_operator_or_keyword(token) => Err(src.syntax_error(*pos)), _ => Err(validation_err( "Invalid KeyConditionExpression: expected attribute path", )), } } -fn parse_key_value(tokens: &[Token], pos: &mut usize) -> Result { +fn parse_key_value( + tokens: &[Token], + src: &Source<'_>, + pos: &mut usize, +) -> Result { if *pos >= tokens.len() { - return Err(validation_err( - "Invalid KeyConditionExpression: expected value", - )); + // Input ends where a value is required (`pk =`). + return Err(src.syntax_error(*pos)); } match &tokens[*pos] { Token::Placeholder(name) => { @@ -942,6 +1008,9 @@ fn parse_key_value(tokens: &[Token], pos: &mut usize) -> Result Err(src.syntax_error(*pos)), _ => Err(validation_err( "Invalid KeyConditionExpression: key condition values must be expression attribute value placeholders", )), @@ -1902,4 +1971,59 @@ mod tests { kc.resolve_key_schema(&schema, &HashMap::new()).unwrap(); assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); } + + // Syntax error wording measured 2026-10-25 (us-east-1) on Query. + + fn kce_msg(src: &str) -> String { + match parse_key_condition_from(&tokenize(src).unwrap(), src) { + Err(DynamoDbError::ValidationException(m)) => m, + other => panic!("expected ValidationException, got {other:?}"), + } + } + + #[test] + fn repeated_operator_quotes_the_source_window() { + // [d22] `pk = = :v` + assert_eq!( + kce_msg("pk = = :v"), + "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :v\"" + ); + assert_eq!(kce_msg("pk = :v AND sk = = :s"), "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :s\""); + } + + #[test] + fn trailing_keyword_is_eof_with_the_keyword_as_window() { + // [d23] `pk = :v AND` + assert_eq!( + kce_msg("pk = :v AND"), + "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"AND\"" + ); + assert_eq!(kce_msg("pk ="), "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"=\""); + } + + #[test] + fn stripped_outer_parentheses_keep_the_source_window() { + // The window is taken from the full token list, so the stripped + // parenthesis does not shift the quoted text. + assert_eq!( + kce_msg("(pk = = :v)"), + "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :v\"" + ); + } + + #[test] + fn other_key_condition_texts_are_unchanged() { + assert_eq!( + kce_msg("pk = :v OR sk = :s"), + "Invalid KeyConditionExpression: only AND is supported between key conditions" + ); + assert_eq!( + kce_msg("pk"), + "Invalid KeyConditionExpression: expected operator after operand" + ); + assert_eq!( + kce_msg("pk = :v AND sk = sk2"), + "Invalid KeyConditionExpression: key condition values must be expression attribute value placeholders" + ); + } } diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index c9f8e207b..63a975b03 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -12,12 +12,14 @@ mod ast; mod evaluator; mod key_condition; mod kind; +mod operator_count; mod parser; mod parser_common; mod projection; mod reserved_words; mod resolver; mod search_condition; +mod syntax_error; mod tokenizer; mod update_evaluator; mod update_parser; @@ -26,11 +28,12 @@ pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction}; pub use evaluator::evaluate_condition; pub use key_condition::{ KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands, - parse_key_condition, + parse_key_condition, parse_key_condition_from, }; pub use kind::ExpressionKind; -pub use parser::{parse_condition, parse_condition_with_depth_limit}; -pub use projection::{Projection, parse_projection}; +pub use operator_count::{MAX_EXPRESSION_OPERATORS, count_operators, validate_operator_count}; +pub use parser::{parse_condition, parse_condition_from, parse_condition_with_depth_limit}; +pub use projection::{Projection, parse_projection, parse_projection_from}; pub use reserved_words::validate_no_reserved_words; pub use resolver::{ ExpressionMaps, collect_key_condition_refs, collect_value_placeholders, resolve_element_name, @@ -42,6 +45,7 @@ pub use search_condition::{ SearchCondition, validate_conditions_against_search_schema, validate_search_condition_expression, }; +pub use syntax_error::{is_operator_or_keyword, syntax_error, token_text}; pub use tokenizer::{Token, tokenize, tokenize_for, tokenize_with_limit}; pub use update_evaluator::apply_update_validated; pub use update_parser::{parse_update, parse_update_from}; diff --git a/crates/core/src/expression/operator_count.rs b/crates/core/src/expression/operator_count.rs new file mode 100644 index 000000000..ef3f4ba45 --- /dev/null +++ b/crates/core/src/expression/operator_count.rs @@ -0,0 +1,129 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The operator cap Amazon `DynamoDB` applies to condition, filter and key +//! condition expressions. +//! +//! Measured 2026-10-25 (us-east-1) with `PutItem`, `Scan` and `Query`: every +//! comparison (`=`, `<>`, `<`, `<=`, `>`, `>=`), `AND`, `OR`, `NOT`, `BETWEEN` +//! (its inner `AND` not counted), `IN` (list elements not counted) and every +//! function call (`size` included) counts one; parentheses, paths and +//! placeholders count zero. An expression whose count exceeds 300 is refused +//! with `Invalid : The expression contains too many operators; operator +//! count: `; a count of exactly 300 is accepted. + +use super::ast::Expr; +use super::kind::ExpressionKind; +use crate::error::DynamoDbError; + +/// The largest operator count the service accepts. +pub const MAX_EXPRESSION_OPERATORS: usize = 300; + +/// Count the operators in a parsed condition as the service counts them. +#[must_use] +pub fn count_operators(expr: &Expr) -> usize { + match expr { + Expr::Path(_) | Expr::Placeholder(_) => 0, + Expr::Not(inner) => 1 + count_operators(inner), + Expr::And(left, right) | Expr::Or(left, right) => { + 1 + count_operators(left) + count_operators(right) + } + Expr::Compare { left, right, .. } | Expr::Arithmetic { left, right, .. } => { + 1 + count_operators(left) + count_operators(right) + } + Expr::Between { operand, low, high } => { + 1 + count_operators(operand) + count_operators(low) + count_operators(high) + } + Expr::In { operand, list } => { + 1 + count_operators(operand) + list.iter().map(count_operators).sum::() + } + Expr::Function { args, .. } => 1 + args.iter().map(count_operators).sum::(), + } +} + +/// Refuse an expression with more than [`MAX_EXPRESSION_OPERATORS`] operators. +/// +/// # Errors +/// +/// Returns `ValidationException` carrying the `Invalid :` prefix and the +/// full operator count. +pub fn validate_operator_count(expr: &Expr, kind: ExpressionKind) -> Result<(), DynamoDbError> { + let count = count_operators(expr); + if count > MAX_EXPRESSION_OPERATORS { + return Err(DynamoDbError::ValidationException(format!( + "Invalid {kind}: The expression contains too many operators; operator count: {count}" + ))); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::expression::parser::parse_condition; + use crate::expression::tokenizer::tokenize; + + fn count(src: &str) -> usize { + count_operators(&parse_condition(&tokenize(src).unwrap()).unwrap()) + } + + fn chain(term: &str, n: usize, joiner: &str) -> String { + vec![term; n].join(joiner) + } + + // Expected counts are the service's answers of 2026-10-25 (probe cases in + // brackets). + + #[test] + fn comparisons_and_joiners_count_one_each() { + assert_eq!(count(&chain("#v = :v", 300, " OR ")), 599); // [a02] + assert_eq!(count(&chain("#v <> :v", 300, " OR ")), 599); // [a05] + assert_eq!(count(&chain("#v >= :v", 300, " AND ")), 599); // [a09, a03] + assert_eq!(count(&format!("attribute_not_exists(pk) OR {}", chain("#v = :v", 300, " OR "))), 601); // [a01] + } + + #[test] + fn not_functions_between_in_and_size_count_one_each() { + assert_eq!(count(&chain("NOT #v = :v", 200, " OR ")), 599); // [a10] + assert_eq!(count(&chain("NOT NOT #v = :v", 200, " OR ")), 799); // [a22] + assert_eq!(count(&chain("#v BETWEEN :v AND :v", 160, " OR ")), 319); // [a40] + assert_eq!(count(&chain("#v IN (:v, :v, :v)", 170, " OR ")), 339); // [a41] + assert_eq!(count(&chain("#v IN (:v)", 200, " OR ")), 399); // [a12] + assert_eq!(count(&chain("attribute_exists(#v)", 170, " OR ")), 339); // [a43] + assert_eq!(count(&chain("contains(#v, :v)", 200, " OR ")), 399); // [a45] + assert_eq!(count(&chain("size(#v) = :v", 230, " OR ")), 689); // [a47] + assert_eq!(count(&chain("size(#v) BETWEEN :v AND :v", 130, " OR ")), 389); // [a53] + } + + #[test] + fn parentheses_count_zero() { + assert_eq!(count(&chain("(#v = :v)", 300, " OR ")), 599); // [a19] + assert_eq!(count(&chain("((#v = :v) OR (#v = :v))", 140, " OR ")), 559); // [a51] + assert_eq!(count(&format!("attribute_exists(pk) AND ({})", chain("#v = :v", 300, " OR "))), 601); // [a04] + assert_eq!(count(&format!("attribute_exists(pk) AND NOT ({})", chain("#v = :v", 150, " OR "))), 302); // [a52] + } + + #[test] + fn cap_is_exclusive_at_300() { + let kind = ExpressionKind::Condition; + let at_cap = format!("NOT attribute_not_exists(pk) OR {}", chain("#v = :v", 149, " OR ")); // [a49] + assert_eq!(count(&at_cap), 300); + assert!(validate_operator_count(&parse_condition(&tokenize(&at_cap).unwrap()).unwrap(), kind).is_ok()); + + let over = chain("#v = :v", 151, " OR "); // [a30] + let err = validate_operator_count(&parse_condition(&tokenize(&over).unwrap()).unwrap(), kind).unwrap_err(); + assert!(matches!(err, DynamoDbError::ValidationException(m) + if m == "Invalid ConditionExpression: The expression contains too many operators; operator count: 301")); + + let under = chain("#v = :v", 150, " OR "); // [a30] + assert!(validate_operator_count(&parse_condition(&tokenize(&under).unwrap()).unwrap(), kind).is_ok()); + } + + #[test] + fn message_carries_the_kind() { + let expr = parse_condition(&tokenize(&chain("#v = :v", 300, " OR ")).unwrap()).unwrap(); + let err = validate_operator_count(&expr, ExpressionKind::Filter).unwrap_err(); + assert!(matches!(err, DynamoDbError::ValidationException(m) + if m == "Invalid FilterExpression: The expression contains too many operators; operator count: 599")); // [b01] + } +} diff --git a/crates/core/src/expression/parser.rs b/crates/core/src/expression/parser.rs index f44bdfab6..cc49d73d3 100755 --- a/crates/core/src/expression/parser.rs +++ b/crates/core/src/expression/parser.rs @@ -20,7 +20,9 @@ //! ``` use super::ast::{CompareOp, Expr}; +use super::kind::ExpressionKind; use super::parser_common; +use super::syntax_error::{is_operator_or_keyword, syntax_error}; use super::tokenizer::Token; use crate::error::DynamoDbError; @@ -41,13 +43,37 @@ pub fn parse_condition(tokens: &[Token]) -> Result { pub fn parse_condition_with_depth_limit( tokens: &[Token], max_depth: usize, +) -> Result { + parse_condition_from(tokens, "", max_depth) +} + +/// Parse a condition expression whose tokens came from `source`, so a syntax +/// error can quote the source window around the offending token as Amazon +/// `DynamoDB` does (`Syntax error; token: "=", near: "= = :v"`). An empty +/// `source` joins the token texts instead. +/// +/// # Errors +/// +/// Returns `ValidationException` for syntax errors or depth exceeded. +pub fn parse_condition_from( + tokens: &[Token], + source: &str, + max_depth: usize, ) -> Result { parser_common::check_redundant_parens(tokens) .map_err(|body| validation_err(&format!("Invalid ConditionExpression: {body}")))?; let mut pos = 0; let mut depth = 0; - let expr = parse_or(tokens, &mut pos, &mut depth, max_depth)?; + let expr = parse_or(tokens, source, &mut pos, &mut depth, max_depth)?; if pos < tokens.len() { + // A token after a complete condition. Measured 2026-10-25 for an + // operator (`#v = :v =`) and a path (`#v = :v #v = :v`); other tokens + // keep the previous text. + if is_operator_or_keyword(&tokens[pos]) + || matches!(tokens[pos], Token::Ident(_) | Token::NameRef(_)) + { + return Err(syntax_error(ExpressionKind::Condition, source, tokens, pos)); + } return Err(validation_err(&format!( "Invalid ConditionExpression: unexpected token at position {pos}" ))); @@ -57,14 +83,15 @@ pub fn parse_condition_with_depth_limit( fn parse_or( tokens: &[Token], + src: &str, pos: &mut usize, depth: &mut usize, max_depth: usize, ) -> Result { - let mut left = parse_and(tokens, pos, depth, max_depth)?; + let mut left = parse_and(tokens, src, pos, depth, max_depth)?; while *pos < tokens.len() && tokens[*pos] == Token::Or { *pos += 1; - let right = parse_and(tokens, pos, depth, max_depth)?; + let right = parse_and(tokens, src, pos, depth, max_depth)?; left = Expr::Or(Box::new(left), Box::new(right)); } Ok(left) @@ -72,14 +99,15 @@ fn parse_or( fn parse_and( tokens: &[Token], + src: &str, pos: &mut usize, depth: &mut usize, max_depth: usize, ) -> Result { - let mut left = parse_not(tokens, pos, depth, max_depth)?; + let mut left = parse_not(tokens, src, pos, depth, max_depth)?; while *pos < tokens.len() && tokens[*pos] == Token::And { *pos += 1; - let right = parse_not(tokens, pos, depth, max_depth)?; + let right = parse_not(tokens, src, pos, depth, max_depth)?; left = Expr::And(Box::new(left), Box::new(right)); } Ok(left) @@ -87,6 +115,7 @@ fn parse_and( fn parse_not( tokens: &[Token], + src: &str, pos: &mut usize, depth: &mut usize, max_depth: usize, @@ -99,23 +128,29 @@ fn parse_not( "Invalid ConditionExpression: expression nesting depth exceeded", )); } - let expr = parse_not(tokens, pos, depth, max_depth)?; + let expr = parse_not(tokens, src, pos, depth, max_depth)?; *depth -= 1; return Ok(Expr::Not(Box::new(expr))); } - parse_primary(tokens, pos, depth, max_depth) + parse_primary(tokens, src, pos, depth, max_depth) } fn parse_primary( tokens: &[Token], + src: &str, pos: &mut usize, depth: &mut usize, max_depth: usize, ) -> Result { if *pos >= tokens.len() { - return Err(validation_err( - "Invalid ConditionExpression: unexpected end of expression", - )); + if tokens.is_empty() { + return Err(validation_err( + "Invalid ConditionExpression: unexpected end of expression", + )); + } + // Input ends where a condition is required (`#v = :v AND`): measured + // 2026-10-25 as token "" with the last token as the window. + return Err(syntax_error(ExpressionKind::Condition, src, tokens, *pos)); } // Parenthesized expression @@ -127,7 +162,7 @@ fn parse_primary( "Invalid ConditionExpression: expression nesting depth exceeded", )); } - let expr = parse_or(tokens, pos, depth, max_depth)?; + let expr = parse_or(tokens, src, pos, depth, max_depth)?; *depth -= 1; parser_common::expect_token(tokens, pos, &Token::RParen, ")", "ConditionExpression")?; return Ok(expr); @@ -140,17 +175,17 @@ fn parse_primary( && *pos + 1 < tokens.len() && tokens[*pos + 1] == Token::LParen { - return parse_function_call(tokens, pos); + return parse_function_call(tokens, src, pos); } } // Operand — then check for comparator, BETWEEN, or IN - let left = parse_operand(tokens, pos)?; + let left = parse_operand(tokens, src, pos)?; if *pos < tokens.len() { if let Some(op) = try_comparator(&tokens[*pos]) { *pos += 1; - let right = parse_operand(tokens, pos)?; + let right = parse_operand(tokens, src, pos)?; return Ok(Expr::Compare { left: Box::new(left), op, @@ -161,9 +196,9 @@ fn parse_primary( // BETWEEN operand AND operand if tokens[*pos] == Token::Between { *pos += 1; - let low = parse_operand(tokens, pos)?; + let low = parse_operand(tokens, src, pos)?; parser_common::expect_token(tokens, pos, &Token::And, "AND", "ConditionExpression")?; - let high = parse_operand(tokens, pos)?; + let high = parse_operand(tokens, src, pos)?; return Ok(Expr::Between { operand: Box::new(left), low: Box::new(low), @@ -175,10 +210,10 @@ fn parse_primary( if tokens[*pos] == Token::In { *pos += 1; parser_common::expect_token(tokens, pos, &Token::LParen, "(", "ConditionExpression")?; - let mut list = vec![parse_operand(tokens, pos)?]; + let mut list = vec![parse_operand(tokens, src, pos)?]; while *pos < tokens.len() && tokens[*pos] == Token::Comma { *pos += 1; - list.push(parse_operand(tokens, pos)?); + list.push(parse_operand(tokens, src, pos)?); } parser_common::expect_token(tokens, pos, &Token::RParen, ")", "ConditionExpression")?; return Ok(Expr::In { @@ -194,11 +229,10 @@ fn parse_primary( )) } -fn parse_operand(tokens: &[Token], pos: &mut usize) -> Result { +fn parse_operand(tokens: &[Token], src: &str, pos: &mut usize) -> Result { if *pos >= tokens.len() { - return Err(validation_err( - "Invalid ConditionExpression: expected operand", - )); + // Input ends where an operand is required (`#v = :v AND NOT`). + return Err(syntax_error(ExpressionKind::Condition, src, tokens, *pos)); } match &tokens[*pos] { @@ -213,7 +247,7 @@ fn parse_operand(tokens: &[Token], pos: &mut usize) -> Result Result { + Err(syntax_error(ExpressionKind::Condition, src, tokens, *pos)) + } _ => Err(validation_err( "Invalid ConditionExpression: expected attribute path or value placeholder", )), } } -fn parse_function_call(tokens: &[Token], pos: &mut usize) -> Result { +fn parse_function_call( + tokens: &[Token], + src: &str, + pos: &mut usize, +) -> Result { let name = match &tokens[*pos] { Token::Ident(n) => n.to_ascii_lowercase(), _ => { @@ -243,10 +286,10 @@ fn parse_function_call(tokens: &[Token], pos: &mut usize) -> Result Result>, DynamoDbError> { + parse_projection_from(tokens, "") +} + +/// Parse a `ProjectionExpression` whose tokens came from `source`, so a syntax +/// error can quote the source window around the offending token as Amazon +/// `DynamoDB` does. An empty `source` joins the token texts instead. +/// +/// # Errors +/// +/// Returns `ValidationException` for syntax errors. +pub fn parse_projection_from( + tokens: &[Token], + source: &str, +) -> Result>, DynamoDbError> { if tokens.is_empty() { return Ok(Vec::new()); } let mut pos = 0; - let mut paths = vec![super::parser_common::parse_path(tokens, &mut pos)?]; + let mut paths = vec![parse_projection_path(tokens, source, &mut pos)?]; while pos < tokens.len() { if tokens[pos] != Token::Comma { return Err(DynamoDbError::ValidationException(format!( @@ -34,11 +50,29 @@ pub fn parse_projection(tokens: &[Token]) -> Result>, Dynam ))); } pos += 1; - paths.push(super::parser_common::parse_path(tokens, &mut pos)?); + paths.push(parse_projection_path(tokens, source, &mut pos)?); } Ok(paths) } +/// Parse one projected path. Input that ends where a path is required (`#v,`) +/// and a comma, operator or keyword there (`#v, , #v`) answer the service's +/// syntax error (measured 2026-10-25: token ",", near ", , #v"; token "", +/// near ","). Any other token keeps the previous text. +fn parse_projection_path( + tokens: &[Token], + source: &str, + pos: &mut usize, +) -> Result, DynamoDbError> { + match tokens.get(*pos) { + None | Some(Token::Comma) => Err(syntax_error(ExpressionKind::Projection, source, tokens, *pos)), + Some(token) if is_operator_or_keyword(token) => { + Err(syntax_error(ExpressionKind::Projection, source, tokens, *pos)) + } + Some(_) => super::parser_common::parse_path(tokens, pos), + } +} + /// A node in the projection trie. /// /// Each node selects part of the item. `terminal` means the whole value at @@ -681,4 +715,40 @@ mod tests { other => panic!("Expected L, got {other:?}"), } } + + // Syntax error wording measured 2026-10-25 (us-east-1) on GetItem. + + fn proj_msg(src: &str) -> String { + match parse_projection_from(&tokenize(src).unwrap(), src) { + Err(DynamoDbError::ValidationException(m)) => m, + other => panic!("expected ValidationException, got {other:?}"), + } + } + + #[test] + fn doubled_comma_quotes_the_source_window() { + // [d27] `#v, , #v` + assert_eq!( + proj_msg("#v, , #v"), + "Invalid ProjectionExpression: Syntax error; token: \",\", near: \", , #v\"" + ); + } + + #[test] + fn trailing_comma_is_eof_with_the_comma_as_window() { + // [d28] `#v,` + assert_eq!( + proj_msg("#v,"), + "Invalid ProjectionExpression: Syntax error; token: \"\", near: \",\"" + ); + } + + #[test] + fn other_projection_texts_are_unchanged() { + assert_eq!( + proj_msg("#v #w"), + "Invalid ProjectionExpression: unexpected token at position 1" + ); + assert_eq!(proj_msg("#v, )"), "Invalid expression: expected attribute name"); + } } diff --git a/crates/core/src/expression/syntax_error.rs b/crates/core/src/expression/syntax_error.rs new file mode 100644 index 000000000..0db63fd9b --- /dev/null +++ b/crates/core/src/expression/syntax_error.rs @@ -0,0 +1,232 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The `Syntax error; token: "", near: ""` wording Amazon `DynamoDB` +//! uses when a parser meets a token it cannot accept. +//! +//! Measured 2026-10-25 (us-east-1) on `ConditionExpression`, `FilterExpression`, +//! `KeyConditionExpression`, `UpdateExpression` and `ProjectionExpression`: +//! the token is the offending token's text, or `` when the input ends +//! where a token is required; the window is the source text from the start of +//! the token before the offending one to the end of the token after it, with +//! the source's own whitespace kept (`#v==:v` answers `near: "==:v"`) and a +//! missing neighbour dropped (`= #v = :v` answers `near: "= #v"`, `#v = :v =` +//! answers `near: ":v ="`). For `` the window is the last token's text +//! (`#v = :v AND` answers `token: "", near: "AND"`). + +use std::ops::Range; + +use super::kind::ExpressionKind; +use super::tokenizer::Token; +use crate::error::DynamoDbError; + +/// The text a token is shown as in a syntax error. +#[must_use] +pub fn token_text(token: &Token) -> String { + match token { + Token::Ident(s) => s.clone(), + Token::NameRef(s) => format!("#{s}"), + Token::Placeholder(s) => format!(":{s}"), + Token::Eq => "=".to_owned(), + Token::Ne => "<>".to_owned(), + Token::Lt => "<".to_owned(), + Token::Le => "<=".to_owned(), + Token::Gt => ">".to_owned(), + Token::Ge => ">=".to_owned(), + Token::Plus => "+".to_owned(), + Token::Minus => "-".to_owned(), + Token::Comma => ",".to_owned(), + Token::Dot => ".".to_owned(), + Token::LBracket => "[".to_owned(), + Token::RBracket => "]".to_owned(), + Token::LParen => "(".to_owned(), + Token::RParen => ")".to_owned(), + Token::And => "AND".to_owned(), + Token::Or => "OR".to_owned(), + Token::Not => "NOT".to_owned(), + Token::Between => "BETWEEN".to_owned(), + Token::In => "IN".to_owned(), + Token::Set => "SET".to_owned(), + Token::Remove => "REMOVE".to_owned(), + Token::Add => "ADD".to_owned(), + Token::Delete => "DELETE".to_owned(), + } +} + +/// Whether `token` is an operator (`=`, `<>`, `<`, `<=`, `>`, `>=`, `+`, `-`) or +/// a keyword (`AND`, `OR`, `NOT`, `BETWEEN`, `IN`, `SET`, `REMOVE`, `ADD`, +/// `DELETE`): the token classes measured to answer the service's syntax error +/// when they appear where an operand or a connector is required. Punctuation +/// and operands are not in the measured set and keep their previous texts. +#[must_use] +pub fn is_operator_or_keyword(token: &Token) -> bool { + !matches!( + token, + Token::Ident(_) + | Token::NameRef(_) + | Token::Placeholder(_) + | Token::Comma + | Token::Dot + | Token::LBracket + | Token::RBracket + | Token::LParen + | Token::RParen + ) +} + +/// The byte length a token occupies in the source it was read from. Keywords +/// are matched case-insensitively by the tokenizer, so their length is the +/// length of the keyword; every other token's text is reproduced verbatim. +fn token_len(token: &Token) -> usize { + match token { + Token::Ident(s) => s.len(), + Token::NameRef(s) | Token::Placeholder(s) => 1 + s.len(), + _ => token_text(token).len(), + } +} + +/// Byte ranges of `tokens` in `source`, recovered by walking the source with +/// the tokenizer's whitespace rule (space, tab, newline, carriage return). +/// Returns `None` when the tokens do not line up with the source (a caller +/// that passed a source the tokens did not come from), so the window falls +/// back to the token texts. +fn token_spans(source: &str, tokens: &[Token]) -> Option>> { + let bytes = source.as_bytes(); + let mut spans = Vec::with_capacity(tokens.len()); + let mut i = 0; + for token in tokens { + while i < bytes.len() && matches!(bytes[i], b' ' | b'\t' | b'\n' | b'\r') { + i += 1; + } + let end = i + token_len(token); + if end > bytes.len() { + return None; + } + spans.push(i..end); + i = end; + } + Some(spans) +} + +/// Build the service's syntax error for the token at `pos` (or `` when +/// `pos == tokens.len()`), prefixed with `Invalid :`. +/// +/// `source` is the expression text the tokens came from; an empty source +/// (a caller holding only tokens) joins the token texts with single spaces. +#[must_use] +pub fn syntax_error( + kind: ExpressionKind, + source: &str, + tokens: &[Token], + pos: usize, +) -> DynamoDbError { + let token = tokens.get(pos).map_or_else(|| "".to_owned(), token_text); + let near = near_window(source, tokens, pos); + DynamoDbError::ValidationException(format!( + "Invalid {kind}: Syntax error; token: \"{token}\", near: \"{near}\"" + )) +} + +/// The window of source text around the token at `pos`: from the previous +/// token to the next one, each dropped when absent. At end of input the window +/// is the last token alone. +fn near_window(source: &str, tokens: &[Token], pos: usize) -> String { + if tokens.is_empty() { + return String::new(); + } + let (first, last) = if pos >= tokens.len() { + (tokens.len() - 1, tokens.len() - 1) + } else { + (pos.saturating_sub(1), (pos + 1).min(tokens.len() - 1)) + }; + if let Some(spans) = (!source.is_empty()) + .then(|| token_spans(source, tokens)) + .flatten() + { + return source[spans[first].start..spans[last].end].to_owned(); + } + tokens[first..=last] + .iter() + .map(token_text) + .collect::>() + .join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::expression::tokenizer::tokenize; + + fn msg(kind: ExpressionKind, source: &str, pos: usize) -> String { + let tokens = tokenize(source).unwrap(); + match syntax_error(kind, source, &tokens, pos) { + DynamoDbError::ValidationException(m) => m, + other => panic!("{other:?}"), + } + } + + // Expected texts measured 2026-10-25 (us-east-1), probe cases in brackets. + + #[test] + fn repeated_operator_in_the_middle_shows_three_tokens() { + // [d01] `#v = = :v`: the second `=` is the offending token. + assert_eq!( + msg(ExpressionKind::Condition, "#v = = :v", 2), + "Invalid ConditionExpression: Syntax error; token: \"=\", near: \"= = :v\"" + ); + } + + #[test] + fn window_keeps_the_source_whitespace() { + // [d17] no spaces, [d18] a tab, [d12] longer tokens. + assert!(msg(ExpressionKind::Condition, "#v==:v", 2).ends_with("near: \"==:v\"")); + assert!(msg(ExpressionKind::Condition, "#v =\t= :v", 2).ends_with("near: \"=\t= :v\"")); + assert!( + msg(ExpressionKind::Condition, "#longname = = :longvalue", 2) + .ends_with("near: \"= = :longvalue\"") + ); + } + + #[test] + fn missing_neighbours_are_dropped() { + // [d03] at the start, [d04] at the end, [d29] alone, [d30] two tokens. + assert!(msg(ExpressionKind::Condition, "= #v = :v", 0).ends_with("near: \"= #v\"")); + assert!(msg(ExpressionKind::Condition, "#v = :v =", 3).ends_with("near: \":v =\"")); + assert!(msg(ExpressionKind::Condition, "=", 0).ends_with("near: \"=\"")); + assert!(msg(ExpressionKind::Condition, "= =", 0).ends_with("near: \"= =\"")); + } + + #[test] + fn end_of_input_is_eof_with_the_last_token() { + // [d05] trailing AND, [d26] trailing comma on an update. + assert_eq!( + msg(ExpressionKind::Condition, "#v = :v AND", 4), + "Invalid ConditionExpression: Syntax error; token: \"\", near: \"AND\"" + ); + assert_eq!( + msg(ExpressionKind::Update, "SET #v = :v,", 5), + "Invalid UpdateExpression: Syntax error; token: \"\", near: \",\"" + ); + } + + #[test] + fn keyword_tokens_show_upper_case_and_match_their_source_length() { + // [d07] doubled AND; a lower-case keyword still lines up with the source. + assert_eq!( + msg(ExpressionKind::Condition, "#v = :v AND AND #v = :v", 4), + "Invalid ConditionExpression: Syntax error; token: \"AND\", near: \"AND AND #v\"" + ); + assert!(msg(ExpressionKind::Condition, "#v = :v and and #v", 4).ends_with("near: \"and and #v\"")); + } + + #[test] + fn without_a_source_the_window_joins_token_texts() { + let tokens = tokenize("#v = = :v").unwrap(); + let DynamoDbError::ValidationException(m) = + syntax_error(ExpressionKind::Filter, "", &tokens, 2) + else { + panic!() + }; + assert_eq!(m, "Invalid FilterExpression: Syntax error; token: \"=\", near: \"= = :v\""); + } +} diff --git a/crates/core/src/expression/update_parser.rs b/crates/core/src/expression/update_parser.rs index a67c22e6c..da3a9ac66 100755 --- a/crates/core/src/expression/update_parser.rs +++ b/crates/core/src/expression/update_parser.rs @@ -17,59 +17,30 @@ //! ``` use super::ast::{ArithOp, Expr, UpdateAction}; +use super::kind::ExpressionKind; use super::parser_common; +use super::syntax_error::{is_operator_or_keyword, syntax_error}; use super::tokenizer::Token; use crate::error::DynamoDbError; +const KIND: ExpressionKind = ExpressionKind::Update; + /// Parse an update expression token stream into a list of actions. /// /// # Errors /// /// Returns `ValidationException` for syntax errors. pub fn parse_update(tokens: &[Token]) -> Result, DynamoDbError> { - parser_common::check_redundant_parens(tokens).map_err(|msg| { - DynamoDbError::ValidationException(format!("Invalid UpdateExpression: {msg}")) - })?; - - let mut pos = 0; - let mut actions = Vec::new(); - - while pos < tokens.len() { - match &tokens[pos] { - Token::Set => { - pos += 1; - parse_set_actions(tokens, &mut pos, &mut actions)?; - } - Token::Remove => { - pos += 1; - parse_remove_actions(tokens, &mut pos, &mut actions)?; - } - Token::Add => { - pos += 1; - parse_add_actions(tokens, &mut pos, &mut actions)?; - } - Token::Delete => { - pos += 1; - parse_delete_actions(tokens, &mut pos, &mut actions)?; - } - _ => { - return Err(validation_err( - "Invalid UpdateExpression: expected SET, REMOVE, ADD, or DELETE", - )); - } - } - } - - if actions.is_empty() { - return Err(validation_err( - "Invalid UpdateExpression: expression must contain at least one action", - )); - } - - Ok(actions) + parse_update_from(tokens, "") } -/// Parse an update expression with DynamoDB-compatible syntax error messages. +/// Parse an update expression whose tokens came from `source`, so a syntax +/// error can quote the source window around the offending token as Amazon +/// `DynamoDB` does. An empty `source` joins the token texts instead. +/// +/// # Errors +/// +/// Returns `ValidationException` for syntax errors. pub fn parse_update_from( tokens: &[Token], source: &str, @@ -85,27 +56,24 @@ pub fn parse_update_from( match &tokens[pos] { Token::Set => { pos += 1; - parse_set_actions(tokens, &mut pos, &mut actions)?; + parse_set_actions(tokens, source, &mut pos, &mut actions)?; } Token::Remove => { pos += 1; - parse_remove_actions(tokens, &mut pos, &mut actions)?; + parse_remove_actions(tokens, source, &mut pos, &mut actions)?; } Token::Add => { pos += 1; - parse_add_actions(tokens, &mut pos, &mut actions)?; + parse_add_actions(tokens, source, &mut pos, &mut actions)?; } Token::Delete => { pos += 1; - parse_delete_actions(tokens, &mut pos, &mut actions)?; - } - token => { - let token_text = token_display_text(token); - let near = build_near_context(source, &token_text); - return Err(validation_err(&format!( - "Invalid UpdateExpression: Syntax error; token: \"{token_text}\", near: \"{near}\"" - ))); + parse_delete_actions(tokens, source, &mut pos, &mut actions)?; } + // A token where a section keyword is required, such as the second + // `+` of `SET #v = :v + :v + :v`, which answers token "+", near + // ":v + :v" (measured 2026-10-25). + _ => return Err(syntax_error(KIND, source, tokens, pos)), } } @@ -118,58 +86,48 @@ pub fn parse_update_from( Ok(actions) } -fn token_display_text(token: &Token) -> String { - match token { - Token::Ident(s) => s.clone(), - Token::NameRef(s) => format!("#{s}"), - Token::Placeholder(s) => format!(":{s}"), - Token::Eq => "=".to_owned(), - Token::Ne => "<>".to_owned(), - Token::Lt => "<".to_owned(), - Token::Le => "<=".to_owned(), - Token::Gt => ">".to_owned(), - Token::Ge => ">=".to_owned(), - Token::Plus => "+".to_owned(), - Token::Minus => "-".to_owned(), - Token::Comma => ",".to_owned(), - Token::Dot => ".".to_owned(), - Token::LBracket => "[".to_owned(), - Token::RBracket => "]".to_owned(), - Token::LParen => "(".to_owned(), - Token::RParen => ")".to_owned(), - Token::And => "AND".to_owned(), - Token::Or => "OR".to_owned(), - Token::Not => "NOT".to_owned(), - Token::Between => "BETWEEN".to_owned(), - Token::In => "IN".to_owned(), - Token::Set => "SET".to_owned(), - Token::Remove => "REMOVE".to_owned(), - Token::Add => "ADD".to_owned(), - Token::Delete => "DELETE".to_owned(), - } -} - -fn build_near_context(source: &str, token_text: &str) -> String { - if source.is_empty() { - return token_text.to_owned(); - } - if let Some(start) = source.find(token_text) { - let end = std::cmp::min(start + token_text.len() + 7, source.len()); - source[start..end].trim_end().to_owned() - } else { - token_text.to_owned() +/// Parse the path that starts an action. Input that ends here (`REMOVE`, +/// `SET #v = :v,`) or an operator here (`SET = :v`) is a syntax error in the +/// service's wording (measured 2026-10-25). +fn parse_action_path( + tokens: &[Token], + src: &str, + pos: &mut usize, +) -> Result, DynamoDbError> { + match tokens.get(*pos) { + None => Err(syntax_error(KIND, src, tokens, *pos)), + Some(token) if is_operator_or_keyword(token) => { + Err(syntax_error(KIND, src, tokens, *pos)) + } + _ => parser_common::parse_path(tokens, pos), } } fn parse_set_actions( tokens: &[Token], + src: &str, pos: &mut usize, actions: &mut Vec, ) -> Result<(), DynamoDbError> { loop { - let path = parser_common::parse_path(tokens, pos)?; - parser_common::expect_token(tokens, pos, &Token::Eq, "=", "UpdateExpression")?; - let value = parse_value_expr(tokens, pos)?; + let path = parse_action_path(tokens, src, pos)?; + // `SET #v :v` answers token ":v", near "#v :v" (measured 2026-10-25); + // end of input and an operator or keyword here follow the same rule. + // Any other token keeps the previous text. + match tokens.get(*pos) { + Some(Token::Eq) => {} + None | Some(Token::Placeholder(_)) => { + return Err(syntax_error(KIND, src, tokens, *pos)); + } + Some(token) if is_operator_or_keyword(token) => { + return Err(syntax_error(KIND, src, tokens, *pos)); + } + Some(_) => { + parser_common::expect_token(tokens, pos, &Token::Eq, "=", "UpdateExpression")?; + } + } + *pos += 1; + let value = parse_value_expr(tokens, src, pos)?; actions.push(UpdateAction::Set { path, value }); if *pos < tokens.len() && tokens[*pos] == Token::Comma { @@ -183,11 +141,12 @@ fn parse_set_actions( fn parse_remove_actions( tokens: &[Token], + src: &str, pos: &mut usize, actions: &mut Vec, ) -> Result<(), DynamoDbError> { loop { - let path = parser_common::parse_path(tokens, pos)?; + let path = parse_action_path(tokens, src, pos)?; actions.push(UpdateAction::Remove { path }); if *pos < tokens.len() && tokens[*pos] == Token::Comma { @@ -200,8 +159,8 @@ fn parse_remove_actions( } /// Parse a SET value expression: `operand` or `operand +/- operand`. -fn parse_value_expr(tokens: &[Token], pos: &mut usize) -> Result { - let left = parse_set_operand(tokens, pos)?; +fn parse_value_expr(tokens: &[Token], src: &str, pos: &mut usize) -> Result { + let left = parse_set_operand(tokens, src, pos)?; if *pos < tokens.len() { let arith_op = match &tokens[*pos] { @@ -211,7 +170,7 @@ fn parse_value_expr(tokens: &[Token], pos: &mut usize) -> Result Result Result { +fn parse_set_operand(tokens: &[Token], src: &str, pos: &mut usize) -> Result { if *pos >= tokens.len() { - return Err(validation_err("Invalid UpdateExpression: expected operand")); + // `SET #v = :v +` answers token "", near "+" (measured 2026-10-25). + return Err(syntax_error(KIND, src, tokens, *pos)); } match &tokens[*pos] { @@ -241,7 +201,7 @@ fn parse_set_operand(tokens: &[Token], pos: &mut usize) -> Result Result parser_common::parse_path(tokens, pos).map(Expr::Path), Token::LParen => { *pos += 1; // consume '(' - let expr = parse_value_expr(tokens, pos)?; + let expr = parse_value_expr(tokens, src, pos)?; if *pos >= tokens.len() || tokens[*pos] != Token::RParen { return Err(validation_err( "Invalid UpdateExpression: expected closing ')'", @@ -258,13 +218,21 @@ fn parse_set_operand(tokens: &[Token], pos: &mut usize) -> Result Err(syntax_error(KIND, src, tokens, *pos)), _ => Err(validation_err( "Invalid UpdateExpression: expected path, placeholder, or function", )), } } -fn parse_set_function_call(tokens: &[Token], pos: &mut usize) -> Result { +fn parse_set_function_call( + tokens: &[Token], + src: &str, + pos: &mut usize, +) -> Result { let name = match &tokens[*pos] { Token::Ident(n) => n.to_ascii_lowercase(), _ => { @@ -278,10 +246,10 @@ fn parse_set_function_call(tokens: &[Token], pos: &mut usize) -> Result bool { /// Parse ADD actions: `ADD path value (, path value)*` fn parse_add_actions( tokens: &[Token], + src: &str, pos: &mut usize, actions: &mut Vec, ) -> Result<(), DynamoDbError> { loop { - let path = parser_common::parse_path(tokens, pos)?; + let path = parse_action_path(tokens, src, pos)?; let value = parse_add_delete_value(tokens, pos)?; actions.push(UpdateAction::Add { path, value }); if *pos < tokens.len() && tokens[*pos] == Token::Comma { @@ -315,11 +284,12 @@ fn parse_add_actions( /// Parse DELETE actions: `DELETE path value (, path value)*` fn parse_delete_actions( tokens: &[Token], + src: &str, pos: &mut usize, actions: &mut Vec, ) -> Result<(), DynamoDbError> { loop { - let path = parser_common::parse_path(tokens, pos)?; + let path = parse_action_path(tokens, src, pos)?; let value = parse_add_delete_value(tokens, pos)?; actions.push(UpdateAction::Delete { path, value }); if *pos < tokens.len() && tokens[*pos] == Token::Comma { @@ -517,10 +487,11 @@ mod tests { #[test] fn parse_invalid_action_keyword_rejected() { + // A token where a section keyword is required is the service's syntax + // error; without a source the window joins the token texts. let err = parse("price = :v").unwrap_err(); - assert!( - matches!(err, DynamoDbError::ValidationException(msg) if msg.contains("expected SET")) - ); + assert!(matches!(err, DynamoDbError::ValidationException(msg) + if msg == "Invalid UpdateExpression: Syntax error; token: \"price\", near: \"price =\"")); } #[test] @@ -568,4 +539,41 @@ mod tests { "Expected validation error for stray ')', got: {err:?}" ); } + + // Syntax error wording measured 2026-10-25 (us-east-1) on UpdateItem. + + fn upd_msg(src: &str) -> String { + match parse_update_from(&tokenize(src).unwrap(), src) { + Err(DynamoDbError::ValidationException(m)) => m, + other => panic!("expected ValidationException, got {other:?}"), + } + } + + fn syntax(token: &str, near: &str) -> String { + format!("Invalid UpdateExpression: Syntax error; token: \"{token}\", near: \"{near}\"") + } + + #[test] + fn measured_update_syntax_errors() { + assert_eq!(upd_msg("SET #v = = :v"), syntax("=", "= = :v")); // [d24] + assert_eq!(upd_msg("SET #v = :v + + :v"), syntax("+", "+ + :v")); // [d25] + assert_eq!(upd_msg("SET #v = :v,"), syntax("", ",")); // [d26] + assert_eq!(upd_msg("SET #v = :v + :v + :v"), syntax("+", ":v + :v")); // [b07] + assert_eq!(upd_msg("SET #v = :v +"), syntax("", "+")); // [u08] + assert_eq!(upd_msg("SET #v = :v REMOVE"), syntax("", "REMOVE")); // [u10] + assert_eq!(upd_msg("SET = :v"), syntax("=", "SET = :v")); // [u11] + assert_eq!(upd_msg("SET #v :v"), syntax(":v", "#v :v")); // [u12] + } + + #[test] + fn other_update_texts_are_unchanged() { + assert_eq!( + upd_msg("SET #v #w = :v"), + "Invalid UpdateExpression: expected '='" + ); + assert_eq!( + upd_msg("SET #v = (:v"), + "Invalid UpdateExpression: expected closing ')'" + ); + } } diff --git a/crates/core/src/serde_helpers.rs b/crates/core/src/serde_helpers.rs index 3a4ffb3cd..292bb9bfc 100644 --- a/crates/core/src/serde_helpers.rs +++ b/crates/core/src/serde_helpers.rs @@ -26,24 +26,16 @@ fn is_placeholder_ident(rest: &str) -> bool { /// Validate one placeholder key. Length is checked before syntax. /// -/// `include_size_in_too_long`: the Names too-long message appends -/// `; size of key: N`, the Values one does not (Amazon `DynamoDB` quirk). -fn validate_placeholder_key( - key: &str, - prefix: char, - field_name: &str, - include_size_in_too_long: bool, -) -> Result<(), String> { +/// The too-long message carries `; size of key: N` for both maps: measured +/// 2026-10-25 (us-east-1) on PutItem, Scan and Query for +/// `ExpressionAttributeValues` as well as `ExpressionAttributeNames`. +fn validate_placeholder_key(key: &str, prefix: char, field_name: &str) -> Result<(), String> { if key.len() > MAX_PLACEHOLDER_KEY_BYTES { - let mut msg = format!( + return Err(format!( "{field_name} contains invalid key: The expression attribute map \ - contains a key that is too long;" - ); - if include_size_in_too_long { - use std::fmt::Write as _; - let _ = write!(msg, " size of key: {}", key.len()); - } - return Err(msg); + contains a key that is too long; size of key: {}", + key.len() + )); } if !key.strip_prefix(prefix).is_some_and(is_placeholder_ident) { return Err(format!( @@ -61,7 +53,6 @@ fn deserialize_placeholder_map<'de, D, T>( deserializer: D, prefix: char, field_name: &str, - include_size_in_too_long: bool, check_value: impl Fn(&str, &Value) -> Result<(), String>, convert: impl Fn(Value) -> Result, ) -> Result>, D::Error> @@ -76,8 +67,7 @@ where } let mut out = HashMap::with_capacity(raw.len()); for (key, value) in raw { - validate_placeholder_key(&key, prefix, field_name, include_size_in_too_long) - .map_err(de::Error::custom)?; + validate_placeholder_key(&key, prefix, field_name).map_err(de::Error::custom)?; check_value(&key, &value).map_err(de::Error::custom)?; let converted = convert(value).map_err(de::Error::custom)?; out.insert(key, converted); @@ -101,7 +91,6 @@ where deserializer, '#', "ExpressionAttributeNames", - true, |key, value| { // Only a genuine empty *string* is rejected. A non-string falls // through to `convert` -> type error -> SerializationException, @@ -134,7 +123,6 @@ where deserializer, ':', "ExpressionAttributeValues", - false, |key, value| { // Empty AttributeValue (no datatype). Caught here so the error names // its key. Mirrors the empty-object check in `types::attribute_value`; @@ -265,13 +253,19 @@ mod tests { } #[test] - fn values_key_too_long_omits_size() { + fn values_key_too_long_reports_size() { + // Measured 2026-10-25 (us-east-1), PutItem, Scan and Query: the Values + // message carries the size suffix like the Names one. let key = format!(":{}", "a".repeat(255)); // 256 bytes including ':' let json = format!(r#"{{"values":{{"{key}":{{"S":"x"}}}}}}"#); let msg = values_err(&json); - assert!(msg.contains("contains a key that is too long;"), "{msg}"); - // Quirk: the values variant omits "; size of key: N". - assert!(!msg.contains("size of key"), "{msg}"); + assert!( + msg.contains( + "ExpressionAttributeValues contains invalid key: The expression \ + attribute map contains a key that is too long; size of key: 256" + ), + "{msg}" + ); } #[test] diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 913333015..8d03f18e3 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -8,8 +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, - tokenize_for, tokenize_with_limit, validate_no_reserved_words, validate_ordering_operand_types, + parse_condition_from, parse_key_condition_from, parse_projection_from, parse_update_from, + tokenize_for, tokenize_with_limit, validate_no_reserved_words, validate_operator_count, + validate_ordering_operand_types, }; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{AttributeValue, ConditionalOperator, ExpectedAttributeValue}; @@ -89,10 +90,26 @@ pub fn check_expression_size( pub fn parse_condition_expr(expr: &str, limits: &LimitsConfig) -> Result { check_expression_size(expr, ExpressionKind::Condition, limits)?; tokenize_expression(expr, limits) - .and_then(|tokens| parse_condition_with_depth_limit(&tokens, limits.max_expression_depth)) + .and_then(|tokens| parse_condition_from(&tokens, expr, limits.max_expression_depth)) .map_err(|e| prefix_expression_error(e, ExpressionKind::Condition)) } +/// Refuse a condition or filter whose operator count exceeds the service's cap +/// of 300 (`Invalid : The expression contains too many operators; +/// operator count: `). +/// +/// Measured 2026-10-25 (us-east-1): the check runs after the syntax, reserved +/// word, undefined placeholder and operand type checks and before the unused +/// placeholder check and the table lookup. `TransactWriteItems` counts a +/// different total for the same text and does not call this. +/// +/// # Errors +/// +/// Returns `DynamoDbError::ValidationException` when the count is over the cap. +pub fn check_operator_count(expr: &Expr, kind: ExpressionKind) -> Result<(), DynamoDbError> { + validate_operator_count(expr, kind) +} + /// Tokenize, reserved-word check, and parse an `UpdateExpression`. /// /// Errors carry the `UpdateExpression` prefix, matching Amazon DynamoDB. @@ -205,6 +222,9 @@ pub fn resolve_condition( if let Some(ref expr) = condition { validate_ordering_operand_types(expr, &maps) .map_err(|e| prefix_expression_error(e, ExpressionKind::Condition))?; + // After the operand type check (an ordering operator on a BOOL beats + // the count), before the unused placeholder check and the table lookup. + check_operator_count(expr, ExpressionKind::Condition)?; } Ok((condition, maps)) } @@ -230,7 +250,7 @@ pub fn parse_projection_expr( if limits.enforce_reserved_keywords { validate_no_reserved_words(&tokens)?; } - parse_projection(&tokens) + parse_projection_from(&tokens, proj_str) }); result.map_err(|e| prefix_expression_error(e, ExpressionKind::Projection)) } @@ -257,7 +277,17 @@ pub fn parse_key_condition_expr( if limits.enforce_reserved_keywords { validate_no_reserved_words(&tokens)?; } - parse_key_condition(&tokens) + // The service counts operators on the whole expression before it + // applies the key condition grammar: `pk = :v OR` + 150 terms answers + // the count, not the operator refusal, and 151 AND-joined equalities + // answer the count ahead of the one-condition-per-key check (measured + // 2026-10-25). The general condition parser supplies the count; when + // it does not accept the text, the key condition parser reports the + // error in its own words. + if let Ok(expr) = parse_condition_from(&tokens, expr, limits.max_expression_depth) { + check_operator_count(&expr, ExpressionKind::KeyCondition)?; + } + parse_key_condition_from(&tokens, expr) }) .map_err(|e| prefix_expression_error(e, ExpressionKind::KeyCondition)) } @@ -407,4 +437,71 @@ mod tests { "got {err:?}" ); } + + // Operator cap placement, measured 2026-10-25 (us-east-1). + + fn chain(n: usize) -> String { + vec!["#v = :v"; n].join(" OR ") + } + + #[test] + fn count_over_the_cap_is_refused_with_the_full_count() { + let limits = LimitsConfig::default(); + // 151 comparisons and 150 ORs: 301 [a30]. + let err = resolve_condition(Some(&chain(151)), None, None, None, None, &limits).unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid ConditionExpression: The expression contains too many operators; operator count: 301"), "got {err:?}"); + // 150 comparisons and 149 ORs: 299, accepted [a30]. + assert!(resolve_condition(Some(&chain(150)), None, None, None, None, &limits).is_ok()); + } + + #[test] + fn ordering_operand_type_beats_the_count() { + // [p17] 299 operators plus `#v < :b` with a BOOL value. + let limits = LimitsConfig::default(); + let expr = format!("{} OR #v < :b", chain(150)); + let mut values = HashMap::new(); + values.insert(":v".to_owned(), AttributeValue::S("x".to_owned())); + values.insert(":b".to_owned(), AttributeValue::Bool(true)); + let err = resolve_condition(Some(&expr), None, Some(&values), None, None, &limits).unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg.contains("Incorrect operand type for operator or function; operator or function: <, operand type: BOOL")), "got {err:?}"); + } + + #[test] + fn syntax_error_beats_the_count() { + // [e04] a 300-term chain followed by ` = =`. + let limits = LimitsConfig::default(); + let expr = format!("{} = =", chain(300)); + let err = resolve_condition(Some(&expr), None, None, None, None, &limits).unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid ConditionExpression: Syntax error; token: \"=\", near: \":v = =\""), "got {err:?}"); + } + + #[test] + fn key_condition_count_runs_before_the_key_grammar() { + let limits = LimitsConfig::default(); + // [a62] `pk = :v OR` + 150 terms: 301, the count, not the OR refusal. + let expr = format!("pk = :v OR {}", vec!["#v = :v"; 150].join(" AND ")); + let err = parse_key_condition_expr(&expr, &limits).unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid KeyConditionExpression: The expression contains too many operators; operator count: 301"), "got {err:?}"); + // [a63] two conditions joined by OR under the cap: the key grammar answers. + let err = parse_key_condition_expr("pk = :v OR sk = :s", &limits).unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid KeyConditionExpression: only AND is supported between key conditions"), "got {err:?}"); + // [d23] a syntax error is reported by the key grammar in the service's words. + let err = parse_key_condition_expr("pk = :v AND", &limits).unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"AND\""), "got {err:?}"); + } + + #[test] + fn projection_syntax_error_quotes_the_source() { + // [d27] + let limits = LimitsConfig::default(); + let err = parse_projection_expr("#v, , #v", &limits).unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid ProjectionExpression: Syntax error; token: \",\", near: \", , #v\""), "got {err:?}"); + } } diff --git a/crates/engine/src/put_item.rs b/crates/engine/src/put_item.rs index ffd6f70b4..f03bd67b5 100755 --- a/crates/engine/src/put_item.rs +++ b/crates/engine/src/put_item.rs @@ -74,25 +74,11 @@ pub async fn handle_put_item( )?; crate::validate_put_delete_return_values(&body)?; - let input: PutItemInput = serde_json::from_value(body).map_err(|e| { - let msg = e.to_string(); - if msg.contains("parameter values were invalid") - || msg.contains("may not be empty") - || msg.contains("contains duplicates") - || msg.contains("Null attribute value") - || msg.contains("validation error detected") - || msg.contains("must not be empty") - || msg.contains("Syntax error; key") - || msg.contains("AttributeValue is empty") - || msg.contains("AttributeValue has more than one datatypes set") - { - DynamoDbError::ValidationException(msg) - } else { - DynamoDbError::SerializationException(format!( - "Start of structure or map found where not expected: {e}" - )) - } - })?; + // The shared classifier also recognises the placeholder map errors + // (`contains invalid key`, `contains invalid value`): a too-long + // ExpressionAttributeNames or ExpressionAttributeValues key is a + // ValidationException, as on every other handler (measured 2026-10-25). + let input: PutItemInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; // Reject mixing legacy and expression parameters, then EAN/EAV supplied // without a referencing expression. diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 848f5fdbb..14be83efe 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -358,6 +358,9 @@ pub async fn handle_query( if let Some(ref filter_expr) = filter { let names = input.expression_attribute_names.as_ref(); validate_name_refs_in_expr(filter_expr, names, ExpressionKind::Filter)?; + // The operator cap follows the undefined name check and precedes the + // unused placeholder check (measured 2026-10-25). + crate::expression_helpers::check_operator_count(filter_expr, ExpressionKind::Filter)?; } // Parse ProjectionExpression or desugar legacy AttributesToGet diff --git a/crates/engine/src/scan.rs b/crates/engine/src/scan.rs index 1c1de2274..bf95f309d 100755 --- a/crates/engine/src/scan.rs +++ b/crates/engine/src/scan.rs @@ -139,6 +139,13 @@ pub async fn handle_scan( ) }; + // The operator cap runs before the unused placeholder check and the table + // lookup (measured 2026-10-25: the count beats an unused value, a missing + // table and an unknown IndexName). + if let Some(ref f) = filter { + crate::expression_helpers::check_operator_count(f, ExpressionKind::Filter)?; + } + // Parse ProjectionExpression or desugar legacy AttributesToGet let (effective_projection_str, extra_proj_names) = if input.projection_expression.is_some() { (input.projection_expression.clone(), HashMap::new()) From a8b8739239dc0a527da5f40b233543595c0b98ba Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:39:42 +0000 Subject: [PATCH 02/37] test(expression): wire tests for the operator cap, the map key length and the syntax error wording tests/test_expression_operator_limits.py covers every row the change encodes, from measurements on 2026-10-25 between 10:39 and 10:52 UTC. On the write paths the assertions compare the text after the service's "1 validation error detected: " prefix, which ExtendDB does not emit. test_value_key_too_long now expects the size suffix. --- ...est_expression_attribute_map_validation.py | 6 +- tests/test_expression_operator_limits.py | 597 ++++++++++++++++++ 2 files changed, 600 insertions(+), 3 deletions(-) create mode 100644 tests/test_expression_operator_limits.py diff --git a/tests/test_expression_attribute_map_validation.py b/tests/test_expression_attribute_map_validation.py index f073452a4..763dfc725 100644 --- a/tests/test_expression_attribute_map_validation.py +++ b/tests/test_expression_attribute_map_validation.py @@ -183,11 +183,11 @@ def test_value_key_too_long(self, dynamodb_client_no_validation, hash_table): ) err = exc_info.value.response["Error"] assert err["Code"] == "ValidationException" - # Quirk: unlike ExpressionAttributeNames, the values variant omits the - # "; size of key: N" suffix. + # Measured 2026-10-25 (us-east-1) on Scan, Query and PutItem: the values + # variant carries the "; size of key: N" suffix like the names one. assert err["Message"] == ( "ExpressionAttributeValues contains invalid key: The expression " - "attribute map contains a key that is too long;" + "attribute map contains a key that is too long; size of key: 256" ) def test_value_empty_attribute_value(self, dynamodb_client_no_validation, hash_table): diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py new file mode 100644 index 000000000..f4129f5a4 --- /dev/null +++ b/tests/test_expression_operator_limits.py @@ -0,0 +1,597 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Expression operator cap, placeholder key length and syntax error wording. + +Three request shapes Amazon DynamoDB refuses with texts ExtendDB did not match: + + - an expression with more than 300 operators: + ``Invalid : The expression contains too many operators; operator + count: ``, on ConditionExpression (PutItem, UpdateItem, DeleteItem), + FilterExpression (Scan, Query) and KeyConditionExpression (Query). Every + comparison operator, AND, OR, NOT, BETWEEN, IN and function call counts + one; parentheses, paths, placeholders and list elements count zero. + - an ExpressionAttributeNames or ExpressionAttributeValues key over 255 + bytes on PutItem: a ValidationException carrying ``size of key: ``, + not a SerializationException. + - a repeated or misplaced operator or keyword: ``Syntax error; token: "", + near: ""`` where the window is the source text from the token + before the offending one to the token after it, and ```` with the + last token as the window when the input ends early. + +Every expected text was measured against Amazon DynamoDB on 2026-10-25 +(us-east-1); the probe case id is noted on each assertion. The write paths +carry a ``1 validation error detected: `` prefix on the service that ExtendDB +does not emit; those assertions compare the text after the prefix. + +Dual-target against Amazon DynamoDB and extenddb. +""" + +from __future__ import annotations + +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table + +PREFIX = "1 validation error detected: " + +TOO_MANY = "The expression contains too many operators; operator count: " + + +def _error(func) -> tuple[str, str]: + with pytest.raises(ClientError) as exc_info: + func() + err = exc_info.value.response["Error"] + return err["Code"], err["Message"] + + +def _validation(func) -> str: + code, msg = _error(func) + assert code == "ValidationException", (code, msg) + return msg + + +def _after_prefix(msg: str) -> str: + return msg[len(PREFIX) :] if msg.startswith(PREFIX) else msg + + +def chain(term: str, n: int, joiner: str = " OR ") -> str: + return joiner.join([term] * n) + + +def syntax(kind: str, token: str, near: str) -> str: + return f'Invalid {kind}: Syntax error; token: "{token}", near: "{near}"' + + +@pytest.fixture(scope="module") +def table(dynamodb_client): + """Composite-key table with one item for the Query and Scan rows.""" + 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: + dynamodb_client.put_item( + TableName=name, + Item={"pk": {"S": "p1"}, "sk": {"S": "s1"}, "v": {"S": "x"}}, + ) + yield name + + +NAMES = {"#v": "v"} +VALUES = {":v": {"S": "x"}} + + +def put(client, table, condition, **kwargs): + args = { + "TableName": table, + "Item": {"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + "ConditionExpression": condition, + "ExpressionAttributeNames": NAMES, + "ExpressionAttributeValues": VALUES, + } + args.update(kwargs) + return lambda: client.put_item(**args) + + +def scan(client, table, filter_expr, **kwargs): + args = { + "TableName": table, + "FilterExpression": filter_expr, + "ExpressionAttributeNames": NAMES, + "ExpressionAttributeValues": VALUES, + } + args.update(kwargs) + return lambda: client.scan(**args) + + +def query(client, table, kce, **kwargs): + args = { + "TableName": table, + "KeyConditionExpression": kce, + "ExpressionAttributeNames": NAMES, + "ExpressionAttributeValues": VALUES, + } + args.update(kwargs) + return lambda: client.query(**args) + + +class TestOperatorCount: + """More than 300 operators is refused with the full count.""" + + @pytest.mark.parametrize( + "case, expr, count", + [ + ("a01", "attribute_not_exists(pk) OR " + chain("#v = :v", 300), 601), + ("a02", chain("#v = :v", 300), 599), + ("a03", chain("#v = :v", 300, " AND "), 599), + ("a05", chain("#v <> :v", 300), 599), + ("a09", chain("#v >= :v", 300), 599), + ("a10", chain("NOT #v = :v", 200), 599), + ("a22", chain("NOT NOT #v = :v", 200), 799), + ("a12", chain("#v IN (:v)", 200), 399), + ("a19", chain("(#v = :v)", 300), 599), + ("a40", chain("#v BETWEEN :v AND :v", 160), 319), + ("a41", chain("#v IN (:v, :v, :v)", 170), 339), + ("a43", chain("attribute_exists(#v)", 170), 339), + ("a45", chain("contains(#v, :v)", 200), 399), + ("a47", chain("size(#v) = :v", 230), 689), + ("a48", chain("#v = :v AND #v = :v", 170), 679), + ("a51", chain("((#v = :v) OR (#v = :v))", 140), 559), + ("a52", "attribute_exists(pk) AND NOT (" + chain("#v = :v", 150) + ")", 302), + ("a53", chain("size(#v) BETWEEN :v AND :v", 130), 389), + ("a30", chain("#v = :v", 151), 301), + ("a50", "NOT attribute_not_exists(pk) OR " + chain("#v = :v", 150), 302), + ], + ) + def test_put_item_condition_count(self, dynamodb_client, table, case, expr, count): + msg = _validation(put(dynamodb_client, table, expr)) + assert _after_prefix(msg) == f"Invalid ConditionExpression: {TOO_MANY}{count}", case + + @pytest.mark.parametrize( + "case, expr", + [ + ("a30", chain("#v = :v", 150)), # 299 + ("a49", "NOT attribute_not_exists(pk) OR " + chain("#v = :v", 149)), # 300 + ("a42", chain("#v IN (:v, :v, :v, :v, :v)", 130)), # 259 + ("a54", chain("#v IN (:v)", 150)), # 299 + ("a46", chain("attribute_type(#v, :v)", 150)), # 299 + ], + ) + def test_put_item_condition_at_or_under_the_cap_is_evaluated( + self, dynamodb_client, table, case, expr + ): + # The condition is false for the absent key, so nothing is written. + code, _ = _error(put(dynamodb_client, table, expr)) + assert code == "ConditionalCheckFailedException", case + + def test_update_item_condition_count(self, dynamodb_client, table): + # [u01] 599 refused; [u03] 300 accepted (condition evaluated). + msg = _validation( + lambda: dynamodb_client.update_item( + TableName=table, + Key={"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + UpdateExpression="SET #w = :v", + ConditionExpression=chain("#v = :v", 300), + ExpressionAttributeNames={"#v": "v", "#w": "w"}, + ExpressionAttributeValues=VALUES, + ) + ) + assert _after_prefix(msg) == f"Invalid ConditionExpression: {TOO_MANY}599" + code, _ = _error( + lambda: dynamodb_client.update_item( + TableName=table, + Key={"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + UpdateExpression="SET #w = :v", + ConditionExpression="NOT attribute_not_exists(pk) OR " + chain("#v = :v", 149), + ExpressionAttributeNames={"#v": "v", "#w": "w"}, + ExpressionAttributeValues=VALUES, + ) + ) + assert code == "ConditionalCheckFailedException" + + def test_delete_item_condition_count(self, dynamodb_client, table): + # [d01] + msg = _validation( + lambda: dynamodb_client.delete_item( + TableName=table, + Key={"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + ConditionExpression=chain("#v = :v", 300), + ExpressionAttributeNames=NAMES, + ExpressionAttributeValues=VALUES, + ) + ) + assert _after_prefix(msg) == f"Invalid ConditionExpression: {TOO_MANY}599" + + def test_scan_filter_count(self, dynamodb_client, table): + # [b01] 599 refused, no prefix; [b02] 299 accepted; [b03] 301 refused; + # [a57] BETWEEN counts one on Scan too. + msg = _validation(scan(dynamodb_client, table, chain("#v = :v", 300))) + assert msg == f"Invalid FilterExpression: {TOO_MANY}599" + assert "Count" in scan(dynamodb_client, table, chain("#v = :v", 150))() + msg = _validation(scan(dynamodb_client, table, chain("#v = :v", 151))) + assert msg == f"Invalid FilterExpression: {TOO_MANY}301" + msg = _validation(scan(dynamodb_client, table, chain("#v BETWEEN :v AND :v", 160))) + assert msg == f"Invalid FilterExpression: {TOO_MANY}319" + + def test_query_filter_count(self, dynamodb_client, table): + # [b06] + msg = _validation( + query( + dynamodb_client, + table, + "pk = :p", + FilterExpression=chain("#v = :v", 300), + ExpressionAttributeValues={":v": {"S": "x"}, ":p": {"S": "p1"}}, + ) + ) + assert msg == f"Invalid FilterExpression: {TOO_MANY}599" + + def test_key_condition_count(self, dynamodb_client, table): + # [b04] 601; [a58] BETWEEN; [a59] begins_with; [a61] 151 equalities. + rows = [ + ("b04", "pk = :v AND " + chain("#v = :v", 300, " AND "), 601), + ("a58", "pk = :v AND " + chain("#v BETWEEN :v AND :v", 150, " AND "), 301), + ("a59", "pk = :v AND " + chain("begins_with(#v, :v)", 170, " AND "), 341), + ("a61", chain("#v = :v", 151, " AND "), 301), + ] + for case, kce, count in rows: + msg = _validation(query(dynamodb_client, table, kce)) + assert msg == f"Invalid KeyConditionExpression: {TOO_MANY}{count}", case + + def test_key_condition_count_precedes_the_key_grammar(self, dynamodb_client, table): + # [a62] `pk = :v OR` + 150 terms answers the count, not the operator + # refusal. The service also runs the count ahead of its + # one-condition-per-key check (b05, a60); ExtendDB has no such check. + msg = _validation(query(dynamodb_client, table, "pk = :v OR " + chain("#v = :v", 150, " AND "))) + assert msg == f"Invalid KeyConditionExpression: {TOO_MANY}301" + + +class TestOperatorCountOrder: + """Where the count falls against the other request checks.""" + + def test_syntax_error_beats_the_count(self, dynamodb_client, table): + # [e04], [e05] + msg = _validation(put(dynamodb_client, table, chain("#v = :v", 300) + " = =")) + assert _after_prefix(msg) == syntax("ConditionExpression", "=", ":v = =") + msg = _validation(put(dynamodb_client, table, "= = " + chain("#v = :v", 300))) + assert _after_prefix(msg) == syntax("ConditionExpression", "=", "= =") + + def test_redundant_parentheses_and_reserved_word_beat_the_count(self, dynamodb_client, table): + # [p14], [p12] + msg = _validation(put(dynamodb_client, table, "((#v = :v)) OR " + chain("#v = :v", 299))) + assert _after_prefix(msg) == ( + "Invalid ConditionExpression: The expression has redundant parentheses;" + ) + msg = _validation(put(dynamodb_client, table, chain("#v = :v", 299) + " OR status = :v")) + assert _after_prefix(msg) == ( + "Invalid ConditionExpression: Attribute name is a reserved keyword; " + "reserved keyword: status" + ) + + def test_ordering_operand_type_beats_the_count(self, dynamodb_client, table): + # [p17] + msg = _validation( + put( + dynamodb_client, + table, + chain("#v = :v", 299) + " OR #v < :b", + ExpressionAttributeValues={":v": {"S": "x"}, ":b": {"BOOL": True}}, + ) + ) + assert _after_prefix(msg) == ( + "Invalid ConditionExpression: Incorrect operand type for operator or " + "function; operator or function: <, operand type: BOOL" + ) + + def test_count_beats_unused_value_missing_table_and_key_mismatch( + self, dynamodb_client, table + ): + # [e02], [p05], [p06] + expected = f"Invalid ConditionExpression: {TOO_MANY}599" + msg = _validation( + put( + dynamodb_client, + table, + chain("#v = :v", 300), + ExpressionAttributeValues={":v": {"S": "x"}, ":u": {"S": "y"}}, + ) + ) + assert _after_prefix(msg) == expected + msg = _validation( + put(dynamodb_client, "extenddb-missing-b501", chain("#v = :v", 300)) + ) + assert _after_prefix(msg) == expected + msg = _validation( + put(dynamodb_client, table, chain("#v = :v", 300), Item={"pk": {"N": "1"}, "sk": {"S": "a"}}) + ) + assert _after_prefix(msg) == expected + + def test_scan_count_beats_unused_missing_table_and_unknown_index( + self, dynamodb_client, table + ): + # [s02], [s07], [s08] + expected = f"Invalid FilterExpression: {TOO_MANY}599" + msg = _validation( + scan( + dynamodb_client, + table, + chain("#v = :v", 300), + ExpressionAttributeValues={":v": {"S": "x"}, ":u": {"S": "y"}}, + ) + ) + assert msg == expected + assert _validation(scan(dynamodb_client, "extenddb-missing-b501", chain("#v = :v", 300))) == expected + assert _validation(scan(dynamodb_client, table, chain("#v = :v", 300), IndexName="nope")) == expected + + def test_update_item_condition_count_beats_update_expression_faults( + self, dynamodb_client, table + ): + # [u04] update syntax error, [u07] update undefined name: the condition's + # count is reported first. + for update in ("SET #w = = :v", "SET #w = :v"): + msg = _validation( + lambda update=update: dynamodb_client.update_item( + TableName=table, + Key={"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + UpdateExpression=update, + ConditionExpression=chain("#v = :v", 300), + ExpressionAttributeNames=NAMES, + ExpressionAttributeValues=VALUES, + ) + ) + assert _after_prefix(msg) == f"Invalid ConditionExpression: {TOO_MANY}599", update + + +class TestPlaceholderKeyLength: + """A placeholder key over 255 bytes is a ValidationException with its size.""" + + @staticmethod + def _names_msg(field: str, size: int) -> str: + return ( + f"{field} contains invalid key: The expression attribute map contains " + f"a key that is too long; size of key: {size}" + ) + + def test_put_item_names_key(self, dynamodb_client_no_validation, table): + # [c01] 255 accepted (condition evaluated), 256 and 257 refused. + ok = "#" + "a" * 254 + code, _ = _error( + put(dynamodb_client_no_validation, table, f"{ok} = :v", ExpressionAttributeNames={ok: "v"}) + ) + assert code == "ConditionalCheckFailedException" + for size in (256, 257): + key = "#" + "a" * (size - 1) + msg = _validation( + put(dynamodb_client_no_validation, table, f"{key} = :v", ExpressionAttributeNames={key: "v"}) + ) + assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", size) + + def test_put_item_values_key(self, dynamodb_client_no_validation, table): + # [c02] 255 accepted, 256 and 257 refused with the size suffix. + ok = ":" + "a" * 254 + code, _ = _error( + put(dynamodb_client_no_validation, table, f"#v = {ok}", ExpressionAttributeValues={ok: {"S": "x"}}) + ) + assert code == "ConditionalCheckFailedException" + for size in (256, 257): + key = ":" + "a" * (size - 1) + msg = _validation( + put( + dynamodb_client_no_validation, + table, + f"#v = {key}", + ExpressionAttributeValues={key: {"S": "x"}}, + ) + ) + assert _after_prefix(msg) == self._names_msg("ExpressionAttributeValues", size) + + def test_put_item_key_length_is_bytes_and_checked_before_syntax( + self, dynamodb_client_no_validation, table + ): + # [c03] 127 two-byte characters: 255 bytes, passes the length check and + # fails key syntax; [c04] 128: 257 bytes; [c05] 258 bytes with an + # invalid character reports the length. + key = "#" + "\u00e9" * 127 + msg = _validation( + put(dynamodb_client_no_validation, table, "#v = :v", ExpressionAttributeNames={"#v": "v", key: "w"}) + ) + assert _after_prefix(msg) == ( + f'ExpressionAttributeNames contains invalid key: Syntax error; key: "{key}"' + ) + key = "#" + "\u00e9" * 128 + msg = _validation( + put(dynamodb_client_no_validation, table, "#v = :v", ExpressionAttributeNames={"#v": "v", key: "w"}) + ) + assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", 257) + key = "#" + "a" * 255 + "-x" + msg = _validation( + put(dynamodb_client_no_validation, table, "#v = :v", ExpressionAttributeNames={"#v": "v", key: "w"}) + ) + assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", 258) + + def test_put_item_too_long_key_beats_the_expression_checks( + self, dynamodb_client_no_validation, table + ): + # [c06] unreferenced, [c07] with a 300-term chain, [c08] with a syntax + # error, [c09] with an undefined name, [c10] with an unused value. + key = "#" + "w" * 255 + names = {"#v": "v", key: "w"} + expected = self._names_msg("ExpressionAttributeNames", 256) + for condition, extra in [ + ("#v = :v", {}), + (chain("#v = :v", 300), {}), + ("#v = = :v", {}), + ("#x = :v", {}), + ("#v = :v", {"ExpressionAttributeValues": {":v": {"S": "x"}, ":u": {"S": "y"}}}), + ]: + msg = _validation( + put(dynamodb_client_no_validation, table, condition, ExpressionAttributeNames=names, **extra) + ) + assert _after_prefix(msg) == expected, condition + + def test_scan_query_update_keys(self, dynamodb_client_no_validation, table): + # [c12] Scan names, [s10] Scan values, [s11] Query values, [s12] Query + # names: no prefix. [c13] UpdateItem names: prefix on the service. + nkey = "#" + "w" * 255 + vkey = ":" + "w" * 255 + assert _validation( + scan(dynamodb_client_no_validation, table, f"{nkey} = :v", ExpressionAttributeNames={nkey: "w"}) + ) == self._names_msg("ExpressionAttributeNames", 256) + assert _validation( + scan(dynamodb_client_no_validation, table, f"#v = {vkey}", ExpressionAttributeValues={vkey: {"S": "x"}}) + ) == self._names_msg("ExpressionAttributeValues", 256) + assert _validation( + query( + dynamodb_client_no_validation, + table, + "pk = :p", + FilterExpression=f"#v = {vkey}", + ExpressionAttributeValues={":p": {"S": "p1"}, vkey: {"S": "x"}}, + ) + ) == self._names_msg("ExpressionAttributeValues", 256) + assert _validation( + query( + dynamodb_client_no_validation, + table, + "pk = :v", + ExpressionAttributeNames={nkey: "w"}, + ) + ) == self._names_msg("ExpressionAttributeNames", 256) + msg = _validation( + lambda: dynamodb_client_no_validation.update_item( + TableName=table, + Key={"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + UpdateExpression=f"SET {nkey} = :v", + ExpressionAttributeNames={nkey: "w"}, + ExpressionAttributeValues=VALUES, + ) + ) + assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", 256) + + +class TestSyntaxErrorWording: + """Token and window for a repeated or misplaced operator or keyword.""" + + @pytest.mark.parametrize( + "case, expr, token, near", + [ + ("d01", "#v = = :v", "=", "= = :v"), + ("d02", "attribute_not_exists(pk) OR #v = = :v", "=", "= = :v"), + ("d13", "attribute_exists(pk) AND #v = :v AND #v = = :v", "=", "= = :v"), + ("d03", "= #v = :v", "=", "= #v"), + ("d04", "#v = :v =", "=", ":v ="), + ("d05", "#v = :v AND", "", "AND"), + ("d06", "#v = :v OR", "", "OR"), + ("d07", "#v = :v AND AND #v = :v", "AND", "AND AND #v"), + ("d08", "#v = :v OR OR #v = :v", "OR", "OR OR #v"), + ("d09", "AND #v = :v", "AND", "AND #v"), + ("d10", "#v < > :v", ">", "< > :v"), + ("d11", "#v = :v #v = :v", "#v", ":v #v ="), + ("d14", "#v <> <> :v", "<>", "<> <> :v"), + ("d15", "#v >= >= :v", ">=", ">= >= :v"), + ("d16", "#v = = = :v", "=", "= = ="), + ("d17", "#v==:v", "=", "==:v"), + ("d18", "#v =\t= :v", "=", "=\t= :v"), + ("d19", "#v = :v AND NOT", "", "NOT"), + ("d29", "=", "=", "="), + ("d30", "= =", "=", "= ="), + ], + ) + def test_put_item_condition(self, dynamodb_client, table, case, expr, token, near): + msg = _validation(put(dynamodb_client, table, expr)) + assert _after_prefix(msg) == syntax("ConditionExpression", token, near), case + + def test_put_item_long_tokens(self, dynamodb_client, table): + # [d12] + msg = _validation( + put( + dynamodb_client, + table, + "#longname = = :longvalue", + ExpressionAttributeNames={"#longname": "v"}, + ExpressionAttributeValues={":longvalue": {"S": "x"}}, + ) + ) + assert _after_prefix(msg) == syntax("ConditionExpression", "=", "= = :longvalue") + + def test_scan_filter(self, dynamodb_client, table): + # [d20], [d21]: no prefix on Scan. + assert _validation(scan(dynamodb_client, table, "#v = = :v")) == syntax( + "FilterExpression", "=", "= = :v" + ) + assert _validation(scan(dynamodb_client, table, "#v = :v AND")) == syntax( + "FilterExpression", "", "AND" + ) + + def test_query_key_condition(self, dynamodb_client, table): + # [d22], [d23] + assert _validation(query(dynamodb_client, table, "pk = = :v")) == syntax( + "KeyConditionExpression", "=", "= = :v" + ) + assert _validation(query(dynamodb_client, table, "pk = :v AND")) == syntax( + "KeyConditionExpression", "", "AND" + ) + + @pytest.mark.parametrize( + "case, expr, token, near", + [ + ("d24", "SET #v = = :v", "=", "= = :v"), + ("d25", "SET #v = :v + + :v", "+", "+ + :v"), + ("d26", "SET #v = :v,", "", ","), + ("b07", "SET #v = :v + :v + :v", "+", ":v + :v"), + ("u08", "SET #v = :v +", "", "+"), + ("u10", "SET #v = :v REMOVE", "", "REMOVE"), + ("u11", "SET = :v", "=", "SET = :v"), + ("u12", "SET #v :v", ":v", "#v :v"), + ], + ) + def test_update_expression(self, dynamodb_client, table, case, expr, token, near): + msg = _validation( + lambda: dynamodb_client.update_item( + TableName=table, + Key={"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + UpdateExpression=expr, + ExpressionAttributeNames=NAMES, + ExpressionAttributeValues=VALUES, + ) + ) + assert _after_prefix(msg) == syntax("UpdateExpression", token, near), case + + def test_projection_expression(self, dynamodb_client, table): + # [d27], [d28] + for expr, token, near in [("#v, , #v", ",", ", , #v"), ("#v,", "", ",")]: + msg = _validation( + lambda expr=expr: dynamodb_client.get_item( + TableName=table, + Key={"pk": {"S": "p1"}, "sk": {"S": "s1"}}, + ProjectionExpression=expr, + ExpressionAttributeNames=NAMES, + ) + ) + assert msg == syntax("ProjectionExpression", token, near), expr + + def test_syntax_error_beats_the_other_expression_checks(self, dynamodb_client, table): + # [e06] undefined name, [e07] undefined value, [e08] unused value, + # [e09] unused name, [e10] operand type. + rows = [ + ("#w = = :v", ":v", {}), + ("#v = = :u", ":u", {}), + ("#v = = :v", ":v", {"ExpressionAttributeValues": {":v": {"S": "x"}, ":u": {"S": "y"}}}), + ("#v = = :v", ":v", {"ExpressionAttributeNames": {"#v": "v", "#x": "x"}}), + ( + "begins_with(#v, :n) AND #v = = :v", + ":v", + {"ExpressionAttributeValues": {":v": {"S": "x"}, ":n": {"N": "1"}}}, + ), + ] + for condition, last, extra in rows: + msg = _validation(put(dynamodb_client, table, condition, **extra)) + assert _after_prefix(msg) == syntax("ConditionExpression", "=", f"= = {last}"), condition From 110401b0832d9357f90d7b8cdb775c8964c9f042 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:39:42 +0000 Subject: [PATCH 03/37] refactor(expression): move key condition resolution and the key condition and projection tests into their own files Pure move. key_condition.rs had grown to 2029 lines and projection.rs to 754; the resolve methods go to key_condition_resolve.rs and the two test modules to key_condition_tests.rs and projection_tests.rs, using the #[path] pattern evaluator_tests.rs already uses. --- crates/core/src/expression/key_condition.rs | 1412 +---------------- .../src/expression/key_condition_resolve.rs | 458 ++++++ .../src/expression/key_condition_tests.rs | 965 +++++++++++ crates/core/src/expression/mod.rs | 1 + crates/core/src/expression/projection.rs | 461 +----- .../core/src/expression/projection_tests.rs | 460 ++++++ 6 files changed, 1888 insertions(+), 1869 deletions(-) create mode 100644 crates/core/src/expression/key_condition_resolve.rs create mode 100644 crates/core/src/expression/key_condition_tests.rs create mode 100644 crates/core/src/expression/projection_tests.rs diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 787382c68..6b1cdeb8f 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -19,9 +19,6 @@ use super::parser_common; use super::syntax_error::{is_operator_or_keyword, syntax_error}; use super::tokenizer::Token; use crate::error::DynamoDbError; -use crate::types::{ - KeySchemaElement, KeyType, hash_key_elements, is_multipart_key_schema, range_key_elements, -}; /// Parsed key condition: partition key value expression(s) and optional sort key condition. /// @@ -44,450 +41,6 @@ pub struct KeyCondition { pub extra_sk_conditions: Vec<(Vec, Expr)>, } -impl KeyCondition { - /// Correct PK/SK assignment using the table's key schema. - /// - /// For single-attribute keys: when both the PK and SK conditions are equality - /// comparisons, the parser cannot distinguish which is which without knowing - /// the key schema. This method resolves `#name` references and swaps PK/SK - /// if the current PK path actually refers to the sort key attribute. - /// - /// For multi-part keys: all equality conditions are initially parsed as - /// PK + SK pairs. This method reclassifies them based on the key schema, - /// moving HASH attribute conditions to `extra_pk_conditions` and keeping - /// the RANGE condition as `sk_condition`. - /// - /// Call this after parsing and before passing to the storage layer. - /// - /// # Errors - /// - /// Returns `ValidationException` if a `#name` reference cannot be resolved. - pub fn resolve_pk_sk( - &mut self, - pk_attr: &str, - names: &std::collections::HashMap, - ) -> Result<(), DynamoDbError> { - // Only ambiguous when SK is an Eq comparison (both clauses were Eq). - let sk_is_eq = matches!( - self.sk_condition, - Some(SortKeyCondition::Compare { - op: CompareOp::Eq, - .. - }) - ); - if !sk_is_eq { - return Ok(()); - } - - // Resolve the current PK path's top-level attribute name. - let pk_name = match self.pk_path.first() { - Some(PathElement::Attribute(name)) => { - if let Some(ref_name) = name.strip_prefix('#') { - names.get(ref_name).map(String::as_str).ok_or_else(|| { - DynamoDbError::ValidationException(format!( - "Invalid KeyConditionExpression: An expression attribute name used in \ - the document path is not defined; attribute name: #{ref_name}" - )) - })? - } else { - name.as_str() - } - } - _ => return Ok(()), - }; - - // If the current PK path already matches the actual PK attribute, no swap needed. - if pk_name == pk_attr { - return Ok(()); - } - - // Swap: current PK is actually the SK, and the SK condition holds the real PK. - if let Some(SortKeyCondition::Compare { - path: sk_path, - op: CompareOp::Eq, - value: sk_value, - }) = self.sk_condition.take() - { - let old_pk_path = std::mem::replace(&mut self.pk_path, sk_path); - let old_pk_value = std::mem::replace(&mut self.pk_value, sk_value); - self.sk_condition = Some(SortKeyCondition::Compare { - path: old_pk_path, - op: CompareOp::Eq, - value: old_pk_value, - }); - } - - Ok(()) - } - - /// Classify and validate the conditions of a multi-attribute key schema. - /// - /// A multi-attribute key schema has more than one HASH attribute, more - /// than one RANGE attribute, or both. `hash_attrs` and `range_attrs` are - /// the index's HASH and RANGE attribute names in key-schema order. The - /// parser cannot tell HASH from RANGE equalities, and clause order in the - /// expression is free, so every clause is assigned here by name. - /// - /// The rules the service applies: - /// - /// - Each key attribute may carry one condition; a second one is refused - /// as `KeyConditionExpressions must only contain one condition per key`. - /// - Every HASH attribute needs an equality condition. Every one without - /// it is named, in key-schema order, in `HASH key attributes ... must - /// have equality conditions specified in the query`. - /// - Conditions on RANGE attributes must cover a leading run of them in - /// key-schema order. Every RANGE attribute before the last one that has - /// a condition needs an equality; only that last one may use `<`, `<=`, - /// `>`, `>=`, `BETWEEN` or `begins_with`. `h = :h AND b = :b` on a schema - /// whose RANGE attributes are `a, b` is refused, and so is - /// `h = :h AND a = :a AND b > :b AND c = :c`. - /// - /// On return the HASH conditions are in key-schema order (`pk_path` and - /// `extra_pk_conditions`, matching the composite partition key the write - /// path builds). When a RANGE attribute carries a non-equality condition, - /// that condition is `sk_condition` and the equalities before it are - /// `extra_sk_conditions`; otherwise `sk_condition` is the equality on the - /// first RANGE attribute and the rest follow in `extra_sk_conditions`. - /// Either way `extra_sk_conditions` is in key-schema order. A storage - /// backend maps each condition to its column by attribute name. - /// - /// Call this instead of [`KeyCondition::resolve_pk_sk`] when the key - /// schema is multi-attribute. A schema with one HASH and at most one - /// RANGE attribute is left unchanged. - /// - /// # Errors - /// - /// Returns `ValidationException` when a `#name` reference cannot be - /// resolved, a HASH attribute has no equality condition, the RANGE - /// conditions skip an attribute or put a non-equality before the last - /// one, or a non-equality names a HASH attribute, or a non-key attribute - /// while a RANGE attribute also has a condition. - pub fn resolve_multipart( - &mut self, - hash_attrs: &[&str], - range_attrs: &[&str], - names: &std::collections::HashMap, - ) -> Result<(), DynamoDbError> { - self.resolve_multipart_with(hash_attrs, range_attrs, names, |_, _| Ok(())) - } - - /// [`Self::resolve_multipart`] with a check on every clause's value, - /// called with the clause's path and value after the structural rules - /// (one condition per key, condition count, HASH coverage, RANGE gap) and - /// before the non-key rule. That is where the service reports a value of - /// the wrong type (measured 2026-10-21: a wrong-typed value loses to a - /// duplicate, a count overflow, a missing HASH attribute and a RANGE gap, - /// and wins over a condition on a non-key attribute). - /// - /// # Errors - /// - /// As [`Self::resolve_multipart`], plus whatever `value_check` returns. - pub fn resolve_multipart_with( - &mut self, - hash_attrs: &[&str], - range_attrs: &[&str], - names: &std::collections::HashMap, - mut value_check: F, - ) -> Result<(), DynamoDbError> - where - F: FnMut(&[PathElement], &Expr) -> Result<(), DynamoDbError>, - { - if hash_attrs.len() <= 1 && range_attrs.len() <= 1 { - return Ok(()); - } - - // Every equality clause, whichever field the parser put it in. - let mut all_eq: Vec<(Vec, Expr)> = Vec::new(); - all_eq.push((self.pk_path.clone(), self.pk_value.clone())); - all_eq.append(&mut self.extra_pk_conditions); - all_eq.append(&mut self.extra_sk_conditions); - - // The parser allows at most one non-equality clause. - let mut non_eq: Option = None; - if let Some(sk) = self.sk_condition.take() { - match sk { - SortKeyCondition::Compare { - path, - op: CompareOp::Eq, - value, - } => all_eq.push((path, value)), - other => non_eq = Some(other), - } - } - - let mut hash_eqs: Vec<(usize, Vec, Expr)> = Vec::new(); - let mut range_eqs: Vec<(usize, Vec, Expr)> = Vec::new(); - let mut other_eqs: Vec<(Vec, Expr)> = Vec::new(); - for (path, value) in all_eq { - let attr_name = resolve_path_attr(&path, names)?; - if let Some(pos) = hash_attrs.iter().position(|a| *a == attr_name) { - hash_eqs.push((pos, path, value)); - } else if let Some(pos) = range_attrs.iter().position(|a| *a == attr_name) { - range_eqs.push((pos, path, value)); - } else { - other_eqs.push((path, value)); - } - } - - // The non-equality clause's attribute: its RANGE position when it - // names a RANGE attribute, its HASH position when it names a HASH - // attribute, neither when it names a non-key attribute. - let non_eq_attr = match &non_eq { - Some(cond) => Some(resolve_path_attr(cond.path(), names)?), - None => None, - }; - let non_eq_pos = non_eq_attr - .as_deref() - .and_then(|a| range_attrs.iter().position(|r| *r == a)); - let non_eq_hash_pos = non_eq_attr - .as_deref() - .and_then(|a| hash_attrs.iter().position(|h| *h == a)); - - // One condition per key attribute. A second condition on one HASH or - // RANGE attribute, equality or not, is refused before any coverage - // check (measured on the service, 2026-10-21). - hash_eqs.sort_by_key(|(pos, _, _)| *pos); - range_eqs.sort_by_key(|(pos, _, _)| *pos); - let duplicated = hash_eqs.windows(2).any(|w| w[0].0 == w[1].0) - || range_eqs.windows(2).any(|w| w[0].0 == w[1].0) - || non_eq_pos.is_some_and(|p| range_eqs.iter().any(|(q, _, _)| *q == p)) - || non_eq_hash_pos.is_some_and(|p| hash_eqs.iter().any(|(q, _, _)| *q == p)); - if duplicated { - return Err(DynamoDbError::ValidationException( - "Invalid KeyConditionExpression: KeyConditionExpressions must only contain \ - one condition per key" - .to_string(), - )); - } - - // More conditions than key attributes (measured 2026-10-21: the count - // is reported ahead of which attribute is missing). - let condition_count = - hash_eqs.len() + range_eqs.len() + other_eqs.len() + usize::from(non_eq.is_some()); - let key_attribute_count = hash_attrs.len() + range_attrs.len(); - if condition_count > key_attribute_count { - return Err(DynamoDbError::ValidationException(format!( - "The number of query conditions ({condition_count}) exceeds the number of key \ - attributes defined in the schema ({key_attribute_count})" - ))); - } - - // Every HASH attribute needs an equality condition. On a - // multi-attribute key schema the service names every HASH attribute - // without one, in key-schema order (measured 2026-10-21); the - // single-attribute `Query condition missed key schema element` - // wording belongs to the single-attribute path in the engine. - let missing_hash: Vec<&str> = hash_attrs - .iter() - .enumerate() - .filter(|(pos, _)| !hash_eqs.iter().any(|(p, _, _)| p == pos)) - .map(|(_, attr)| *attr) - .collect(); - if !missing_hash.is_empty() { - return Err(DynamoDbError::ValidationException(format!( - "HASH key attributes {} must have equality conditions specified in the query", - missing_hash.join(", ") - ))); - } - - // RANGE conditions must cover a leading run of the RANGE attributes, - // with an equality on every one before the last. - let last_pos = range_eqs.iter().map(|(p, _, _)| *p).chain(non_eq_pos).max(); - if let Some(last_pos) = last_pos { - let without_eq: Vec<&str> = range_attrs[..last_pos] - .iter() - .enumerate() - .filter(|(pos, _)| !range_eqs.iter().any(|(p, _, _)| p == pos)) - .map(|(_, attr)| *attr) - .collect(); - if !without_eq.is_empty() { - return Err(DynamoDbError::ValidationException(format!( - "RANGE key attributes {} must have equality conditions specified in the \ - query because a condition is present on key attribute {}", - without_eq.join(", "), - range_attrs[last_pos] - ))); - } - } - - for (_, path, value) in hash_eqs.iter().chain(range_eqs.iter()) { - value_check(path, value)?; - } - for (path, value) in &other_eqs { - value_check(path, value)?; - } - match &non_eq { - Some(SortKeyCondition::Compare { path, value, .. }) => value_check(path, value)?, - Some(SortKeyCondition::Between { path, low, high }) => { - value_check(path, low)?; - value_check(path, high)?; - } - Some(SortKeyCondition::BeginsWith { path, prefix }) => value_check(path, prefix)?, - None => {} - } - - // A condition on an attribute outside the index key schema. The - // service refuses it by naming the first RANGE attribute that has no - // condition (measured 2026-10-21: `h = :h AND z = :z` on RANGE - // `a, b, c, d` is `Query condition missed key schema element: a`; - // with `a` given, `b`). The count check above has already refused - // the case where every key attribute has a condition as well. - let non_key_non_eq = non_eq.is_some() && non_eq_pos.is_none() && non_eq_hash_pos.is_none(); - if !other_eqs.is_empty() || non_key_non_eq { - let missing_range = range_attrs - .iter() - .enumerate() - .find(|(pos, _)| { - !range_eqs.iter().any(|(p, _, _)| p == pos) && non_eq_pos != Some(*pos) - }) - .map(|(_, attr)| *attr) - .unwrap_or(hash_attrs[0]); - return Err(DynamoDbError::ValidationException(format!( - "Query condition missed key schema element: {missing_range}" - ))); - } - - let mut hash_iter = hash_eqs.into_iter().map(|(_, path, value)| (path, value)); - if let Some((first_path, first_value)) = hash_iter.next() { - self.pk_path = first_path; - self.pk_value = first_value; - self.extra_pk_conditions = hash_iter.collect(); - } - - let mut range_eqs: Vec<(Vec, Expr)> = range_eqs - .into_iter() - .map(|(_, path, value)| (path, value)) - .collect(); - - if let Some(cond) = non_eq { - self.sk_condition = Some(cond); - } else if range_eqs.is_empty() { - self.sk_condition = None; - } else { - let (path, value) = range_eqs.remove(0); - self.sk_condition = Some(SortKeyCondition::Compare { - path, - op: CompareOp::Eq, - value, - }); - } - self.extra_sk_conditions = range_eqs; - - Ok(()) - } - - /// Assign every clause to its key attribute under `key_schema`, the key - /// schema of the table or index the query reads. - /// - /// A multi-attribute key schema goes through - /// [`Self::resolve_multipart_with`], which classifies every clause by name, - /// applies the service's rules for such a schema and calls `value_check` - /// where the service reports a value of the wrong type. On any other key - /// schema `value_check` runs on every clause first, which is where the - /// service reports it for such a schema (measured 2026-10-21), and then - /// [`Self::resolve_pk_sk`] picks the partition key clause. - /// - /// The engine reads a `Query` key condition through this, and so does - /// authorization when it finds the partition key value for - /// `dynamodb:LeadingKeys`, so both read the same clause as the partition - /// key. On a multi-attribute key schema `pk_path` then names the first - /// HASH attribute. - /// - /// # Errors - /// - /// As [`Self::resolve_multipart_with`] on a multi-attribute key schema and - /// as [`Self::resolve_pk_sk`] on any other, plus whatever `value_check` - /// returns. - pub fn resolve_key_schema_with( - &mut self, - key_schema: &[KeySchemaElement], - names: &std::collections::HashMap, - mut value_check: F, - ) -> Result<(), DynamoDbError> - where - F: FnMut(&[PathElement], &Expr) -> Result<(), DynamoDbError>, - { - if is_multipart_key_schema(key_schema) { - let hash_attrs: Vec<&str> = hash_key_elements(key_schema) - .iter() - .map(|ks| ks.attribute_name.as_str()) - .collect(); - let range_attrs: Vec<&str> = range_key_elements(key_schema) - .iter() - .map(|ks| ks.attribute_name.as_str()) - .collect(); - return self.resolve_multipart_with(&hash_attrs, &range_attrs, names, value_check); - } - self.for_each_clause(&mut value_check)?; - match key_schema.iter().find(|ks| ks.key_type == KeyType::Hash) { - Some(hash) => self.resolve_pk_sk(&hash.attribute_name, names), - None => Ok(()), - } - } - - /// [`Self::resolve_key_schema_with`] without a value check. - /// - /// # Errors - /// - /// As [`Self::resolve_key_schema_with`]. - pub fn resolve_key_schema( - &mut self, - key_schema: &[KeySchemaElement], - names: &std::collections::HashMap, - ) -> Result<(), DynamoDbError> { - self.resolve_key_schema_with(key_schema, names, |_, _| Ok(())) - } - - /// Call `f` with the path and value of every clause: the partition key - /// clause, the extra HASH and RANGE equalities, and each operand of the - /// sort key condition. - fn for_each_clause(&self, f: &mut F) -> Result<(), DynamoDbError> - where - F: FnMut(&[PathElement], &Expr) -> Result<(), DynamoDbError>, - { - f(&self.pk_path, &self.pk_value)?; - for (path, value) in &self.extra_pk_conditions { - f(path, value)?; - } - for (path, value) in &self.extra_sk_conditions { - f(path, value)?; - } - match &self.sk_condition { - Some(SortKeyCondition::Compare { path, value, .. }) => f(path, value), - Some(SortKeyCondition::Between { path, low, high }) => { - f(path, low)?; - f(path, high) - } - Some(SortKeyCondition::BeginsWith { path, prefix }) => f(path, prefix), - None => Ok(()), - } - } -} - -/// Resolve a path's top-level attribute name, handling `#name` references. -fn resolve_path_attr( - path: &[PathElement], - names: &std::collections::HashMap, -) -> Result { - match path.first() { - Some(PathElement::Attribute(name)) => { - if let Some(ref_name) = name.strip_prefix('#') { - names.get(ref_name).cloned().ok_or_else(|| { - DynamoDbError::ValidationException(format!( - "Invalid KeyConditionExpression: An expression attribute name used in \ - the document path is not defined; attribute name: #{ref_name}" - )) - }) - } else { - Ok(name.clone()) - } - } - _ => Err(DynamoDbError::ValidationException( - "Invalid key condition path".to_owned(), - )), - } -} - /// Sort key condition variants. #[derive(Debug, Clone)] pub enum SortKeyCondition { @@ -1064,966 +617,5 @@ fn validation_err(msg: &str) -> DynamoDbError { } #[cfg(test)] -mod tests { - use super::*; - use crate::expression::tokenize; - use std::collections::HashMap; - - #[test] - fn key_condition_redundant_parens_rejected_with_canonical_message() { - for expr in ["((pk = :v))", "((#pk = :pk)) AND (#sk = :sk)"] { - let tokens = tokenize(expr).unwrap(); - let err = parse_key_condition(&tokens).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid KeyConditionExpression: The expression has redundant parentheses;"), - "expr {expr}: got {err:?}" - ); - } - } - - #[test] - fn key_condition_valid_parens_accepted() { - for expr in [ - "(pk = :v)", - "(#pk = :pk) AND (#sk = :sk)", - "(#pk = :pk AND #sk = :sk)", - "(#pk = :pk AND (#sk = :sk))", - ] { - let tokens = tokenize(expr).unwrap(); - assert!( - parse_key_condition(&tokens).is_ok(), - "expr {expr} should parse" - ); - } - } - - #[test] - fn resolve_pk_sk_swaps_when_reversed() { - // "sk = :sk AND pk = :pk" — parser assigns first Eq as PK - let tokens = tokenize("sk = :sk AND pk = :pk").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); - - kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - match &kc.sk_condition { - Some(SortKeyCondition::Compare { - path, - op: CompareOp::Eq, - .. - }) => { - assert_eq!(path, &vec![PathElement::Attribute("sk".to_owned())]); - } - other => panic!("expected Eq SK condition, got {other:?}"), - } - } - - #[test] - fn resolve_pk_sk_no_swap_when_correct() { - let tokens = tokenize("pk = :pk AND sk = :sk").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - - kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - } - - #[test] - fn resolve_pk_sk_with_name_refs() { - let tokens = tokenize("#s = :sk AND #p = :pk").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - - let mut names = HashMap::new(); - names.insert("s".to_owned(), "sortkey".to_owned()); - names.insert("p".to_owned(), "partkey".to_owned()); - - kc.resolve_pk_sk("partkey", &names).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("#p".to_owned())]); - } - - #[test] - fn resolve_pk_sk_noop_for_non_eq_sk() { - // "pk = :pk AND sk > :val" — SK is not Eq, no ambiguity - let tokens = tokenize("pk = :pk AND sk > :val").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - } - - #[test] - fn resolve_pk_sk_noop_for_single_clause() { - let tokens = tokenize("pk = :pk").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - } - - #[test] - fn parse_three_clause_multipart() { - // pk1 = :v1 AND pk2 = :v2 AND sk = :v3 - let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk = :v3").unwrap(); - let kc = parse_key_condition(&tokens).unwrap(); - // First clause is pk_path, one extra_pk, one sk - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); - assert_eq!(kc.extra_pk_conditions.len(), 1); - assert!(kc.sk_condition.is_some()); - } - - #[test] - fn parse_four_clause_multipart() { - let tokens = tokenize("a = :a AND b = :b AND c = :c AND d = :d").unwrap(); - let kc = parse_key_condition(&tokens).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("a".to_owned())]); - assert_eq!(kc.extra_pk_conditions.len(), 2); - assert!(kc.sk_condition.is_some()); - } - - #[test] - fn parse_multipart_with_range_condition() { - // pk1 = :v1 AND pk2 = :v2 AND sk > :v3 - let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk > :v3").unwrap(); - let kc = parse_key_condition(&tokens).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); - // pk2 is in extra_pk_conditions (will be reclassified by resolve_multipart) - assert_eq!(kc.extra_pk_conditions.len(), 1); - match &kc.sk_condition { - Some(SortKeyCondition::Compare { - op: CompareOp::Gt, .. - }) => {} - other => panic!("expected Gt SK condition, got {other:?}"), - } - } - - #[test] - fn parse_reversed_sort_key_comparison() { - let tokens = tokenize("pk = :pk AND :lo <= sk").unwrap(); - let kc = parse_key_condition(&tokens).unwrap(); - - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - match &kc.sk_condition { - Some(SortKeyCondition::Compare { - path, - op: CompareOp::Ge, - value: Expr::Placeholder(name), - }) => { - assert_eq!(path, &vec![PathElement::Attribute("sk".to_owned())]); - assert_eq!(name, "lo"); - } - other => panic!("expected reversed Ge SK condition, got {other:?}"), - } - } - - #[test] - fn parse_reversed_partition_key_equality() { - let tokens = tokenize(":pk = pk").unwrap(); - let kc = parse_key_condition(&tokens).unwrap(); - - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - assert_eq!(kc.pk_value, Expr::Placeholder("pk".to_owned())); - } - - #[test] - fn reverse_comparator_maps_each_operator_and_is_involutive() { - use CompareOp::{Eq, Ge, Gt, Le, Lt, Ne}; - - let cases = [(Eq, Eq), (Ne, Ne), (Lt, Gt), (Le, Ge), (Gt, Lt), (Ge, Le)]; - - for (op, reversed) in cases { - assert_eq!(reverse_comparator(op), reversed); - assert_eq!(reverse_comparator(reverse_comparator(op)), op); - } - } - - #[test] - fn resolve_multipart_reclassifies() { - let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 = :v3").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let names = HashMap::new(); - kc.resolve_multipart(&["pk1", "pk2"], &["sk1"], &names) - .unwrap(); - - // After resolve_multipart, pk_path + extra_pk should have pk1 and pk2 - let pk_count = 1 + kc.extra_pk_conditions.len(); - assert_eq!(pk_count, 2); - // sk_condition should be the sk1 equality - assert!(kc.sk_condition.is_some()); - } - - #[test] - fn resolve_multipart_with_range() { - let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 > :v3").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let names = HashMap::new(); - kc.resolve_multipart(&["pk1", "pk2"], &["sk1"], &names) - .unwrap(); - - assert_eq!(1 + kc.extra_pk_conditions.len(), 2); - match &kc.sk_condition { - Some(SortKeyCondition::Compare { - op: CompareOp::Gt, .. - }) => {} - other => panic!("expected Gt SK condition, got {other:?}"), - } - } - - #[test] - fn resolve_multipart_reorders_to_schema_order() { - // Expression order: pk2, pk1, sk — reversed from key schema order [pk1, pk2] - let tokens = tokenize("pk2 = :v2 AND pk1 = :v1 AND sk = :v3").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let names = HashMap::new(); - kc.resolve_multipart(&["pk1", "pk2"], &["sk"], &names) - .unwrap(); - - // After resolve_multipart, pk_path should be pk1 (first in schema) - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); - // extra_pk_conditions should have pk2 - assert_eq!(kc.extra_pk_conditions.len(), 1); - assert_eq!( - kc.extra_pk_conditions[0].0, - vec![PathElement::Attribute("pk2".to_owned())] - ); - } - - #[test] - fn resolve_multipart_multi_range() { - // 2 HASH + 2 RANGE, all equality conditions - let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 = :v3 AND sk2 = :v4").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let names = HashMap::new(); - kc.resolve_multipart(&["pk1", "pk2"], &["sk1", "sk2"], &names) - .unwrap(); - - // 2 PK conditions - assert_eq!(1 + kc.extra_pk_conditions.len(), 2); - // Primary SK condition is sk1 - match &kc.sk_condition { - Some(SortKeyCondition::Compare { - path, - op: CompareOp::Eq, - .. - }) => { - assert_eq!(path, &vec![PathElement::Attribute("sk1".to_owned())]); - } - other => panic!("expected Eq SK condition on sk1, got {other:?}"), - } - // Extra SK condition is sk2 - assert_eq!(kc.extra_sk_conditions.len(), 1); - assert_eq!( - kc.extra_sk_conditions[0].0, - vec![PathElement::Attribute("sk2".to_owned())] - ); - } - - const NESTED_KEY_ERR: &str = "Invalid KeyConditionExpression: KeyConditionExpressions cannot have conditions on nested attributes"; - - #[test] - fn nested_dot_path_on_key_rejected() { - for expr in [ - "pk.foo = :v", - "pk = :p AND sk.foo = :v", - "begins_with(sk.foo, :v)", - "foo.bar = :v", - ] { - let tokens = tokenize(expr).unwrap(); - let err = parse_key_condition(&tokens).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if msg == NESTED_KEY_ERR), - "expr {expr}: got {err:?}" - ); - } - } - - #[test] - fn nested_path_in_all_clause_shapes_rejected() { - // Exercises every `raw_clause_path` arm (Compare/Between/BeginsWith) and a - // 3-clause multi-part shape with a nested middle clause. Multi-part keys - // are an ExtendDB extension real DynamoDB cannot express, hence a - // parser-level test. The reject loop runs before classification, so a - // nested clause in any position is rejected up front. - for expr in [ - "pk.foo > :v", // single non-eq (Compare arm) - "pk = :p AND sk.foo BETWEEN :a AND :b", // Between arm - "pk = :p AND begins_with(sk[0], :v)", // BeginsWith arm, index - "pk = :p AND :v < sk.foo", // reversed value-first - "pk1 = :v1 AND pk2.x = :v2 AND sk = :v3", // multi-part, nested middle - ] { - let tokens = tokenize(expr).unwrap(); - let err = parse_key_condition(&tokens).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if msg == NESTED_KEY_ERR), - "expr {expr}: got {err:?}" - ); - } - } - - #[test] - fn index_path_on_key_rejected() { - for expr in ["pk[0] = :v", "pk = :p AND sk[0] = :v"] { - let tokens = tokenize(expr).unwrap(); - let err = parse_key_condition(&tokens).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if msg == NESTED_KEY_ERR), - "expr {expr}: got {err:?}" - ); - } - } - - #[test] - fn nested_path_via_name_placeholder_rejected() { - // The check is structural (path length), so it fires before #name - // resolution. - let tokens = tokenize("#d.foo = :v").unwrap(); - let err = parse_key_condition(&tokens).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if msg == NESTED_KEY_ERR), - "got {err:?}" - ); - } - - #[test] - fn top_level_key_paths_accepted() { - for expr in ["pk = :v", "pk = :p AND sk = :s", "#pk = :p AND #sk = :s"] { - let tokens = tokenize(expr).unwrap(); - assert!( - parse_key_condition(&tokens).is_ok(), - "expr {expr} should parse" - ); - } - } - - /// One expected clause: attribute, operand placeholder, equality. - type ExpectedClause = (&'static str, &'static str, bool); - - /// The attribute and operand of each clause, and whether it is an - /// equality, which is what authorization reads to find the partition value - /// of a key condition the engine rejects for its operator. - #[test] - fn clause_operands_name_every_single_operand_clause() { - let cases: &[(&str, &[ExpectedClause])] = &[ - ("pk = :v", &[("pk", "v", true)]), - ( - "pk = :v AND sk = :s", - &[("pk", "v", true), ("sk", "s", true)], - ), - ("pk > :v", &[("pk", "v", false)]), - (":v > pk", &[("pk", "v", false)]), - ("begins_with(pk, :v)", &[("pk", "v", false)]), - ("(pk >= :v)", &[("pk", "v", false)]), - ("#p <= :v", &[("#p", "v", false)]), - ( - "pk = :v AND sk < :s", - &[("pk", "v", true), ("sk", "s", false)], - ), - ( - "pk > :v AND sk = :s", - &[("pk", "v", false), ("sk", "s", true)], - ), - ( - "pk < :v AND sk > :s", - &[("pk", "v", false), ("sk", "s", false)], - ), - ( - "pk = :u AND pk > :v", - &[("pk", "u", true), ("pk", "v", false)], - ), - // BETWEEN names two operands, so it contributes none. - ("pk BETWEEN :lo AND :hi", &[]), - ("pk = :v AND sk BETWEEN :lo AND :hi", &[("pk", "v", true)]), - ]; - for (expr, want) in cases { - let tokens = tokenize(expr).unwrap(); - let got = key_condition_clause_operands(&tokens).unwrap(); - let got: Vec<(String, String, bool)> = got - .into_iter() - .map(|clause| { - let name = match &clause.path[0] { - PathElement::Attribute(n) => n.clone(), - PathElement::Index(i) => format!("[{i}]"), - }; - let value = match clause.value { - Expr::Placeholder(n) => n, - other => format!("{other:?}"), - }; - (name, value, clause.equality) - }) - .collect(); - let want: Vec<(String, String, bool)> = want - .iter() - .map(|(a, v, e)| ((*a).to_owned(), (*v).to_owned(), *e)) - .collect(); - assert_eq!(got, want, "expr {expr}"); - } - } - - /// The same syntax errors and unsupported constructs `parse_key_condition` - /// rejects before classification. - #[test] - fn clause_operands_reject_what_the_parser_rejects() { - for expr in [ - "pk :: :v", - "pk > :v OR sk = :s", - "((pk = :v))", - "pk.sub > :v", - "pk <> :v", - "pk >", - ] { - let Ok(tokens) = tokenize(expr) else { - continue; - }; - assert!( - key_condition_clause_operands(&tokens).is_err(), - "expr {expr} should be rejected" - ); - } - } - - /// The index key schema the single-HASH cases use: HASH `h`, then RANGE - /// `a`, `b`, `c`, `d`. - const ONE_HASH: [&str; 1] = ["h"]; - const FOUR_RANGE: [&str; 4] = ["a", "b", "c", "d"]; - - /// Parse `expr` and classify it against `h` + `a, b, c, d`. - fn classify_one_hash(expr: &str) -> Result { - classify_with_names(expr, &HashMap::new()) - } - - fn classify_with_names( - expr: &str, - names: &HashMap, - ) -> Result { - let tokens = tokenize(expr).unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_multipart(&ONE_HASH, &FOUR_RANGE, names)?; - Ok(kc) - } - - /// The attribute names of `extra_sk_conditions`, in order. - fn extra_sk_names(kc: &KeyCondition) -> Vec { - kc.extra_sk_conditions - .iter() - .map(|(path, _)| match path.first() { - Some(PathElement::Attribute(name)) => name.clone(), - other => panic!("unexpected path {other:?}"), - }) - .collect() - } - - /// The sort-key condition's attribute and a label for its operator. - fn sk_shape(kc: &KeyCondition) -> Option<(String, &'static str)> { - let cond = kc.sk_condition.as_ref()?; - let name = match cond.path().first() { - Some(PathElement::Attribute(name)) => name.clone(), - other => panic!("unexpected path {other:?}"), - }; - let op = match cond { - SortKeyCondition::Compare { op, .. } => match op { - CompareOp::Eq => "=", - CompareOp::Ne => "<>", - CompareOp::Lt => "<", - CompareOp::Le => "<=", - CompareOp::Gt => ">", - CompareOp::Ge => ">=", - }, - SortKeyCondition::Between { .. } => "BETWEEN", - SortKeyCondition::BeginsWith { .. } => "begins_with", - }; - Some((name, op)) - } - - fn assert_range_gap(expr: &str, without_eq: &str, present: &str) { - let err = classify_one_hash(expr).unwrap_err(); - let want = format!( - "RANGE key attributes {without_eq} must have equality conditions specified in the \ - query because a condition is present on key attribute {present}" - ); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}, want {want}" - ); - } - - #[test] - fn one_hash_multi_range_hash_only_condition_is_accepted() { - let kc = classify_one_hash("h = :h").unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("h".to_owned())]); - assert!(kc.extra_pk_conditions.is_empty()); - assert!(kc.sk_condition.is_none()); - assert!(kc.extra_sk_conditions.is_empty()); - } - - #[test] - fn one_hash_multi_range_equality_prefixes_are_accepted() { - // Equalities on a leading run of the RANGE attributes, up to all four. - for (expr, extra) in [ - ("h = :h AND a = :a", vec![]), - ("h = :h AND a = :a AND b = :b", vec!["b"]), - ("h = :h AND a = :a AND b = :b AND c = :c", vec!["b", "c"]), - ( - "h = :h AND a = :a AND b = :b AND c = :c AND d = :d", - vec!["b", "c", "d"], - ), - ] { - let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); - assert_eq!( - kc.pk_path, - vec![PathElement::Attribute("h".to_owned())], - "{expr}" - ); - assert!(kc.extra_pk_conditions.is_empty(), "{expr}"); - assert_eq!(sk_shape(&kc), Some(("a".to_owned(), "=")), "{expr}"); - assert_eq!(extra_sk_names(&kc), extra, "{expr}"); - } - } - - #[test] - fn one_hash_multi_range_clause_order_is_free() { - // The defect: the first clause was taken as the partition key, so - // `b = :b AND h = :h AND a = :a` was refused as missing `h`. - for expr in [ - "b = :b AND h = :h AND a = :a", - "a = :a AND b = :b AND h = :h", - "b = :b AND a = :a AND h = :h", - ] { - let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); - assert_eq!( - kc.pk_path, - vec![PathElement::Attribute("h".to_owned())], - "{expr}" - ); - assert_eq!(sk_shape(&kc), Some(("a".to_owned(), "=")), "{expr}"); - assert_eq!(extra_sk_names(&kc), vec!["b"], "{expr}"); - } - } - - #[test] - fn one_hash_multi_range_operator_on_the_last_given_attribute_is_accepted() { - for (expr, sk, extra) in [ - ("h = :h AND a > :a", ("a", ">"), vec![]), - ("h = :h AND a = :a AND b < :b", ("b", "<"), vec!["a"]), - ( - "h = :h AND a = :a AND b = :b AND c > :c", - ("c", ">"), - vec!["a", "b"], - ), - ( - "h = :h AND a = :a AND begins_with(b, :b)", - ("b", "begins_with"), - vec!["a"], - ), - ( - "h = :h AND a = :a AND b = :b AND c = :c AND begins_with(d, :d)", - ("d", "begins_with"), - vec!["a", "b", "c"], - ), - ( - "h = :h AND a = :a AND b = :b AND c = :c AND d BETWEEN :x AND :y", - ("d", "BETWEEN"), - vec!["a", "b", "c"], - ), - ( - "c > :c AND b = :b AND h = :h AND a = :a", - ("c", ">"), - vec!["a", "b"], - ), - ] { - let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); - assert_eq!( - kc.pk_path, - vec![PathElement::Attribute("h".to_owned())], - "{expr}" - ); - assert_eq!(sk_shape(&kc), Some((sk.0.to_owned(), sk.1)), "{expr}"); - assert_eq!(extra_sk_names(&kc), extra, "{expr}"); - } - } - - #[test] - fn one_hash_multi_range_gap_is_refused() { - // A condition on a RANGE attribute needs an equality on every RANGE - // attribute before it. The defect accepted `h = :h AND b = :b` and - // returned no items. - assert_range_gap("h = :h AND b = :b", "a", "b"); - assert_range_gap("h = :h AND a = :a AND c = :c", "b", "c"); - assert_range_gap("h = :h AND a = :a AND b = :b AND d > :d", "c", "d"); - } - - #[test] - fn one_hash_multi_range_operator_before_a_later_condition_is_refused() { - assert_range_gap("h = :h AND a = :a AND b > :b AND c = :c", "b", "c"); - assert_range_gap("h = :h AND begins_with(a, :a) AND b = :b", "a", "b"); - } - - #[test] - fn one_hash_multi_range_missing_hash_is_refused() { - for expr in [ - "a = :a AND b = :b AND c = :c", - "a = :a AND b = :b", - "a = :a", - ] { - let err = classify_one_hash(expr).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "HASH key attributes h must have equality conditions specified in the query"), - "expr {expr}: got {err:?}" - ); - } - } - - /// Classify against HASH `h1`, `h2` and RANGE `r`. - fn classify_two_hash(expr: &str) -> Result { - let tokens = tokenize(expr).unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_multipart(&["h1", "h2"], &["r"], &HashMap::new())?; - Ok(kc) - } - - #[test] - fn two_hash_missing_hash_names_every_missing_attribute() { - for (expr, missing) in [ - ("h1 = :x", "h2"), - ("h2 = :x", "h1"), - ("h1 = :x AND r = :y", "h2"), - ("r = :y", "h1, h2"), - ("h1 = :x AND h2 > :y", "h2"), - ] { - let err = classify_two_hash(expr).unwrap_err(); - let want = format!( - "HASH key attributes {missing} must have equality conditions specified in the query" - ); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}" - ); - } - assert!(classify_two_hash("h1 = :x AND h2 = :y").is_ok()); - assert!(classify_two_hash("h1 = :x AND h2 = :y AND r > :z").is_ok()); - } - - #[test] - fn a_second_condition_on_one_key_attribute_is_refused() { - const WANT: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only \ - contain one condition per key"; - for expr in [ - "h = :x AND h = :y", - "h = :x AND h = :y AND a = :z", - "h = :x AND a = :y AND a = :z", - "h = :h AND a = :a AND a > :x", - "h = :h AND a > :x AND a = :a", - "h = :h AND a = :a AND b = :n AND b > :lo", - "h = :h AND h > :x", - "h = :h AND h = :y AND c = :c", - "a = :a AND a = :y", - ] { - let err = classify_one_hash(expr).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if msg == WANT), - "expr {expr}: got {err:?}" - ); - } - for expr in [ - "h1 = :x AND h1 = :y AND h2 = :z", - "h1 = :x AND h1 = :y", - "h1 = :x AND h2 = :n AND r = :r AND r > :y", - "h1 = :x AND r = :r AND r = :y", - ] { - let err = classify_two_hash(expr).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if msg == WANT), - "expr {expr}: got {err:?}" - ); - } - } - - #[test] - fn a_condition_on_a_non_key_attribute_names_the_first_uncovered_range_attribute() { - for (expr, missing) in [ - ("h = :h AND z = :z", "a"), - ("h = :h AND z = :z AND y = :y", "a"), - ("h = :h AND z > :z", "a"), - ("h = :h AND a = :a AND z = :z", "b"), - ("h = :h AND a = :a AND z > :z", "b"), - ("h = :h AND a > :a AND z = :z", "b"), - ("h = :h AND a = :a AND b = :b AND z > :z", "c"), - ("h = :h AND a = :a AND b = :b AND c = :c AND z = :z", "d"), - ] { - let err = classify_one_hash(expr).unwrap_err(); - let want = format!("Query condition missed key schema element: {missing}"); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}" - ); - } - let err = classify_two_hash("h1 = :x AND h2 = :y AND z = :z").unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Query condition missed key schema element: r")); - // A gap is reported before the non-key attribute. - let err = classify_one_hash("h = :h AND b = :b AND z = :z").unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg.starts_with("RANGE key attributes a must have equality conditions"))); - // A missing HASH attribute is reported before the non-key attribute. - let err = classify_two_hash("h1 = :x AND z = :z").unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "HASH key attributes h2 must have equality conditions specified in the query")); - } - - #[test] - fn more_conditions_than_key_attributes_are_refused_by_count() { - for (expr, n) in [ - ( - "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND z = :z", - 6, - ), - ( - "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND z > :z", - 6, - ), - ( - "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND PK = :p", - 6, - ), - ] { - let err = classify_one_hash(expr).unwrap_err(); - let want = format!( - "The number of query conditions ({n}) exceeds the number of key attributes \ - defined in the schema (5)" - ); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}" - ); - } - let err = classify_two_hash("h1 = :x AND h2 = :y AND r = :r AND z = :z").unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "The number of query conditions (4) exceeds the number of key attributes defined in the schema (3)")); - } - - #[test] - fn the_count_is_refused_before_a_missing_hash_attribute_or_a_range_gap() { - // Each count case above has every key attribute, so they also pass - // with the count check moved after the missing-HASH and RANGE-gap - // checks. These lack the HASH attribute or leave a RANGE gap. - let count = |n: usize, attrs: usize| { - format!( - "The number of query conditions ({n}) exceeds the number of key attributes \ - defined in the schema ({attrs})" - ) - }; - for expr in [ - "a = :a AND b = :b AND c = :c AND d = :d AND z1 = :z AND z2 = :y", - "h = :h AND b = :b AND c = :c AND d = :d AND z1 = :z AND z2 = :y", - ] { - let err = classify_one_hash(expr).unwrap_err(); - let want = count(6, 5); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}" - ); - } - let expr = "a = :a AND b = :b AND c = :c AND z1 = :z AND z2 = :y"; - let err = classify_two_hash(expr).unwrap_err(); - let want = count(5, 3); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}" - ); - // The same five clauses on HASH `h` and RANGE `a`, `b`, `c`, `d` do not - // exceed its five key attributes, so the missing HASH attribute is - // reported. - let err = classify_one_hash(expr).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "HASH key attributes h must have equality conditions specified in the query"), - "expr {expr}: got {err:?}" - ); - } - - #[test] - fn one_hash_multi_range_resolves_name_references() { - let names: HashMap = [("hh", "h"), ("aa", "a"), ("bb", "b")] - .into_iter() - .map(|(k, v)| (k.to_owned(), v.to_owned())) - .collect(); - let kc = classify_with_names("#bb > :b AND #hh = :h AND #aa = :a", &names).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("#hh".to_owned())]); - assert_eq!(sk_shape(&kc), Some(("#bb".to_owned(), ">"))); - assert_eq!(extra_sk_names(&kc), vec!["#aa"]); - - let err = classify_with_names("#hh = :h AND #bb = :b", &names).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg.starts_with("RANGE key attributes a must have")), - "got {err:?}" - ); - } - - #[test] - fn one_hash_one_range_schema_is_left_unchanged() { - let tokens = tokenize("sk = :s AND pk = :p").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_multipart(&["pk"], &["sk"], &HashMap::new()) - .unwrap(); - // Still the parser's assignment; resolve_pk_sk handles this schema. - assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); - } - - #[test] - fn multi_hash_partition_key_need_not_come_first() { - // With two HASH attributes the first clause used to be checked as the - // first HASH attribute before reclassification, so this order was - // refused as missing `pk1`. - let tokens = tokenize("sk = :s AND pk1 = :a AND pk2 = :b").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_multipart(&["pk1", "pk2"], &["sk"], &HashMap::new()) - .unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); - assert_eq!( - kc.extra_pk_conditions[0].0, - vec![PathElement::Attribute("pk2".to_owned())] - ); - assert_eq!(sk_shape(&kc), Some(("sk".to_owned(), "="))); - assert!(kc.extra_sk_conditions.is_empty()); - } - - #[test] - fn multi_hash_multi_range_operator_after_equality_keeps_both() { - // The non-equality on the second RANGE attribute is the sort-key - // condition, and the equality on the first is carried with it. - let tokens = tokenize("pk1 = :a AND pk2 = :b AND s1 = :x AND s2 > :y").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_multipart(&["pk1", "pk2"], &["s1", "s2"], &HashMap::new()) - .unwrap(); - assert_eq!(sk_shape(&kc), Some(("s2".to_owned(), ">"))); - assert_eq!(extra_sk_names(&kc), vec!["s1"]); - } - - fn key(name: &str, key_type: KeyType) -> KeySchemaElement { - KeySchemaElement { - attribute_name: name.to_owned(), - key_type, - } - } - - #[test] - fn resolve_key_schema_reads_a_multi_attribute_schema_by_name() { - // Authorization reads the partition key value from `pk_path` after this - // call, so it must name the first HASH attribute for every clause order - // the engine serves. - let two_hash = [ - key("g1", KeyType::Hash), - key("g2", KeyType::Hash), - key("gs", KeyType::Range), - ]; - let two_range = [ - key("h", KeyType::Hash), - key("a", KeyType::Range), - key("b", KeyType::Range), - ]; - for (schema, expr) in [ - (&two_hash[..], "g2 = :g AND g1 = :v AND gs = :x"), - (&two_hash[..], "gs = :x AND g1 = :v AND g2 = :g"), - (&two_hash[..], "g2 = :g AND g1 = :v AND gs > :lo"), - (&two_range[..], "a = :a AND h = :v AND b = :c"), - (&two_range[..], "b = :c AND h = :v AND a = :a"), - (&two_range[..], "b > :lo AND a = :a AND h = :v"), - (&two_range[..], "begins_with(b, :p) AND a = :a AND h = :v"), - ] { - let tokens = tokenize(expr).unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_key_schema(schema, &HashMap::new()) - .unwrap_or_else(|e| panic!("{expr}: {e:?}")); - let hash = &schema[0].attribute_name; - assert_eq!( - kc.pk_path, - vec![PathElement::Attribute(hash.clone())], - "{expr}" - ); - assert_eq!(kc.pk_value, Expr::Placeholder("v".to_owned()), "{expr}"); - } - } - - #[test] - fn resolve_key_schema_checks_values_before_resolve_pk_sk() { - let schema = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; - let tokens = tokenize("sk BETWEEN :lo AND :hi AND pk = :p").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let mut checked = Vec::new(); - kc.resolve_key_schema_with(&schema, &HashMap::new(), |_, value| { - checked.push(format!("{value:?}")); - Ok(()) - }) - .unwrap(); - assert_eq!(checked.len(), 3, "{checked:?}"); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - - let tokens = tokenize("sk = :s AND pk = :p").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let err = kc - .resolve_key_schema_with(&schema, &HashMap::new(), |_, _| { - Err(validation_err("checked")) - }) - .unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) if msg == "checked")); - // The failed check left the parser's assignment in place. - assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); - - kc.resolve_key_schema(&schema, &HashMap::new()).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - } - - // Syntax error wording measured 2026-10-25 (us-east-1) on Query. - - fn kce_msg(src: &str) -> String { - match parse_key_condition_from(&tokenize(src).unwrap(), src) { - Err(DynamoDbError::ValidationException(m)) => m, - other => panic!("expected ValidationException, got {other:?}"), - } - } - - #[test] - fn repeated_operator_quotes_the_source_window() { - // [d22] `pk = = :v` - assert_eq!( - kce_msg("pk = = :v"), - "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :v\"" - ); - assert_eq!(kce_msg("pk = :v AND sk = = :s"), "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :s\""); - } - - #[test] - fn trailing_keyword_is_eof_with_the_keyword_as_window() { - // [d23] `pk = :v AND` - assert_eq!( - kce_msg("pk = :v AND"), - "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"AND\"" - ); - assert_eq!(kce_msg("pk ="), "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"=\""); - } - - #[test] - fn stripped_outer_parentheses_keep_the_source_window() { - // The window is taken from the full token list, so the stripped - // parenthesis does not shift the quoted text. - assert_eq!( - kce_msg("(pk = = :v)"), - "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :v\"" - ); - } - - #[test] - fn other_key_condition_texts_are_unchanged() { - assert_eq!( - kce_msg("pk = :v OR sk = :s"), - "Invalid KeyConditionExpression: only AND is supported between key conditions" - ); - assert_eq!( - kce_msg("pk"), - "Invalid KeyConditionExpression: expected operator after operand" - ); - assert_eq!( - kce_msg("pk = :v AND sk = sk2"), - "Invalid KeyConditionExpression: key condition values must be expression attribute value placeholders" - ); - } -} +#[path = "key_condition_tests.rs"] +mod tests; diff --git a/crates/core/src/expression/key_condition_resolve.rs b/crates/core/src/expression/key_condition_resolve.rs new file mode 100644 index 000000000..8ce4b3813 --- /dev/null +++ b/crates/core/src/expression/key_condition_resolve.rs @@ -0,0 +1,458 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Key schema resolution for a parsed [`KeyCondition`]: correcting the +//! partition and sort key assignment once the table's key schema is known. + +use std::collections::HashMap; + +use super::ast::{CompareOp, Expr, PathElement}; +use super::key_condition::{KeyCondition, SortKeyCondition}; +use crate::error::DynamoDbError; +use crate::types::{ + KeySchemaElement, KeyType, hash_key_elements, is_multipart_key_schema, range_key_elements, +}; + +impl KeyCondition { + /// Correct PK/SK assignment using the table's key schema. + /// + /// For single-attribute keys: when both the PK and SK conditions are equality + /// comparisons, the parser cannot distinguish which is which without knowing + /// the key schema. This method resolves `#name` references and swaps PK/SK + /// if the current PK path actually refers to the sort key attribute. + /// + /// For multi-part keys: all equality conditions are initially parsed as + /// PK + SK pairs. This method reclassifies them based on the key schema, + /// moving HASH attribute conditions to `extra_pk_conditions` and keeping + /// the RANGE condition as `sk_condition`. + /// + /// Call this after parsing and before passing to the storage layer. + /// + /// # Errors + /// + /// Returns `ValidationException` if a `#name` reference cannot be resolved. + pub fn resolve_pk_sk( + &mut self, + pk_attr: &str, + names: &HashMap, + ) -> Result<(), DynamoDbError> { + // Only ambiguous when SK is an Eq comparison (both clauses were Eq). + let sk_is_eq = matches!( + self.sk_condition, + Some(SortKeyCondition::Compare { + op: CompareOp::Eq, + .. + }) + ); + if !sk_is_eq { + return Ok(()); + } + + // Resolve the current PK path's top-level attribute name. + let pk_name = match self.pk_path.first() { + Some(PathElement::Attribute(name)) => { + if let Some(ref_name) = name.strip_prefix('#') { + names.get(ref_name).map(String::as_str).ok_or_else(|| { + DynamoDbError::ValidationException(format!( + "Invalid KeyConditionExpression: An expression attribute name used in \ + the document path is not defined; attribute name: #{ref_name}" + )) + })? + } else { + name.as_str() + } + } + _ => return Ok(()), + }; + + // If the current PK path already matches the actual PK attribute, no swap needed. + if pk_name == pk_attr { + return Ok(()); + } + + // Swap: current PK is actually the SK, and the SK condition holds the real PK. + if let Some(SortKeyCondition::Compare { + path: sk_path, + op: CompareOp::Eq, + value: sk_value, + }) = self.sk_condition.take() + { + let old_pk_path = std::mem::replace(&mut self.pk_path, sk_path); + let old_pk_value = std::mem::replace(&mut self.pk_value, sk_value); + self.sk_condition = Some(SortKeyCondition::Compare { + path: old_pk_path, + op: CompareOp::Eq, + value: old_pk_value, + }); + } + + Ok(()) + } + + /// Classify and validate the conditions of a multi-attribute key schema. + /// + /// A multi-attribute key schema has more than one HASH attribute, more + /// than one RANGE attribute, or both. `hash_attrs` and `range_attrs` are + /// the index's HASH and RANGE attribute names in key-schema order. The + /// parser cannot tell HASH from RANGE equalities, and clause order in the + /// expression is free, so every clause is assigned here by name. + /// + /// The rules the service applies: + /// + /// - Each key attribute may carry one condition; a second one is refused + /// as `KeyConditionExpressions must only contain one condition per key`. + /// - Every HASH attribute needs an equality condition. Every one without + /// it is named, in key-schema order, in `HASH key attributes ... must + /// have equality conditions specified in the query`. + /// - Conditions on RANGE attributes must cover a leading run of them in + /// key-schema order. Every RANGE attribute before the last one that has + /// a condition needs an equality; only that last one may use `<`, `<=`, + /// `>`, `>=`, `BETWEEN` or `begins_with`. `h = :h AND b = :b` on a schema + /// whose RANGE attributes are `a, b` is refused, and so is + /// `h = :h AND a = :a AND b > :b AND c = :c`. + /// + /// On return the HASH conditions are in key-schema order (`pk_path` and + /// `extra_pk_conditions`, matching the composite partition key the write + /// path builds). When a RANGE attribute carries a non-equality condition, + /// that condition is `sk_condition` and the equalities before it are + /// `extra_sk_conditions`; otherwise `sk_condition` is the equality on the + /// first RANGE attribute and the rest follow in `extra_sk_conditions`. + /// Either way `extra_sk_conditions` is in key-schema order. A storage + /// backend maps each condition to its column by attribute name. + /// + /// Call this instead of [`KeyCondition::resolve_pk_sk`] when the key + /// schema is multi-attribute. A schema with one HASH and at most one + /// RANGE attribute is left unchanged. + /// + /// # Errors + /// + /// Returns `ValidationException` when a `#name` reference cannot be + /// resolved, a HASH attribute has no equality condition, the RANGE + /// conditions skip an attribute or put a non-equality before the last + /// one, or a non-equality names a HASH attribute, or a non-key attribute + /// while a RANGE attribute also has a condition. + pub fn resolve_multipart( + &mut self, + hash_attrs: &[&str], + range_attrs: &[&str], + names: &HashMap, + ) -> Result<(), DynamoDbError> { + self.resolve_multipart_with(hash_attrs, range_attrs, names, |_, _| Ok(())) + } + + /// [`Self::resolve_multipart`] with a check on every clause's value, + /// called with the clause's path and value after the structural rules + /// (one condition per key, condition count, HASH coverage, RANGE gap) and + /// before the non-key rule. That is where the service reports a value of + /// the wrong type (measured 2026-10-21: a wrong-typed value loses to a + /// duplicate, a count overflow, a missing HASH attribute and a RANGE gap, + /// and wins over a condition on a non-key attribute). + /// + /// # Errors + /// + /// As [`Self::resolve_multipart`], plus whatever `value_check` returns. + pub fn resolve_multipart_with( + &mut self, + hash_attrs: &[&str], + range_attrs: &[&str], + names: &HashMap, + mut value_check: F, + ) -> Result<(), DynamoDbError> + where + F: FnMut(&[PathElement], &Expr) -> Result<(), DynamoDbError>, + { + if hash_attrs.len() <= 1 && range_attrs.len() <= 1 { + return Ok(()); + } + + // Every equality clause, whichever field the parser put it in. + let mut all_eq: Vec<(Vec, Expr)> = Vec::new(); + all_eq.push((self.pk_path.clone(), self.pk_value.clone())); + all_eq.append(&mut self.extra_pk_conditions); + all_eq.append(&mut self.extra_sk_conditions); + + // The parser allows at most one non-equality clause. + let mut non_eq: Option = None; + if let Some(sk) = self.sk_condition.take() { + match sk { + SortKeyCondition::Compare { + path, + op: CompareOp::Eq, + value, + } => all_eq.push((path, value)), + other => non_eq = Some(other), + } + } + + let mut hash_eqs: Vec<(usize, Vec, Expr)> = Vec::new(); + let mut range_eqs: Vec<(usize, Vec, Expr)> = Vec::new(); + let mut other_eqs: Vec<(Vec, Expr)> = Vec::new(); + for (path, value) in all_eq { + let attr_name = resolve_path_attr(&path, names)?; + if let Some(pos) = hash_attrs.iter().position(|a| *a == attr_name) { + hash_eqs.push((pos, path, value)); + } else if let Some(pos) = range_attrs.iter().position(|a| *a == attr_name) { + range_eqs.push((pos, path, value)); + } else { + other_eqs.push((path, value)); + } + } + + // The non-equality clause's attribute: its RANGE position when it + // names a RANGE attribute, its HASH position when it names a HASH + // attribute, neither when it names a non-key attribute. + let non_eq_attr = match &non_eq { + Some(cond) => Some(resolve_path_attr(cond.path(), names)?), + None => None, + }; + let non_eq_pos = non_eq_attr + .as_deref() + .and_then(|a| range_attrs.iter().position(|r| *r == a)); + let non_eq_hash_pos = non_eq_attr + .as_deref() + .and_then(|a| hash_attrs.iter().position(|h| *h == a)); + + // One condition per key attribute. A second condition on one HASH or + // RANGE attribute, equality or not, is refused before any coverage + // check (measured on the service, 2026-10-21). + hash_eqs.sort_by_key(|(pos, _, _)| *pos); + range_eqs.sort_by_key(|(pos, _, _)| *pos); + let duplicated = hash_eqs.windows(2).any(|w| w[0].0 == w[1].0) + || range_eqs.windows(2).any(|w| w[0].0 == w[1].0) + || non_eq_pos.is_some_and(|p| range_eqs.iter().any(|(q, _, _)| *q == p)) + || non_eq_hash_pos.is_some_and(|p| hash_eqs.iter().any(|(q, _, _)| *q == p)); + if duplicated { + return Err(DynamoDbError::ValidationException( + "Invalid KeyConditionExpression: KeyConditionExpressions must only contain \ + one condition per key" + .to_string(), + )); + } + + // More conditions than key attributes (measured 2026-10-21: the count + // is reported ahead of which attribute is missing). + let condition_count = + hash_eqs.len() + range_eqs.len() + other_eqs.len() + usize::from(non_eq.is_some()); + let key_attribute_count = hash_attrs.len() + range_attrs.len(); + if condition_count > key_attribute_count { + return Err(DynamoDbError::ValidationException(format!( + "The number of query conditions ({condition_count}) exceeds the number of key \ + attributes defined in the schema ({key_attribute_count})" + ))); + } + + // Every HASH attribute needs an equality condition. On a + // multi-attribute key schema the service names every HASH attribute + // without one, in key-schema order (measured 2026-10-21); the + // single-attribute `Query condition missed key schema element` + // wording belongs to the single-attribute path in the engine. + let missing_hash: Vec<&str> = hash_attrs + .iter() + .enumerate() + .filter(|(pos, _)| !hash_eqs.iter().any(|(p, _, _)| p == pos)) + .map(|(_, attr)| *attr) + .collect(); + if !missing_hash.is_empty() { + return Err(DynamoDbError::ValidationException(format!( + "HASH key attributes {} must have equality conditions specified in the query", + missing_hash.join(", ") + ))); + } + + // RANGE conditions must cover a leading run of the RANGE attributes, + // with an equality on every one before the last. + let last_pos = range_eqs.iter().map(|(p, _, _)| *p).chain(non_eq_pos).max(); + if let Some(last_pos) = last_pos { + let without_eq: Vec<&str> = range_attrs[..last_pos] + .iter() + .enumerate() + .filter(|(pos, _)| !range_eqs.iter().any(|(p, _, _)| p == pos)) + .map(|(_, attr)| *attr) + .collect(); + if !without_eq.is_empty() { + return Err(DynamoDbError::ValidationException(format!( + "RANGE key attributes {} must have equality conditions specified in the \ + query because a condition is present on key attribute {}", + without_eq.join(", "), + range_attrs[last_pos] + ))); + } + } + + for (_, path, value) in hash_eqs.iter().chain(range_eqs.iter()) { + value_check(path, value)?; + } + for (path, value) in &other_eqs { + value_check(path, value)?; + } + match &non_eq { + Some(SortKeyCondition::Compare { path, value, .. }) => value_check(path, value)?, + Some(SortKeyCondition::Between { path, low, high }) => { + value_check(path, low)?; + value_check(path, high)?; + } + Some(SortKeyCondition::BeginsWith { path, prefix }) => value_check(path, prefix)?, + None => {} + } + + // A condition on an attribute outside the index key schema. The + // service refuses it by naming the first RANGE attribute that has no + // condition (measured 2026-10-21: `h = :h AND z = :z` on RANGE + // `a, b, c, d` is `Query condition missed key schema element: a`; + // with `a` given, `b`). The count check above has already refused + // the case where every key attribute has a condition as well. + let non_key_non_eq = non_eq.is_some() && non_eq_pos.is_none() && non_eq_hash_pos.is_none(); + if !other_eqs.is_empty() || non_key_non_eq { + let missing_range = range_attrs + .iter() + .enumerate() + .find(|(pos, _)| { + !range_eqs.iter().any(|(p, _, _)| p == pos) && non_eq_pos != Some(*pos) + }) + .map(|(_, attr)| *attr) + .unwrap_or(hash_attrs[0]); + return Err(DynamoDbError::ValidationException(format!( + "Query condition missed key schema element: {missing_range}" + ))); + } + + let mut hash_iter = hash_eqs.into_iter().map(|(_, path, value)| (path, value)); + if let Some((first_path, first_value)) = hash_iter.next() { + self.pk_path = first_path; + self.pk_value = first_value; + self.extra_pk_conditions = hash_iter.collect(); + } + + let mut range_eqs: Vec<(Vec, Expr)> = range_eqs + .into_iter() + .map(|(_, path, value)| (path, value)) + .collect(); + + if let Some(cond) = non_eq { + self.sk_condition = Some(cond); + } else if range_eqs.is_empty() { + self.sk_condition = None; + } else { + let (path, value) = range_eqs.remove(0); + self.sk_condition = Some(SortKeyCondition::Compare { + path, + op: CompareOp::Eq, + value, + }); + } + self.extra_sk_conditions = range_eqs; + + Ok(()) + } + + /// Assign every clause to its key attribute under `key_schema`, the key + /// schema of the table or index the query reads. + /// + /// A multi-attribute key schema goes through + /// [`Self::resolve_multipart_with`], which classifies every clause by name, + /// applies the service's rules for such a schema and calls `value_check` + /// where the service reports a value of the wrong type. On any other key + /// schema `value_check` runs on every clause first, which is where the + /// service reports it for such a schema (measured 2026-10-21), and then + /// [`Self::resolve_pk_sk`] picks the partition key clause. + /// + /// The engine reads a `Query` key condition through this, and so does + /// authorization when it finds the partition key value for + /// `dynamodb:LeadingKeys`, so both read the same clause as the partition + /// key. On a multi-attribute key schema `pk_path` then names the first + /// HASH attribute. + /// + /// # Errors + /// + /// As [`Self::resolve_multipart_with`] on a multi-attribute key schema and + /// as [`Self::resolve_pk_sk`] on any other, plus whatever `value_check` + /// returns. + pub fn resolve_key_schema_with( + &mut self, + key_schema: &[KeySchemaElement], + names: &HashMap, + mut value_check: F, + ) -> Result<(), DynamoDbError> + where + F: FnMut(&[PathElement], &Expr) -> Result<(), DynamoDbError>, + { + if is_multipart_key_schema(key_schema) { + let hash_attrs: Vec<&str> = hash_key_elements(key_schema) + .iter() + .map(|ks| ks.attribute_name.as_str()) + .collect(); + let range_attrs: Vec<&str> = range_key_elements(key_schema) + .iter() + .map(|ks| ks.attribute_name.as_str()) + .collect(); + return self.resolve_multipart_with(&hash_attrs, &range_attrs, names, value_check); + } + self.for_each_clause(&mut value_check)?; + match key_schema.iter().find(|ks| ks.key_type == KeyType::Hash) { + Some(hash) => self.resolve_pk_sk(&hash.attribute_name, names), + None => Ok(()), + } + } + + /// [`Self::resolve_key_schema_with`] without a value check. + /// + /// # Errors + /// + /// As [`Self::resolve_key_schema_with`]. + pub fn resolve_key_schema( + &mut self, + key_schema: &[KeySchemaElement], + names: &HashMap, + ) -> Result<(), DynamoDbError> { + self.resolve_key_schema_with(key_schema, names, |_, _| Ok(())) + } + + /// Call `f` with the path and value of every clause: the partition key + /// clause, the extra HASH and RANGE equalities, and each operand of the + /// sort key condition. + fn for_each_clause(&self, f: &mut F) -> Result<(), DynamoDbError> + where + F: FnMut(&[PathElement], &Expr) -> Result<(), DynamoDbError>, + { + f(&self.pk_path, &self.pk_value)?; + for (path, value) in &self.extra_pk_conditions { + f(path, value)?; + } + for (path, value) in &self.extra_sk_conditions { + f(path, value)?; + } + match &self.sk_condition { + Some(SortKeyCondition::Compare { path, value, .. }) => f(path, value), + Some(SortKeyCondition::Between { path, low, high }) => { + f(path, low)?; + f(path, high) + } + Some(SortKeyCondition::BeginsWith { path, prefix }) => f(path, prefix), + None => Ok(()), + } + } +} + +/// Resolve a path's top-level attribute name, handling `#name` references. +fn resolve_path_attr( + path: &[PathElement], + names: &HashMap, +) -> Result { + match path.first() { + Some(PathElement::Attribute(name)) => { + if let Some(ref_name) = name.strip_prefix('#') { + names.get(ref_name).cloned().ok_or_else(|| { + DynamoDbError::ValidationException(format!( + "Invalid KeyConditionExpression: An expression attribute name used in \ + the document path is not defined; attribute name: #{ref_name}" + )) + }) + } else { + Ok(name.clone()) + } + } + _ => Err(DynamoDbError::ValidationException( + "Invalid key condition path".to_owned(), + )), + } +} diff --git a/crates/core/src/expression/key_condition_tests.rs b/crates/core/src/expression/key_condition_tests.rs new file mode 100644 index 000000000..a39483dd7 --- /dev/null +++ b/crates/core/src/expression/key_condition_tests.rs @@ -0,0 +1,965 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::expression::tokenize; +use crate::types::{KeySchemaElement, KeyType}; +use std::collections::HashMap; + +#[test] +fn key_condition_redundant_parens_rejected_with_canonical_message() { + for expr in ["((pk = :v))", "((#pk = :pk)) AND (#sk = :sk)"] { + let tokens = tokenize(expr).unwrap(); + let err = parse_key_condition(&tokens).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid KeyConditionExpression: The expression has redundant parentheses;"), + "expr {expr}: got {err:?}" + ); + } +} + +#[test] +fn key_condition_valid_parens_accepted() { + for expr in [ + "(pk = :v)", + "(#pk = :pk) AND (#sk = :sk)", + "(#pk = :pk AND #sk = :sk)", + "(#pk = :pk AND (#sk = :sk))", + ] { + let tokens = tokenize(expr).unwrap(); + assert!( + parse_key_condition(&tokens).is_ok(), + "expr {expr} should parse" + ); + } +} + +#[test] +fn resolve_pk_sk_swaps_when_reversed() { + // "sk = :sk AND pk = :pk" — parser assigns first Eq as PK + let tokens = tokenize("sk = :sk AND pk = :pk").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); + + kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); + match &kc.sk_condition { + Some(SortKeyCondition::Compare { + path, + op: CompareOp::Eq, + .. + }) => { + assert_eq!(path, &vec![PathElement::Attribute("sk".to_owned())]); + } + other => panic!("expected Eq SK condition, got {other:?}"), + } +} + +#[test] +fn resolve_pk_sk_no_swap_when_correct() { + let tokens = tokenize("pk = :pk AND sk = :sk").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); + + kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); +} + +#[test] +fn resolve_pk_sk_with_name_refs() { + let tokens = tokenize("#s = :sk AND #p = :pk").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + + let mut names = HashMap::new(); + names.insert("s".to_owned(), "sortkey".to_owned()); + names.insert("p".to_owned(), "partkey".to_owned()); + + kc.resolve_pk_sk("partkey", &names).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("#p".to_owned())]); +} + +#[test] +fn resolve_pk_sk_noop_for_non_eq_sk() { + // "pk = :pk AND sk > :val" — SK is not Eq, no ambiguity + let tokens = tokenize("pk = :pk AND sk > :val").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); +} + +#[test] +fn resolve_pk_sk_noop_for_single_clause() { + let tokens = tokenize("pk = :pk").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); +} + +#[test] +fn parse_three_clause_multipart() { + // pk1 = :v1 AND pk2 = :v2 AND sk = :v3 + let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk = :v3").unwrap(); + let kc = parse_key_condition(&tokens).unwrap(); + // First clause is pk_path, one extra_pk, one sk + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); + assert_eq!(kc.extra_pk_conditions.len(), 1); + assert!(kc.sk_condition.is_some()); +} + +#[test] +fn parse_four_clause_multipart() { + let tokens = tokenize("a = :a AND b = :b AND c = :c AND d = :d").unwrap(); + let kc = parse_key_condition(&tokens).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("a".to_owned())]); + assert_eq!(kc.extra_pk_conditions.len(), 2); + assert!(kc.sk_condition.is_some()); +} + +#[test] +fn parse_multipart_with_range_condition() { + // pk1 = :v1 AND pk2 = :v2 AND sk > :v3 + let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk > :v3").unwrap(); + let kc = parse_key_condition(&tokens).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); + // pk2 is in extra_pk_conditions (will be reclassified by resolve_multipart) + assert_eq!(kc.extra_pk_conditions.len(), 1); + match &kc.sk_condition { + Some(SortKeyCondition::Compare { + op: CompareOp::Gt, .. + }) => {} + other => panic!("expected Gt SK condition, got {other:?}"), + } +} + +#[test] +fn parse_reversed_sort_key_comparison() { + let tokens = tokenize("pk = :pk AND :lo <= sk").unwrap(); + let kc = parse_key_condition(&tokens).unwrap(); + + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); + match &kc.sk_condition { + Some(SortKeyCondition::Compare { + path, + op: CompareOp::Ge, + value: Expr::Placeholder(name), + }) => { + assert_eq!(path, &vec![PathElement::Attribute("sk".to_owned())]); + assert_eq!(name, "lo"); + } + other => panic!("expected reversed Ge SK condition, got {other:?}"), + } +} + +#[test] +fn parse_reversed_partition_key_equality() { + let tokens = tokenize(":pk = pk").unwrap(); + let kc = parse_key_condition(&tokens).unwrap(); + + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); + assert_eq!(kc.pk_value, Expr::Placeholder("pk".to_owned())); +} + +#[test] +fn reverse_comparator_maps_each_operator_and_is_involutive() { + use CompareOp::{Eq, Ge, Gt, Le, Lt, Ne}; + + let cases = [(Eq, Eq), (Ne, Ne), (Lt, Gt), (Le, Ge), (Gt, Lt), (Ge, Le)]; + + for (op, reversed) in cases { + assert_eq!(reverse_comparator(op), reversed); + assert_eq!(reverse_comparator(reverse_comparator(op)), op); + } +} + +#[test] +fn resolve_multipart_reclassifies() { + let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 = :v3").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let names = HashMap::new(); + kc.resolve_multipart(&["pk1", "pk2"], &["sk1"], &names) + .unwrap(); + + // After resolve_multipart, pk_path + extra_pk should have pk1 and pk2 + let pk_count = 1 + kc.extra_pk_conditions.len(); + assert_eq!(pk_count, 2); + // sk_condition should be the sk1 equality + assert!(kc.sk_condition.is_some()); +} + +#[test] +fn resolve_multipart_with_range() { + let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 > :v3").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let names = HashMap::new(); + kc.resolve_multipart(&["pk1", "pk2"], &["sk1"], &names) + .unwrap(); + + assert_eq!(1 + kc.extra_pk_conditions.len(), 2); + match &kc.sk_condition { + Some(SortKeyCondition::Compare { + op: CompareOp::Gt, .. + }) => {} + other => panic!("expected Gt SK condition, got {other:?}"), + } +} + +#[test] +fn resolve_multipart_reorders_to_schema_order() { + // Expression order: pk2, pk1, sk — reversed from key schema order [pk1, pk2] + let tokens = tokenize("pk2 = :v2 AND pk1 = :v1 AND sk = :v3").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let names = HashMap::new(); + kc.resolve_multipart(&["pk1", "pk2"], &["sk"], &names) + .unwrap(); + + // After resolve_multipart, pk_path should be pk1 (first in schema) + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); + // extra_pk_conditions should have pk2 + assert_eq!(kc.extra_pk_conditions.len(), 1); + assert_eq!( + kc.extra_pk_conditions[0].0, + vec![PathElement::Attribute("pk2".to_owned())] + ); +} + +#[test] +fn resolve_multipart_multi_range() { + // 2 HASH + 2 RANGE, all equality conditions + let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 = :v3 AND sk2 = :v4").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let names = HashMap::new(); + kc.resolve_multipart(&["pk1", "pk2"], &["sk1", "sk2"], &names) + .unwrap(); + + // 2 PK conditions + assert_eq!(1 + kc.extra_pk_conditions.len(), 2); + // Primary SK condition is sk1 + match &kc.sk_condition { + Some(SortKeyCondition::Compare { + path, + op: CompareOp::Eq, + .. + }) => { + assert_eq!(path, &vec![PathElement::Attribute("sk1".to_owned())]); + } + other => panic!("expected Eq SK condition on sk1, got {other:?}"), + } + // Extra SK condition is sk2 + assert_eq!(kc.extra_sk_conditions.len(), 1); + assert_eq!( + kc.extra_sk_conditions[0].0, + vec![PathElement::Attribute("sk2".to_owned())] + ); +} + +const NESTED_KEY_ERR: &str = "Invalid KeyConditionExpression: KeyConditionExpressions cannot have conditions on nested attributes"; + +#[test] +fn nested_dot_path_on_key_rejected() { + for expr in [ + "pk.foo = :v", + "pk = :p AND sk.foo = :v", + "begins_with(sk.foo, :v)", + "foo.bar = :v", + ] { + let tokens = tokenize(expr).unwrap(); + let err = parse_key_condition(&tokens).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if msg == NESTED_KEY_ERR), + "expr {expr}: got {err:?}" + ); + } +} + +#[test] +fn nested_path_in_all_clause_shapes_rejected() { + // Exercises every `raw_clause_path` arm (Compare/Between/BeginsWith) and a + // 3-clause multi-part shape with a nested middle clause. Multi-part keys + // are an ExtendDB extension real DynamoDB cannot express, hence a + // parser-level test. The reject loop runs before classification, so a + // nested clause in any position is rejected up front. + for expr in [ + "pk.foo > :v", // single non-eq (Compare arm) + "pk = :p AND sk.foo BETWEEN :a AND :b", // Between arm + "pk = :p AND begins_with(sk[0], :v)", // BeginsWith arm, index + "pk = :p AND :v < sk.foo", // reversed value-first + "pk1 = :v1 AND pk2.x = :v2 AND sk = :v3", // multi-part, nested middle + ] { + let tokens = tokenize(expr).unwrap(); + let err = parse_key_condition(&tokens).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if msg == NESTED_KEY_ERR), + "expr {expr}: got {err:?}" + ); + } +} + +#[test] +fn index_path_on_key_rejected() { + for expr in ["pk[0] = :v", "pk = :p AND sk[0] = :v"] { + let tokens = tokenize(expr).unwrap(); + let err = parse_key_condition(&tokens).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if msg == NESTED_KEY_ERR), + "expr {expr}: got {err:?}" + ); + } +} + +#[test] +fn nested_path_via_name_placeholder_rejected() { + // The check is structural (path length), so it fires before #name + // resolution. + let tokens = tokenize("#d.foo = :v").unwrap(); + let err = parse_key_condition(&tokens).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if msg == NESTED_KEY_ERR), + "got {err:?}" + ); +} + +#[test] +fn top_level_key_paths_accepted() { + for expr in ["pk = :v", "pk = :p AND sk = :s", "#pk = :p AND #sk = :s"] { + let tokens = tokenize(expr).unwrap(); + assert!( + parse_key_condition(&tokens).is_ok(), + "expr {expr} should parse" + ); + } +} + +/// One expected clause: attribute, operand placeholder, equality. +type ExpectedClause = (&'static str, &'static str, bool); + +/// The attribute and operand of each clause, and whether it is an +/// equality, which is what authorization reads to find the partition value +/// of a key condition the engine rejects for its operator. +#[test] +fn clause_operands_name_every_single_operand_clause() { + let cases: &[(&str, &[ExpectedClause])] = &[ + ("pk = :v", &[("pk", "v", true)]), + ( + "pk = :v AND sk = :s", + &[("pk", "v", true), ("sk", "s", true)], + ), + ("pk > :v", &[("pk", "v", false)]), + (":v > pk", &[("pk", "v", false)]), + ("begins_with(pk, :v)", &[("pk", "v", false)]), + ("(pk >= :v)", &[("pk", "v", false)]), + ("#p <= :v", &[("#p", "v", false)]), + ( + "pk = :v AND sk < :s", + &[("pk", "v", true), ("sk", "s", false)], + ), + ( + "pk > :v AND sk = :s", + &[("pk", "v", false), ("sk", "s", true)], + ), + ( + "pk < :v AND sk > :s", + &[("pk", "v", false), ("sk", "s", false)], + ), + ( + "pk = :u AND pk > :v", + &[("pk", "u", true), ("pk", "v", false)], + ), + // BETWEEN names two operands, so it contributes none. + ("pk BETWEEN :lo AND :hi", &[]), + ("pk = :v AND sk BETWEEN :lo AND :hi", &[("pk", "v", true)]), + ]; + for (expr, want) in cases { + let tokens = tokenize(expr).unwrap(); + let got = key_condition_clause_operands(&tokens).unwrap(); + let got: Vec<(String, String, bool)> = got + .into_iter() + .map(|clause| { + let name = match &clause.path[0] { + PathElement::Attribute(n) => n.clone(), + PathElement::Index(i) => format!("[{i}]"), + }; + let value = match clause.value { + Expr::Placeholder(n) => n, + other => format!("{other:?}"), + }; + (name, value, clause.equality) + }) + .collect(); + let want: Vec<(String, String, bool)> = want + .iter() + .map(|(a, v, e)| ((*a).to_owned(), (*v).to_owned(), *e)) + .collect(); + assert_eq!(got, want, "expr {expr}"); + } +} + +/// The same syntax errors and unsupported constructs `parse_key_condition` +/// rejects before classification. +#[test] +fn clause_operands_reject_what_the_parser_rejects() { + for expr in [ + "pk :: :v", + "pk > :v OR sk = :s", + "((pk = :v))", + "pk.sub > :v", + "pk <> :v", + "pk >", + ] { + let Ok(tokens) = tokenize(expr) else { + continue; + }; + assert!( + key_condition_clause_operands(&tokens).is_err(), + "expr {expr} should be rejected" + ); + } +} + +/// The index key schema the single-HASH cases use: HASH `h`, then RANGE +/// `a`, `b`, `c`, `d`. +const ONE_HASH: [&str; 1] = ["h"]; +const FOUR_RANGE: [&str; 4] = ["a", "b", "c", "d"]; + +/// Parse `expr` and classify it against `h` + `a, b, c, d`. +fn classify_one_hash(expr: &str) -> Result { + classify_with_names(expr, &HashMap::new()) +} + +fn classify_with_names( + expr: &str, + names: &HashMap, +) -> Result { + let tokens = tokenize(expr).unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_multipart(&ONE_HASH, &FOUR_RANGE, names)?; + Ok(kc) +} + +/// The attribute names of `extra_sk_conditions`, in order. +fn extra_sk_names(kc: &KeyCondition) -> Vec { + kc.extra_sk_conditions + .iter() + .map(|(path, _)| match path.first() { + Some(PathElement::Attribute(name)) => name.clone(), + other => panic!("unexpected path {other:?}"), + }) + .collect() +} + +/// The sort-key condition's attribute and a label for its operator. +fn sk_shape(kc: &KeyCondition) -> Option<(String, &'static str)> { + let cond = kc.sk_condition.as_ref()?; + let name = match cond.path().first() { + Some(PathElement::Attribute(name)) => name.clone(), + other => panic!("unexpected path {other:?}"), + }; + let op = match cond { + SortKeyCondition::Compare { op, .. } => match op { + CompareOp::Eq => "=", + CompareOp::Ne => "<>", + CompareOp::Lt => "<", + CompareOp::Le => "<=", + CompareOp::Gt => ">", + CompareOp::Ge => ">=", + }, + SortKeyCondition::Between { .. } => "BETWEEN", + SortKeyCondition::BeginsWith { .. } => "begins_with", + }; + Some((name, op)) +} + +fn assert_range_gap(expr: &str, without_eq: &str, present: &str) { + let err = classify_one_hash(expr).unwrap_err(); + let want = format!( + "RANGE key attributes {without_eq} must have equality conditions specified in the \ + query because a condition is present on key attribute {present}" + ); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}, want {want}" + ); +} + +#[test] +fn one_hash_multi_range_hash_only_condition_is_accepted() { + let kc = classify_one_hash("h = :h").unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("h".to_owned())]); + assert!(kc.extra_pk_conditions.is_empty()); + assert!(kc.sk_condition.is_none()); + assert!(kc.extra_sk_conditions.is_empty()); +} + +#[test] +fn one_hash_multi_range_equality_prefixes_are_accepted() { + // Equalities on a leading run of the RANGE attributes, up to all four. + for (expr, extra) in [ + ("h = :h AND a = :a", vec![]), + ("h = :h AND a = :a AND b = :b", vec!["b"]), + ("h = :h AND a = :a AND b = :b AND c = :c", vec!["b", "c"]), + ( + "h = :h AND a = :a AND b = :b AND c = :c AND d = :d", + vec!["b", "c", "d"], + ), + ] { + let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); + assert_eq!( + kc.pk_path, + vec![PathElement::Attribute("h".to_owned())], + "{expr}" + ); + assert!(kc.extra_pk_conditions.is_empty(), "{expr}"); + assert_eq!(sk_shape(&kc), Some(("a".to_owned(), "=")), "{expr}"); + assert_eq!(extra_sk_names(&kc), extra, "{expr}"); + } +} + +#[test] +fn one_hash_multi_range_clause_order_is_free() { + // The defect: the first clause was taken as the partition key, so + // `b = :b AND h = :h AND a = :a` was refused as missing `h`. + for expr in [ + "b = :b AND h = :h AND a = :a", + "a = :a AND b = :b AND h = :h", + "b = :b AND a = :a AND h = :h", + ] { + let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); + assert_eq!( + kc.pk_path, + vec![PathElement::Attribute("h".to_owned())], + "{expr}" + ); + assert_eq!(sk_shape(&kc), Some(("a".to_owned(), "=")), "{expr}"); + assert_eq!(extra_sk_names(&kc), vec!["b"], "{expr}"); + } +} + +#[test] +fn one_hash_multi_range_operator_on_the_last_given_attribute_is_accepted() { + for (expr, sk, extra) in [ + ("h = :h AND a > :a", ("a", ">"), vec![]), + ("h = :h AND a = :a AND b < :b", ("b", "<"), vec!["a"]), + ( + "h = :h AND a = :a AND b = :b AND c > :c", + ("c", ">"), + vec!["a", "b"], + ), + ( + "h = :h AND a = :a AND begins_with(b, :b)", + ("b", "begins_with"), + vec!["a"], + ), + ( + "h = :h AND a = :a AND b = :b AND c = :c AND begins_with(d, :d)", + ("d", "begins_with"), + vec!["a", "b", "c"], + ), + ( + "h = :h AND a = :a AND b = :b AND c = :c AND d BETWEEN :x AND :y", + ("d", "BETWEEN"), + vec!["a", "b", "c"], + ), + ( + "c > :c AND b = :b AND h = :h AND a = :a", + ("c", ">"), + vec!["a", "b"], + ), + ] { + let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); + assert_eq!( + kc.pk_path, + vec![PathElement::Attribute("h".to_owned())], + "{expr}" + ); + assert_eq!(sk_shape(&kc), Some((sk.0.to_owned(), sk.1)), "{expr}"); + assert_eq!(extra_sk_names(&kc), extra, "{expr}"); + } +} + +#[test] +fn one_hash_multi_range_gap_is_refused() { + // A condition on a RANGE attribute needs an equality on every RANGE + // attribute before it. The defect accepted `h = :h AND b = :b` and + // returned no items. + assert_range_gap("h = :h AND b = :b", "a", "b"); + assert_range_gap("h = :h AND a = :a AND c = :c", "b", "c"); + assert_range_gap("h = :h AND a = :a AND b = :b AND d > :d", "c", "d"); +} + +#[test] +fn one_hash_multi_range_operator_before_a_later_condition_is_refused() { + assert_range_gap("h = :h AND a = :a AND b > :b AND c = :c", "b", "c"); + assert_range_gap("h = :h AND begins_with(a, :a) AND b = :b", "a", "b"); +} + +#[test] +fn one_hash_multi_range_missing_hash_is_refused() { + for expr in [ + "a = :a AND b = :b AND c = :c", + "a = :a AND b = :b", + "a = :a", + ] { + let err = classify_one_hash(expr).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "HASH key attributes h must have equality conditions specified in the query"), + "expr {expr}: got {err:?}" + ); + } +} + +/// Classify against HASH `h1`, `h2` and RANGE `r`. +fn classify_two_hash(expr: &str) -> Result { + let tokens = tokenize(expr).unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_multipart(&["h1", "h2"], &["r"], &HashMap::new())?; + Ok(kc) +} + +#[test] +fn two_hash_missing_hash_names_every_missing_attribute() { + for (expr, missing) in [ + ("h1 = :x", "h2"), + ("h2 = :x", "h1"), + ("h1 = :x AND r = :y", "h2"), + ("r = :y", "h1, h2"), + ("h1 = :x AND h2 > :y", "h2"), + ] { + let err = classify_two_hash(expr).unwrap_err(); + let want = format!( + "HASH key attributes {missing} must have equality conditions specified in the query" + ); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}" + ); + } + assert!(classify_two_hash("h1 = :x AND h2 = :y").is_ok()); + assert!(classify_two_hash("h1 = :x AND h2 = :y AND r > :z").is_ok()); +} + +#[test] +fn a_second_condition_on_one_key_attribute_is_refused() { + const WANT: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only \ + contain one condition per key"; + for expr in [ + "h = :x AND h = :y", + "h = :x AND h = :y AND a = :z", + "h = :x AND a = :y AND a = :z", + "h = :h AND a = :a AND a > :x", + "h = :h AND a > :x AND a = :a", + "h = :h AND a = :a AND b = :n AND b > :lo", + "h = :h AND h > :x", + "h = :h AND h = :y AND c = :c", + "a = :a AND a = :y", + ] { + let err = classify_one_hash(expr).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if msg == WANT), + "expr {expr}: got {err:?}" + ); + } + for expr in [ + "h1 = :x AND h1 = :y AND h2 = :z", + "h1 = :x AND h1 = :y", + "h1 = :x AND h2 = :n AND r = :r AND r > :y", + "h1 = :x AND r = :r AND r = :y", + ] { + let err = classify_two_hash(expr).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if msg == WANT), + "expr {expr}: got {err:?}" + ); + } +} + +#[test] +fn a_condition_on_a_non_key_attribute_names_the_first_uncovered_range_attribute() { + for (expr, missing) in [ + ("h = :h AND z = :z", "a"), + ("h = :h AND z = :z AND y = :y", "a"), + ("h = :h AND z > :z", "a"), + ("h = :h AND a = :a AND z = :z", "b"), + ("h = :h AND a = :a AND z > :z", "b"), + ("h = :h AND a > :a AND z = :z", "b"), + ("h = :h AND a = :a AND b = :b AND z > :z", "c"), + ("h = :h AND a = :a AND b = :b AND c = :c AND z = :z", "d"), + ] { + let err = classify_one_hash(expr).unwrap_err(); + let want = format!("Query condition missed key schema element: {missing}"); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}" + ); + } + let err = classify_two_hash("h1 = :x AND h2 = :y AND z = :z").unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Query condition missed key schema element: r")); + // A gap is reported before the non-key attribute. + let err = classify_one_hash("h = :h AND b = :b AND z = :z").unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg.starts_with("RANGE key attributes a must have equality conditions"))); + // A missing HASH attribute is reported before the non-key attribute. + let err = classify_two_hash("h1 = :x AND z = :z").unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "HASH key attributes h2 must have equality conditions specified in the query")); +} + +#[test] +fn more_conditions_than_key_attributes_are_refused_by_count() { + for (expr, n) in [ + ( + "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND z = :z", + 6, + ), + ( + "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND z > :z", + 6, + ), + ( + "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND PK = :p", + 6, + ), + ] { + let err = classify_one_hash(expr).unwrap_err(); + let want = format!( + "The number of query conditions ({n}) exceeds the number of key attributes \ + defined in the schema (5)" + ); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}" + ); + } + let err = classify_two_hash("h1 = :x AND h2 = :y AND r = :r AND z = :z").unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "The number of query conditions (4) exceeds the number of key attributes defined in the schema (3)")); +} + +#[test] +fn the_count_is_refused_before_a_missing_hash_attribute_or_a_range_gap() { + // Each count case above has every key attribute, so they also pass + // with the count check moved after the missing-HASH and RANGE-gap + // checks. These lack the HASH attribute or leave a RANGE gap. + let count = |n: usize, attrs: usize| { + format!( + "The number of query conditions ({n}) exceeds the number of key attributes \ + defined in the schema ({attrs})" + ) + }; + for expr in [ + "a = :a AND b = :b AND c = :c AND d = :d AND z1 = :z AND z2 = :y", + "h = :h AND b = :b AND c = :c AND d = :d AND z1 = :z AND z2 = :y", + ] { + let err = classify_one_hash(expr).unwrap_err(); + let want = count(6, 5); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}" + ); + } + let expr = "a = :a AND b = :b AND c = :c AND z1 = :z AND z2 = :y"; + let err = classify_two_hash(expr).unwrap_err(); + let want = count(5, 3); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}" + ); + // The same five clauses on HASH `h` and RANGE `a`, `b`, `c`, `d` do not + // exceed its five key attributes, so the missing HASH attribute is + // reported. + let err = classify_one_hash(expr).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "HASH key attributes h must have equality conditions specified in the query"), + "expr {expr}: got {err:?}" + ); +} + +#[test] +fn one_hash_multi_range_resolves_name_references() { + let names: HashMap = [("hh", "h"), ("aa", "a"), ("bb", "b")] + .into_iter() + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + let kc = classify_with_names("#bb > :b AND #hh = :h AND #aa = :a", &names).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("#hh".to_owned())]); + assert_eq!(sk_shape(&kc), Some(("#bb".to_owned(), ">"))); + assert_eq!(extra_sk_names(&kc), vec!["#aa"]); + + let err = classify_with_names("#hh = :h AND #bb = :b", &names).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg.starts_with("RANGE key attributes a must have")), + "got {err:?}" + ); +} + +#[test] +fn one_hash_one_range_schema_is_left_unchanged() { + let tokens = tokenize("sk = :s AND pk = :p").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_multipart(&["pk"], &["sk"], &HashMap::new()) + .unwrap(); + // Still the parser's assignment; resolve_pk_sk handles this schema. + assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); +} + +#[test] +fn multi_hash_partition_key_need_not_come_first() { + // With two HASH attributes the first clause used to be checked as the + // first HASH attribute before reclassification, so this order was + // refused as missing `pk1`. + let tokens = tokenize("sk = :s AND pk1 = :a AND pk2 = :b").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_multipart(&["pk1", "pk2"], &["sk"], &HashMap::new()) + .unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); + assert_eq!( + kc.extra_pk_conditions[0].0, + vec![PathElement::Attribute("pk2".to_owned())] + ); + assert_eq!(sk_shape(&kc), Some(("sk".to_owned(), "="))); + assert!(kc.extra_sk_conditions.is_empty()); +} + +#[test] +fn multi_hash_multi_range_operator_after_equality_keeps_both() { + // The non-equality on the second RANGE attribute is the sort-key + // condition, and the equality on the first is carried with it. + let tokens = tokenize("pk1 = :a AND pk2 = :b AND s1 = :x AND s2 > :y").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_multipart(&["pk1", "pk2"], &["s1", "s2"], &HashMap::new()) + .unwrap(); + assert_eq!(sk_shape(&kc), Some(("s2".to_owned(), ">"))); + assert_eq!(extra_sk_names(&kc), vec!["s1"]); +} + +fn key(name: &str, key_type: KeyType) -> KeySchemaElement { + KeySchemaElement { + attribute_name: name.to_owned(), + key_type, + } +} + +#[test] +fn resolve_key_schema_reads_a_multi_attribute_schema_by_name() { + // Authorization reads the partition key value from `pk_path` after this + // call, so it must name the first HASH attribute for every clause order + // the engine serves. + let two_hash = [ + key("g1", KeyType::Hash), + key("g2", KeyType::Hash), + key("gs", KeyType::Range), + ]; + let two_range = [ + key("h", KeyType::Hash), + key("a", KeyType::Range), + key("b", KeyType::Range), + ]; + for (schema, expr) in [ + (&two_hash[..], "g2 = :g AND g1 = :v AND gs = :x"), + (&two_hash[..], "gs = :x AND g1 = :v AND g2 = :g"), + (&two_hash[..], "g2 = :g AND g1 = :v AND gs > :lo"), + (&two_range[..], "a = :a AND h = :v AND b = :c"), + (&two_range[..], "b = :c AND h = :v AND a = :a"), + (&two_range[..], "b > :lo AND a = :a AND h = :v"), + (&two_range[..], "begins_with(b, :p) AND a = :a AND h = :v"), + ] { + let tokens = tokenize(expr).unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_key_schema(schema, &HashMap::new()) + .unwrap_or_else(|e| panic!("{expr}: {e:?}")); + let hash = &schema[0].attribute_name; + assert_eq!( + kc.pk_path, + vec![PathElement::Attribute(hash.clone())], + "{expr}" + ); + assert_eq!(kc.pk_value, Expr::Placeholder("v".to_owned()), "{expr}"); + } +} + +#[test] +fn resolve_key_schema_checks_values_before_resolve_pk_sk() { + let schema = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; + let tokens = tokenize("sk BETWEEN :lo AND :hi AND pk = :p").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let mut checked = Vec::new(); + kc.resolve_key_schema_with(&schema, &HashMap::new(), |_, value| { + checked.push(format!("{value:?}")); + Ok(()) + }) + .unwrap(); + assert_eq!(checked.len(), 3, "{checked:?}"); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); + + let tokens = tokenize("sk = :s AND pk = :p").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let err = kc + .resolve_key_schema_with(&schema, &HashMap::new(), |_, _| { + Err(validation_err("checked")) + }) + .unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) if msg == "checked")); + // The failed check left the parser's assignment in place. + assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); + + kc.resolve_key_schema(&schema, &HashMap::new()).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); +} + +// Syntax error wording measured 2026-10-25 (us-east-1) on Query. + +fn kce_msg(src: &str) -> String { + match parse_key_condition_from(&tokenize(src).unwrap(), src) { + Err(DynamoDbError::ValidationException(m)) => m, + other => panic!("expected ValidationException, got {other:?}"), + } +} + +#[test] +fn repeated_operator_quotes_the_source_window() { + // [d22] `pk = = :v` + assert_eq!( + kce_msg("pk = = :v"), + "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :v\"" + ); + assert_eq!(kce_msg("pk = :v AND sk = = :s"), "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :s\""); +} + +#[test] +fn trailing_keyword_is_eof_with_the_keyword_as_window() { + // [d23] `pk = :v AND` + assert_eq!( + kce_msg("pk = :v AND"), + "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"AND\"" + ); + assert_eq!(kce_msg("pk ="), "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"=\""); +} + +#[test] +fn stripped_outer_parentheses_keep_the_source_window() { + // The window is taken from the full token list, so the stripped + // parenthesis does not shift the quoted text. + assert_eq!( + kce_msg("(pk = = :v)"), + "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :v\"" + ); +} + +#[test] +fn other_key_condition_texts_are_unchanged() { + assert_eq!( + kce_msg("pk = :v OR sk = :s"), + "Invalid KeyConditionExpression: only AND is supported between key conditions" + ); + assert_eq!( + kce_msg("pk"), + "Invalid KeyConditionExpression: expected operator after operand" + ); + assert_eq!( + kce_msg("pk = :v AND sk = sk2"), + "Invalid KeyConditionExpression: key condition values must be expression attribute value placeholders" + ); +} diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 63a975b03..dea971f6a 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -11,6 +11,7 @@ mod ast; mod evaluator; mod key_condition; +mod key_condition_resolve; mod kind; mod operator_count; mod parser; diff --git a/crates/core/src/expression/projection.rs b/crates/core/src/expression/projection.rs index a1c8463bf..5b0e8a9bc 100755 --- a/crates/core/src/expression/projection.rs +++ b/crates/core/src/expression/projection.rs @@ -293,462 +293,5 @@ fn project_value(value: &AttributeValue, node: &ProjNode) -> Option, - ) -> Result { - let tokens = tokenize(expr_str)?; - let paths = parse_projection(&tokens)?; - let maps = ExpressionMaps::new(names, HashMap::new()); - apply_projection(item, &paths, &maps) - } - - fn sample_item() -> Item { - let mut inner = BTreeMap::new(); - inner.insert("city".into(), AttributeValue::S("NYC".into())); - inner.insert("zip".into(), AttributeValue::S("10001".into())); - let mut item = BTreeMap::new(); - item.insert("pk".into(), AttributeValue::S("key1".into())); - item.insert("name".into(), AttributeValue::S("Alice".into())); - item.insert("age".into(), AttributeValue::N("30".into())); - item.insert("address".into(), AttributeValue::M(inner)); - item - } - - #[test] - fn project_single_attribute() { - let item = sample_item(); - let result = project("name", &item, HashMap::new()).unwrap(); - assert_eq!(result.len(), 1); - assert_eq!(result.get("name"), Some(&AttributeValue::S("Alice".into()))); - } - - #[test] - fn project_multiple_attributes() { - let item = sample_item(); - let result = project("name, age", &item, HashMap::new()).unwrap(); - assert_eq!(result.len(), 2); - assert!(result.contains_key("name")); - assert!(result.contains_key("age")); - } - - #[test] - fn project_missing_attribute_omitted() { - let item = sample_item(); - let result = project("name, missing", &item, HashMap::new()).unwrap(); - assert_eq!(result.len(), 1); - assert!(result.contains_key("name")); - } - - #[test] - fn project_nested_path() { - let item = sample_item(); - let result = project("address.city", &item, HashMap::new()).unwrap(); - assert!(result.contains_key("address")); - if let Some(AttributeValue::M(m)) = result.get("address") { - assert_eq!(m.get("city"), Some(&AttributeValue::S("NYC".into()))); - assert!(!m.contains_key("zip")); // Only city projected - } else { - panic!("Expected M"); - } - } - - #[test] - fn project_with_name_ref() { - let item = sample_item(); - let mut names = HashMap::new(); - names.insert("n".into(), "name".into()); - let result = project("#n", &item, names).unwrap(); - assert_eq!(result.len(), 1); - assert_eq!(result.get("name"), Some(&AttributeValue::S("Alice".into()))); - } - - #[test] - fn project_empty_expression() { - let item = sample_item(); - let tokens = tokenize("").unwrap(); - let paths = parse_projection(&tokens).unwrap(); - assert!(paths.is_empty()); - let maps = ExpressionMaps::new(HashMap::new(), HashMap::new()); - let result = apply_projection(&item, &paths, &maps).unwrap(); - assert!(result.is_empty()); - } - - #[test] - fn project_all_attributes() { - let item = sample_item(); - let result = project("pk, name, age, address", &item, HashMap::new()).unwrap(); - assert_eq!(result.len(), 4); - } - - #[test] - fn project_list_index() { - let mut item = BTreeMap::new(); - item.insert("pk".into(), AttributeValue::S("k1".into())); - item.insert( - "mylist".into(), - AttributeValue::L(vec![ - AttributeValue::S("zero".into()), - AttributeValue::S("one".into()), - AttributeValue::S("two".into()), - ]), - ); - - let result = project("mylist[0]", &item, HashMap::new()).unwrap(); - assert_eq!(result.len(), 1); - match result.get("mylist") { - Some(AttributeValue::L(list)) => { - assert_eq!(list.len(), 1); - assert_eq!(list[0], AttributeValue::S("zero".into())); - } - other => panic!("Expected L, got {other:?}"), - } - - let result = project("mylist[1]", &item, HashMap::new()).unwrap(); - match result.get("mylist") { - Some(AttributeValue::L(list)) => { - assert_eq!(list.len(), 1); - assert_eq!(list[0], AttributeValue::S("one".into())); - } - other => panic!("Expected L, got {other:?}"), - } - - // Out-of-bounds index returns empty - let result = project("mylist[5]", &item, HashMap::new()).unwrap(); - assert!(result.is_empty()); - } - - fn list_item() -> Item { - let mut item = BTreeMap::new(); - item.insert("pk".into(), AttributeValue::S("p1".into())); - item.insert( - "mylist".into(), - AttributeValue::L(vec![ - AttributeValue::S("zero".into()), - AttributeValue::S("one".into()), - AttributeValue::S("two".into()), - AttributeValue::S("three".into()), - ]), - ); - item.insert( - "with_null".into(), - AttributeValue::L(vec![ - AttributeValue::S("keep0".into()), - AttributeValue::Null, - AttributeValue::S("keep2".into()), - ]), - ); - item - } - - fn assert_list(result: &Item, key: &str, expected: &[AttributeValue]) { - match result.get(key) { - Some(AttributeValue::L(list)) => assert_eq!(list.as_slice(), expected), - other => panic!("Expected L for {key}, got {other:?}"), - } - } - - #[test] - fn project_two_list_indices_compacted() { - let item = list_item(); - let result = project("mylist[0], mylist[2]", &item, HashMap::new()).unwrap(); - assert_list( - &result, - "mylist", - &[ - AttributeValue::S("zero".into()), - AttributeValue::S("two".into()), - ], - ); - } - - #[test] - fn project_list_indices_ordered_by_index_not_expression() { - let item = list_item(); - // Reversed expression order still comes out in ascending index order. - let result = project("mylist[2], mylist[0]", &item, HashMap::new()).unwrap(); - assert_list( - &result, - "mylist", - &[ - AttributeValue::S("zero".into()), - AttributeValue::S("two".into()), - ], - ); - } - - #[test] - fn project_list_index_gap_compacted() { - let item = list_item(); - let result = project("mylist[1], mylist[3]", &item, HashMap::new()).unwrap(); - assert_list( - &result, - "mylist", - &[ - AttributeValue::S("one".into()), - AttributeValue::S("three".into()), - ], - ); - } - - #[test] - fn project_null_element_by_index_preserved() { - let item = list_item(); - let result = project("with_null[1]", &item, HashMap::new()).unwrap(); - assert_list(&result, "with_null", &[AttributeValue::Null]); - } - - #[test] - fn project_unselected_null_dropped() { - let item = list_item(); - let result = project("with_null[0], with_null[2]", &item, HashMap::new()).unwrap(); - assert_list( - &result, - "with_null", - &[ - AttributeValue::S("keep0".into()), - AttributeValue::S("keep2".into()), - ], - ); - } - - #[test] - fn project_whole_list_preserves_null() { - let item = list_item(); - let result = project("with_null", &item, HashMap::new()).unwrap(); - assert_list( - &result, - "with_null", - &[ - AttributeValue::S("keep0".into()), - AttributeValue::Null, - AttributeValue::S("keep2".into()), - ], - ); - } - - #[test] - fn project_list_of_maps_subfield_multi() { - let mut item = BTreeMap::new(); - item.insert("pk".into(), AttributeValue::S("p".into())); - let mk = |v: &str, x: &str| { - let mut m = BTreeMap::new(); - m.insert("val".into(), AttributeValue::S(v.into())); - m.insert("x".into(), AttributeValue::S(x.into())); - AttributeValue::M(m) - }; - item.insert( - "lom".into(), - AttributeValue::L(vec![mk("a0", "x0"), mk("a1", "x1"), mk("a2", "x2")]), - ); - - let result = project("lom[0].val, lom[2].val", &item, HashMap::new()).unwrap(); - let only_val = |v: &str| { - let mut m = BTreeMap::new(); - m.insert("val".into(), AttributeValue::S(v.into())); - AttributeValue::M(m) - }; - assert_list(&result, "lom", &[only_val("a0"), only_val("a2")]); - } - - #[test] - fn project_same_index_merges_subfields() { - let mut item = BTreeMap::new(); - item.insert("pk".into(), AttributeValue::S("p".into())); - let mut m = BTreeMap::new(); - m.insert("a".into(), AttributeValue::S("av".into())); - m.insert("b".into(), AttributeValue::S("bv".into())); - m.insert("c".into(), AttributeValue::S("cv".into())); - item.insert("l".into(), AttributeValue::L(vec![AttributeValue::M(m)])); - - // Two paths selecting the same element merge their subfields. - let result = project("l[0].a, l[0].c", &item, HashMap::new()).unwrap(); - let mut expected = BTreeMap::new(); - expected.insert("a".into(), AttributeValue::S("av".into())); - expected.insert("c".into(), AttributeValue::S("cv".into())); - assert_list(&result, "l", &[AttributeValue::M(expected)]); - } - - fn check_overlap(expr: &str, names: HashMap) -> Result<(), DynamoDbError> { - let tokens = tokenize(expr).unwrap(); - let paths = parse_projection(&tokens).unwrap(); - let maps = ExpressionMaps::new(names, HashMap::new()); - Projection::compile(&paths, &maps, true).map(|_| ()) - } - - #[test] - fn compile_without_overlap_rejection_accepts_duplicates() { - // Desugared AttributesToGet keeps the legacy accept-duplicates behavior. - let tokens = tokenize("a, a").unwrap(); - let paths = parse_projection(&tokens).unwrap(); - let maps = ExpressionMaps::new(HashMap::new(), HashMap::new()); - assert!(Projection::compile(&paths, &maps, false).is_ok()); - } - - #[test] - fn compiled_projection_reusable_across_items() { - let tokens = tokenize("name").unwrap(); - let paths = parse_projection(&tokens).unwrap(); - let maps = ExpressionMaps::new(HashMap::new(), HashMap::new()); - let proj = Projection::compile(&paths, &maps, true).unwrap(); - let item = sample_item(); - for _ in 0..2 { - let out = proj.apply(&item); - assert_eq!(out.len(), 1); - assert!(out.contains_key("name")); - } - } - - fn overlap_msg(expr: &str) -> String { - match check_overlap(expr, HashMap::new()) { - Err(DynamoDbError::ValidationException(m)) => m, - other => panic!("expected ValidationException, got {other:?}"), - } - } - - #[test] - fn overlap_parent_then_child() { - assert_eq!( - overlap_msg("a, a.b"), - "Invalid ProjectionExpression: Two document paths overlap with each other; \ - must remove or rewrite one of these paths; path one: [a], path two: [a, b]" - ); - } - - #[test] - fn overlap_child_then_parent() { - assert_eq!( - overlap_msg("a.b, a"), - "Invalid ProjectionExpression: Two document paths overlap with each other; \ - must remove or rewrite one of these paths; path one: [a, b], path two: [a]" - ); - } - - #[test] - fn overlap_exact_duplicate() { - assert_eq!( - overlap_msg("a, a"), - "Invalid ProjectionExpression: Two document paths overlap with each other; \ - must remove or rewrite one of these paths; path one: [a], path two: [a]" - ); - } - - #[test] - fn overlap_index_path_rendering() { - assert_eq!( - overlap_msg("a[0], a"), - "Invalid ProjectionExpression: Two document paths overlap with each other; \ - must remove or rewrite one of these paths; path one: [a, [0]], path two: [a]" - ); - assert_eq!( - overlap_msg("a[0].b, a[0]"), - "Invalid ProjectionExpression: Two document paths overlap with each other; \ - must remove or rewrite one of these paths; path one: [a, [0], b], path two: [a, [0]]" - ); - } - - #[test] - fn overlap_reports_first_pair_in_order() { - assert_eq!( - overlap_msg("x, a.b, a"), - "Invalid ProjectionExpression: Two document paths overlap with each other; \ - must remove or rewrite one of these paths; path one: [a, b], path two: [a]" - ); - } - - #[test] - fn overlap_uses_resolved_names() { - let mut names = HashMap::new(); - names.insert("p".into(), "a".into()); - names.insert("q".into(), "b".into()); - match check_overlap("#p, #p.#q", names) { - Err(DynamoDbError::ValidationException(m)) => assert_eq!( - m, - "Invalid ProjectionExpression: Two document paths overlap with each other; \ - must remove or rewrite one of these paths; path one: [a], path two: [a, b]" - ), - other => panic!("expected ValidationException, got {other:?}"), - } - } - - #[test] - fn no_overlap_for_siblings() { - assert!(check_overlap("a.b, a.c", HashMap::new()).is_ok()); - assert!(check_overlap("a[0], a[1]", HashMap::new()).is_ok()); - assert!(check_overlap("a, b, c", HashMap::new()).is_ok()); - } - - #[test] - fn project_list_index_into_map_preserves_structure() { - let mut item = BTreeMap::new(); - item.insert("pk".into(), AttributeValue::S("p".into())); - let mut map0 = BTreeMap::new(); - map0.insert("val".into(), AttributeValue::S("target".into())); - map0.insert("x".into(), AttributeValue::S("0".into())); - let mut map1 = BTreeMap::new(); - map1.insert("x".into(), AttributeValue::S("0".into())); - item.insert( - "a_list".into(), - AttributeValue::L(vec![AttributeValue::M(map0), AttributeValue::M(map1)]), - ); - - let result = project("a_list[0].val", &item, HashMap::new()).unwrap(); - // Should preserve: {"a_list": [{"val": "target"}]} - match result.get("a_list") { - Some(AttributeValue::L(list)) => { - assert_eq!(list.len(), 1); - match &list[0] { - AttributeValue::M(m) => { - assert_eq!(m.get("val"), Some(&AttributeValue::S("target".into()))); - assert!(!m.contains_key("x")); - } - other => panic!("Expected M, got {other:?}"), - } - } - other => panic!("Expected L, got {other:?}"), - } - } - - // Syntax error wording measured 2026-10-25 (us-east-1) on GetItem. - - fn proj_msg(src: &str) -> String { - match parse_projection_from(&tokenize(src).unwrap(), src) { - Err(DynamoDbError::ValidationException(m)) => m, - other => panic!("expected ValidationException, got {other:?}"), - } - } - - #[test] - fn doubled_comma_quotes_the_source_window() { - // [d27] `#v, , #v` - assert_eq!( - proj_msg("#v, , #v"), - "Invalid ProjectionExpression: Syntax error; token: \",\", near: \", , #v\"" - ); - } - - #[test] - fn trailing_comma_is_eof_with_the_comma_as_window() { - // [d28] `#v,` - assert_eq!( - proj_msg("#v,"), - "Invalid ProjectionExpression: Syntax error; token: \"\", near: \",\"" - ); - } - - #[test] - fn other_projection_texts_are_unchanged() { - assert_eq!( - proj_msg("#v #w"), - "Invalid ProjectionExpression: unexpected token at position 1" - ); - assert_eq!(proj_msg("#v, )"), "Invalid expression: expected attribute name"); - } -} +#[path = "projection_tests.rs"] +mod tests; diff --git a/crates/core/src/expression/projection_tests.rs b/crates/core/src/expression/projection_tests.rs new file mode 100644 index 000000000..a4a218d37 --- /dev/null +++ b/crates/core/src/expression/projection_tests.rs @@ -0,0 +1,460 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::expression::resolver::ExpressionMaps; +use crate::expression::tokenizer::tokenize; +use std::collections::HashMap; + +fn project( + expr_str: &str, + item: &Item, + names: HashMap, +) -> Result { + let tokens = tokenize(expr_str)?; + let paths = parse_projection(&tokens)?; + let maps = ExpressionMaps::new(names, HashMap::new()); + apply_projection(item, &paths, &maps) +} + +fn sample_item() -> Item { + let mut inner = BTreeMap::new(); + inner.insert("city".into(), AttributeValue::S("NYC".into())); + inner.insert("zip".into(), AttributeValue::S("10001".into())); + let mut item = BTreeMap::new(); + item.insert("pk".into(), AttributeValue::S("key1".into())); + item.insert("name".into(), AttributeValue::S("Alice".into())); + item.insert("age".into(), AttributeValue::N("30".into())); + item.insert("address".into(), AttributeValue::M(inner)); + item +} + +#[test] +fn project_single_attribute() { + let item = sample_item(); + let result = project("name", &item, HashMap::new()).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!(result.get("name"), Some(&AttributeValue::S("Alice".into()))); +} + +#[test] +fn project_multiple_attributes() { + let item = sample_item(); + let result = project("name, age", &item, HashMap::new()).unwrap(); + assert_eq!(result.len(), 2); + assert!(result.contains_key("name")); + assert!(result.contains_key("age")); +} + +#[test] +fn project_missing_attribute_omitted() { + let item = sample_item(); + let result = project("name, missing", &item, HashMap::new()).unwrap(); + assert_eq!(result.len(), 1); + assert!(result.contains_key("name")); +} + +#[test] +fn project_nested_path() { + let item = sample_item(); + let result = project("address.city", &item, HashMap::new()).unwrap(); + assert!(result.contains_key("address")); + if let Some(AttributeValue::M(m)) = result.get("address") { + assert_eq!(m.get("city"), Some(&AttributeValue::S("NYC".into()))); + assert!(!m.contains_key("zip")); // Only city projected + } else { + panic!("Expected M"); + } +} + +#[test] +fn project_with_name_ref() { + let item = sample_item(); + let mut names = HashMap::new(); + names.insert("n".into(), "name".into()); + let result = project("#n", &item, names).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!(result.get("name"), Some(&AttributeValue::S("Alice".into()))); +} + +#[test] +fn project_empty_expression() { + let item = sample_item(); + let tokens = tokenize("").unwrap(); + let paths = parse_projection(&tokens).unwrap(); + assert!(paths.is_empty()); + let maps = ExpressionMaps::new(HashMap::new(), HashMap::new()); + let result = apply_projection(&item, &paths, &maps).unwrap(); + assert!(result.is_empty()); +} + +#[test] +fn project_all_attributes() { + let item = sample_item(); + let result = project("pk, name, age, address", &item, HashMap::new()).unwrap(); + assert_eq!(result.len(), 4); +} + +#[test] +fn project_list_index() { + let mut item = BTreeMap::new(); + item.insert("pk".into(), AttributeValue::S("k1".into())); + item.insert( + "mylist".into(), + AttributeValue::L(vec![ + AttributeValue::S("zero".into()), + AttributeValue::S("one".into()), + AttributeValue::S("two".into()), + ]), + ); + + let result = project("mylist[0]", &item, HashMap::new()).unwrap(); + assert_eq!(result.len(), 1); + match result.get("mylist") { + Some(AttributeValue::L(list)) => { + assert_eq!(list.len(), 1); + assert_eq!(list[0], AttributeValue::S("zero".into())); + } + other => panic!("Expected L, got {other:?}"), + } + + let result = project("mylist[1]", &item, HashMap::new()).unwrap(); + match result.get("mylist") { + Some(AttributeValue::L(list)) => { + assert_eq!(list.len(), 1); + assert_eq!(list[0], AttributeValue::S("one".into())); + } + other => panic!("Expected L, got {other:?}"), + } + + // Out-of-bounds index returns empty + let result = project("mylist[5]", &item, HashMap::new()).unwrap(); + assert!(result.is_empty()); +} + +fn list_item() -> Item { + let mut item = BTreeMap::new(); + item.insert("pk".into(), AttributeValue::S("p1".into())); + item.insert( + "mylist".into(), + AttributeValue::L(vec![ + AttributeValue::S("zero".into()), + AttributeValue::S("one".into()), + AttributeValue::S("two".into()), + AttributeValue::S("three".into()), + ]), + ); + item.insert( + "with_null".into(), + AttributeValue::L(vec![ + AttributeValue::S("keep0".into()), + AttributeValue::Null, + AttributeValue::S("keep2".into()), + ]), + ); + item +} + +fn assert_list(result: &Item, key: &str, expected: &[AttributeValue]) { + match result.get(key) { + Some(AttributeValue::L(list)) => assert_eq!(list.as_slice(), expected), + other => panic!("Expected L for {key}, got {other:?}"), + } +} + +#[test] +fn project_two_list_indices_compacted() { + let item = list_item(); + let result = project("mylist[0], mylist[2]", &item, HashMap::new()).unwrap(); + assert_list( + &result, + "mylist", + &[ + AttributeValue::S("zero".into()), + AttributeValue::S("two".into()), + ], + ); +} + +#[test] +fn project_list_indices_ordered_by_index_not_expression() { + let item = list_item(); + // Reversed expression order still comes out in ascending index order. + let result = project("mylist[2], mylist[0]", &item, HashMap::new()).unwrap(); + assert_list( + &result, + "mylist", + &[ + AttributeValue::S("zero".into()), + AttributeValue::S("two".into()), + ], + ); +} + +#[test] +fn project_list_index_gap_compacted() { + let item = list_item(); + let result = project("mylist[1], mylist[3]", &item, HashMap::new()).unwrap(); + assert_list( + &result, + "mylist", + &[ + AttributeValue::S("one".into()), + AttributeValue::S("three".into()), + ], + ); +} + +#[test] +fn project_null_element_by_index_preserved() { + let item = list_item(); + let result = project("with_null[1]", &item, HashMap::new()).unwrap(); + assert_list(&result, "with_null", &[AttributeValue::Null]); +} + +#[test] +fn project_unselected_null_dropped() { + let item = list_item(); + let result = project("with_null[0], with_null[2]", &item, HashMap::new()).unwrap(); + assert_list( + &result, + "with_null", + &[ + AttributeValue::S("keep0".into()), + AttributeValue::S("keep2".into()), + ], + ); +} + +#[test] +fn project_whole_list_preserves_null() { + let item = list_item(); + let result = project("with_null", &item, HashMap::new()).unwrap(); + assert_list( + &result, + "with_null", + &[ + AttributeValue::S("keep0".into()), + AttributeValue::Null, + AttributeValue::S("keep2".into()), + ], + ); +} + +#[test] +fn project_list_of_maps_subfield_multi() { + let mut item = BTreeMap::new(); + item.insert("pk".into(), AttributeValue::S("p".into())); + let mk = |v: &str, x: &str| { + let mut m = BTreeMap::new(); + m.insert("val".into(), AttributeValue::S(v.into())); + m.insert("x".into(), AttributeValue::S(x.into())); + AttributeValue::M(m) + }; + item.insert( + "lom".into(), + AttributeValue::L(vec![mk("a0", "x0"), mk("a1", "x1"), mk("a2", "x2")]), + ); + + let result = project("lom[0].val, lom[2].val", &item, HashMap::new()).unwrap(); + let only_val = |v: &str| { + let mut m = BTreeMap::new(); + m.insert("val".into(), AttributeValue::S(v.into())); + AttributeValue::M(m) + }; + assert_list(&result, "lom", &[only_val("a0"), only_val("a2")]); +} + +#[test] +fn project_same_index_merges_subfields() { + let mut item = BTreeMap::new(); + item.insert("pk".into(), AttributeValue::S("p".into())); + let mut m = BTreeMap::new(); + m.insert("a".into(), AttributeValue::S("av".into())); + m.insert("b".into(), AttributeValue::S("bv".into())); + m.insert("c".into(), AttributeValue::S("cv".into())); + item.insert("l".into(), AttributeValue::L(vec![AttributeValue::M(m)])); + + // Two paths selecting the same element merge their subfields. + let result = project("l[0].a, l[0].c", &item, HashMap::new()).unwrap(); + let mut expected = BTreeMap::new(); + expected.insert("a".into(), AttributeValue::S("av".into())); + expected.insert("c".into(), AttributeValue::S("cv".into())); + assert_list(&result, "l", &[AttributeValue::M(expected)]); +} + +fn check_overlap(expr: &str, names: HashMap) -> Result<(), DynamoDbError> { + let tokens = tokenize(expr).unwrap(); + let paths = parse_projection(&tokens).unwrap(); + let maps = ExpressionMaps::new(names, HashMap::new()); + Projection::compile(&paths, &maps, true).map(|_| ()) +} + +#[test] +fn compile_without_overlap_rejection_accepts_duplicates() { + // Desugared AttributesToGet keeps the legacy accept-duplicates behavior. + let tokens = tokenize("a, a").unwrap(); + let paths = parse_projection(&tokens).unwrap(); + let maps = ExpressionMaps::new(HashMap::new(), HashMap::new()); + assert!(Projection::compile(&paths, &maps, false).is_ok()); +} + +#[test] +fn compiled_projection_reusable_across_items() { + let tokens = tokenize("name").unwrap(); + let paths = parse_projection(&tokens).unwrap(); + let maps = ExpressionMaps::new(HashMap::new(), HashMap::new()); + let proj = Projection::compile(&paths, &maps, true).unwrap(); + let item = sample_item(); + for _ in 0..2 { + let out = proj.apply(&item); + assert_eq!(out.len(), 1); + assert!(out.contains_key("name")); + } +} + +fn overlap_msg(expr: &str) -> String { + match check_overlap(expr, HashMap::new()) { + Err(DynamoDbError::ValidationException(m)) => m, + other => panic!("expected ValidationException, got {other:?}"), + } +} + +#[test] +fn overlap_parent_then_child() { + assert_eq!( + overlap_msg("a, a.b"), + "Invalid ProjectionExpression: Two document paths overlap with each other; \ + must remove or rewrite one of these paths; path one: [a], path two: [a, b]" + ); +} + +#[test] +fn overlap_child_then_parent() { + assert_eq!( + overlap_msg("a.b, a"), + "Invalid ProjectionExpression: Two document paths overlap with each other; \ + must remove or rewrite one of these paths; path one: [a, b], path two: [a]" + ); +} + +#[test] +fn overlap_exact_duplicate() { + assert_eq!( + overlap_msg("a, a"), + "Invalid ProjectionExpression: Two document paths overlap with each other; \ + must remove or rewrite one of these paths; path one: [a], path two: [a]" + ); +} + +#[test] +fn overlap_index_path_rendering() { + assert_eq!( + overlap_msg("a[0], a"), + "Invalid ProjectionExpression: Two document paths overlap with each other; \ + must remove or rewrite one of these paths; path one: [a, [0]], path two: [a]" + ); + assert_eq!( + overlap_msg("a[0].b, a[0]"), + "Invalid ProjectionExpression: Two document paths overlap with each other; \ + must remove or rewrite one of these paths; path one: [a, [0], b], path two: [a, [0]]" + ); +} + +#[test] +fn overlap_reports_first_pair_in_order() { + assert_eq!( + overlap_msg("x, a.b, a"), + "Invalid ProjectionExpression: Two document paths overlap with each other; \ + must remove or rewrite one of these paths; path one: [a, b], path two: [a]" + ); +} + +#[test] +fn overlap_uses_resolved_names() { + let mut names = HashMap::new(); + names.insert("p".into(), "a".into()); + names.insert("q".into(), "b".into()); + match check_overlap("#p, #p.#q", names) { + Err(DynamoDbError::ValidationException(m)) => assert_eq!( + m, + "Invalid ProjectionExpression: Two document paths overlap with each other; \ + must remove or rewrite one of these paths; path one: [a], path two: [a, b]" + ), + other => panic!("expected ValidationException, got {other:?}"), + } +} + +#[test] +fn no_overlap_for_siblings() { + assert!(check_overlap("a.b, a.c", HashMap::new()).is_ok()); + assert!(check_overlap("a[0], a[1]", HashMap::new()).is_ok()); + assert!(check_overlap("a, b, c", HashMap::new()).is_ok()); +} + +#[test] +fn project_list_index_into_map_preserves_structure() { + let mut item = BTreeMap::new(); + item.insert("pk".into(), AttributeValue::S("p".into())); + let mut map0 = BTreeMap::new(); + map0.insert("val".into(), AttributeValue::S("target".into())); + map0.insert("x".into(), AttributeValue::S("0".into())); + let mut map1 = BTreeMap::new(); + map1.insert("x".into(), AttributeValue::S("0".into())); + item.insert( + "a_list".into(), + AttributeValue::L(vec![AttributeValue::M(map0), AttributeValue::M(map1)]), + ); + + let result = project("a_list[0].val", &item, HashMap::new()).unwrap(); + // Should preserve: {"a_list": [{"val": "target"}]} + match result.get("a_list") { + Some(AttributeValue::L(list)) => { + assert_eq!(list.len(), 1); + match &list[0] { + AttributeValue::M(m) => { + assert_eq!(m.get("val"), Some(&AttributeValue::S("target".into()))); + assert!(!m.contains_key("x")); + } + other => panic!("Expected M, got {other:?}"), + } + } + other => panic!("Expected L, got {other:?}"), + } +} + +// Syntax error wording measured 2026-10-25 (us-east-1) on GetItem. + +fn proj_msg(src: &str) -> String { + match parse_projection_from(&tokenize(src).unwrap(), src) { + Err(DynamoDbError::ValidationException(m)) => m, + other => panic!("expected ValidationException, got {other:?}"), + } +} + +#[test] +fn doubled_comma_quotes_the_source_window() { + // [d27] `#v, , #v` + assert_eq!( + proj_msg("#v, , #v"), + "Invalid ProjectionExpression: Syntax error; token: \",\", near: \", , #v\"" + ); +} + +#[test] +fn trailing_comma_is_eof_with_the_comma_as_window() { + // [d28] `#v,` + assert_eq!( + proj_msg("#v,"), + "Invalid ProjectionExpression: Syntax error; token: \"\", near: \",\"" + ); +} + +#[test] +fn other_projection_texts_are_unchanged() { + assert_eq!( + proj_msg("#v #w"), + "Invalid ProjectionExpression: unexpected token at position 1" + ); + assert_eq!(proj_msg("#v, )"), "Invalid expression: expected attribute name"); +} From fc0726063067461345a362a8a059633a81f05cb6 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:39:42 +0000 Subject: [PATCH 04/37] style(expression): apply rustfmt to the new expression code --- .../src/expression/key_condition_tests.rs | 10 +++- crates/core/src/expression/operator_count.rs | 48 +++++++++++++--- crates/core/src/expression/projection.rs | 16 ++++-- .../core/src/expression/projection_tests.rs | 5 +- crates/core/src/expression/syntax_error.rs | 14 ++++- crates/core/src/expression/update_parser.rs | 4 +- crates/engine/src/expression_helpers.rs | 55 +++++++++++++------ 7 files changed, 115 insertions(+), 37 deletions(-) diff --git a/crates/core/src/expression/key_condition_tests.rs b/crates/core/src/expression/key_condition_tests.rs index a39483dd7..968306974 100644 --- a/crates/core/src/expression/key_condition_tests.rs +++ b/crates/core/src/expression/key_condition_tests.rs @@ -925,7 +925,10 @@ fn repeated_operator_quotes_the_source_window() { kce_msg("pk = = :v"), "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :v\"" ); - assert_eq!(kce_msg("pk = :v AND sk = = :s"), "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :s\""); + assert_eq!( + kce_msg("pk = :v AND sk = = :s"), + "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \"= = :s\"" + ); } #[test] @@ -935,7 +938,10 @@ fn trailing_keyword_is_eof_with_the_keyword_as_window() { kce_msg("pk = :v AND"), "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"AND\"" ); - assert_eq!(kce_msg("pk ="), "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"=\""); + assert_eq!( + kce_msg("pk ="), + "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"=\"" + ); } #[test] diff --git a/crates/core/src/expression/operator_count.rs b/crates/core/src/expression/operator_count.rs index ef3f4ba45..a0548d11d 100644 --- a/crates/core/src/expression/operator_count.rs +++ b/crates/core/src/expression/operator_count.rs @@ -79,7 +79,13 @@ mod tests { assert_eq!(count(&chain("#v = :v", 300, " OR ")), 599); // [a02] assert_eq!(count(&chain("#v <> :v", 300, " OR ")), 599); // [a05] assert_eq!(count(&chain("#v >= :v", 300, " AND ")), 599); // [a09, a03] - assert_eq!(count(&format!("attribute_not_exists(pk) OR {}", chain("#v = :v", 300, " OR "))), 601); // [a01] + assert_eq!( + count(&format!( + "attribute_not_exists(pk) OR {}", + chain("#v = :v", 300, " OR ") + )), + 601 + ); // [a01] } #[test] @@ -92,31 +98,57 @@ mod tests { assert_eq!(count(&chain("attribute_exists(#v)", 170, " OR ")), 339); // [a43] assert_eq!(count(&chain("contains(#v, :v)", 200, " OR ")), 399); // [a45] assert_eq!(count(&chain("size(#v) = :v", 230, " OR ")), 689); // [a47] - assert_eq!(count(&chain("size(#v) BETWEEN :v AND :v", 130, " OR ")), 389); // [a53] + assert_eq!( + count(&chain("size(#v) BETWEEN :v AND :v", 130, " OR ")), + 389 + ); // [a53] } #[test] fn parentheses_count_zero() { assert_eq!(count(&chain("(#v = :v)", 300, " OR ")), 599); // [a19] assert_eq!(count(&chain("((#v = :v) OR (#v = :v))", 140, " OR ")), 559); // [a51] - assert_eq!(count(&format!("attribute_exists(pk) AND ({})", chain("#v = :v", 300, " OR "))), 601); // [a04] - assert_eq!(count(&format!("attribute_exists(pk) AND NOT ({})", chain("#v = :v", 150, " OR "))), 302); // [a52] + assert_eq!( + count(&format!( + "attribute_exists(pk) AND ({})", + chain("#v = :v", 300, " OR ") + )), + 601 + ); // [a04] + assert_eq!( + count(&format!( + "attribute_exists(pk) AND NOT ({})", + chain("#v = :v", 150, " OR ") + )), + 302 + ); // [a52] } #[test] fn cap_is_exclusive_at_300() { let kind = ExpressionKind::Condition; - let at_cap = format!("NOT attribute_not_exists(pk) OR {}", chain("#v = :v", 149, " OR ")); // [a49] + let at_cap = format!( + "NOT attribute_not_exists(pk) OR {}", + chain("#v = :v", 149, " OR ") + ); // [a49] assert_eq!(count(&at_cap), 300); - assert!(validate_operator_count(&parse_condition(&tokenize(&at_cap).unwrap()).unwrap(), kind).is_ok()); + assert!( + validate_operator_count(&parse_condition(&tokenize(&at_cap).unwrap()).unwrap(), kind) + .is_ok() + ); let over = chain("#v = :v", 151, " OR "); // [a30] - let err = validate_operator_count(&parse_condition(&tokenize(&over).unwrap()).unwrap(), kind).unwrap_err(); + let err = + validate_operator_count(&parse_condition(&tokenize(&over).unwrap()).unwrap(), kind) + .unwrap_err(); assert!(matches!(err, DynamoDbError::ValidationException(m) if m == "Invalid ConditionExpression: The expression contains too many operators; operator count: 301")); let under = chain("#v = :v", 150, " OR "); // [a30] - assert!(validate_operator_count(&parse_condition(&tokenize(&under).unwrap()).unwrap(), kind).is_ok()); + assert!( + validate_operator_count(&parse_condition(&tokenize(&under).unwrap()).unwrap(), kind) + .is_ok() + ); } #[test] diff --git a/crates/core/src/expression/projection.rs b/crates/core/src/expression/projection.rs index 5b0e8a9bc..5cc9838a1 100755 --- a/crates/core/src/expression/projection.rs +++ b/crates/core/src/expression/projection.rs @@ -65,10 +65,18 @@ fn parse_projection_path( pos: &mut usize, ) -> Result, DynamoDbError> { match tokens.get(*pos) { - None | Some(Token::Comma) => Err(syntax_error(ExpressionKind::Projection, source, tokens, *pos)), - Some(token) if is_operator_or_keyword(token) => { - Err(syntax_error(ExpressionKind::Projection, source, tokens, *pos)) - } + None | Some(Token::Comma) => Err(syntax_error( + ExpressionKind::Projection, + source, + tokens, + *pos, + )), + Some(token) if is_operator_or_keyword(token) => Err(syntax_error( + ExpressionKind::Projection, + source, + tokens, + *pos, + )), Some(_) => super::parser_common::parse_path(tokens, pos), } } diff --git a/crates/core/src/expression/projection_tests.rs b/crates/core/src/expression/projection_tests.rs index a4a218d37..c347c9cb9 100644 --- a/crates/core/src/expression/projection_tests.rs +++ b/crates/core/src/expression/projection_tests.rs @@ -456,5 +456,8 @@ fn other_projection_texts_are_unchanged() { proj_msg("#v #w"), "Invalid ProjectionExpression: unexpected token at position 1" ); - assert_eq!(proj_msg("#v, )"), "Invalid expression: expected attribute name"); + assert_eq!( + proj_msg("#v, )"), + "Invalid expression: expected attribute name" + ); } diff --git a/crates/core/src/expression/syntax_error.rs b/crates/core/src/expression/syntax_error.rs index 0db63fd9b..d24edb24a 100644 --- a/crates/core/src/expression/syntax_error.rs +++ b/crates/core/src/expression/syntax_error.rs @@ -120,7 +120,9 @@ pub fn syntax_error( tokens: &[Token], pos: usize, ) -> DynamoDbError { - let token = tokens.get(pos).map_or_else(|| "".to_owned(), token_text); + let token = tokens + .get(pos) + .map_or_else(|| "".to_owned(), token_text); let near = near_window(source, tokens, pos); DynamoDbError::ValidationException(format!( "Invalid {kind}: Syntax error; token: \"{token}\", near: \"{near}\"" @@ -216,7 +218,10 @@ mod tests { msg(ExpressionKind::Condition, "#v = :v AND AND #v = :v", 4), "Invalid ConditionExpression: Syntax error; token: \"AND\", near: \"AND AND #v\"" ); - assert!(msg(ExpressionKind::Condition, "#v = :v and and #v", 4).ends_with("near: \"and and #v\"")); + assert!( + msg(ExpressionKind::Condition, "#v = :v and and #v", 4) + .ends_with("near: \"and and #v\"") + ); } #[test] @@ -227,6 +232,9 @@ mod tests { else { panic!() }; - assert_eq!(m, "Invalid FilterExpression: Syntax error; token: \"=\", near: \"= = :v\""); + assert_eq!( + m, + "Invalid FilterExpression: Syntax error; token: \"=\", near: \"= = :v\"" + ); } } diff --git a/crates/core/src/expression/update_parser.rs b/crates/core/src/expression/update_parser.rs index da3a9ac66..333e9302b 100755 --- a/crates/core/src/expression/update_parser.rs +++ b/crates/core/src/expression/update_parser.rs @@ -96,9 +96,7 @@ fn parse_action_path( ) -> Result, DynamoDbError> { match tokens.get(*pos) { None => Err(syntax_error(KIND, src, tokens, *pos)), - Some(token) if is_operator_or_keyword(token) => { - Err(syntax_error(KIND, src, tokens, *pos)) - } + Some(token) if is_operator_or_keyword(token) => Err(syntax_error(KIND, src, tokens, *pos)), _ => parser_common::parse_path(tokens, pos), } } diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 8d03f18e3..571dc849c 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -448,9 +448,13 @@ mod tests { fn count_over_the_cap_is_refused_with_the_full_count() { let limits = LimitsConfig::default(); // 151 comparisons and 150 ORs: 301 [a30]. - let err = resolve_condition(Some(&chain(151)), None, None, None, None, &limits).unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid ConditionExpression: The expression contains too many operators; operator count: 301"), "got {err:?}"); + let err = + resolve_condition(Some(&chain(151)), None, None, None, None, &limits).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid ConditionExpression: The expression contains too many operators; operator count: 301"), + "got {err:?}" + ); // 150 comparisons and 149 ORs: 299, accepted [a30]. assert!(resolve_condition(Some(&chain(150)), None, None, None, None, &limits).is_ok()); } @@ -463,9 +467,13 @@ mod tests { let mut values = HashMap::new(); values.insert(":v".to_owned(), AttributeValue::S("x".to_owned())); values.insert(":b".to_owned(), AttributeValue::Bool(true)); - let err = resolve_condition(Some(&expr), None, Some(&values), None, None, &limits).unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg.contains("Incorrect operand type for operator or function; operator or function: <, operand type: BOOL")), "got {err:?}"); + let err = + resolve_condition(Some(&expr), None, Some(&values), None, None, &limits).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg.contains("Incorrect operand type for operator or function; operator or function: <, operand type: BOOL")), + "got {err:?}" + ); } #[test] @@ -474,8 +482,11 @@ mod tests { let limits = LimitsConfig::default(); let expr = format!("{} = =", chain(300)); let err = resolve_condition(Some(&expr), None, None, None, None, &limits).unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid ConditionExpression: Syntax error; token: \"=\", near: \":v = =\""), "got {err:?}"); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid ConditionExpression: Syntax error; token: \"=\", near: \":v = =\""), + "got {err:?}" + ); } #[test] @@ -484,16 +495,25 @@ mod tests { // [a62] `pk = :v OR` + 150 terms: 301, the count, not the OR refusal. let expr = format!("pk = :v OR {}", vec!["#v = :v"; 150].join(" AND ")); let err = parse_key_condition_expr(&expr, &limits).unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid KeyConditionExpression: The expression contains too many operators; operator count: 301"), "got {err:?}"); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid KeyConditionExpression: The expression contains too many operators; operator count: 301"), + "got {err:?}" + ); // [a63] two conditions joined by OR under the cap: the key grammar answers. let err = parse_key_condition_expr("pk = :v OR sk = :s", &limits).unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid KeyConditionExpression: only AND is supported between key conditions"), "got {err:?}"); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid KeyConditionExpression: only AND is supported between key conditions"), + "got {err:?}" + ); // [d23] a syntax error is reported by the key grammar in the service's words. let err = parse_key_condition_expr("pk = :v AND", &limits).unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"AND\""), "got {err:?}"); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"AND\""), + "got {err:?}" + ); } #[test] @@ -501,7 +521,10 @@ mod tests { // [d27] let limits = LimitsConfig::default(); let err = parse_projection_expr("#v, , #v", &limits).unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid ProjectionExpression: Syntax error; token: \",\", near: \", , #v\""), "got {err:?}"); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid ProjectionExpression: Syntax error; token: \",\", near: \", , #v\""), + "got {err:?}" + ); } } From cb42fc1769fde5a7d608fe74cf721f3f4c7f6429 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:39:43 +0000 Subject: [PATCH 05/37] fix(expression): show a keyword as written in a syntax error, and leave legacy filters out of the operator count A syntax error at a lower-case keyword names the token as the client wrote it: "#v = :v and and #v = :v" answers token "and", not "AND", on FilterExpression, ConditionExpression and KeyConditionExpression (measured 2026-10-25). The token is now taken from the source text, as the window already was. Scan and Query counted the expression they build from a legacy ScanFilter or QueryFilter, so 151 or more legacy conditions were refused as too many operators. The service accepts 160 conditions in ScanFilter, QueryFilter and Expected (measured 2026-10-25). The count now applies to a FilterExpression only; Expected was not counted before this change. --- .../src/expression/key_condition_tests.rs | 25 +++++- crates/core/src/expression/syntax_error.rs | 28 +++++-- crates/engine/src/query.rs | 8 +- crates/engine/src/scan.rs | 7 +- tests/test_expression_operator_limits.py | 13 +++ tests/test_legacy_filter_operator_count.py | 84 +++++++++++++++++++ 6 files changed, 148 insertions(+), 17 deletions(-) create mode 100644 tests/test_legacy_filter_operator_count.py diff --git a/crates/core/src/expression/key_condition_tests.rs b/crates/core/src/expression/key_condition_tests.rs index 968306974..fac335046 100644 --- a/crates/core/src/expression/key_condition_tests.rs +++ b/crates/core/src/expression/key_condition_tests.rs @@ -395,7 +395,8 @@ fn clause_operands_name_every_single_operand_clause() { } /// The same syntax errors and unsupported constructs `parse_key_condition` -/// rejects before classification. +/// rejects before classification, with the same error: both read the clauses +/// through one parser. #[test] fn clause_operands_reject_what_the_parser_rejects() { for expr in [ @@ -409,9 +410,16 @@ fn clause_operands_reject_what_the_parser_rejects() { let Ok(tokens) = tokenize(expr) else { continue; }; - assert!( - key_condition_clause_operands(&tokens).is_err(), - "expr {expr} should be rejected" + let Err(operands_err) = key_condition_clause_operands(&tokens) else { + panic!("expr {expr} should be rejected"); + }; + let Err(parser_err) = parse_key_condition(&tokens) else { + panic!("expr {expr} should be rejected by parse_key_condition"); + }; + assert_eq!( + format!("{operands_err:?}"), + format!("{parser_err:?}"), + "expr {expr}" ); } } @@ -931,6 +939,15 @@ fn repeated_operator_quotes_the_source_window() { ); } +#[test] +fn a_lower_case_keyword_is_shown_as_written() { + // Measured 2026-10-25: the token and the window are the source text. + assert_eq!( + kce_msg("pk = :p and and sk = :s"), + "Invalid KeyConditionExpression: Syntax error; token: \"and\", near: \"and and sk\"" + ); +} + #[test] fn trailing_keyword_is_eof_with_the_keyword_as_window() { // [d23] `pk = :v AND` diff --git a/crates/core/src/expression/syntax_error.rs b/crates/core/src/expression/syntax_error.rs index d24edb24a..9b5d4e303 100644 --- a/crates/core/src/expression/syntax_error.rs +++ b/crates/core/src/expression/syntax_error.rs @@ -20,7 +20,8 @@ use super::kind::ExpressionKind; use super::tokenizer::Token; use crate::error::DynamoDbError; -/// The text a token is shown as in a syntax error. +/// The text a token is shown as in a syntax error when the source it came +/// from is not available. With a source, the token is shown as written. #[must_use] pub fn token_text(token: &Token) -> String { match token { @@ -120,9 +121,17 @@ pub fn syntax_error( tokens: &[Token], pos: usize, ) -> DynamoDbError { - let token = tokens - .get(pos) - .map_or_else(|| "".to_owned(), token_text); + // The token is shown as the client wrote it: a lower-case `and` answers + // `token: "and"` (measured 2026-10-25 on FilterExpression, + // ConditionExpression and KeyConditionExpression). + let spans = (!source.is_empty()) + .then(|| token_spans(source, tokens)) + .flatten(); + let token = match (tokens.get(pos), &spans) { + (None, _) => "".to_owned(), + (Some(_), Some(spans)) => source[spans[pos].clone()].to_owned(), + (Some(t), None) => token_text(t), + }; let near = near_window(source, tokens, pos); DynamoDbError::ValidationException(format!( "Invalid {kind}: Syntax error; token: \"{token}\", near: \"{near}\"" @@ -212,15 +221,16 @@ mod tests { } #[test] - fn keyword_tokens_show_upper_case_and_match_their_source_length() { - // [d07] doubled AND; a lower-case keyword still lines up with the source. + fn keyword_tokens_show_the_source_text() { + // [d07] doubled AND; H501-1 s01, s30, k07: a lower-case keyword is + // shown as written, in the token and in the window. assert_eq!( msg(ExpressionKind::Condition, "#v = :v AND AND #v = :v", 4), "Invalid ConditionExpression: Syntax error; token: \"AND\", near: \"AND AND #v\"" ); - assert!( - msg(ExpressionKind::Condition, "#v = :v and and #v", 4) - .ends_with("near: \"and and #v\"") + assert_eq!( + msg(ExpressionKind::Filter, "#v = :v and and #v = :v", 4), + "Invalid FilterExpression: Syntax error; token: \"and\", near: \"and and #v\"" ); } diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 14be83efe..efe7d6843 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -359,8 +359,12 @@ pub async fn handle_query( let names = input.expression_attribute_names.as_ref(); validate_name_refs_in_expr(filter_expr, names, ExpressionKind::Filter)?; // The operator cap follows the undefined name check and precedes the - // unused placeholder check (measured 2026-10-25). - crate::expression_helpers::check_operator_count(filter_expr, ExpressionKind::Filter)?; + // unused placeholder check (measured 2026-10-25). It applies to a + // FilterExpression only: a legacy QueryFilter of 160 conditions is + // accepted (measured 2026-10-25). + if filter_maps.is_none() { + crate::expression_helpers::check_operator_count(filter_expr, ExpressionKind::Filter)?; + } } // Parse ProjectionExpression or desugar legacy AttributesToGet diff --git a/crates/engine/src/scan.rs b/crates/engine/src/scan.rs index bf95f309d..4b413b9a5 100755 --- a/crates/engine/src/scan.rs +++ b/crates/engine/src/scan.rs @@ -141,8 +141,11 @@ pub async fn handle_scan( // The operator cap runs before the unused placeholder check and the table // lookup (measured 2026-10-25: the count beats an unused value, a missing - // table and an unknown IndexName). - if let Some(ref f) = filter { + // table and an unknown IndexName). It applies to a FilterExpression only: + // a legacy ScanFilter of 160 conditions is accepted (measured 2026-10-25). + if filter_maps.is_none() + && let Some(ref f) = filter + { crate::expression_helpers::check_operator_count(f, ExpressionKind::Filter)?; } diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index f4129f5a4..db89fed88 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -503,6 +503,7 @@ class TestSyntaxErrorWording: ("d19", "#v = :v AND NOT", "", "NOT"), ("d29", "=", "=", "="), ("d30", "= =", "=", "= ="), + ("H501-1 s30", "#v = :v and and #v = :v", "and", "and and #v"), ], ) def test_put_item_condition(self, dynamodb_client, table, case, expr, token, near): @@ -530,6 +531,10 @@ def test_scan_filter(self, dynamodb_client, table): assert _validation(scan(dynamodb_client, table, "#v = :v AND")) == syntax( "FilterExpression", "", "AND" ) + # [H501-1 s01]: a lower-case keyword is shown as written. + assert _validation(scan(dynamodb_client, table, "#v = :v and and #v = :v")) == syntax( + "FilterExpression", "and", "and and #v" + ) def test_query_key_condition(self, dynamodb_client, table): # [d22], [d23] @@ -539,6 +544,14 @@ def test_query_key_condition(self, dynamodb_client, table): assert _validation(query(dynamodb_client, table, "pk = :v AND")) == syntax( "KeyConditionExpression", "", "AND" ) + # [H501-1 k07] + lower = query( + dynamodb_client, + table, + "pk = :p and and sk = :s", + ExpressionAttributeValues={":p": {"S": "p1"}, ":s": {"S": "a"}, ":v": {"S": "x"}}, + ) + assert _validation(lower) == syntax("KeyConditionExpression", "and", "and and sk") @pytest.mark.parametrize( "case, expr, token, near", diff --git a/tests/test_legacy_filter_operator_count.py b/tests/test_legacy_filter_operator_count.py new file mode 100644 index 000000000..86303fc3a --- /dev/null +++ b/tests/test_legacy_filter_operator_count.py @@ -0,0 +1,84 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""The 300-operator cap does not apply to the legacy condition parameters. + +ScanFilter, QueryFilter and Expected are not expressions, and Amazon DynamoDB +accepts 160 conditions in each: a Scan with a 160-condition ScanFilter and a +Query with a 160-condition QueryFilter return normally, and a PutItem with a +160-condition Expected is evaluated (measured 2026-10-25 in us-east-1, each +request twice). ExtendDB desugars these parameters into expressions, which +must not be counted. + +Dual-target against Amazon DynamoDB and extenddb. +""" + +from __future__ import annotations + +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table + +CONDITIONS = 160 + + +def _eq_conditions(n: int) -> dict: + return { + f"a{i}": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "x"}]} + for i in range(n) + } + + +@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: + dynamodb_client.put_item( + TableName=name, + Item={"pk": {"S": "p1"}, "sk": {"S": "s1"}, "v": {"S": "x"}}, + ) + yield name + + +def test_scan_filter_with_160_conditions_is_not_counted(dynamodb_client, table): + # H501-1 n16: OK, Count 0, ScannedCount 1. + out = dynamodb_client.scan( + TableName=table, Limit=1, ScanFilter=_eq_conditions(CONDITIONS) + ) + assert out["Count"] == 0 + assert out["ScannedCount"] == 1 + + +def test_query_filter_with_160_conditions_is_not_counted(dynamodb_client, table): + # H501-1 n18: OK, Count 0. + out = dynamodb_client.query( + TableName=table, + Limit=1, + KeyConditions={ + "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "p1"}]} + }, + QueryFilter=_eq_conditions(CONDITIONS), + ) + assert out["Count"] == 0 + + +def test_expected_with_160_conditions_is_evaluated(dynamodb_client, table): + # H501-1 n19: ConditionalCheckFailedException, the item has none of the + # compared attributes. + with pytest.raises(ClientError) as exc_info: + dynamodb_client.put_item( + TableName=table, + Item={"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + Expected={f"a{i}": {"Value": {"S": "x"}} for i in range(CONDITIONS)}, + ) + assert exc_info.value.response["Error"]["Code"] == "ConditionalCheckFailedException" From 3eaa074e714c10c6c6e7d4efcdfab4a5a5264878 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:39:43 +0000 Subject: [PATCH 06/37] test(expression): cite the measurement date on the rows added for the keyword text and the legacy count --- crates/core/src/expression/syntax_error.rs | 2 +- tests/test_expression_operator_limits.py | 6 +++--- tests/test_legacy_filter_operator_count.py | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/core/src/expression/syntax_error.rs b/crates/core/src/expression/syntax_error.rs index 9b5d4e303..e35c03279 100644 --- a/crates/core/src/expression/syntax_error.rs +++ b/crates/core/src/expression/syntax_error.rs @@ -222,7 +222,7 @@ mod tests { #[test] fn keyword_tokens_show_the_source_text() { - // [d07] doubled AND; H501-1 s01, s30, k07: a lower-case keyword is + // [d07] doubled AND; a lower-case keyword (measured 2026-10-25) is // shown as written, in the token and in the window. assert_eq!( msg(ExpressionKind::Condition, "#v = :v AND AND #v = :v", 4), diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index db89fed88..9812fe4dc 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -503,7 +503,7 @@ class TestSyntaxErrorWording: ("d19", "#v = :v AND NOT", "", "NOT"), ("d29", "=", "=", "="), ("d30", "= =", "=", "= ="), - ("H501-1 s30", "#v = :v and and #v = :v", "and", "and and #v"), + ("lower-case and", "#v = :v and and #v = :v", "and", "and and #v"), ], ) def test_put_item_condition(self, dynamodb_client, table, case, expr, token, near): @@ -531,7 +531,7 @@ def test_scan_filter(self, dynamodb_client, table): assert _validation(scan(dynamodb_client, table, "#v = :v AND")) == syntax( "FilterExpression", "", "AND" ) - # [H501-1 s01]: a lower-case keyword is shown as written. + # Measured 2026-10-25: a lower-case keyword is shown as written. assert _validation(scan(dynamodb_client, table, "#v = :v and and #v = :v")) == syntax( "FilterExpression", "and", "and and #v" ) @@ -544,7 +544,7 @@ def test_query_key_condition(self, dynamodb_client, table): assert _validation(query(dynamodb_client, table, "pk = :v AND")) == syntax( "KeyConditionExpression", "", "AND" ) - # [H501-1 k07] + # Measured 2026-10-25: a lower-case keyword in a key condition. lower = query( dynamodb_client, table, diff --git a/tests/test_legacy_filter_operator_count.py b/tests/test_legacy_filter_operator_count.py index 86303fc3a..c42ab0a34 100644 --- a/tests/test_legacy_filter_operator_count.py +++ b/tests/test_legacy_filter_operator_count.py @@ -51,7 +51,7 @@ def table(dynamodb_client): def test_scan_filter_with_160_conditions_is_not_counted(dynamodb_client, table): - # H501-1 n16: OK, Count 0, ScannedCount 1. + # Measured 2026-10-25: OK, Count 0, ScannedCount 1. out = dynamodb_client.scan( TableName=table, Limit=1, ScanFilter=_eq_conditions(CONDITIONS) ) @@ -60,7 +60,7 @@ def test_scan_filter_with_160_conditions_is_not_counted(dynamodb_client, table): def test_query_filter_with_160_conditions_is_not_counted(dynamodb_client, table): - # H501-1 n18: OK, Count 0. + # Measured 2026-10-25: OK, Count 0. out = dynamodb_client.query( TableName=table, Limit=1, @@ -73,7 +73,7 @@ def test_query_filter_with_160_conditions_is_not_counted(dynamodb_client, table) def test_expected_with_160_conditions_is_evaluated(dynamodb_client, table): - # H501-1 n19: ConditionalCheckFailedException, the item has none of the + # Measured 2026-10-25: ConditionalCheckFailedException, the item has none of the # compared attributes. with pytest.raises(ClientError) as exc_info: dynamodb_client.put_item( From f560eb9bf41ee609c2a0fd755d2cd6b5e1bec9a5 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:39:43 +0000 Subject: [PATCH 07/37] test(expression): split the UpdateItem cap row and mark the evaluated case as failing on MongoDB On MongoDB, a 300-operator UpdateItem condition answers InternalServerError: the MongoDB filter compiler nests one level per OR or AND, and a chain of 150 terms fails inside MongoDB. The compiler is not changed here. The refusal above the cap stays an unconditional test; the evaluation at the cap is now a test of its own with a strict expected failure on MongoDB. --- tests/test_expression_operator_limits.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index 9812fe4dc..f0cad2192 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -29,6 +29,8 @@ from __future__ import annotations +import os + import pytest from botocore.exceptions import ClientError @@ -38,6 +40,18 @@ TOO_MANY = "The expression contains too many operators; operator count: " +# On MongoDB an UpdateItem condition is compiled to a filter whose OR and AND +# chains nest one level per operator, and a chain of 150 terms fails inside +# MongoDB with InternalServerError. This change does not touch that compiler. +# The MongoDB test runner sets EXTENDDB_TEST_MONGODB_CONTAINER. +# TODO: remove this marker once the MongoDB filter compiler flattens chains. +XFAIL_ON_MONGODB_DEEP_OR = pytest.mark.xfail( + bool(os.environ.get("EXTENDDB_TEST_MONGODB_CONTAINER", "").strip()), + reason="MongoDB answers InternalServerError for a condition chain of 150 terms", + raises=AssertionError, + strict=True, +) + def _error(func) -> tuple[str, str]: with pytest.raises(ClientError) as exc_info: @@ -185,6 +199,10 @@ def test_update_item_condition_count(self, dynamodb_client, table): ) ) assert _after_prefix(msg) == f"Invalid ConditionExpression: {TOO_MANY}599" + + @XFAIL_ON_MONGODB_DEEP_OR + def test_update_item_condition_at_the_cap_is_evaluated(self, dynamodb_client, table): + # [u03] 300 accepted (condition evaluated). code, _ = _error( lambda: dynamodb_client.update_item( TableName=table, From 077d435d29634ef33dfafd9a50d5a3489b2bb7b4 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:39:43 +0000 Subject: [PATCH 08/37] fix(expression): keep leading whitespace in the window of a fault at the first token When the faulty token is the first one, the service starts the near window at the start of the expression: ` = #v = :v` answers `near: " = #v"` on FilterExpression, KeyConditionExpression and ProjectionExpression (measured 2026-10-25 at 16:54 UTC, each request twice). The window started at the token. A unit test and a wire test pin the measured rows. --- .../src/expression/key_condition_tests.rs | 9 +++++++ crates/core/src/expression/syntax_error.rs | 21 +++++++++++++--- tests/test_expression_operator_limits.py | 24 +++++++++++++++++++ 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/crates/core/src/expression/key_condition_tests.rs b/crates/core/src/expression/key_condition_tests.rs index fac335046..cbb9308c6 100644 --- a/crates/core/src/expression/key_condition_tests.rs +++ b/crates/core/src/expression/key_condition_tests.rs @@ -971,6 +971,15 @@ fn stripped_outer_parentheses_keep_the_source_window() { ); } +#[test] +fn a_fault_at_the_first_token_keeps_leading_whitespace() { + // Measured 2026-10-25: the window starts at the start of the expression. + assert_eq!( + kce_msg(" = pk = :v"), + "Invalid KeyConditionExpression: Syntax error; token: \"=\", near: \" = pk\"" + ); +} + #[test] fn other_key_condition_texts_are_unchanged() { assert_eq!( diff --git a/crates/core/src/expression/syntax_error.rs b/crates/core/src/expression/syntax_error.rs index e35c03279..2ae935c5f 100644 --- a/crates/core/src/expression/syntax_error.rs +++ b/crates/core/src/expression/syntax_error.rs @@ -139,8 +139,10 @@ pub fn syntax_error( } /// The window of source text around the token at `pos`: from the previous -/// token to the next one, each dropped when absent. At end of input the window -/// is the last token alone. +/// token to the next one, each dropped when absent. When the faulty token is +/// the first one, the window starts at the start of the source, leading +/// whitespace kept (measured 2026-10-25: ` = #v = :v` answers +/// `near: " = #v"`). At end of input the window is the last token alone. fn near_window(source: &str, tokens: &[Token], pos: usize) -> String { if tokens.is_empty() { return String::new(); @@ -154,7 +156,8 @@ fn near_window(source: &str, tokens: &[Token], pos: usize) -> String { .then(|| token_spans(source, tokens)) .flatten() { - return source[spans[first].start..spans[last].end].to_owned(); + let start = if pos == 0 { 0 } else { spans[first].start }; + return source[start..spans[last].end].to_owned(); } tokens[first..=last] .iter() @@ -207,6 +210,18 @@ mod tests { assert!(msg(ExpressionKind::Condition, "= =", 0).ends_with("near: \"= =\"")); } + #[test] + fn a_fault_at_the_first_token_keeps_leading_whitespace() { + // Measured 2026-10-25 on FilterExpression, KeyConditionExpression and + // ProjectionExpression. + assert!(msg(ExpressionKind::Filter, " = #v = :v", 0).ends_with("near: \" = #v\"")); + assert!(msg(ExpressionKind::Filter, "\t= #v = :v", 0).ends_with("near: \"\t= #v\"")); + assert!(msg(ExpressionKind::Filter, " AND #v = :v", 0).ends_with("near: \" AND #v\"")); + assert!(msg(ExpressionKind::KeyCondition, " = pk = :v", 0).ends_with("near: \" = pk\"")); + assert!(msg(ExpressionKind::Projection, " , #v", 0).ends_with("near: \" , #v\"")); + assert!(msg(ExpressionKind::Filter, "= #v = :v", 0).ends_with("near: \"= #v\"")); + } + #[test] fn end_of_input_is_eof_with_the_last_token() { // [d05] trailing AND, [d26] trailing comma on an update. diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index f0cad2192..211f39a8d 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -554,6 +554,30 @@ def test_scan_filter(self, dynamodb_client, table): "FilterExpression", "and", "and and #v" ) + def test_fault_at_the_first_token_keeps_leading_whitespace(self, dynamodb_client, table): + # Measured 2026-10-25: the window starts at the start of the expression. + for expr, token, near in [ + (" = #v = :v", "=", " = #v"), + ("\t= #v = :v", "=", "\t= #v"), + (" AND #v = :v", "AND", " AND #v"), + ("= #v = :v", "=", "= #v"), + ]: + assert _validation(scan(dynamodb_client, table, expr)) == syntax( + "FilterExpression", token, near + ), expr + assert _validation(query(dynamodb_client, table, " = pk = :v")) == syntax( + "KeyConditionExpression", "=", " = pk" + ) + msg = _validation( + lambda: dynamodb_client.get_item( + TableName=table, + Key={"pk": {"S": "p1"}, "sk": {"S": "s1"}}, + ProjectionExpression=" , #v", + ExpressionAttributeNames=NAMES, + ) + ) + assert msg == syntax("ProjectionExpression", ",", " , #v") + def test_query_key_condition(self, dynamodb_client, table): # [d22], [d23] assert _validation(query(dynamodb_client, table, "pk = = :v")) == syntax( From f1578c9f7712471f94c311c834a274b117f26683 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:19:22 +0000 Subject: [PATCH 09/37] fix(scan): check the Limit, Segment and TotalSegments ranges before the filter A Scan with Limit 0 or TotalSegments 0 beside a FilterExpression of more than 300 operators answered the operator count. The service answers the range check, and so did main, which has no count. The range checks now run right after the server reads the request, ahead of the expression checks and the table lookup. Measured 2026-11-19 in us-east-1, each request sent twice with the same answer: - Limit 0 or TotalSegments 0 answers the range check beside a filter syntax error, an undefined value or an operand of the wrong type. The same request also answers the range check beside an operator count of 301, an unused value or a missing table. - A Segment without TotalSegments, or a Segment that is not less than TotalSegments, beside a count of 301 answers the count. The pairing and order checks stay after the count. The service words the range faults as "1 validation error detected: Value at 'Limit' failed to satisfy constraint: ...". This commit leaves the texts as they are. --- crates/engine/src/scan.rs | 93 +++++++++++++++++++++++---------------- 1 file changed, 54 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/scan.rs b/crates/engine/src/scan.rs index fa6681090..21cb07975 100755 --- a/crates/engine/src/scan.rs +++ b/crates/engine/src/scan.rs @@ -68,8 +68,16 @@ pub async fn handle_scan( )?; let input: ScanInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; + // The Limit, Segment and TotalSegments ranges come before the expression + // checks and the table lookup (measured 2026-11-19: `Limit: 0` or + // `TotalSegments: 0` beside a filter syntax error, an undefined value, an + // operand of the wrong type, an operator count over the cap, an unused + // value or a missing table answers the range). The Segment pairing and + // order checks come after the operator count and stay below. + validate_scan_ranges(&input)?; + // Validate Filter/Projection expressions before the existence - // check; index resolution, Segment/Limit/Select and key checks stay after. + // check; index resolution, Segment pairing, Select and key checks stay after. // --- Legacy vs expression mutual exclusivity checks --- let has_fe = input.filter_expression.is_some(); @@ -309,7 +317,9 @@ pub async fn handle_scan( )?; } - // Validate Segment/TotalSegments — DynamoDB returns different messages per direction + // The Segment and TotalSegments pairing and order, after the operator + // count (measured 2026-11-19). The service reports a missing partner with + // a message per direction. The ranges are checked in validate_scan_ranges. match (input.segment, input.total_segments) { (Some(_), None) => { return Err(DynamoDbError::ValidationException( @@ -323,44 +333,13 @@ pub async fn handle_scan( .to_owned(), )); } - (Some(seg), Some(total)) => { - if total < 1 { - return Err(DynamoDbError::ValidationException( - "The parameter TotalSegments should be greater than or equal to 1".to_owned(), - )); - } - if total > 1_000_000 { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value '{total}' at 'totalSegments' failed to satisfy constraint: Member must have value less than or equal to 1000000" - ))); - } - if seg < 0 { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value '{seg}' at 'segment' failed to satisfy constraint: Member must have value greater than or equal to 0" - ))); - } - if seg > 999_999 { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value '{seg}' at 'segment' failed to satisfy constraint: Member must have value less than or equal to 999999" - ))); - } - if seg >= total { - return Err(DynamoDbError::ValidationException(format!( - "The Segment parameter is zero-based and must be less than parameter TotalSegments: \ - Segment: {seg} is not less than TotalSegments: {total}" - ))); - } + (Some(seg), Some(total)) if seg >= total => { + return Err(DynamoDbError::ValidationException(format!( + "The Segment parameter is zero-based and must be less than parameter TotalSegments: \ + Segment: {seg} is not less than TotalSegments: {total}" + ))); } - (None, None) => {} - } - - // Validate Limit >= 1 - if let Some(limit) = input.limit - && limit < 1 - { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value '{limit}' at 'limit' failed to satisfy constraint: Member must have value greater than or equal to 1" - ))); + _ => {} } // For index scans, build a key_info that reflects the index's key schema. @@ -529,3 +508,39 @@ pub async fn handle_scan( }, }) } + +/// Refuse a Limit, Segment or TotalSegments value outside its range. The +/// Segment and TotalSegments ranges are checked when both are present; a +/// missing partner is reported by the pairing check in `handle_scan`. +fn validate_scan_ranges(input: &ScanInput) -> Result<(), DynamoDbError> { + if let (Some(seg), Some(total)) = (input.segment, input.total_segments) { + if total < 1 { + return Err(DynamoDbError::ValidationException( + "The parameter TotalSegments should be greater than or equal to 1".to_owned(), + )); + } + if total > 1_000_000 { + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value '{total}' at 'totalSegments' failed to satisfy constraint: Member must have value less than or equal to 1000000" + ))); + } + if seg < 0 { + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value '{seg}' at 'segment' failed to satisfy constraint: Member must have value greater than or equal to 0" + ))); + } + if seg > 999_999 { + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value '{seg}' at 'segment' failed to satisfy constraint: Member must have value less than or equal to 999999" + ))); + } + } + if let Some(limit) = input.limit + && limit < 1 + { + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value '{limit}' at 'limit' failed to satisfy constraint: Member must have value greater than or equal to 1" + ))); + } + Ok(()) +} From 6865836678c54b2b17bebea33796410ec9c63814 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:22:24 +0000 Subject: [PATCH 10/37] fix(expression): check placeholders and operand types before the operator count The operator count ran ahead of the undefined placeholder check and the operand type checks. A condition or filter over the cap that also held an undefined placeholder or an operand of the wrong type answered the count. The service answers the other fault. The service checks the placeholders and operand types of a condition or filter in one pass, before it counts operators. It reads the expression left to right and reports the first fault. The new `validate_placeholders_and_operands` makes the same pass. It refuses: - a `#name` or `:value` that the request does not define, - a literal of a type that does not order in an ordering comparison or `BETWEEN`, - a `begins_with` prefix that is not a string or binary value. It replaces the ordering check on PutItem, UpdateItem and DeleteItem and the name check on Query. It also replaces the `begins_with` and ordering checks of a FilterExpression on Scan and Query. A legacy ScanFilter or QueryFilter keeps those two checks where they were. Measured 2026-11-19 in us-east-1, each request sent twice with the same answer. With 151 `#v = :v` terms joined by OR: - `OR #v = :zz`, with `:zz` undefined, answers the undefined value on Scan, Query, PutItem, UpdateItem and DeleteItem. - `OR #x = :v` answers the undefined name on Scan, Query and PutItem. - `OR begins_with(#v, :n)`, with `:n` an N, answers the `begins_with` operand type on Scan, Query and PutItem. - With 150 terms, `OR #v < :b`, with `:b` a BOOL, answers the operand type on Scan and Query. - An unused `:u` beside the 151 terms answers the count on Query. The check reads no item, so some answers change without a count. The new answers below match the service: - An undefined value beside an unused value answers the undefined value on Scan, Query and PutItem. - An undefined value on a missing table answers the undefined value on Scan and PutItem. Query still looks up the table first. - On PutItem, `attribute_not_exists(pk) OR #v = :zz` for an absent item answers the undefined value. Before, evaluation skipped `:zz` and wrote the item. - A Query that reads no item answers an undefined value in its filter. - `#v = :zz OR #v < :b` answers the undefined value on Scan, and `:b < #x` answers the undefined name. - On Scan and Query, a filter operand of the wrong type answers ahead of a ProjectionExpression syntax error and an unused value. --- crates/core/src/expression/mod.rs | 2 + crates/core/src/expression/operand_check.rs | 210 ++++++++++++++++++++ crates/core/src/expression/resolver.rs | 16 +- crates/engine/src/expression_helpers.rs | 132 ++++++++---- crates/engine/src/query.rs | 93 ++------- crates/engine/src/scan.rs | 20 +- 6 files changed, 345 insertions(+), 128 deletions(-) create mode 100644 crates/core/src/expression/operand_check.rs diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 74744d63c..5ac6ae6bc 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -15,6 +15,7 @@ mod evaluator; mod key_condition; mod key_condition_resolve; mod kind; +mod operand_check; mod operator_count; mod parser; mod parser_common; @@ -36,6 +37,7 @@ pub use key_condition::{ parse_key_condition, parse_key_condition_from, }; pub use kind::ExpressionKind; +pub use operand_check::validate_placeholders_and_operands; pub use operator_count::{MAX_EXPRESSION_OPERATORS, count_operators, validate_operator_count}; pub use parser::{parse_condition, parse_condition_from, parse_condition_with_depth_limit}; pub use projection::{Projection, parse_projection, parse_projection_from}; diff --git a/crates/core/src/expression/operand_check.rs b/crates/core/src/expression/operand_check.rs new file mode 100644 index 000000000..af9edcc48 --- /dev/null +++ b/crates/core/src/expression/operand_check.rs @@ -0,0 +1,210 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The placeholder and operand type checks Amazon `DynamoDB` runs on a parsed +//! condition or filter before it counts the operators. + +use super::ast::{Expr, PathElement}; +use super::resolver::{ + ExpressionMaps, attribute_type_code, ordering_op_symbol, reject_non_orderable_literal, +}; +use crate::error::DynamoDbError; +use crate::types::AttributeValue; + +/// Check a condition or filter the way Amazon `DynamoDB` checks it before it +/// counts operators: every `#name` and `:value` must be defined, an ordering +/// comparison or `BETWEEN` must not have a literal of a type that does not +/// order, and `begins_with` must have a string or binary prefix. +/// +/// The tree is walked as written, left to right, and the operands of a node +/// are checked before the node, so the first fault in that order is returned. +/// Measured 2026-11-19 (us-east-1) on Scan and PutItem: `#v < :b OR #v = :zz`, +/// with `:b` a BOOL and `:zz` undefined, answers the operand type, `#v = :zz +/// OR #v < :b` answers the undefined value, and `:b < #x` answers the +/// undefined name. The check reads no item, so it also finds a placeholder in +/// a branch that evaluation skips. +/// +/// The messages carry no expression-kind prefix; the caller adds it. +/// +/// # Errors +/// +/// Returns `ValidationException` for the first undefined name or value, or +/// the first operand of a type the operator or function refuses. +pub fn validate_placeholders_and_operands( + expr: &Expr, + maps: &ExpressionMaps, +) -> Result<(), DynamoDbError> { + match expr { + Expr::Path(elements) => { + for element in elements { + if let PathElement::Attribute(name) = element + && let Some(name_ref) = name.strip_prefix('#') + { + maps.resolve_name(name_ref)?; + } + } + Ok(()) + } + Expr::Placeholder(name) => maps.resolve_value(name).map(drop), + Expr::Compare { left, op, right } => { + validate_placeholders_and_operands(left, maps)?; + validate_placeholders_and_operands(right, maps)?; + if let Some(symbol) = ordering_op_symbol(*op) { + reject_non_orderable_literal(left, maps, symbol)?; + reject_non_orderable_literal(right, maps, symbol)?; + } + Ok(()) + } + Expr::Between { operand, low, high } => { + for part in [operand, low, high] { + validate_placeholders_and_operands(part, maps)?; + } + for part in [operand, low, high] { + reject_non_orderable_literal(part, maps, "BETWEEN")?; + } + Ok(()) + } + Expr::Function { name, args } => { + for arg in args { + validate_placeholders_and_operands(arg, maps)?; + } + if name == "begins_with" { + reject_begins_with_prefix(args, maps)?; + } + Ok(()) + } + Expr::And(left, right) | Expr::Or(left, right) | Expr::Arithmetic { left, right, .. } => { + validate_placeholders_and_operands(left, maps)?; + validate_placeholders_and_operands(right, maps) + } + Expr::Not(inner) => validate_placeholders_and_operands(inner, maps), + Expr::In { operand, list } => { + validate_placeholders_and_operands(operand, maps)?; + list.iter() + .try_for_each(|item| validate_placeholders_and_operands(item, maps)) + } + } +} + +/// Reject a `begins_with` call whose prefix is a literal (`:value`) of a type +/// other than S or B. +pub(super) fn reject_begins_with_prefix( + args: &[Expr], + maps: &ExpressionMaps, +) -> Result<(), DynamoDbError> { + if args.len() == 2 + && let Expr::Placeholder(ref placeholder) = args[1] + && let Some(val) = maps.values.get(placeholder) + && !matches!(val, AttributeValue::S(_) | AttributeValue::B(_)) + { + let type_code = attribute_type_code(val); + return Err(DynamoDbError::ValidationException(format!( + "Incorrect operand type for operator or function; operator or function: begins_with, operand type: {type_code}" + ))); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use super::*; + use crate::expression::parser::parse_condition; + use crate::expression::tokenizer::tokenize; + + const UNDEFINED_NAME: &str = + "An expression attribute name used in the document path is not defined; attribute name: "; + const UNDEFINED_VALUE: &str = + "An expression attribute value used in expression is not defined; attribute value: "; + const OPERAND: &str = "Incorrect operand type for operator or function; operator or function: "; + + /// `#v` is defined; `:v` is an S, `:b` a BOOL and `:n` an N. + fn maps() -> ExpressionMaps { + ExpressionMaps::new( + HashMap::from([("v".to_owned(), "v".to_owned())]), + HashMap::from([ + ("v".to_owned(), AttributeValue::S("x".to_owned())), + ("b".to_owned(), AttributeValue::Bool(true)), + ("n".to_owned(), AttributeValue::N("1".to_owned())), + ]), + ) + } + + fn check(src: &str) -> Result<(), String> { + let expr = parse_condition(&tokenize(src).unwrap()).unwrap(); + validate_placeholders_and_operands(&expr, &maps()).map_err(|e| match e { + DynamoDbError::ValidationException(m) => m, + other => panic!("expected ValidationException, got {other:?}"), + }) + } + + #[test] + fn the_first_fault_as_written_is_reported() { + // The service's answers of 2026-11-19 (us-east-1); probe cases in the + // first column. + let rows = [ + ( + "s09", + "#v < :b OR #v = :zz", + format!("{OPERAND}<, operand type: BOOL"), + ), + ( + "s10", + "#v = :zz OR #v < :b", + format!("{UNDEFINED_VALUE}:zz"), + ), + ("s11", "#x = :zz", format!("{UNDEFINED_NAME}#x")), + ("s12", ":zz = #x", format!("{UNDEFINED_VALUE}:zz")), + ( + "s29", + "begins_with(#v, :n) OR #v < :b", + format!("{OPERAND}begins_with, operand type: N"), + ), + ( + "s30", + "#v < :b OR begins_with(#v, :n)", + format!("{OPERAND}<, operand type: BOOL"), + ), + ("w02", ":b < #x", format!("{UNDEFINED_NAME}#x")), + ( + "w03", + "#v BETWEEN :b AND :zz", + format!("{UNDEFINED_VALUE}:zz"), + ), + ("w05", "begins_with(#x, :n)", format!("{UNDEFINED_NAME}#x")), + ("w07", "#x BETWEEN :b AND :v", format!("{UNDEFINED_NAME}#x")), + ("w08", "size(#x) < :b", format!("{UNDEFINED_NAME}#x")), + ("w10", ":b < :zz", format!("{UNDEFINED_VALUE}:zz")), + ( + "p04", + "attribute_not_exists(pk) OR #v = :zz", + format!("{UNDEFINED_VALUE}:zz"), + ), + ( + "f11", + "size(#v) < :b", + format!("{OPERAND}<, operand type: BOOL"), + ), + ]; + for (case, src, want) in rows { + assert_eq!(check(src), Err(want), "{case}: {src}"); + } + } + + #[test] + fn a_name_inside_a_document_path_is_checked() { + assert_eq!(check("#v.#w[0] = :v"), Err(format!("{UNDEFINED_NAME}#w"))); + } + + #[test] + fn defined_placeholders_and_accepted_types_pass() { + for src in [ + "#v = :v AND begins_with(#v, :v) AND #v BETWEEN :v AND :n", + "#v = :b OR #v <> :b OR #v IN (:b, :n) OR contains(#v, :b)", + "NOT attribute_exists(#v) AND size(#v) > :n", + ] { + assert_eq!(check(src), Ok(()), "{src}"); + } + } +} diff --git a/crates/core/src/expression/resolver.rs b/crates/core/src/expression/resolver.rs index 41637b9cd..6ee3f8fb9 100755 --- a/crates/core/src/expression/resolver.rs +++ b/crates/core/src/expression/resolver.rs @@ -507,17 +507,7 @@ pub fn validate_begins_with_operands( ) -> Result<(), DynamoDbError> { match expr { Expr::Function { name, args } if name == "begins_with" => { - if args.len() == 2 - && let Expr::Placeholder(ref placeholder) = args[1] - && let Some(val) = maps.values.get(placeholder) - && !matches!(val, AttributeValue::S(_) | AttributeValue::B(_)) - { - let type_code = attribute_type_code(val); - return Err(DynamoDbError::ValidationException(format!( - "Incorrect operand type for operator or function; operator or function: begins_with, operand type: {type_code}" - ))); - } - Ok(()) + super::operand_check::reject_begins_with_prefix(args, maps) } Expr::And(left, right) | Expr::Or(left, right) => { validate_begins_with_operands(left, maps)?; @@ -587,7 +577,7 @@ pub fn validate_ordering_operand_types( /// The DynamoDB symbol for an ordering operator, or `None` for equality and /// inequality (which accept every operand type). -fn ordering_op_symbol(op: CompareOp) -> Option<&'static str> { +pub(super) fn ordering_op_symbol(op: CompareOp) -> Option<&'static str> { match op { CompareOp::Lt => Some("<"), CompareOp::Le => Some("<="), @@ -599,7 +589,7 @@ fn ordering_op_symbol(op: CompareOp) -> Option<&'static str> { /// Reject a literal (`:value`) operand whose resolved type is not orderable. /// Non-literal operands (document paths, function results) are left to runtime. -fn reject_non_orderable_literal( +pub(super) fn reject_non_orderable_literal( operand: &Expr, maps: &ExpressionMaps, op_label: &str, diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 5188e18ef..db602d923 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -10,7 +10,7 @@ use extenddb_core::expression::{ Expr, ExpressionKind, ExpressionMaps, KeyCondition, PathElement, Token, UpdateAction, parse_condition_from, parse_key_condition_from, parse_projection_from, parse_update_from, tokenize_for, tokenize_with_limit, validate_no_reserved_words, validate_operator_count, - validate_ordering_operand_types, + validate_placeholders_and_operands, }; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{AttributeValue, ConditionalOperator, ExpectedAttributeValue}; @@ -110,6 +110,28 @@ pub fn check_operator_count(expr: &Expr, kind: ExpressionKind) -> Result<(), Dyn validate_operator_count(expr, kind) } +/// Check a parsed condition or filter in the service's order: its placeholders +/// and operand types (see [`validate_placeholders_and_operands`]), then its +/// operator count. Measured 2026-11-19 (us-east-1) on Scan, Query, PutItem, +/// UpdateItem and DeleteItem: with 151 `#v = :v` terms joined by OR, an added +/// `OR #v = :zz` with `:zz` undefined answers the undefined value, `OR #x = +/// :v` the undefined name, `OR #v < :b` with `:b` a BOOL and `OR +/// begins_with(#v, :n)` with `:n` an N the operand type, and an unused `:u` +/// the count. +/// +/// # Errors +/// +/// Returns `DynamoDbError::ValidationException` with the `Invalid :` +/// prefix for the first fault. +pub fn check_parsed_condition( + expr: &Expr, + maps: &ExpressionMaps, + kind: ExpressionKind, +) -> Result<(), DynamoDbError> { + validate_placeholders_and_operands(expr, maps).map_err(|e| prefix_expression_error(e, kind))?; + check_operator_count(expr, kind) +} + /// Tokenize, reserved-word check, and parse an `UpdateExpression`. /// /// Errors carry the `UpdateExpression` prefix, matching Amazon DynamoDB. @@ -220,11 +242,8 @@ pub fn resolve_condition( let maps = build_expression_maps(names, values); let condition = parse_optional_condition(condition_expression, limits)?; if let Some(ref expr) = condition { - validate_ordering_operand_types(expr, &maps) - .map_err(|e| prefix_expression_error(e, ExpressionKind::Condition))?; - // After the operand type check (an ordering operator on a BOOL beats - // the count), before the unused placeholder check and the table lookup. - check_operator_count(expr, ExpressionKind::Condition)?; + // Before the unused placeholder check and the table lookup. + check_parsed_condition(expr, &maps, ExpressionKind::Condition)?; } Ok((condition, maps)) } @@ -444,48 +463,93 @@ mod tests { vec!["#v = :v"; n].join(" OR ") } + /// Resolve `expr` with `#v` defined, `:v` an S, `:b` a BOOL and `:n` an N. + fn resolve(expr: &str) -> Result<(Option, ExpressionMaps), DynamoDbError> { + let names = HashMap::from([("#v".to_owned(), "v".to_owned())]); + let values = HashMap::from([ + (":v".to_owned(), AttributeValue::S("x".to_owned())), + (":b".to_owned(), AttributeValue::Bool(true)), + (":n".to_owned(), AttributeValue::N("1".to_owned())), + ]); + resolve_condition( + Some(expr), + Some(&names), + Some(&values), + None, + None, + &LimitsConfig::default(), + ) + } + + fn resolve_err(expr: &str) -> String { + match resolve(expr) { + Err(DynamoDbError::ValidationException(msg)) => msg, + other => panic!("expected ValidationException, got {other:?}"), + } + } + #[test] fn count_over_the_cap_is_refused_with_the_full_count() { - let limits = LimitsConfig::default(); // 151 comparisons and 150 ORs: 301 [a30]. - let err = - resolve_condition(Some(&chain(151)), None, None, None, None, &limits).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid ConditionExpression: The expression contains too many operators; operator count: 301"), - "got {err:?}" + assert_eq!( + resolve_err(&chain(151)), + "Invalid ConditionExpression: The expression contains too many operators; operator count: 301" ); // 150 comparisons and 149 ORs: 299, accepted [a30]. - assert!(resolve_condition(Some(&chain(150)), None, None, None, None, &limits).is_ok()); + assert!(resolve(&chain(150)).is_ok()); } #[test] - fn ordering_operand_type_beats_the_count() { - // [p17] 299 operators plus `#v < :b` with a BOOL value. - let limits = LimitsConfig::default(); - let expr = format!("{} OR #v < :b", chain(150)); - let mut values = HashMap::new(); - values.insert(":v".to_owned(), AttributeValue::S("x".to_owned())); - values.insert(":b".to_owned(), AttributeValue::Bool(true)); - let err = - resolve_condition(Some(&expr), None, Some(&values), None, None, &limits).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg.contains("Incorrect operand type for operator or function; operator or function: <, operand type: BOOL")), - "got {err:?}" + fn placeholder_and_operand_faults_beat_the_count() { + // The service's answers of 2026-11-19 (us-east-1) on PutItem; [p17] of + // 2026-10-25 for the BOOL operand. + let rows = [ + ( + "p01", + format!("{} OR #v = :zz", chain(151)), + "An expression attribute value used in expression is not defined; attribute value: :zz", + ), + ( + "p02", + format!("{} OR #x = :v", chain(151)), + "An expression attribute name used in the document path is not defined; attribute name: #x", + ), + ( + "p03", + format!("{} OR begins_with(#v, :n)", chain(151)), + "Incorrect operand type for operator or function; operator or function: begins_with, operand type: N", + ), + ( + "p17", + format!("{} OR #v < :b", chain(150)), + "Incorrect operand type for operator or function; operator or function: <, operand type: BOOL", + ), + ]; + for (case, expr, want) in rows { + assert_eq!( + resolve_err(&expr), + format!("Invalid ConditionExpression: {want}"), + "{case}" + ); + } + } + + #[test] + fn an_undefined_value_in_a_branch_evaluation_skips_is_refused() { + // [p04] measured 2026-11-19: `attribute_not_exists(pk)` holds for an + // absent item, and the service still refuses `:zz`. + assert_eq!( + resolve_err("attribute_not_exists(pk) OR #v = :zz"), + "Invalid ConditionExpression: An expression attribute value used in expression is not defined; attribute value: :zz" ); } #[test] fn syntax_error_beats_the_count() { // [e04] a 300-term chain followed by ` = =`. - let limits = LimitsConfig::default(); - let expr = format!("{} = =", chain(300)); - let err = resolve_condition(Some(&expr), None, None, None, None, &limits).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid ConditionExpression: Syntax error; token: \"=\", near: \":v = =\""), - "got {err:?}" + assert_eq!( + resolve_err(&format!("{} = =", chain(300))), + "Invalid ConditionExpression: Syntax error; token: \"=\", near: \":v = =\"" ); } diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 4fa245241..f8c9f5680 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -354,17 +354,20 @@ pub async fn handle_query( ) }; - // Validate #name references in filter are defined in ExpressionAttributeNames - if let Some(ref filter_expr) = filter { - let names = input.expression_attribute_names.as_ref(); - validate_name_refs_in_expr(filter_expr, names, ExpressionKind::Filter)?; - // The operator cap follows the undefined name check and precedes the - // unused placeholder check (measured 2026-10-25). It applies to a - // FilterExpression only: a legacy QueryFilter of 160 conditions is - // accepted (measured 2026-10-25). - if filter_maps.is_none() { - crate::expression_helpers::check_operator_count(filter_expr, ExpressionKind::Filter)?; - } + // A FilterExpression's placeholders and operand types, then its operator + // count, come before the projection and the unused placeholder check + // (measured 2026-10-25 and 2026-11-19: an undefined name or value or an + // operand of the wrong type beats the count, and the count beats an + // unused value). A legacy QueryFilter of 160 conditions is accepted + // (measured 2026-10-25), so it is not counted. + if filter_maps.is_none() + && let Some(ref filter_expr) = filter + { + crate::expression_helpers::check_parsed_condition( + filter_expr, + &maps, + ExpressionKind::Filter, + )?; } // Parse ProjectionExpression or desugar legacy AttributesToGet @@ -485,8 +488,11 @@ pub async fn handle_query( ExpressionMaps::new(names, values) }; - // Validate begins_with operand types upfront (before any rows are read). - if let Some(ref f) = filter { + // The operand types of a legacy QueryFilter, before any rows are read. A + // FilterExpression's were checked with its placeholders above. + if filter_maps.is_some() + && let Some(ref f) = filter + { extenddb_core::expression::validate_begins_with_operands(f, &combined_maps).map_err( |e| crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter), )?; @@ -704,67 +710,6 @@ fn refuse_begins_with_on_number( Ok(()) } -/// Validate that all `#name` references in an expression AST are defined. -fn validate_name_refs_in_expr( - expr: &extenddb_core::expression::Expr, - names: Option<&HashMap>, - expr_type: ExpressionKind, -) -> Result<(), DynamoDbError> { - use extenddb_core::expression::Expr; - match expr { - Expr::Path(elements) => { - for el in elements { - if let PathElement::Attribute(name) = el - && let Some(ref_name) = name.strip_prefix('#') - { - let key_with_hash = format!("#{ref_name}"); - let defined = names.as_ref().is_some_and(|m| { - m.contains_key(ref_name) || m.contains_key(key_with_hash.as_str()) - }); - if !defined { - return Err(DynamoDbError::ValidationException(format!( - "Invalid {expr_type}: An expression attribute name used in the document path is not defined; attribute name: #{ref_name}" - ))); - } - } - } - Ok(()) - } - Expr::Compare { left, right, .. } => { - validate_name_refs_in_expr(left, names, expr_type)?; - validate_name_refs_in_expr(right, names, expr_type) - } - Expr::And(l, r) | Expr::Or(l, r) => { - validate_name_refs_in_expr(l, names, expr_type)?; - validate_name_refs_in_expr(r, names, expr_type) - } - Expr::Not(inner) => validate_name_refs_in_expr(inner, names, expr_type), - Expr::Between { operand, low, high } => { - validate_name_refs_in_expr(operand, names, expr_type)?; - validate_name_refs_in_expr(low, names, expr_type)?; - validate_name_refs_in_expr(high, names, expr_type) - } - Expr::In { operand, list } => { - validate_name_refs_in_expr(operand, names, expr_type)?; - for item in list { - validate_name_refs_in_expr(item, names, expr_type)?; - } - Ok(()) - } - Expr::Function { args, .. } => { - for arg in args { - validate_name_refs_in_expr(arg, names, expr_type)?; - } - Ok(()) - } - Expr::Arithmetic { left, right, .. } => { - validate_name_refs_in_expr(left, names, expr_type)?; - validate_name_refs_in_expr(right, names, expr_type) - } - Expr::Placeholder(_) => Ok(()), - } -} - /// Reject an explicitly empty `KeyConditionExpression` with DynamoDB's exact /// message. An absent expression (`None`) is allowed here; required-ness is /// enforced later. Only the empty-string case (`Some("")`) is rejected, and it diff --git a/crates/engine/src/scan.rs b/crates/engine/src/scan.rs index 21cb07975..756dfb578 100755 --- a/crates/engine/src/scan.rs +++ b/crates/engine/src/scan.rs @@ -147,14 +147,17 @@ pub async fn handle_scan( ) }; - // The operator cap runs before the unused placeholder check and the table - // lookup (measured 2026-10-25: the count beats an unused value, a missing - // table and an unknown IndexName). It applies to a FilterExpression only: - // a legacy ScanFilter of 160 conditions is accepted (measured 2026-10-25). + // A FilterExpression's placeholders and operand types, then its operator + // count, are checked before the projection, the unused placeholder check + // and the table lookup (measured 2026-10-25 and 2026-11-19: the count + // beats an unused value, a missing table and an unknown IndexName, and an + // undefined placeholder or an operand of the wrong type beats the count). + // A legacy ScanFilter of 160 conditions is accepted (measured + // 2026-10-25), so it is not counted. if filter_maps.is_none() && let Some(ref f) = filter { - crate::expression_helpers::check_operator_count(f, ExpressionKind::Filter)?; + crate::expression_helpers::check_parsed_condition(f, &maps, ExpressionKind::Filter)?; } // Parse ProjectionExpression or desugar legacy AttributesToGet @@ -434,8 +437,11 @@ pub async fn handle_scan( } } - // Validate begins_with operand types upfront (before any rows are scanned). - if let Some(ref f) = filter { + // The operand types of a legacy ScanFilter, before any rows are scanned. + // A FilterExpression's were checked with its placeholders above. + if filter_maps.is_some() + && let Some(ref f) = filter + { extenddb_core::expression::validate_begins_with_operands(f, &combined_maps).map_err( |e| crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter), )?; From 469404e3d9eda372a52da4e6830c65869891d853 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:26:08 +0000 Subject: [PATCH 11/37] fix(partiql): leave the operator count of a statement to the PartiQL parser PartiQL runs a statement through the Scan, Query, UpdateItem and DeleteItem handlers with an expression that it writes for the statement. The writer pushes each NOT onto the predicates under it, so the written text holds more operators than the statement. A SELECT whose WHERE is a NOT over 150 ANDed comparisons answered `operator count: 449`. The Query, UPDATE and DELETE forms with 101 terms answered 302, 304 and 304. The service runs all four, and the PartiQL parser already applies the cap to the statement. The cap is now the `[limits]` setting `max_expression_operators`, beside `max_expression_tokens` and `max_expression_depth`. Its default is the service's 300. PartiQL already raises the size and token limits for the requests that it makes from a statement. Now it also lifts the operator cap for them. Measured 2026-11-19 in us-east-1, each statement sent twice with the same answer. The SELECT and the Query form return the item, and the UPDATE and DELETE forms succeed. --- crates/core/src/expression/operator_count.rs | 40 ++++++++++++-------- crates/core/src/limits/mod.rs | 9 +++++ crates/engine/src/expression_helpers.rs | 22 +++++++---- crates/engine/src/partiql/mod.rs | 32 ++++++++++++---- crates/engine/src/query.rs | 1 + crates/engine/src/scan.rs | 7 +++- 6 files changed, 80 insertions(+), 31 deletions(-) diff --git a/crates/core/src/expression/operator_count.rs b/crates/core/src/expression/operator_count.rs index a0548d11d..89e66ace8 100644 --- a/crates/core/src/expression/operator_count.rs +++ b/crates/core/src/expression/operator_count.rs @@ -41,15 +41,21 @@ pub fn count_operators(expr: &Expr) -> usize { } } -/// Refuse an expression with more than [`MAX_EXPRESSION_OPERATORS`] operators. +/// Refuse an expression with more than `max` operators. The service's cap, +/// and the default of `LimitsConfig::max_expression_operators`, is +/// [`MAX_EXPRESSION_OPERATORS`]. /// /// # Errors /// /// Returns `ValidationException` carrying the `Invalid :` prefix and the /// full operator count. -pub fn validate_operator_count(expr: &Expr, kind: ExpressionKind) -> Result<(), DynamoDbError> { +pub fn validate_operator_count( + expr: &Expr, + kind: ExpressionKind, + max: usize, +) -> Result<(), DynamoDbError> { let count = count_operators(expr); - if count > MAX_EXPRESSION_OPERATORS { + if count > max { return Err(DynamoDbError::ValidationException(format!( "Invalid {kind}: The expression contains too many operators; operator count: {count}" ))); @@ -127,35 +133,39 @@ mod tests { #[test] fn cap_is_exclusive_at_300() { let kind = ExpressionKind::Condition; + let check = |src: &str| { + let expr = parse_condition(&tokenize(src).unwrap()).unwrap(); + validate_operator_count(&expr, kind, MAX_EXPRESSION_OPERATORS) + }; let at_cap = format!( "NOT attribute_not_exists(pk) OR {}", chain("#v = :v", 149, " OR ") ); // [a49] assert_eq!(count(&at_cap), 300); - assert!( - validate_operator_count(&parse_condition(&tokenize(&at_cap).unwrap()).unwrap(), kind) - .is_ok() - ); + assert!(check(&at_cap).is_ok()); let over = chain("#v = :v", 151, " OR "); // [a30] - let err = - validate_operator_count(&parse_condition(&tokenize(&over).unwrap()).unwrap(), kind) - .unwrap_err(); + let err = check(&over).unwrap_err(); assert!(matches!(err, DynamoDbError::ValidationException(m) if m == "Invalid ConditionExpression: The expression contains too many operators; operator count: 301")); let under = chain("#v = :v", 150, " OR "); // [a30] - assert!( - validate_operator_count(&parse_condition(&tokenize(&under).unwrap()).unwrap(), kind) - .is_ok() - ); + assert!(check(&under).is_ok()); } #[test] fn message_carries_the_kind() { let expr = parse_condition(&tokenize(&chain("#v = :v", 300, " OR ")).unwrap()).unwrap(); - let err = validate_operator_count(&expr, ExpressionKind::Filter).unwrap_err(); + let err = validate_operator_count(&expr, ExpressionKind::Filter, MAX_EXPRESSION_OPERATORS) + .unwrap_err(); assert!(matches!(err, DynamoDbError::ValidationException(m) if m == "Invalid FilterExpression: The expression contains too many operators; operator count: 599")); // [b01] } + + #[test] + fn a_raised_cap_accepts_more_operators() { + let expr = parse_condition(&tokenize(&chain("#v = :v", 300, " OR ")).unwrap()).unwrap(); + assert!(validate_operator_count(&expr, ExpressionKind::Filter, 599).is_ok()); + assert!(validate_operator_count(&expr, ExpressionKind::Filter, 598).is_err()); + } } diff --git a/crates/core/src/limits/mod.rs b/crates/core/src/limits/mod.rs index 5a7ca4178..eba5f3dc8 100755 --- a/crates/core/src/limits/mod.rs +++ b/crates/core/src/limits/mod.rs @@ -58,6 +58,11 @@ pub struct LimitsConfig { /// calls in an update. #[serde(default = "default_max_expression_depth")] pub max_expression_depth: usize, + /// Maximum operators in a condition, filter or key condition expression + /// (DynamoDB: 300). Each comparison, `AND`, `OR`, `NOT`, `BETWEEN`, `IN` + /// and function call counts one. + #[serde(default = "default_max_expression_operators")] + pub max_expression_operators: usize, /// Maximum policy document size in bytes (before JSON parsing). #[serde(default = "default_max_policy_document_bytes")] pub max_policy_document_bytes: usize, @@ -96,6 +101,7 @@ impl Default for LimitsConfig { max_expression_tokens: default_max_expression_tokens(), max_expression_length_bytes: default_max_expression_length_bytes(), max_expression_depth: default_max_expression_depth(), + max_expression_operators: default_max_expression_operators(), max_policy_document_bytes: default_max_policy_document_bytes(), max_import_file_bytes: default_max_import_file_bytes(), max_import_item_count: default_max_import_item_count(), @@ -156,6 +162,9 @@ fn default_max_expression_length_bytes() -> usize { fn default_max_expression_depth() -> usize { 150 } +fn default_max_expression_operators() -> usize { + crate::expression::MAX_EXPRESSION_OPERATORS +} fn default_max_policy_document_bytes() -> usize { // AWS IAM limit: 6,144 bytes for inline policies. 6_144 diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index db602d923..114e7f917 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -94,9 +94,10 @@ pub fn parse_condition_expr(expr: &str, limits: &LimitsConfig) -> Result: The expression contains too many operators; -/// operator count: `). +/// Refuse a condition or filter whose operator count exceeds +/// `limits.max_expression_operators`, the service's cap of 300 by default +/// (`Invalid : The expression contains too many operators; operator +/// count: `). /// /// Measured 2026-10-25 (us-east-1): the check runs after the syntax, reserved /// word, undefined placeholder and operand type checks and before the unused @@ -106,8 +107,12 @@ pub fn parse_condition_expr(expr: &str, limits: &LimitsConfig) -> Result Result<(), DynamoDbError> { - validate_operator_count(expr, kind) +pub fn check_operator_count( + expr: &Expr, + kind: ExpressionKind, + limits: &LimitsConfig, +) -> Result<(), DynamoDbError> { + validate_operator_count(expr, kind, limits.max_expression_operators) } /// Check a parsed condition or filter in the service's order: its placeholders @@ -127,9 +132,10 @@ pub fn check_parsed_condition( expr: &Expr, maps: &ExpressionMaps, kind: ExpressionKind, + limits: &LimitsConfig, ) -> Result<(), DynamoDbError> { validate_placeholders_and_operands(expr, maps).map_err(|e| prefix_expression_error(e, kind))?; - check_operator_count(expr, kind) + check_operator_count(expr, kind, limits) } /// Tokenize, reserved-word check, and parse an `UpdateExpression`. @@ -243,7 +249,7 @@ pub fn resolve_condition( let condition = parse_optional_condition(condition_expression, limits)?; if let Some(ref expr) = condition { // Before the unused placeholder check and the table lookup. - check_parsed_condition(expr, &maps, ExpressionKind::Condition)?; + check_parsed_condition(expr, &maps, ExpressionKind::Condition, limits)?; } Ok((condition, maps)) } @@ -304,7 +310,7 @@ pub fn parse_key_condition_expr( // it does not accept the text, the key condition parser reports the // error in its own words. if let Ok(expr) = parse_condition_from(&tokens, expr, limits.max_expression_depth) { - check_operator_count(&expr, ExpressionKind::KeyCondition)?; + check_operator_count(&expr, ExpressionKind::KeyCondition, limits)?; } parse_key_condition_from(&tokens, expr) }) diff --git a/crates/engine/src/partiql/mod.rs b/crates/engine/src/partiql/mod.rs index fb5e21044..afa7d11dc 100644 --- a/crates/engine/src/partiql/mod.rs +++ b/crates/engine/src/partiql/mod.rs @@ -155,17 +155,23 @@ const TRANSLATED_EXPRESSION_LIMIT: usize = 16 * MAX_STATEMENT_LENGTH; /// The limits the requests a statement is translated into run with: `limits` /// with the size and token limits of an expression raised to -/// [`TRANSLATED_EXPRESSION_LIMIT`]. The classic limits (4096 bytes and 4096 -/// tokens) apply to the expressions a caller writes. The text written for a -/// statement is longer than the statement wherever a name or a value becomes -/// a placeholder, and the service runs a statement within its own limits -/// (8192 characters, 300 operators in its condition) whose text would be past -/// the classic ones (measured 2026-11-02: a condition of 150 `begins_with` -/// calls ANDed, 4275 bytes as classic text). +/// [`TRANSLATED_EXPRESSION_LIMIT`], and no operator cap. The classic limits +/// (4096 bytes, 4096 tokens and 300 operators) apply to the expressions a +/// caller writes. The text written for a statement is longer than the +/// statement wherever a name or a value becomes a placeholder, and the service +/// runs a statement within its own limits (8192 characters, 300 operators in +/// its condition) whose text would be past the classic ones (measured +/// 2026-11-02: a condition of 150 `begins_with` calls ANDed, 4275 bytes as +/// classic text). The PartiQL parser applies the operator cap to the +/// statement. The written text holds more operators wherever a NOT is pushed +/// onto the predicates under it or a key existence condition is added +/// (measured 2026-11-19: a SELECT whose WHERE is NOT over 150 ANDed +/// comparisons, 449 operators as classic text, returns the item). fn translation_limits(limits: &LimitsConfig) -> LimitsConfig { LimitsConfig { max_expression_length_bytes: TRANSLATED_EXPRESSION_LIMIT, max_expression_tokens: TRANSLATED_EXPRESSION_LIMIT, + max_expression_operators: usize::MAX, ..limits.clone() } } @@ -459,6 +465,18 @@ mod tests { ); } + #[test] + fn a_translated_expression_has_no_operator_cap() { + // The PartiQL parser counts the statement's operators; the text + // written for it is not counted again. + let classic = LimitsConfig::default(); + assert_eq!(classic.max_expression_operators, 300); + assert_eq!( + translation_limits(&classic).max_expression_operators, + usize::MAX + ); + } + #[test] fn the_expression_prefix_is_dropped() { let sentence = "Incorrect operand type for operator or function; operator or function: <, \ diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index f8c9f5680..ab8183c0e 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -367,6 +367,7 @@ pub async fn handle_query( filter_expr, &maps, ExpressionKind::Filter, + &ctx.limits, )?; } diff --git a/crates/engine/src/scan.rs b/crates/engine/src/scan.rs index 756dfb578..e47f06140 100755 --- a/crates/engine/src/scan.rs +++ b/crates/engine/src/scan.rs @@ -157,7 +157,12 @@ pub async fn handle_scan( if filter_maps.is_none() && let Some(ref f) = filter { - crate::expression_helpers::check_parsed_condition(f, &maps, ExpressionKind::Filter)?; + crate::expression_helpers::check_parsed_condition( + f, + &maps, + ExpressionKind::Filter, + &ctx.limits, + )?; } // Parse ProjectionExpression or desugar legacy AttributesToGet From 75b03dfb9a42bd832ccbf055ae7a787c3cd9fe80 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:26:57 +0000 Subject: [PATCH 12/37] docs(expression): correct the TransactWriteItems sentence of the operator count The doc comment of `check_operator_count` said that TransactWriteItems counts a different total for the same text. It counts the same way as PutItem. The cap is still not applied to TransactWriteItems. Measured 2026-11-19 in us-east-1, each request sent twice with the same answer. A transacted Put of 151, 200 or 300 `#v = :v` terms joined by OR answers operator count 301, 399 or 599. A ConditionCheck of 151 terms answers 301, and the service evaluates a Put of 150 terms. PutItem answers 399 and 599 for 200 and 300 terms. --- crates/engine/src/expression_helpers.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 114e7f917..2d3546fc1 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -101,8 +101,11 @@ pub fn parse_condition_expr(expr: &str, limits: &LimitsConfig) -> Result Date: Thu, 19 Nov 2026 16:28:59 +0000 Subject: [PATCH 13/37] fix(expression): keep the trailing whitespace in the window of an end-of-input syntax error When an expression ends where a token is required, the window of the syntax error is the last token. The service also keeps the whitespace after it, and this server dropped it. Measured 2026-11-19 in us-east-1, each request sent twice with the same answer: - FilterExpression `#v = :v AND ` answers `token: "", near: "AND "`, and a tab after the AND stays in the window too. - UpdateExpression `SET #v = :v, ` answers `near: ", "`. - KeyConditionExpression `pk = :p AND ` answers `near: "AND "`, and ProjectionExpression `#v, ` answers `near: ", "`. - FilterExpression ` NOT` answers `near: "NOT"`. A single token keeps no leading whitespace at the end of input. - FilterExpression `#v = = :v ` answers `near: "= = :v"`. Before the end of input, the window still ends at the token after the offending one. --- crates/core/src/expression/syntax_error.rs | 37 ++++++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/crates/core/src/expression/syntax_error.rs b/crates/core/src/expression/syntax_error.rs index 2ae935c5f..ce1471a4c 100644 --- a/crates/core/src/expression/syntax_error.rs +++ b/crates/core/src/expression/syntax_error.rs @@ -12,7 +12,8 @@ //! the source's own whitespace kept (`#v==:v` answers `near: "==:v"`) and a //! missing neighbour dropped (`= #v = :v` answers `near: "= #v"`, `#v = :v =` //! answers `near: ":v ="`). For `` the window is the last token's text -//! (`#v = :v AND` answers `token: "", near: "AND"`). +//! and the whitespace after it (`#v = :v AND` answers `token: "", near: +//! "AND"`; `#v = :v AND ` answers `near: "AND "`, measured 2026-11-19). use std::ops::Range; @@ -142,7 +143,9 @@ pub fn syntax_error( /// token to the next one, each dropped when absent. When the faulty token is /// the first one, the window starts at the start of the source, leading /// whitespace kept (measured 2026-10-25: ` = #v = :v` answers -/// `near: " = #v"`). At end of input the window is the last token alone. +/// `near: " = #v"`). At end of input the window is the last token and the +/// rest of the source, trailing whitespace kept (measured 2026-11-19: +/// `SET #v = :v, ` answers `near: ", "`). fn near_window(source: &str, tokens: &[Token], pos: usize) -> String { if tokens.is_empty() { return String::new(); @@ -157,7 +160,12 @@ fn near_window(source: &str, tokens: &[Token], pos: usize) -> String { .flatten() { let start = if pos == 0 { 0 } else { spans[first].start }; - return source[start..spans[last].end].to_owned(); + let end = if pos >= tokens.len() { + source.len() + } else { + spans[last].end + }; + return source[start..end].to_owned(); } tokens[first..=last] .iter() @@ -235,6 +243,29 @@ mod tests { ); } + #[test] + fn end_of_input_keeps_the_trailing_whitespace() { + // Measured 2026-11-19 (us-east-1), probe cases in brackets. A single + // token keeps no leading whitespace at end of input [e10]. + let rows = [ + ("x01", ExpressionKind::Filter, "#v = :v AND ", 4, "AND "), + ("x02", ExpressionKind::Update, "SET #v = :v, ", 5, ", "), + ("x04", ExpressionKind::Filter, "#v = :v AND\t", 4, "AND\t"), + ("x06", ExpressionKind::Projection, "#v, ", 2, ", "), + ("e10", ExpressionKind::Filter, " NOT", 1, "NOT"), + ("e11", ExpressionKind::Filter, " NOT ", 1, "NOT "), + ]; + for (case, kind, source, pos, near) in rows { + assert!( + msg(kind, source, pos).ends_with(&format!("token: \"\", near: \"{near}\"")), + "{case}: {}", + msg(kind, source, pos) + ); + } + // [x03] Before the end of input the window still ends at the next token. + assert!(msg(ExpressionKind::Filter, "#v = = :v ", 2).ends_with("near: \"= = :v\"")); + } + #[test] fn keyword_tokens_show_the_source_text() { // [d07] doubled AND; a lower-case keyword (measured 2026-10-25) is From df22608c1bea7b7829d979108883036df8bb12b7 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:30:43 +0000 Subject: [PATCH 14/37] fix(expression): answer a fault at an ADD or DELETE value with the syntax error An ADD or DELETE action takes a path and a placeholder. Any other token where the placeholder is required, and the end of input, now answer `Invalid UpdateExpression: Syntax error; token: ..., near: ...`. The server no longer answers `ADD/DELETE value must be a placeholder` or `expected value for ADD/DELETE action`. Measured 2026-11-19 in us-east-1, each request sent twice with the same answer: - `ADD #v = :v` and `DELETE #v = :v` answer `token: "=", near: "#v = :v"`. - `ADD #v` and `DELETE #v` answer `token: "", near: "#v"`. - `ADD #v #w` answers `token: "#w", near: "#v #w"`, and `ADD #v, #w` answers `token: ",", near: "#v, #w"`. - `ADD #v (:v)` answers `token: "(", near: "#v (:v"`, and `DELETE #v AND :v` answers `token: "AND", near: "#v AND :v"`. A unit test now pins the window of `SET #v = :a + :b, #w = :c + :d + :e`. The service answers `token: "+", near: ":d + :e"`. A search for the text of the token would find the first `+` and quote `+ :b, #w`. --- crates/core/src/expression/update_parser.rs | 29 +++++++++--------- .../src/expression/update_parser_tests.rs | 30 +++++++++++++++++++ 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/crates/core/src/expression/update_parser.rs b/crates/core/src/expression/update_parser.rs index e30ddd300..0c91b8ab5 100755 --- a/crates/core/src/expression/update_parser.rs +++ b/crates/core/src/expression/update_parser.rs @@ -328,7 +328,7 @@ fn parse_add_actions( ) -> Result<(), DynamoDbError> { loop { let path = parse_action_path(tokens, src, pos)?; - let value = parse_add_delete_value(tokens, pos)?; + let value = parse_add_delete_value(tokens, src, pos)?; actions.push(UpdateAction::Add { path, value }); if *pos < tokens.len() && tokens[*pos] == Token::Comma { *pos += 1; @@ -348,7 +348,7 @@ fn parse_delete_actions( ) -> Result<(), DynamoDbError> { loop { let path = parse_action_path(tokens, src, pos)?; - let value = parse_add_delete_value(tokens, pos)?; + let value = parse_add_delete_value(tokens, src, pos)?; actions.push(UpdateAction::Delete { path, value }); if *pos < tokens.len() && tokens[*pos] == Token::Comma { *pos += 1; @@ -359,22 +359,23 @@ fn parse_delete_actions( Ok(()) } -/// Parse a value for ADD/DELETE — only placeholders are valid. -fn parse_add_delete_value(tokens: &[Token], pos: &mut usize) -> Result { - if *pos >= tokens.len() { - return Err(validation_err( - "Invalid UpdateExpression: expected value for ADD/DELETE action", - )); - } - match &tokens[*pos] { - Token::Placeholder(name) => { +/// Parse the value of an ADD or DELETE action, which must be a placeholder. +/// Any other token, and the end of input, answer the service's syntax error +/// (measured 2026-11-19: `ADD #v = :v` and `DELETE #v = :v` answer token +/// "=", near "#v = :v"; `ADD #v` answers token "", near "#v"; `ADD #v +/// #w` answers token "#w", near "#v #w"). +fn parse_add_delete_value( + tokens: &[Token], + src: &str, + pos: &mut usize, +) -> Result { + match tokens.get(*pos) { + Some(Token::Placeholder(name)) => { let expr = Expr::Placeholder(name.clone()); *pos += 1; Ok(expr) } - _ => Err(validation_err( - "Invalid UpdateExpression: ADD/DELETE value must be a placeholder", - )), + _ => Err(syntax_error(KIND, src, tokens, *pos)), } } diff --git a/crates/core/src/expression/update_parser_tests.rs b/crates/core/src/expression/update_parser_tests.rs index c9f0ec2ae..bc0d347c8 100644 --- a/crates/core/src/expression/update_parser_tests.rs +++ b/crates/core/src/expression/update_parser_tests.rs @@ -240,6 +240,36 @@ fn measured_update_syntax_errors() { assert_eq!(upd_msg("SET #v :v"), syntax(":v", "#v :v")); // [u12] } +#[test] +fn the_window_is_found_by_token_position() { + // [x26] measured 2026-11-19: the second `+` of the second action is the + // offending token. A search for the token's text would find the first + // `+` and quote "+ :b, #w". + assert_eq!( + upd_msg("SET #v = :a + :b, #w = :c + :d + :e"), + syntax("+", ":d + :e") + ); +} + +#[test] +fn add_and_delete_values_answer_the_syntax_error() { + // Measured 2026-11-19 (us-east-1), probe cases in brackets: any token + // where the value is required, and the end of input. + let rows = [ + ("x07", "ADD #v = :v", "=", "#v = :v"), + ("x08", "DELETE #v = :v", "=", "#v = :v"), + ("x09", "ADD #v", "", "#v"), + ("x10", "DELETE #v", "", "#v"), + ("x11", "ADD #v #w", "#w", "#v #w"), + ("x27", "ADD #v, #w", ",", "#v, #w"), + ("x29", "ADD #v (:v)", "(", "#v (:v"), + ("x30", "DELETE #v AND :v", "AND", "#v AND :v"), + ]; + for (case, src, token, near) in rows { + assert_eq!(upd_msg(src), syntax(token, near), "{case}"); + } +} + #[test] fn other_update_texts_are_unchanged() { assert_eq!( From 6c57306e4a74416ef48c1af72305764fae3db19d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:32:01 +0000 Subject: [PATCH 15/37] fix(expression): answer a projection fault after or inside a path with the syntax error A ProjectionExpression with a token other than a comma after a path answered `unexpected token at position `. Input that ended inside a path answered `expected attribute name after '.'` or `expected numeric index in brackets`. The service answers `Invalid ProjectionExpression: Syntax error; token: ..., near: ...` to each. Measured 2026-11-19 in us-east-1 on GetItem, each request sent twice with the same answer: - `#v = #v` answers `token: "=", near: "#v = #v"`, and `#v AND #v` answers `token: "AND", near: "#v AND #v"`. - `#v #w`, `#v :v`, `#v (` and `#v )` answer the syntax error at the second token, and `#v[1] = #v` answers `near: "] = #v"`. - `#v.` answers `token: "", near: "."`. `#v[` and `#v[1` answer `` near `[` and near `1`. - `#v.=` answers `token: "=", near: ".="`. Other faults inside a path, such as a name that is not a number between brackets, keep their texts. --- crates/core/src/expression/projection.rs | 28 +++++++++++++--- .../core/src/expression/projection_tests.rs | 33 ++++++++++++++++--- 2 files changed, 52 insertions(+), 9 deletions(-) diff --git a/crates/core/src/expression/projection.rs b/crates/core/src/expression/projection.rs index 5cc9838a1..c846a91e3 100755 --- a/crates/core/src/expression/projection.rs +++ b/crates/core/src/expression/projection.rs @@ -44,10 +44,16 @@ pub fn parse_projection_from( let mut pos = 0; let mut paths = vec![parse_projection_path(tokens, source, &mut pos)?]; while pos < tokens.len() { + // Any token but a comma after a path answers the syntax error + // (measured 2026-11-19: `#v = #v` answers token "=", near "#v = #v"; + // `#v AND #v` token "AND"; `#v #w` token "#w"). if tokens[pos] != Token::Comma { - return Err(DynamoDbError::ValidationException(format!( - "Invalid ProjectionExpression: unexpected token at position {pos}" - ))); + return Err(syntax_error( + ExpressionKind::Projection, + source, + tokens, + pos, + )); } pos += 1; paths.push(parse_projection_path(tokens, source, &mut pos)?); @@ -58,7 +64,10 @@ pub fn parse_projection_from( /// Parse one projected path. Input that ends where a path is required (`#v,`) /// and a comma, operator or keyword there (`#v, , #v`) answer the service's /// syntax error (measured 2026-10-25: token ",", near ", , #v"; token "", -/// near ","). Any other token keeps the previous text. +/// near ","). Input that ends inside a path (`#v.`, `#v[`, `#v[1`) and an +/// operator or keyword after a dot (`#v.=`) answer it too (measured +/// 2026-11-19: `#v.` answers token "", near "."; `#v.=` answers token +/// "=", near ".="). Any other token keeps the previous text. fn parse_projection_path( tokens: &[Token], source: &str, @@ -77,7 +86,16 @@ fn parse_projection_path( tokens, *pos, )), - Some(_) => super::parser_common::parse_path(tokens, pos), + Some(_) => super::parser_common::parse_path(tokens, pos).map_err(|err| { + let after_dot = *pos > 0 && tokens[*pos - 1] == Token::Dot; + match tokens.get(*pos) { + None => syntax_error(ExpressionKind::Projection, source, tokens, *pos), + Some(token) if after_dot && is_operator_or_keyword(token) => { + syntax_error(ExpressionKind::Projection, source, tokens, *pos) + } + Some(_) => err, + } + }), } } diff --git a/crates/core/src/expression/projection_tests.rs b/crates/core/src/expression/projection_tests.rs index c347c9cb9..d57769edf 100644 --- a/crates/core/src/expression/projection_tests.rs +++ b/crates/core/src/expression/projection_tests.rs @@ -450,12 +450,37 @@ fn trailing_comma_is_eof_with_the_comma_as_window() { ); } +#[test] +fn a_fault_after_or_inside_a_path_answers_the_syntax_error() { + // Measured 2026-11-19 (us-east-1), probe cases in the first column. + let rows = [ + ("x13", "#v = #v", "=", "#v = #v"), + ("x14", "#v AND #v", "AND", "#v AND #v"), + ("j01", "#v #w", "#w", "#v #w"), + ("j02", "#v :v", ":v", "#v :v"), + ("j03", "#v (", "(", "#v ("), + ("j04", "#v )", ")", "#v )"), + ("j10", "#v[1] = #v", "=", "] = #v"), + ("x15", "#v.", "", "."), + ("j05", "#v[", "", "["), + ("j06", "#v[1", "", "1"), + ("j07", "#v.#w.", "", "."), + ("j08", "#v. ", "", ". "), + ("j09", "#v.=", "=", ".="), + ]; + for (case, src, token, near) in rows { + assert_eq!( + proj_msg(src), + format!( + "Invalid ProjectionExpression: Syntax error; token: \"{token}\", near: \"{near}\"" + ), + "{case}" + ); + } +} + #[test] fn other_projection_texts_are_unchanged() { - assert_eq!( - proj_msg("#v #w"), - "Invalid ProjectionExpression: unexpected token at position 1" - ); assert_eq!( proj_msg("#v, )"), "Invalid expression: expected attribute name" From 695af261dddd9786276d7481229f694004862827 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:33:13 +0000 Subject: [PATCH 16/37] fix(expression): answer a token other than a parenthesis after IN with the syntax error A condition with IN followed by anything but `(` answered `Invalid ConditionExpression: expected '('`. The service answers its syntax error. Measured 2026-11-19 in us-east-1, each request sent twice with the same answer, on PutItem and Scan: - `#v IN IN (:v)` answers `token: "IN", near: "IN IN ("`. - `#v IN :v` answers `token: ":v", near: "IN :v"`. - `#v IN` answers `token: "", near: "IN"`. --- crates/core/src/expression/parser.rs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/core/src/expression/parser.rs b/crates/core/src/expression/parser.rs index f26f46792..447e20423 100755 --- a/crates/core/src/expression/parser.rs +++ b/crates/core/src/expression/parser.rs @@ -212,7 +212,14 @@ fn parse_primary( // IN (operand, operand, ...) if tokens[*pos] == Token::In { *pos += 1; - parser_common::expect_token(tokens, pos, &Token::LParen, "(", "ConditionExpression")?; + // Any token but `(` after IN, and the end of input, answer the + // syntax error (measured 2026-11-19: `#v IN IN (:v)` answers token + // "IN", near "IN IN ("; `#v IN :v` token ":v"; `#v IN` token + // "", near "IN"). + if tokens.get(*pos) != Some(&Token::LParen) { + return Err(syntax_error(ExpressionKind::Condition, src, tokens, *pos)); + } + *pos += 1; let mut list = vec![parse_operand(tokens, src, pos, depth, max_depth)?]; while *pos < tokens.len() && tokens[*pos] == Token::Comma { *pos += 1; @@ -582,4 +589,23 @@ mod tests { ); } } + + #[test] + fn a_token_other_than_a_parenthesis_after_in_answers_the_syntax_error() { + // Measured 2026-11-19 (us-east-1), probe cases in the first column. + for (case, src, token, near) in [ + ("x17", "#v IN IN (:v)", "IN", "IN IN ("), + ("i01", "#v IN :v", ":v", "IN :v"), + ("i02", "#v IN", "", "IN"), + ] { + let err = parse_condition_from(&tokenize(src).unwrap(), src, 150).unwrap_err(); + let want = format!( + "Invalid ConditionExpression: Syntax error; token: \"{token}\", near: \"{near}\"" + ); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "{case}: got {err:?}" + ); + } + } } From 1e2171cfd16903926f7f15bddfeca0a723a8d6bd Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:36:48 +0000 Subject: [PATCH 17/37] fix(expression): report a key condition syntax error first, and refuse OR and NOT The service reads a KeyConditionExpression with the condition grammar before it applies the key condition rules. A syntax error in that grammar comes first. An OR or a NOT that the grammar accepts gets `Invalid KeyConditionExpression: Invalid operator used in KeyConditionExpression`. This server ran the condition grammar only to count operators, and the key condition parser answered every fault in its own words. `pk = :p OR` and `pk = :p =` answered `only AND is supported between key conditions`. `NOT pk = :p` and `pk = :p AND NOT sk = :s` answered the syntax error form. Now the server reports a syntax error from the condition grammar first, then the operator count, then the key condition rules. In those rules an OR between clauses and a NOT at the start of a clause answer the invalid operator text. Measured 2026-11-19 in us-east-1 on Query, each request sent twice with the same answer: - `NOT pk = :p`, `pk = :p AND NOT sk = :s`, `NOT NOT pk = :p`, `pk = :p OR sk = :s` and `(pk = :p) OR (sk = :s)` answer the invalid operator text. - `pk = :p AND NOT` answers `token: "", near: "NOT"`, and `pk = :p OR` answers `token: "", near: "OR"`. - `pk = :p =` answers `token: "=", near: ":p ="`, and `pk = :p sk = :s` answers `token: "sk", near: ":p sk ="`. - `pk = :p OR OR sk = :s` answers `token: "OR", near: "OR OR sk"`. A condition grammar fault in another form, such as a BETWEEN without its AND, still reaches the key condition parser, as before. --- crates/core/src/expression/key_condition.rs | 24 +++++-- .../src/expression/key_condition_tests.rs | 20 ++++-- crates/core/src/expression/mod.rs | 2 +- crates/core/src/expression/syntax_error.rs | 7 ++ crates/engine/src/expression_helpers.rs | 69 +++++++++++++++---- 5 files changed, 99 insertions(+), 23 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 6b1cdeb8f..34586880d 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -191,10 +191,15 @@ fn parse_clauses(tokens: &[Token], source: &str) -> Result, Dynam clauses.push(parse_key_clause(tokens, &src, &mut pos)?); while pos < tokens.len() { - if tokens[pos] != Token::And { - return Err(validation_err( - "Invalid KeyConditionExpression: only AND is supported between key conditions", - )); + match tokens[pos] { + Token::And => {} + // Measured 2026-11-19: `pk = :p OR sk = :s` answers this text. + Token::Or => return Err(invalid_operator()), + _ => { + return Err(validation_err( + "Invalid KeyConditionExpression: only AND is supported between key conditions", + )); + } } pos += 1; clauses.push(parse_key_clause(tokens, &src, &mut pos)?); @@ -520,6 +525,9 @@ fn parse_key_operand( let value = parse_key_value(tokens, src, pos)?; Ok(KeyOperand::Value(value)) } + // Measured 2026-11-19: `NOT pk = :p` and `pk = :p AND NOT sk = :s` + // answer this text. + Token::Not => Err(invalid_operator()), // An operator or keyword where an operand is required (`AND pk = :v`). token if is_operator_or_keyword(token) => Err(src.syntax_error(*pos)), _ => Err(validation_err( @@ -616,6 +624,14 @@ fn validation_err(msg: &str) -> DynamoDbError { DynamoDbError::ValidationException(msg.to_owned()) } +/// The refusal of an OR or a NOT in a key condition that the condition +/// grammar accepts. +fn invalid_operator() -> DynamoDbError { + validation_err( + "Invalid KeyConditionExpression: Invalid operator used in KeyConditionExpression", + ) +} + #[cfg(test)] #[path = "key_condition_tests.rs"] mod tests; diff --git a/crates/core/src/expression/key_condition_tests.rs b/crates/core/src/expression/key_condition_tests.rs index cbb9308c6..d156d9a60 100644 --- a/crates/core/src/expression/key_condition_tests.rs +++ b/crates/core/src/expression/key_condition_tests.rs @@ -980,12 +980,24 @@ fn a_fault_at_the_first_token_keeps_leading_whitespace() { ); } +#[test] +fn or_and_not_answer_the_invalid_operator_refusal() { + // Measured 2026-11-19 (us-east-1): [x25], [x20], [x21]. + for src in [ + "pk = :v OR sk = :s", + "NOT pk = :p", + "pk = :p AND NOT sk = :s", + ] { + assert_eq!( + kce_msg(src), + "Invalid KeyConditionExpression: Invalid operator used in KeyConditionExpression", + "{src}" + ); + } +} + #[test] fn other_key_condition_texts_are_unchanged() { - assert_eq!( - kce_msg("pk = :v OR sk = :s"), - "Invalid KeyConditionExpression: only AND is supported between key conditions" - ); assert_eq!( kce_msg("pk"), "Invalid KeyConditionExpression: expected operator after operand" diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 5ac6ae6bc..df086a478 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -52,7 +52,7 @@ pub use search_condition::{ SearchCondition, validate_conditions_against_search_schema, validate_search_condition_expression, }; -pub use syntax_error::{is_operator_or_keyword, syntax_error, token_text}; +pub use syntax_error::{is_operator_or_keyword, is_syntax_error, syntax_error, token_text}; pub use tokenizer::{Token, tokenize, tokenize_for, tokenize_with_limit}; pub use update_evaluator::apply_update_validated; pub use update_parser::{parse_update, parse_update_from}; diff --git a/crates/core/src/expression/syntax_error.rs b/crates/core/src/expression/syntax_error.rs index ce1471a4c..b59269e31 100644 --- a/crates/core/src/expression/syntax_error.rs +++ b/crates/core/src/expression/syntax_error.rs @@ -139,6 +139,13 @@ pub fn syntax_error( )) } +/// Whether `err` is a syntax error in the service's wording, as +/// [`syntax_error`] builds it. +#[must_use] +pub fn is_syntax_error(err: &DynamoDbError) -> bool { + matches!(err, DynamoDbError::ValidationException(msg) if msg.contains(": Syntax error; token: \"")) +} + /// The window of source text around the token at `pos`: from the previous /// token to the next one, each dropped when absent. When the faulty token is /// the first one, the window starts at the start of the source, leading diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 2d3546fc1..3e4aec2b0 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_from, parse_key_condition_from, parse_projection_from, parse_update_from, - tokenize_for, tokenize_with_limit, validate_no_reserved_words, validate_operator_count, - validate_placeholders_and_operands, + is_syntax_error, parse_condition_from, parse_key_condition_from, parse_projection_from, + parse_update_from, tokenize_for, tokenize_with_limit, validate_no_reserved_words, + validate_operator_count, validate_placeholders_and_operands, }; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{AttributeValue, ConditionalOperator, ExpectedAttributeValue}; @@ -305,15 +305,22 @@ pub fn parse_key_condition_expr( if limits.enforce_reserved_keywords { validate_no_reserved_words(&tokens)?; } - // The service counts operators on the whole expression before it - // applies the key condition grammar: `pk = :v OR` + 150 terms answers - // the count, not the operator refusal, and 151 AND-joined equalities - // answer the count ahead of the one-condition-per-key check (measured - // 2026-10-25). The general condition parser supplies the count; when - // it does not accept the text, the key condition parser reports the - // error in its own words. - if let Ok(expr) = parse_condition_from(&tokens, expr, limits.max_expression_depth) { - check_operator_count(&expr, ExpressionKind::KeyCondition, limits)?; + // The service reads a key condition with the condition grammar first. + // A syntax error in that grammar comes before the operator count and + // the key condition rules (measured 2026-11-19: `pk = :p OR` answers + // token "", near "OR"; `pk = :p =` token "=", near ":p ="; `pk = + // :p sk = :s` token "sk", near ":p sk ="). The count comes next: `pk = + // :v OR` + 150 terms answers the count, not the operator refusal, and + // 151 AND-joined equalities answer the count ahead of the + // one-condition-per-key check (measured 2026-10-25). When the + // condition grammar refuses the text in another way, the key + // condition parser reports the error in its own words. + match parse_condition_from(&tokens, expr, limits.max_expression_depth) { + Ok(condition) => { + check_operator_count(&condition, ExpressionKind::KeyCondition, limits)?; + } + Err(err) if is_syntax_error(&err) => return Err(err), + Err(_) => {} } parse_key_condition_from(&tokens, expr) }) @@ -573,11 +580,12 @@ mod tests { if msg == "Invalid KeyConditionExpression: The expression contains too many operators; operator count: 301"), "got {err:?}" ); - // [a63] two conditions joined by OR under the cap: the key grammar answers. + // [a63] two conditions joined by OR under the cap: the key grammar + // answers (measured 2026-11-19 as x25). let err = parse_key_condition_expr("pk = :v OR sk = :s", &limits).unwrap_err(); assert!( matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid KeyConditionExpression: only AND is supported between key conditions"), + if msg == "Invalid KeyConditionExpression: Invalid operator used in KeyConditionExpression"), "got {err:?}" ); // [d23] a syntax error is reported by the key grammar in the service's words. @@ -589,6 +597,39 @@ mod tests { ); } + #[test] + fn key_condition_syntax_errors_come_before_the_key_rules() { + // Measured 2026-11-19 (us-east-1) on Query, probe cases in the first + // column. A syntax error in the condition grammar is reported first; + // an OR or a NOT that the grammar accepts is the key rules' refusal. + let invalid = "Invalid operator used in KeyConditionExpression"; + let syntax = + |token: &str, near: &str| format!("Syntax error; token: \"{token}\", near: \"{near}\""); + let rows = [ + ("x20", "NOT pk = :p", invalid.to_owned()), + ("x21", "pk = :p AND NOT sk = :s", invalid.to_owned()), + ("k06", "NOT NOT pk = :p", invalid.to_owned()), + ("k08", "(pk = :p) OR (sk = :s)", invalid.to_owned()), + ("x22", "pk = :p AND NOT", syntax("", "NOT")), + ("x23", "pk = :p OR", syntax("", "OR")), + ("x24", "pk = :p =", syntax("=", ":p =")), + ("k01", "pk = :p sk = :s", syntax("sk", ":p sk =")), + ("k02", "pk = :p AND sk = :s sk", syntax("sk", ":s sk")), + ("k05", "pk = :p OR OR sk = :s", syntax("OR", "OR OR sk")), + ("k10", "NOT", syntax("", "NOT")), + ("k11", "pk = :p AND NOT NOT", syntax("", "NOT")), + ]; + let limits = LimitsConfig::default(); + for (case, expr, want) in rows { + let err = parse_key_condition_expr(expr, &limits).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if *msg == format!("Invalid KeyConditionExpression: {want}")), + "{case}: got {err:?}" + ); + } + } + #[test] fn projection_syntax_error_quotes_the_source() { // [d27] From 414b68f1d5013293486d7dfb43353bf5232f1336 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:39:31 +0000 Subject: [PATCH 18/37] test(expression): move the syntax wording tests and the shared helpers into their own files This is a pure move. The tests of this round would take tests/test_expression_operator_limits.py past 600 lines. The request helpers and the table fixture move to tests/expression_fault_helpers.py, and TestSyntaxErrorWording moves to tests/test_expression_syntax_wording.py. Both test files import the helpers, and pytest collects the same 78 tests as before. --- tests/expression_fault_helpers.py | 100 +++++++++ tests/test_expression_operator_limits.py | 248 +---------------------- tests/test_expression_syntax_wording.py | 173 ++++++++++++++++ 3 files changed, 276 insertions(+), 245 deletions(-) create mode 100644 tests/expression_fault_helpers.py create mode 100644 tests/test_expression_syntax_wording.py diff --git a/tests/expression_fault_helpers.py b/tests/expression_fault_helpers.py new file mode 100644 index 000000000..6a9797e9d --- /dev/null +++ b/tests/expression_fault_helpers.py @@ -0,0 +1,100 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Request helpers and the table fixture shared by the expression fault tests. + +Dual-target against Amazon DynamoDB and extenddb. +""" + +from __future__ import annotations + +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table + +PREFIX = "1 validation error detected: " + + +def _error(func) -> tuple[str, str]: + with pytest.raises(ClientError) as exc_info: + func() + err = exc_info.value.response["Error"] + return err["Code"], err["Message"] + + +def _validation(func) -> str: + code, msg = _error(func) + assert code == "ValidationException", (code, msg) + return msg + + +def _after_prefix(msg: str) -> str: + return msg[len(PREFIX) :] if msg.startswith(PREFIX) else msg + + +def chain(term: str, n: int, joiner: str = " OR ") -> str: + return joiner.join([term] * n) + + +def syntax(kind: str, token: str, near: str) -> str: + return f'Invalid {kind}: Syntax error; token: "{token}", near: "{near}"' + + +@pytest.fixture(scope="module") +def table(dynamodb_client): + """Composite-key table with one item for the Query and Scan rows.""" + 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: + dynamodb_client.put_item( + TableName=name, + Item={"pk": {"S": "p1"}, "sk": {"S": "s1"}, "v": {"S": "x"}}, + ) + yield name + + +NAMES = {"#v": "v"} +VALUES = {":v": {"S": "x"}} + + +def put(client, table, condition, **kwargs): + args = { + "TableName": table, + "Item": {"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + "ConditionExpression": condition, + "ExpressionAttributeNames": NAMES, + "ExpressionAttributeValues": VALUES, + } + args.update(kwargs) + return lambda: client.put_item(**args) + + +def scan(client, table, filter_expr, **kwargs): + args = { + "TableName": table, + "FilterExpression": filter_expr, + "ExpressionAttributeNames": NAMES, + "ExpressionAttributeValues": VALUES, + } + args.update(kwargs) + return lambda: client.scan(**args) + + +def query(client, table, kce, **kwargs): + args = { + "TableName": table, + "KeyConditionExpression": kce, + "ExpressionAttributeNames": NAMES, + "ExpressionAttributeValues": VALUES, + } + args.update(kwargs) + return lambda: client.query(**args) diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index 211f39a8d..be923c3da 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -32,11 +32,10 @@ import os import pytest -from botocore.exceptions import ClientError -from conftest import scoped_table - -PREFIX = "1 validation error detected: " +from expression_fault_helpers import ( + NAMES, VALUES, _after_prefix, _error, _validation, chain, put, query, scan, syntax, table, +) TOO_MANY = "The expression contains too many operators; operator count: " @@ -53,90 +52,6 @@ ) -def _error(func) -> tuple[str, str]: - with pytest.raises(ClientError) as exc_info: - func() - err = exc_info.value.response["Error"] - return err["Code"], err["Message"] - - -def _validation(func) -> str: - code, msg = _error(func) - assert code == "ValidationException", (code, msg) - return msg - - -def _after_prefix(msg: str) -> str: - return msg[len(PREFIX) :] if msg.startswith(PREFIX) else msg - - -def chain(term: str, n: int, joiner: str = " OR ") -> str: - return joiner.join([term] * n) - - -def syntax(kind: str, token: str, near: str) -> str: - return f'Invalid {kind}: Syntax error; token: "{token}", near: "{near}"' - - -@pytest.fixture(scope="module") -def table(dynamodb_client): - """Composite-key table with one item for the Query and Scan rows.""" - 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: - dynamodb_client.put_item( - TableName=name, - Item={"pk": {"S": "p1"}, "sk": {"S": "s1"}, "v": {"S": "x"}}, - ) - yield name - - -NAMES = {"#v": "v"} -VALUES = {":v": {"S": "x"}} - - -def put(client, table, condition, **kwargs): - args = { - "TableName": table, - "Item": {"pk": {"S": "absent"}, "sk": {"S": "absent"}}, - "ConditionExpression": condition, - "ExpressionAttributeNames": NAMES, - "ExpressionAttributeValues": VALUES, - } - args.update(kwargs) - return lambda: client.put_item(**args) - - -def scan(client, table, filter_expr, **kwargs): - args = { - "TableName": table, - "FilterExpression": filter_expr, - "ExpressionAttributeNames": NAMES, - "ExpressionAttributeValues": VALUES, - } - args.update(kwargs) - return lambda: client.scan(**args) - - -def query(client, table, kce, **kwargs): - args = { - "TableName": table, - "KeyConditionExpression": kce, - "ExpressionAttributeNames": NAMES, - "ExpressionAttributeValues": VALUES, - } - args.update(kwargs) - return lambda: client.query(**args) - - class TestOperatorCount: """More than 300 operators is refused with the full count.""" @@ -493,160 +408,3 @@ def test_scan_query_update_keys(self, dynamodb_client_no_validation, table): ) ) assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", 256) - - -class TestSyntaxErrorWording: - """Token and window for a repeated or misplaced operator or keyword.""" - - @pytest.mark.parametrize( - "case, expr, token, near", - [ - ("d01", "#v = = :v", "=", "= = :v"), - ("d02", "attribute_not_exists(pk) OR #v = = :v", "=", "= = :v"), - ("d13", "attribute_exists(pk) AND #v = :v AND #v = = :v", "=", "= = :v"), - ("d03", "= #v = :v", "=", "= #v"), - ("d04", "#v = :v =", "=", ":v ="), - ("d05", "#v = :v AND", "", "AND"), - ("d06", "#v = :v OR", "", "OR"), - ("d07", "#v = :v AND AND #v = :v", "AND", "AND AND #v"), - ("d08", "#v = :v OR OR #v = :v", "OR", "OR OR #v"), - ("d09", "AND #v = :v", "AND", "AND #v"), - ("d10", "#v < > :v", ">", "< > :v"), - ("d11", "#v = :v #v = :v", "#v", ":v #v ="), - ("d14", "#v <> <> :v", "<>", "<> <> :v"), - ("d15", "#v >= >= :v", ">=", ">= >= :v"), - ("d16", "#v = = = :v", "=", "= = ="), - ("d17", "#v==:v", "=", "==:v"), - ("d18", "#v =\t= :v", "=", "=\t= :v"), - ("d19", "#v = :v AND NOT", "", "NOT"), - ("d29", "=", "=", "="), - ("d30", "= =", "=", "= ="), - ("lower-case and", "#v = :v and and #v = :v", "and", "and and #v"), - ], - ) - def test_put_item_condition(self, dynamodb_client, table, case, expr, token, near): - msg = _validation(put(dynamodb_client, table, expr)) - assert _after_prefix(msg) == syntax("ConditionExpression", token, near), case - - def test_put_item_long_tokens(self, dynamodb_client, table): - # [d12] - msg = _validation( - put( - dynamodb_client, - table, - "#longname = = :longvalue", - ExpressionAttributeNames={"#longname": "v"}, - ExpressionAttributeValues={":longvalue": {"S": "x"}}, - ) - ) - assert _after_prefix(msg) == syntax("ConditionExpression", "=", "= = :longvalue") - - def test_scan_filter(self, dynamodb_client, table): - # [d20], [d21]: no prefix on Scan. - assert _validation(scan(dynamodb_client, table, "#v = = :v")) == syntax( - "FilterExpression", "=", "= = :v" - ) - assert _validation(scan(dynamodb_client, table, "#v = :v AND")) == syntax( - "FilterExpression", "", "AND" - ) - # Measured 2026-10-25: a lower-case keyword is shown as written. - assert _validation(scan(dynamodb_client, table, "#v = :v and and #v = :v")) == syntax( - "FilterExpression", "and", "and and #v" - ) - - def test_fault_at_the_first_token_keeps_leading_whitespace(self, dynamodb_client, table): - # Measured 2026-10-25: the window starts at the start of the expression. - for expr, token, near in [ - (" = #v = :v", "=", " = #v"), - ("\t= #v = :v", "=", "\t= #v"), - (" AND #v = :v", "AND", " AND #v"), - ("= #v = :v", "=", "= #v"), - ]: - assert _validation(scan(dynamodb_client, table, expr)) == syntax( - "FilterExpression", token, near - ), expr - assert _validation(query(dynamodb_client, table, " = pk = :v")) == syntax( - "KeyConditionExpression", "=", " = pk" - ) - msg = _validation( - lambda: dynamodb_client.get_item( - TableName=table, - Key={"pk": {"S": "p1"}, "sk": {"S": "s1"}}, - ProjectionExpression=" , #v", - ExpressionAttributeNames=NAMES, - ) - ) - assert msg == syntax("ProjectionExpression", ",", " , #v") - - def test_query_key_condition(self, dynamodb_client, table): - # [d22], [d23] - assert _validation(query(dynamodb_client, table, "pk = = :v")) == syntax( - "KeyConditionExpression", "=", "= = :v" - ) - assert _validation(query(dynamodb_client, table, "pk = :v AND")) == syntax( - "KeyConditionExpression", "", "AND" - ) - # Measured 2026-10-25: a lower-case keyword in a key condition. - lower = query( - dynamodb_client, - table, - "pk = :p and and sk = :s", - ExpressionAttributeValues={":p": {"S": "p1"}, ":s": {"S": "a"}, ":v": {"S": "x"}}, - ) - assert _validation(lower) == syntax("KeyConditionExpression", "and", "and and sk") - - @pytest.mark.parametrize( - "case, expr, token, near", - [ - ("d24", "SET #v = = :v", "=", "= = :v"), - ("d25", "SET #v = :v + + :v", "+", "+ + :v"), - ("d26", "SET #v = :v,", "", ","), - ("b07", "SET #v = :v + :v + :v", "+", ":v + :v"), - ("u08", "SET #v = :v +", "", "+"), - ("u10", "SET #v = :v REMOVE", "", "REMOVE"), - ("u11", "SET = :v", "=", "SET = :v"), - ("u12", "SET #v :v", ":v", "#v :v"), - ], - ) - def test_update_expression(self, dynamodb_client, table, case, expr, token, near): - msg = _validation( - lambda: dynamodb_client.update_item( - TableName=table, - Key={"pk": {"S": "absent"}, "sk": {"S": "absent"}}, - UpdateExpression=expr, - ExpressionAttributeNames=NAMES, - ExpressionAttributeValues=VALUES, - ) - ) - assert _after_prefix(msg) == syntax("UpdateExpression", token, near), case - - def test_projection_expression(self, dynamodb_client, table): - # [d27], [d28] - for expr, token, near in [("#v, , #v", ",", ", , #v"), ("#v,", "", ",")]: - msg = _validation( - lambda expr=expr: dynamodb_client.get_item( - TableName=table, - Key={"pk": {"S": "p1"}, "sk": {"S": "s1"}}, - ProjectionExpression=expr, - ExpressionAttributeNames=NAMES, - ) - ) - assert msg == syntax("ProjectionExpression", token, near), expr - - def test_syntax_error_beats_the_other_expression_checks(self, dynamodb_client, table): - # [e06] undefined name, [e07] undefined value, [e08] unused value, - # [e09] unused name, [e10] operand type. - rows = [ - ("#w = = :v", ":v", {}), - ("#v = = :u", ":u", {}), - ("#v = = :v", ":v", {"ExpressionAttributeValues": {":v": {"S": "x"}, ":u": {"S": "y"}}}), - ("#v = = :v", ":v", {"ExpressionAttributeNames": {"#v": "v", "#x": "x"}}), - ( - "begins_with(#v, :n) AND #v = = :v", - ":v", - {"ExpressionAttributeValues": {":v": {"S": "x"}, ":n": {"N": "1"}}}, - ), - ] - for condition, last, extra in rows: - msg = _validation(put(dynamodb_client, table, condition, **extra)) - assert _after_prefix(msg) == syntax("ConditionExpression", "=", f"= = {last}"), condition diff --git a/tests/test_expression_syntax_wording.py b/tests/test_expression_syntax_wording.py new file mode 100644 index 000000000..65ff036a8 --- /dev/null +++ b/tests/test_expression_syntax_wording.py @@ -0,0 +1,173 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Syntax error wording: the token and the window of a repeated or misplaced +operator or keyword, measured against Amazon DynamoDB (us-east-1). + +Dual-target against Amazon DynamoDB and extenddb. +""" + +from __future__ import annotations + +import pytest + +from expression_fault_helpers import ( + NAMES, VALUES, _after_prefix, _validation, put, query, scan, syntax, table, +) + + +class TestSyntaxErrorWording: + """Token and window for a repeated or misplaced operator or keyword.""" + + @pytest.mark.parametrize( + "case, expr, token, near", + [ + ("d01", "#v = = :v", "=", "= = :v"), + ("d02", "attribute_not_exists(pk) OR #v = = :v", "=", "= = :v"), + ("d13", "attribute_exists(pk) AND #v = :v AND #v = = :v", "=", "= = :v"), + ("d03", "= #v = :v", "=", "= #v"), + ("d04", "#v = :v =", "=", ":v ="), + ("d05", "#v = :v AND", "", "AND"), + ("d06", "#v = :v OR", "", "OR"), + ("d07", "#v = :v AND AND #v = :v", "AND", "AND AND #v"), + ("d08", "#v = :v OR OR #v = :v", "OR", "OR OR #v"), + ("d09", "AND #v = :v", "AND", "AND #v"), + ("d10", "#v < > :v", ">", "< > :v"), + ("d11", "#v = :v #v = :v", "#v", ":v #v ="), + ("d14", "#v <> <> :v", "<>", "<> <> :v"), + ("d15", "#v >= >= :v", ">=", ">= >= :v"), + ("d16", "#v = = = :v", "=", "= = ="), + ("d17", "#v==:v", "=", "==:v"), + ("d18", "#v =\t= :v", "=", "=\t= :v"), + ("d19", "#v = :v AND NOT", "", "NOT"), + ("d29", "=", "=", "="), + ("d30", "= =", "=", "= ="), + ("lower-case and", "#v = :v and and #v = :v", "and", "and and #v"), + ], + ) + def test_put_item_condition(self, dynamodb_client, table, case, expr, token, near): + msg = _validation(put(dynamodb_client, table, expr)) + assert _after_prefix(msg) == syntax("ConditionExpression", token, near), case + + def test_put_item_long_tokens(self, dynamodb_client, table): + # [d12] + msg = _validation( + put( + dynamodb_client, + table, + "#longname = = :longvalue", + ExpressionAttributeNames={"#longname": "v"}, + ExpressionAttributeValues={":longvalue": {"S": "x"}}, + ) + ) + assert _after_prefix(msg) == syntax("ConditionExpression", "=", "= = :longvalue") + + def test_scan_filter(self, dynamodb_client, table): + # [d20], [d21]: no prefix on Scan. + assert _validation(scan(dynamodb_client, table, "#v = = :v")) == syntax( + "FilterExpression", "=", "= = :v" + ) + assert _validation(scan(dynamodb_client, table, "#v = :v AND")) == syntax( + "FilterExpression", "", "AND" + ) + # Measured 2026-10-25: a lower-case keyword is shown as written. + assert _validation(scan(dynamodb_client, table, "#v = :v and and #v = :v")) == syntax( + "FilterExpression", "and", "and and #v" + ) + + def test_fault_at_the_first_token_keeps_leading_whitespace(self, dynamodb_client, table): + # Measured 2026-10-25: the window starts at the start of the expression. + for expr, token, near in [ + (" = #v = :v", "=", " = #v"), + ("\t= #v = :v", "=", "\t= #v"), + (" AND #v = :v", "AND", " AND #v"), + ("= #v = :v", "=", "= #v"), + ]: + assert _validation(scan(dynamodb_client, table, expr)) == syntax( + "FilterExpression", token, near + ), expr + assert _validation(query(dynamodb_client, table, " = pk = :v")) == syntax( + "KeyConditionExpression", "=", " = pk" + ) + msg = _validation( + lambda: dynamodb_client.get_item( + TableName=table, + Key={"pk": {"S": "p1"}, "sk": {"S": "s1"}}, + ProjectionExpression=" , #v", + ExpressionAttributeNames=NAMES, + ) + ) + assert msg == syntax("ProjectionExpression", ",", " , #v") + + def test_query_key_condition(self, dynamodb_client, table): + # [d22], [d23] + assert _validation(query(dynamodb_client, table, "pk = = :v")) == syntax( + "KeyConditionExpression", "=", "= = :v" + ) + assert _validation(query(dynamodb_client, table, "pk = :v AND")) == syntax( + "KeyConditionExpression", "", "AND" + ) + # Measured 2026-10-25: a lower-case keyword in a key condition. + lower = query( + dynamodb_client, + table, + "pk = :p and and sk = :s", + ExpressionAttributeValues={":p": {"S": "p1"}, ":s": {"S": "a"}, ":v": {"S": "x"}}, + ) + assert _validation(lower) == syntax("KeyConditionExpression", "and", "and and sk") + + @pytest.mark.parametrize( + "case, expr, token, near", + [ + ("d24", "SET #v = = :v", "=", "= = :v"), + ("d25", "SET #v = :v + + :v", "+", "+ + :v"), + ("d26", "SET #v = :v,", "", ","), + ("b07", "SET #v = :v + :v + :v", "+", ":v + :v"), + ("u08", "SET #v = :v +", "", "+"), + ("u10", "SET #v = :v REMOVE", "", "REMOVE"), + ("u11", "SET = :v", "=", "SET = :v"), + ("u12", "SET #v :v", ":v", "#v :v"), + ], + ) + def test_update_expression(self, dynamodb_client, table, case, expr, token, near): + msg = _validation( + lambda: dynamodb_client.update_item( + TableName=table, + Key={"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + UpdateExpression=expr, + ExpressionAttributeNames=NAMES, + ExpressionAttributeValues=VALUES, + ) + ) + assert _after_prefix(msg) == syntax("UpdateExpression", token, near), case + + def test_projection_expression(self, dynamodb_client, table): + # [d27], [d28] + for expr, token, near in [("#v, , #v", ",", ", , #v"), ("#v,", "", ",")]: + msg = _validation( + lambda expr=expr: dynamodb_client.get_item( + TableName=table, + Key={"pk": {"S": "p1"}, "sk": {"S": "s1"}}, + ProjectionExpression=expr, + ExpressionAttributeNames=NAMES, + ) + ) + assert msg == syntax("ProjectionExpression", token, near), expr + + def test_syntax_error_beats_the_other_expression_checks(self, dynamodb_client, table): + # [e06] undefined name, [e07] undefined value, [e08] unused value, + # [e09] unused name, [e10] operand type. + rows = [ + ("#w = = :v", ":v", {}), + ("#v = = :u", ":u", {}), + ("#v = = :v", ":v", {"ExpressionAttributeValues": {":v": {"S": "x"}, ":u": {"S": "y"}}}), + ("#v = = :v", ":v", {"ExpressionAttributeNames": {"#v": "v", "#x": "x"}}), + ( + "begins_with(#v, :n) AND #v = = :v", + ":v", + {"ExpressionAttributeValues": {":v": {"S": "x"}, ":n": {"N": "1"}}}, + ), + ] + for condition, last, extra in rows: + msg = _validation(put(dynamodb_client, table, condition, **extra)) + assert _after_prefix(msg) == syntax("ConditionExpression", "=", f"= = {last}"), condition From eecaf95710af607e24395fb91ee8ba195223af70 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:40:44 +0000 Subject: [PATCH 19/37] test(expression): read the MongoDB backend from the test configuration The expected-failure marker of `test_update_item_condition_at_the_cap_is_evaluated` checked `EXTENDDB_TEST_MONGODB_CONTAINER`. A MongoDB run without that variable failed the test with `assert 'InternalServerError' == 'ConditionalCheckFailedException'`. The marker now reads the backend with `configured_backend()`, as the other tests do: `EXTENDDB_TEST_BACKEND`, else the `[storage] backend` of the server's config file. It applies only when the tests target a server. The module docstring now names the checks that the tests of this round cover, and points to the file that holds the syntax wording tests. --- tests/test_expression_operator_limits.py | 32 +++++++++++++----------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index be923c3da..10beef2d6 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -1,38 +1,39 @@ # Copyright 2026 ExtendDB contributors # SPDX-License-Identifier: Apache-2.0 -"""Expression operator cap, placeholder key length and syntax error wording. +"""Expression operator cap and placeholder key length. -Three request shapes Amazon DynamoDB refuses with texts ExtendDB did not match: +Two request shapes Amazon DynamoDB refuses with texts ExtendDB did not match: - an expression with more than 300 operators: ``Invalid : The expression contains too many operators; operator count: ``, on ConditionExpression (PutItem, UpdateItem, DeleteItem), FilterExpression (Scan, Query) and KeyConditionExpression (Query). Every comparison operator, AND, OR, NOT, BETWEEN, IN and function call counts - one; parentheses, paths, placeholders and list elements count zero. + one; parentheses, paths, placeholders and list elements count zero. An + undefined placeholder and an operand of the wrong type come before the + count, and so do the Scan Limit, Segment and TotalSegments ranges. PartiQL + counts the statement, not the text it writes for it. - an ExpressionAttributeNames or ExpressionAttributeValues key over 255 bytes on PutItem: a ValidationException carrying ``size of key: ``, not a SerializationException. - - a repeated or misplaced operator or keyword: ``Syntax error; token: "", - near: ""`` where the window is the source text from the token - before the offending one to the token after it, and ```` with the - last token as the window when the input ends early. -Every expected text was measured against Amazon DynamoDB on 2026-10-25 -(us-east-1); the probe case id is noted on each assertion. The write paths -carry a ``1 validation error detected: `` prefix on the service that ExtendDB -does not emit; those assertions compare the text after the prefix. +The syntax error wording tests are in test_expression_syntax_wording.py. + +Every expected text was measured against Amazon DynamoDB on 2026-10-25 or +2026-11-19 (us-east-1); the probe case id is noted on each assertion. The +write paths carry a ``1 validation error detected: `` prefix on the service +that ExtendDB does not emit; those assertions compare the text after the +prefix. Dual-target against Amazon DynamoDB and extenddb. """ from __future__ import annotations -import os - import pytest +from conftest import _is_real_dynamodb, configured_backend from expression_fault_helpers import ( NAMES, VALUES, _after_prefix, _error, _validation, chain, put, query, scan, syntax, table, ) @@ -42,10 +43,11 @@ # On MongoDB an UpdateItem condition is compiled to a filter whose OR and AND # chains nest one level per operator, and a chain of 150 terms fails inside # MongoDB with InternalServerError. This change does not touch that compiler. -# The MongoDB test runner sets EXTENDDB_TEST_MONGODB_CONTAINER. +# The backend is read as the other tests read it: EXTENDDB_TEST_BACKEND, else +# the server's config file. # TODO: remove this marker once the MongoDB filter compiler flattens chains. XFAIL_ON_MONGODB_DEEP_OR = pytest.mark.xfail( - bool(os.environ.get("EXTENDDB_TEST_MONGODB_CONTAINER", "").strip()), + not _is_real_dynamodb() and configured_backend() == "mongodb", reason="MongoDB answers InternalServerError for a condition chain of 150 terms", raises=AssertionError, strict=True, From f16985f3237d19b89b2e565e5ea6cdfaa3c9d4d9 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:21:24 +0000 Subject: [PATCH 20/37] test(expression): wire tests for the checks around the operator count and for PartiQL statements New tests in tests/test_expression_operator_limits.py, each row measured on 2026-11-19 in us-east-1: - TestChecksAheadOfTheCount: an undefined value, an undefined name, a BOOL beside `<` and an N `begins_with` prefix beside 151 terms on Scan and on Query. Also the write conditions of PutItem, UpdateItem and DeleteItem, and the Query count ahead of an unused value. The last test covers the checks that read no item. Its rows are a branch that evaluation skips, a Query that reads no item, an unused value and a missing table. Two more rows check the fault order inside a filter, and an operand fault ahead of a ProjectionExpression syntax error. - TestScanRangesAheadOfTheCount: Limit 0 and TotalSegments 0 beside the count, an operand type, an undefined value and a syntax error. A Segment without TotalSegments still answers the count. - TestPartiqlStatementCount: a SELECT, a Query form, an UPDATE and a DELETE whose WHERE holds a NOT over ANDed comparisons. The a46 row of `test_put_item_condition_at_or_under_the_cap_is_evaluated` moves to a test of its own. Its `attribute_type` calls used the value "x", and the service now answers `Invalid attribute type name found; type: x` for it. The new test uses the type name "S", and the service evaluates the condition. The changed files pass against DynamoDB on two runs (117 tests), and against a local server on SQLite, PostgreSQL and MongoDB. On MongoDB the marked test is an expected failure. --- tests/test_expression_operator_limits.py | 250 ++++++++++++++++++++++- 1 file changed, 249 insertions(+), 1 deletion(-) diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index 10beef2d6..8a0d98b66 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -93,7 +93,6 @@ def test_put_item_condition_count(self, dynamodb_client, table, case, expr, coun ("a49", "NOT attribute_not_exists(pk) OR " + chain("#v = :v", 149)), # 300 ("a42", chain("#v IN (:v, :v, :v, :v, :v)", 130)), # 259 ("a54", chain("#v IN (:v)", 150)), # 299 - ("a46", chain("attribute_type(#v, :v)", 150)), # 299 ], ) def test_put_item_condition_at_or_under_the_cap_is_evaluated( @@ -103,6 +102,20 @@ def test_put_item_condition_at_or_under_the_cap_is_evaluated( code, _ = _error(put(dynamodb_client, table, expr)) assert code == "ConditionalCheckFailedException", case + def test_put_item_attribute_type_terms_are_evaluated(self, dynamodb_client, table): + # [a46] 150 calls: 299. The type name must be one the service knows: + # with "x" it answers "Invalid attribute type name found" (measured + # 2026-11-19), so the value is "S". + code, _ = _error( + put( + dynamodb_client, + table, + chain("attribute_type(#v, :t)", 150), + ExpressionAttributeValues={":t": {"S": "S"}}, + ) + ) + assert code == "ConditionalCheckFailedException" + def test_update_item_condition_count(self, dynamodb_client, table): # [u01] 599 refused; [u03] 300 accepted (condition evaluated). msg = _validation( @@ -410,3 +423,238 @@ def test_scan_query_update_keys(self, dynamodb_client_no_validation, table): ) ) assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", 256) + + +UNDEFINED_VALUE = ( + "An expression attribute value used in expression is not defined; attribute value: :zz" +) +UNDEFINED_NAME = ( + "An expression attribute name used in the document path is not defined; attribute name: #x" +) +BOOL_OPERAND = ( + "Incorrect operand type for operator or function; operator or function: <, operand type: BOOL" +) +N_PREFIX = ( + "Incorrect operand type for operator or function; operator or function: begins_with, " + "operand type: N" +) +B = {":b": {"BOOL": True}} +N = {":n": {"N": "1"}} +U = {":u": {"S": "y"}} +P = {":p": {"S": "p1"}} + +# Faults the service reports ahead of the count, measured 2026-11-19 on Scan +# (s01-s04) and on Query (q01-q04) with the same answers. +AHEAD_OF_THE_COUNT = [ + ("s01", chain("#v = :v", 150) + " OR #v < :b", B, BOOL_OPERAND), + ("s02", chain("#v = :v", 151) + " OR #v = :zz", {}, UNDEFINED_VALUE), + ("s03", chain("#v = :v", 151) + " OR begins_with(#v, :n)", N, N_PREFIX), + ("s04", chain("#v = :v", 151) + " OR #x = :v", {}, UNDEFINED_NAME), +] + + +class TestChecksAheadOfTheCount: + """Undefined placeholders and operand types come before the count.""" + + @pytest.mark.parametrize("case, expr, values, want", AHEAD_OF_THE_COUNT) + def test_scan_filter(self, dynamodb_client, table, case, expr, values, want): + msg = _validation( + scan(dynamodb_client, table, expr, ExpressionAttributeValues={**VALUES, **values}) + ) + assert msg == f"Invalid FilterExpression: {want}", case + + @pytest.mark.parametrize("case, expr, values, want", AHEAD_OF_THE_COUNT) + def test_query_filter(self, dynamodb_client, table, case, expr, values, want): + msg = _validation( + query( + dynamodb_client, + table, + "pk = :p", + FilterExpression=expr, + ExpressionAttributeValues={**VALUES, **P, **values}, + ) + ) + assert msg == f"Invalid FilterExpression: {want}", case + + def test_query_count_beats_an_unused_value(self, dynamodb_client, table): + # [q05] + msg = _validation( + query( + dynamodb_client, + table, + "pk = :p", + FilterExpression=chain("#v = :v", 151), + ExpressionAttributeValues={**VALUES, **P, **U}, + ) + ) + assert msg == f"Invalid FilterExpression: {TOO_MANY}301" + + def test_write_conditions(self, dynamodb_client, table): + # [p01], [p02], [p03] on PutItem; [u01] on UpdateItem; [d01] on DeleteItem. + key = {"pk": {"S": "absent"}, "sk": {"S": "absent"}} + undefined = chain("#v = :v", 151) + " OR #v = :zz" + rows = [ + ("p01", put(dynamodb_client, table, undefined), UNDEFINED_VALUE), + ( + "p02", + put(dynamodb_client, table, chain("#v = :v", 151) + " OR #x = :v"), + UNDEFINED_NAME, + ), + ( + "p03", + put( + dynamodb_client, + table, + chain("#v = :v", 151) + " OR begins_with(#v, :n)", + ExpressionAttributeValues={**VALUES, **N}, + ), + N_PREFIX, + ), + ( + "u01", + lambda: dynamodb_client.update_item( + TableName=table, + Key=key, + UpdateExpression="SET #w = :v", + ConditionExpression=undefined, + ExpressionAttributeNames={"#v": "v", "#w": "w"}, + ExpressionAttributeValues=VALUES, + ), + UNDEFINED_VALUE, + ), + ( + "d01", + lambda: dynamodb_client.delete_item( + TableName=table, + Key=key, + ConditionExpression=undefined, + ExpressionAttributeNames=NAMES, + ExpressionAttributeValues=VALUES, + ), + UNDEFINED_VALUE, + ), + ] + for case, request, want in rows: + assert _after_prefix(_validation(request)) == f"Invalid ConditionExpression: {want}", case + + def test_the_checks_read_no_item(self, dynamodb_client, table): + # Measured 2026-11-19: the undefined value is found where evaluation + # would skip it or never run, and ahead of the other request faults. + rows = [ + ("p04", put(dynamodb_client, table, "attribute_not_exists(pk) OR #v = :zz"), "Condition", UNDEFINED_VALUE), + ( + "q06", + query( + dynamodb_client, + table, + "pk = :p", + FilterExpression="#v = :zz", + ExpressionAttributeValues={**VALUES, ":p": {"S": "nothing"}}, + ), + "Filter", + UNDEFINED_VALUE, + ), + ( + "s07", + scan(dynamodb_client, table, "#v = :zz", ExpressionAttributeValues={**VALUES, **U}), + "Filter", + UNDEFINED_VALUE, + ), + ("s08", scan(dynamodb_client, "extenddb-missing-b501", "#v = :zz"), "Filter", UNDEFINED_VALUE), + ( + "s10", + scan( + dynamodb_client, + table, + "#v = :zz OR #v < :b", + ExpressionAttributeValues={**VALUES, **B}, + ), + "Filter", + UNDEFINED_VALUE, + ), + ( + "s13", + scan( + dynamodb_client, + table, + "#v < :b", + ExpressionAttributeValues={**VALUES, **B}, + ProjectionExpression="#v, , #v", + ), + "Filter", + BOOL_OPERAND, + ), + ] + for case, request, kind, want in rows: + assert _after_prefix(_validation(request)) == f"Invalid {kind}Expression: {want}", case + + +class TestScanRangesAheadOfTheCount: + """The Scan Limit, Segment and TotalSegments ranges come first.""" + + @pytest.mark.parametrize( + "case, expr, values, extra", + [ + ("s05", chain("#v = :v", 151), {}, {"Limit": 0}), + ("s16", "#v < :b", B, {"Limit": 0}), + ("s17", "#v = :zz", {}, {"Limit": 0}), + ("s22", "#v = = :v", {}, {"Limit": 0}), + ("s06", chain("#v = :v", 151), {}, {"Segment": 0, "TotalSegments": 0}), + ], + ) + def test_range_beats_the_filter_checks( + self, dynamodb_client_no_validation, table, case, expr, values, extra + ): + # Measured 2026-11-19. The service words the range as "Value at + # 'Limit' failed to satisfy constraint: ..."; ExtendDB keeps its own + # wording, so the assertion names the parameter and the bound. + msg = _validation( + scan( + dynamodb_client_no_validation, + table, + expr, + ExpressionAttributeValues={**VALUES, **values}, + **extra, + ) + ) + name = "TotalSegments" if "TotalSegments" in extra else "limit" + assert name in msg or name.capitalize() in msg, (case, msg) + assert "greater than or equal to 1" in msg, (case, msg) + + def test_segment_pairing_comes_after_the_count(self, dynamodb_client_no_validation, table): + # [s27] a Segment without TotalSegments beside 151 terms. + msg = _validation( + scan(dynamodb_client_no_validation, table, chain("#v = :v", 151), Segment=0) + ) + assert msg == f"Invalid FilterExpression: {TOO_MANY}301" + + +class TestPartiqlStatementCount: + """PartiQL counts a statement, not the text it writes for the statement.""" + + def test_not_over_and_joined_terms_runs(self, dynamodb_client, table): + # [e01]-[e04] measured 2026-11-19: the service runs each statement. + key = {"pk": {"S": "p2"}, "sk": {"S": "s2"}} + dynamodb_client.put_item(TableName=table, Item={**key, "v": {"S": "x"}}) + try: + def not_and(n): + return "NOT (" + " AND ".join(["v = 'y'"] * n) + ")" + + items = dynamodb_client.execute_statement( + Statement=f'SELECT * FROM "{table}" WHERE {not_and(150)}' + )["Items"] + assert {"S": "p2"} in [item["pk"] for item in items] + items = dynamodb_client.execute_statement( + Statement=f"SELECT * FROM \"{table}\" WHERE pk = 'p2' AND {not_and(101)}" + )["Items"] + assert [item["pk"] for item in items] == [{"S": "p2"}] + where = f"pk = 'p2' AND sk = 's2' AND {not_and(101)}" + dynamodb_client.execute_statement(Statement=f'UPDATE "{table}" SET w = 1 WHERE {where}') + item = dynamodb_client.get_item(TableName=table, Key=key, ConsistentRead=True)["Item"] + assert item["w"] == {"N": "1"} + dynamodb_client.execute_statement(Statement=f'DELETE FROM "{table}" WHERE {where}') + assert "Item" not in dynamodb_client.get_item( + TableName=table, Key=key, ConsistentRead=True + ) + finally: + dynamodb_client.delete_item(TableName=table, Key=key) From 3ab4e82f43204fc334c080f1896a992fda0b0f9f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:21:46 +0000 Subject: [PATCH 21/37] test(expression): wire tests for the syntax fault forms of this round TestSyntaxFaultForms in tests/test_expression_syntax_wording.py holds the shapes measured on 2026-11-19 in us-east-1: - The window of an end-of-input fault keeps the trailing whitespace, on a filter, a key condition, a projection and an update. - A fault at an ADD or DELETE value answers the syntax error. - The window of `SET #v = :a + :b, #w = :c + :d + :e` is the one at the second `+` of the second action. A search for the text of the token gets it wrong. - A projection fault after or inside a path answers the syntax error. - A token other than a parenthesis after IN answers the syntax error. - OR and NOT in a key condition answer the invalid operator text, after the syntax errors of the condition grammar. The file passes against DynamoDB on two runs, and against a local server on SQLite, PostgreSQL and MongoDB. --- tests/test_expression_syntax_wording.py | 123 ++++++++++++++++++++++++ 1 file changed, 123 insertions(+) diff --git a/tests/test_expression_syntax_wording.py b/tests/test_expression_syntax_wording.py index 65ff036a8..5bbfc3eb9 100644 --- a/tests/test_expression_syntax_wording.py +++ b/tests/test_expression_syntax_wording.py @@ -171,3 +171,126 @@ def test_syntax_error_beats_the_other_expression_checks(self, dynamodb_client, t for condition, last, extra in rows: msg = _validation(put(dynamodb_client, table, condition, **extra)) assert _after_prefix(msg) == syntax("ConditionExpression", "=", f"= = {last}"), condition + + +INVALID_KEY_OPERATOR = "Invalid KeyConditionExpression: Invalid operator used in KeyConditionExpression" + + +class TestSyntaxFaultForms: + """Shapes measured 2026-11-19 (us-east-1); probe case ids on each row.""" + + @staticmethod + def _update(client, table, expr, names=None, values=None): + args = { + "TableName": table, + "Key": {"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + "UpdateExpression": expr, + "ExpressionAttributeNames": names or NAMES, + } + if values is not None: + args["ExpressionAttributeValues"] = values + return lambda: client.update_item(**args) + + @staticmethod + def _get(client, table, projection, names=None): + return lambda: client.get_item( + TableName=table, + Key={"pk": {"S": "p1"}, "sk": {"S": "s1"}}, + ProjectionExpression=projection, + ExpressionAttributeNames=names or NAMES, + ) + + def test_end_of_input_keeps_the_trailing_whitespace(self, dynamodb_client, table): + values = {":p": {"S": "p1"}, ":v": {"S": "x"}} + rows = [ + ("x01", scan(dynamodb_client, table, "#v = :v AND "), "Filter", "AND "), + ("x04", scan(dynamodb_client, table, "#v = :v AND\t"), "Filter", "AND\t"), + ("e10", scan(dynamodb_client, table, " NOT"), "Filter", "NOT"), + ( + "x05", + query(dynamodb_client, table, "pk = :p AND ", ExpressionAttributeValues=values), + "KeyCondition", + "AND ", + ), + ("x06", self._get(dynamodb_client, table, "#v, "), "Projection", ", "), + ( + "x02", + self._update(dynamodb_client, table, "SET #v = :v, ", values=VALUES), + "Update", + ", ", + ), + ] + for case, request, kind, near in rows: + msg = _after_prefix(_validation(request)) + assert msg == syntax(f"{kind}Expression", "", near), case + + def test_add_and_delete_values(self, dynamodb_client, table): + both = {"#v": "v", "#w": "w"} + rows = [ + ("x07", "ADD #v = :v", None, VALUES, "=", "#v = :v"), + ("x08", "DELETE #v = :v", None, VALUES, "=", "#v = :v"), + ("x09", "ADD #v", None, None, "", "#v"), + ("x10", "DELETE #v", None, None, "", "#v"), + ("x11", "ADD #v #w", both, None, "#w", "#v #w"), + ] + for case, expr, names, values, token, near in rows: + request = self._update(dynamodb_client, table, expr, names=names, values=values) + msg = _after_prefix(_validation(request)) + assert msg == syntax("UpdateExpression", token, near), case + + def test_update_window_is_found_by_token_position(self, dynamodb_client, table): + # [x26] A search for the token's text would quote "+ :b, #w". + values = {k: {"N": "1"} for k in (":a", ":b", ":c", ":d", ":e")} + request = self._update( + dynamodb_client, + table, + "SET #v = :a + :b, #w = :c + :d + :e", + names={"#v": "v", "#w": "w"}, + values=values, + ) + msg = _after_prefix(_validation(request)) + assert msg == syntax("UpdateExpression", "+", ":d + :e") + + def test_projection_faults(self, dynamodb_client, table): + rows = [ + ("x13", "#v = #v", None, "=", "#v = #v"), + ("x14", "#v AND #v", None, "AND", "#v AND #v"), + ("x15", "#v.", None, "", "."), + ("j01", "#v #w", {"#v": "v", "#w": "w"}, "#w", "#v #w"), + ("j06", "#v[1", None, "", "1"), + ] + for case, projection, names, token, near in rows: + msg = _validation(self._get(dynamodb_client, table, projection, names=names)) + assert msg == syntax("ProjectionExpression", token, near), case + + def test_in_without_a_parenthesis(self, dynamodb_client, table): + rows = [ + ("x17", put(dynamodb_client, table, "#v IN IN (:v)"), "Condition", "IN", "IN IN ("), + ("i01", put(dynamodb_client, table, "#v IN :v"), "Condition", ":v", "IN :v"), + ("i02", put(dynamodb_client, table, "#v IN"), "Condition", "", "IN"), + ("x18", scan(dynamodb_client, table, "#v IN IN (:v)"), "Filter", "IN", "IN IN ("), + ] + for case, request, kind, token, near in rows: + msg = _after_prefix(_validation(request)) + assert msg == syntax(f"{kind}Expression", token, near), case + + def test_key_condition_operators(self, dynamodb_client, table): + p = {":p": {"S": "p1"}} + ps = {":p": {"S": "p1"}, ":s": {"S": "s1"}} + rows = [ + ("x20", "NOT pk = :p", p, INVALID_KEY_OPERATOR), + ("x21", "pk = :p AND NOT sk = :s", ps, INVALID_KEY_OPERATOR), + ("x25", "pk = :p OR sk = :s", ps, INVALID_KEY_OPERATOR), + ("x22", "pk = :p AND NOT", p, syntax("KeyConditionExpression", "", "NOT")), + ("x23", "pk = :p OR", p, syntax("KeyConditionExpression", "", "OR")), + ("x24", "pk = :p =", p, syntax("KeyConditionExpression", "=", ":p =")), + ("k01", "pk = :p sk = :s", ps, syntax("KeyConditionExpression", "sk", ":p sk =")), + ("k05", "pk = :p OR OR sk = :s", ps, syntax("KeyConditionExpression", "OR", "OR OR sk")), + ] + for case, kce, values, want in rows: + msg = _validation( + lambda kce=kce, values=values: dynamodb_client.query( + TableName=table, KeyConditionExpression=kce, ExpressionAttributeValues=values + ) + ) + assert msg == want, case From 096330a5d5311a4aefc65cb7a6c240bde125fa21 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:24:07 +0000 Subject: [PATCH 22/37] refactor(expression): split the key condition tests into parse, classify and resolve files This is a pure move. key_condition_tests.rs had 1,009 lines. - key_condition_tests.rs keeps the parser tests: parentheses, multi-part parsing, reversed comparisons, nested paths, clause operands and the syntax error wording (372 lines). - key_condition_classify_tests.rs holds the classification of clauses against a multi-attribute key schema (425 lines). - key_condition_resolve_tests.rs holds `resolve_pk_sk`, `resolve_multipart` and `resolve_key_schema` (223 lines). Each file loads with `#[path]` as a test module of key_condition.rs and imports only what it uses. The tests and their bodies are unchanged, and the crate runs the same 1,179 tests. --- crates/core/src/expression/key_condition.rs | 8 + .../key_condition_classify_tests.rs | 425 ++++++++++++ .../expression/key_condition_resolve_tests.rs | 223 ++++++ .../src/expression/key_condition_tests.rs | 637 ------------------ 4 files changed, 656 insertions(+), 637 deletions(-) create mode 100644 crates/core/src/expression/key_condition_classify_tests.rs create mode 100644 crates/core/src/expression/key_condition_resolve_tests.rs diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 34586880d..70d875ec6 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -635,3 +635,11 @@ fn invalid_operator() -> DynamoDbError { #[cfg(test)] #[path = "key_condition_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "key_condition_classify_tests.rs"] +mod classify_tests; + +#[cfg(test)] +#[path = "key_condition_resolve_tests.rs"] +mod resolve_tests; diff --git a/crates/core/src/expression/key_condition_classify_tests.rs b/crates/core/src/expression/key_condition_classify_tests.rs new file mode 100644 index 000000000..7c292810d --- /dev/null +++ b/crates/core/src/expression/key_condition_classify_tests.rs @@ -0,0 +1,425 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::expression::tokenize; +use std::collections::HashMap; + +/// The index key schema the single-HASH cases use: HASH `h`, then RANGE +/// `a`, `b`, `c`, `d`. +const ONE_HASH: [&str; 1] = ["h"]; +const FOUR_RANGE: [&str; 4] = ["a", "b", "c", "d"]; + +/// Parse `expr` and classify it against `h` + `a, b, c, d`. +fn classify_one_hash(expr: &str) -> Result { + classify_with_names(expr, &HashMap::new()) +} + +fn classify_with_names( + expr: &str, + names: &HashMap, +) -> Result { + let tokens = tokenize(expr).unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_multipart(&ONE_HASH, &FOUR_RANGE, names)?; + Ok(kc) +} + +/// The attribute names of `extra_sk_conditions`, in order. +fn extra_sk_names(kc: &KeyCondition) -> Vec { + kc.extra_sk_conditions + .iter() + .map(|(path, _)| match path.first() { + Some(PathElement::Attribute(name)) => name.clone(), + other => panic!("unexpected path {other:?}"), + }) + .collect() +} + +/// The sort-key condition's attribute and a label for its operator. +fn sk_shape(kc: &KeyCondition) -> Option<(String, &'static str)> { + let cond = kc.sk_condition.as_ref()?; + let name = match cond.path().first() { + Some(PathElement::Attribute(name)) => name.clone(), + other => panic!("unexpected path {other:?}"), + }; + let op = match cond { + SortKeyCondition::Compare { op, .. } => match op { + CompareOp::Eq => "=", + CompareOp::Ne => "<>", + CompareOp::Lt => "<", + CompareOp::Le => "<=", + CompareOp::Gt => ">", + CompareOp::Ge => ">=", + }, + SortKeyCondition::Between { .. } => "BETWEEN", + SortKeyCondition::BeginsWith { .. } => "begins_with", + }; + Some((name, op)) +} + +fn assert_range_gap(expr: &str, without_eq: &str, present: &str) { + let err = classify_one_hash(expr).unwrap_err(); + let want = format!( + "RANGE key attributes {without_eq} must have equality conditions specified in the \ + query because a condition is present on key attribute {present}" + ); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}, want {want}" + ); +} + +#[test] +fn one_hash_multi_range_hash_only_condition_is_accepted() { + let kc = classify_one_hash("h = :h").unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("h".to_owned())]); + assert!(kc.extra_pk_conditions.is_empty()); + assert!(kc.sk_condition.is_none()); + assert!(kc.extra_sk_conditions.is_empty()); +} + +#[test] +fn one_hash_multi_range_equality_prefixes_are_accepted() { + // Equalities on a leading run of the RANGE attributes, up to all four. + for (expr, extra) in [ + ("h = :h AND a = :a", vec![]), + ("h = :h AND a = :a AND b = :b", vec!["b"]), + ("h = :h AND a = :a AND b = :b AND c = :c", vec!["b", "c"]), + ( + "h = :h AND a = :a AND b = :b AND c = :c AND d = :d", + vec!["b", "c", "d"], + ), + ] { + let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); + assert_eq!( + kc.pk_path, + vec![PathElement::Attribute("h".to_owned())], + "{expr}" + ); + assert!(kc.extra_pk_conditions.is_empty(), "{expr}"); + assert_eq!(sk_shape(&kc), Some(("a".to_owned(), "=")), "{expr}"); + assert_eq!(extra_sk_names(&kc), extra, "{expr}"); + } +} + +#[test] +fn one_hash_multi_range_clause_order_is_free() { + // The defect: the first clause was taken as the partition key, so + // `b = :b AND h = :h AND a = :a` was refused as missing `h`. + for expr in [ + "b = :b AND h = :h AND a = :a", + "a = :a AND b = :b AND h = :h", + "b = :b AND a = :a AND h = :h", + ] { + let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); + assert_eq!( + kc.pk_path, + vec![PathElement::Attribute("h".to_owned())], + "{expr}" + ); + assert_eq!(sk_shape(&kc), Some(("a".to_owned(), "=")), "{expr}"); + assert_eq!(extra_sk_names(&kc), vec!["b"], "{expr}"); + } +} + +#[test] +fn one_hash_multi_range_operator_on_the_last_given_attribute_is_accepted() { + for (expr, sk, extra) in [ + ("h = :h AND a > :a", ("a", ">"), vec![]), + ("h = :h AND a = :a AND b < :b", ("b", "<"), vec!["a"]), + ( + "h = :h AND a = :a AND b = :b AND c > :c", + ("c", ">"), + vec!["a", "b"], + ), + ( + "h = :h AND a = :a AND begins_with(b, :b)", + ("b", "begins_with"), + vec!["a"], + ), + ( + "h = :h AND a = :a AND b = :b AND c = :c AND begins_with(d, :d)", + ("d", "begins_with"), + vec!["a", "b", "c"], + ), + ( + "h = :h AND a = :a AND b = :b AND c = :c AND d BETWEEN :x AND :y", + ("d", "BETWEEN"), + vec!["a", "b", "c"], + ), + ( + "c > :c AND b = :b AND h = :h AND a = :a", + ("c", ">"), + vec!["a", "b"], + ), + ] { + let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); + assert_eq!( + kc.pk_path, + vec![PathElement::Attribute("h".to_owned())], + "{expr}" + ); + assert_eq!(sk_shape(&kc), Some((sk.0.to_owned(), sk.1)), "{expr}"); + assert_eq!(extra_sk_names(&kc), extra, "{expr}"); + } +} + +#[test] +fn one_hash_multi_range_gap_is_refused() { + // A condition on a RANGE attribute needs an equality on every RANGE + // attribute before it. The defect accepted `h = :h AND b = :b` and + // returned no items. + assert_range_gap("h = :h AND b = :b", "a", "b"); + assert_range_gap("h = :h AND a = :a AND c = :c", "b", "c"); + assert_range_gap("h = :h AND a = :a AND b = :b AND d > :d", "c", "d"); +} + +#[test] +fn one_hash_multi_range_operator_before_a_later_condition_is_refused() { + assert_range_gap("h = :h AND a = :a AND b > :b AND c = :c", "b", "c"); + assert_range_gap("h = :h AND begins_with(a, :a) AND b = :b", "a", "b"); +} + +#[test] +fn one_hash_multi_range_missing_hash_is_refused() { + for expr in [ + "a = :a AND b = :b AND c = :c", + "a = :a AND b = :b", + "a = :a", + ] { + let err = classify_one_hash(expr).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "HASH key attributes h must have equality conditions specified in the query"), + "expr {expr}: got {err:?}" + ); + } +} + +/// Classify against HASH `h1`, `h2` and RANGE `r`. +fn classify_two_hash(expr: &str) -> Result { + let tokens = tokenize(expr).unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_multipart(&["h1", "h2"], &["r"], &HashMap::new())?; + Ok(kc) +} + +#[test] +fn two_hash_missing_hash_names_every_missing_attribute() { + for (expr, missing) in [ + ("h1 = :x", "h2"), + ("h2 = :x", "h1"), + ("h1 = :x AND r = :y", "h2"), + ("r = :y", "h1, h2"), + ("h1 = :x AND h2 > :y", "h2"), + ] { + let err = classify_two_hash(expr).unwrap_err(); + let want = format!( + "HASH key attributes {missing} must have equality conditions specified in the query" + ); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}" + ); + } + assert!(classify_two_hash("h1 = :x AND h2 = :y").is_ok()); + assert!(classify_two_hash("h1 = :x AND h2 = :y AND r > :z").is_ok()); +} + +#[test] +fn a_second_condition_on_one_key_attribute_is_refused() { + const WANT: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only \ + contain one condition per key"; + for expr in [ + "h = :x AND h = :y", + "h = :x AND h = :y AND a = :z", + "h = :x AND a = :y AND a = :z", + "h = :h AND a = :a AND a > :x", + "h = :h AND a > :x AND a = :a", + "h = :h AND a = :a AND b = :n AND b > :lo", + "h = :h AND h > :x", + "h = :h AND h = :y AND c = :c", + "a = :a AND a = :y", + ] { + let err = classify_one_hash(expr).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if msg == WANT), + "expr {expr}: got {err:?}" + ); + } + for expr in [ + "h1 = :x AND h1 = :y AND h2 = :z", + "h1 = :x AND h1 = :y", + "h1 = :x AND h2 = :n AND r = :r AND r > :y", + "h1 = :x AND r = :r AND r = :y", + ] { + let err = classify_two_hash(expr).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if msg == WANT), + "expr {expr}: got {err:?}" + ); + } +} + +#[test] +fn a_condition_on_a_non_key_attribute_names_the_first_uncovered_range_attribute() { + for (expr, missing) in [ + ("h = :h AND z = :z", "a"), + ("h = :h AND z = :z AND y = :y", "a"), + ("h = :h AND z > :z", "a"), + ("h = :h AND a = :a AND z = :z", "b"), + ("h = :h AND a = :a AND z > :z", "b"), + ("h = :h AND a > :a AND z = :z", "b"), + ("h = :h AND a = :a AND b = :b AND z > :z", "c"), + ("h = :h AND a = :a AND b = :b AND c = :c AND z = :z", "d"), + ] { + let err = classify_one_hash(expr).unwrap_err(); + let want = format!("Query condition missed key schema element: {missing}"); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}" + ); + } + let err = classify_two_hash("h1 = :x AND h2 = :y AND z = :z").unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Query condition missed key schema element: r")); + // A gap is reported before the non-key attribute. + let err = classify_one_hash("h = :h AND b = :b AND z = :z").unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg.starts_with("RANGE key attributes a must have equality conditions"))); + // A missing HASH attribute is reported before the non-key attribute. + let err = classify_two_hash("h1 = :x AND z = :z").unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "HASH key attributes h2 must have equality conditions specified in the query")); +} + +#[test] +fn more_conditions_than_key_attributes_are_refused_by_count() { + for (expr, n) in [ + ( + "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND z = :z", + 6, + ), + ( + "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND z > :z", + 6, + ), + ( + "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND PK = :p", + 6, + ), + ] { + let err = classify_one_hash(expr).unwrap_err(); + let want = format!( + "The number of query conditions ({n}) exceeds the number of key attributes \ + defined in the schema (5)" + ); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}" + ); + } + let err = classify_two_hash("h1 = :x AND h2 = :y AND r = :r AND z = :z").unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "The number of query conditions (4) exceeds the number of key attributes defined in the schema (3)")); +} + +#[test] +fn the_count_is_refused_before_a_missing_hash_attribute_or_a_range_gap() { + // Each count case above has every key attribute, so they also pass + // with the count check moved after the missing-HASH and RANGE-gap + // checks. These lack the HASH attribute or leave a RANGE gap. + let count = |n: usize, attrs: usize| { + format!( + "The number of query conditions ({n}) exceeds the number of key attributes \ + defined in the schema ({attrs})" + ) + }; + for expr in [ + "a = :a AND b = :b AND c = :c AND d = :d AND z1 = :z AND z2 = :y", + "h = :h AND b = :b AND c = :c AND d = :d AND z1 = :z AND z2 = :y", + ] { + let err = classify_one_hash(expr).unwrap_err(); + let want = count(6, 5); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}" + ); + } + let expr = "a = :a AND b = :b AND c = :c AND z1 = :z AND z2 = :y"; + let err = classify_two_hash(expr).unwrap_err(); + let want = count(5, 3); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "expr {expr}: got {err:?}" + ); + // The same five clauses on HASH `h` and RANGE `a`, `b`, `c`, `d` do not + // exceed its five key attributes, so the missing HASH attribute is + // reported. + let err = classify_one_hash(expr).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "HASH key attributes h must have equality conditions specified in the query"), + "expr {expr}: got {err:?}" + ); +} + +#[test] +fn one_hash_multi_range_resolves_name_references() { + let names: HashMap = [("hh", "h"), ("aa", "a"), ("bb", "b")] + .into_iter() + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + let kc = classify_with_names("#bb > :b AND #hh = :h AND #aa = :a", &names).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("#hh".to_owned())]); + assert_eq!(sk_shape(&kc), Some(("#bb".to_owned(), ">"))); + assert_eq!(extra_sk_names(&kc), vec!["#aa"]); + + let err = classify_with_names("#hh = :h AND #bb = :b", &names).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg.starts_with("RANGE key attributes a must have")), + "got {err:?}" + ); +} + +#[test] +fn one_hash_one_range_schema_is_left_unchanged() { + let tokens = tokenize("sk = :s AND pk = :p").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_multipart(&["pk"], &["sk"], &HashMap::new()) + .unwrap(); + // Still the parser's assignment; resolve_pk_sk handles this schema. + assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); +} + +#[test] +fn multi_hash_partition_key_need_not_come_first() { + // With two HASH attributes the first clause used to be checked as the + // first HASH attribute before reclassification, so this order was + // refused as missing `pk1`. + let tokens = tokenize("sk = :s AND pk1 = :a AND pk2 = :b").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_multipart(&["pk1", "pk2"], &["sk"], &HashMap::new()) + .unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); + assert_eq!( + kc.extra_pk_conditions[0].0, + vec![PathElement::Attribute("pk2".to_owned())] + ); + assert_eq!(sk_shape(&kc), Some(("sk".to_owned(), "="))); + assert!(kc.extra_sk_conditions.is_empty()); +} + +#[test] +fn multi_hash_multi_range_operator_after_equality_keeps_both() { + // The non-equality on the second RANGE attribute is the sort-key + // condition, and the equality on the first is carried with it. + let tokens = tokenize("pk1 = :a AND pk2 = :b AND s1 = :x AND s2 > :y").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_multipart(&["pk1", "pk2"], &["s1", "s2"], &HashMap::new()) + .unwrap(); + assert_eq!(sk_shape(&kc), Some(("s2".to_owned(), ">"))); + assert_eq!(extra_sk_names(&kc), vec!["s1"]); +} diff --git a/crates/core/src/expression/key_condition_resolve_tests.rs b/crates/core/src/expression/key_condition_resolve_tests.rs new file mode 100644 index 000000000..0de3f86ef --- /dev/null +++ b/crates/core/src/expression/key_condition_resolve_tests.rs @@ -0,0 +1,223 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::expression::tokenize; +use crate::types::{KeySchemaElement, KeyType}; +use std::collections::HashMap; + +#[test] +fn resolve_pk_sk_swaps_when_reversed() { + // "sk = :sk AND pk = :pk" — parser assigns first Eq as PK + let tokens = tokenize("sk = :sk AND pk = :pk").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); + + kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); + match &kc.sk_condition { + Some(SortKeyCondition::Compare { + path, + op: CompareOp::Eq, + .. + }) => { + assert_eq!(path, &vec![PathElement::Attribute("sk".to_owned())]); + } + other => panic!("expected Eq SK condition, got {other:?}"), + } +} + +#[test] +fn resolve_pk_sk_no_swap_when_correct() { + let tokens = tokenize("pk = :pk AND sk = :sk").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); + + kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); +} + +#[test] +fn resolve_pk_sk_with_name_refs() { + let tokens = tokenize("#s = :sk AND #p = :pk").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + + let mut names = HashMap::new(); + names.insert("s".to_owned(), "sortkey".to_owned()); + names.insert("p".to_owned(), "partkey".to_owned()); + + kc.resolve_pk_sk("partkey", &names).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("#p".to_owned())]); +} + +#[test] +fn resolve_pk_sk_noop_for_non_eq_sk() { + // "pk = :pk AND sk > :val" — SK is not Eq, no ambiguity + let tokens = tokenize("pk = :pk AND sk > :val").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); +} + +#[test] +fn resolve_pk_sk_noop_for_single_clause() { + let tokens = tokenize("pk = :pk").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); +} + +#[test] +fn resolve_multipart_reclassifies() { + let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 = :v3").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let names = HashMap::new(); + kc.resolve_multipart(&["pk1", "pk2"], &["sk1"], &names) + .unwrap(); + + // After resolve_multipart, pk_path + extra_pk should have pk1 and pk2 + let pk_count = 1 + kc.extra_pk_conditions.len(); + assert_eq!(pk_count, 2); + // sk_condition should be the sk1 equality + assert!(kc.sk_condition.is_some()); +} + +#[test] +fn resolve_multipart_with_range() { + let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 > :v3").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let names = HashMap::new(); + kc.resolve_multipart(&["pk1", "pk2"], &["sk1"], &names) + .unwrap(); + + assert_eq!(1 + kc.extra_pk_conditions.len(), 2); + match &kc.sk_condition { + Some(SortKeyCondition::Compare { + op: CompareOp::Gt, .. + }) => {} + other => panic!("expected Gt SK condition, got {other:?}"), + } +} + +#[test] +fn resolve_multipart_reorders_to_schema_order() { + // Expression order: pk2, pk1, sk — reversed from key schema order [pk1, pk2] + let tokens = tokenize("pk2 = :v2 AND pk1 = :v1 AND sk = :v3").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let names = HashMap::new(); + kc.resolve_multipart(&["pk1", "pk2"], &["sk"], &names) + .unwrap(); + + // After resolve_multipart, pk_path should be pk1 (first in schema) + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); + // extra_pk_conditions should have pk2 + assert_eq!(kc.extra_pk_conditions.len(), 1); + assert_eq!( + kc.extra_pk_conditions[0].0, + vec![PathElement::Attribute("pk2".to_owned())] + ); +} + +#[test] +fn resolve_multipart_multi_range() { + // 2 HASH + 2 RANGE, all equality conditions + let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 = :v3 AND sk2 = :v4").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let names = HashMap::new(); + kc.resolve_multipart(&["pk1", "pk2"], &["sk1", "sk2"], &names) + .unwrap(); + + // 2 PK conditions + assert_eq!(1 + kc.extra_pk_conditions.len(), 2); + // Primary SK condition is sk1 + match &kc.sk_condition { + Some(SortKeyCondition::Compare { + path, + op: CompareOp::Eq, + .. + }) => { + assert_eq!(path, &vec![PathElement::Attribute("sk1".to_owned())]); + } + other => panic!("expected Eq SK condition on sk1, got {other:?}"), + } + // Extra SK condition is sk2 + assert_eq!(kc.extra_sk_conditions.len(), 1); + assert_eq!( + kc.extra_sk_conditions[0].0, + vec![PathElement::Attribute("sk2".to_owned())] + ); +} + +fn key(name: &str, key_type: KeyType) -> KeySchemaElement { + KeySchemaElement { + attribute_name: name.to_owned(), + key_type, + } +} + +#[test] +fn resolve_key_schema_reads_a_multi_attribute_schema_by_name() { + // Authorization reads the partition key value from `pk_path` after this + // call, so it must name the first HASH attribute for every clause order + // the engine serves. + let two_hash = [ + key("g1", KeyType::Hash), + key("g2", KeyType::Hash), + key("gs", KeyType::Range), + ]; + let two_range = [ + key("h", KeyType::Hash), + key("a", KeyType::Range), + key("b", KeyType::Range), + ]; + for (schema, expr) in [ + (&two_hash[..], "g2 = :g AND g1 = :v AND gs = :x"), + (&two_hash[..], "gs = :x AND g1 = :v AND g2 = :g"), + (&two_hash[..], "g2 = :g AND g1 = :v AND gs > :lo"), + (&two_range[..], "a = :a AND h = :v AND b = :c"), + (&two_range[..], "b = :c AND h = :v AND a = :a"), + (&two_range[..], "b > :lo AND a = :a AND h = :v"), + (&two_range[..], "begins_with(b, :p) AND a = :a AND h = :v"), + ] { + let tokens = tokenize(expr).unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + kc.resolve_key_schema(schema, &HashMap::new()) + .unwrap_or_else(|e| panic!("{expr}: {e:?}")); + let hash = &schema[0].attribute_name; + assert_eq!( + kc.pk_path, + vec![PathElement::Attribute(hash.clone())], + "{expr}" + ); + assert_eq!(kc.pk_value, Expr::Placeholder("v".to_owned()), "{expr}"); + } +} + +#[test] +fn resolve_key_schema_checks_values_before_resolve_pk_sk() { + let schema = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; + let tokens = tokenize("sk BETWEEN :lo AND :hi AND pk = :p").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let mut checked = Vec::new(); + kc.resolve_key_schema_with(&schema, &HashMap::new(), |_, value| { + checked.push(format!("{value:?}")); + Ok(()) + }) + .unwrap(); + assert_eq!(checked.len(), 3, "{checked:?}"); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); + + let tokens = tokenize("sk = :s AND pk = :p").unwrap(); + let mut kc = parse_key_condition(&tokens).unwrap(); + let err = kc + .resolve_key_schema_with(&schema, &HashMap::new(), |_, _| { + Err(validation_err("checked")) + }) + .unwrap_err(); + assert!(matches!(&err, DynamoDbError::ValidationException(msg) if msg == "checked")); + // The failed check left the parser's assignment in place. + assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); + + kc.resolve_key_schema(&schema, &HashMap::new()).unwrap(); + assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); +} diff --git a/crates/core/src/expression/key_condition_tests.rs b/crates/core/src/expression/key_condition_tests.rs index d156d9a60..703143b69 100644 --- a/crates/core/src/expression/key_condition_tests.rs +++ b/crates/core/src/expression/key_condition_tests.rs @@ -3,8 +3,6 @@ use super::*; use crate::expression::tokenize; -use crate::types::{KeySchemaElement, KeyType}; -use std::collections::HashMap; #[test] fn key_condition_redundant_parens_rejected_with_canonical_message() { @@ -35,67 +33,6 @@ fn key_condition_valid_parens_accepted() { } } -#[test] -fn resolve_pk_sk_swaps_when_reversed() { - // "sk = :sk AND pk = :pk" — parser assigns first Eq as PK - let tokens = tokenize("sk = :sk AND pk = :pk").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); - - kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - match &kc.sk_condition { - Some(SortKeyCondition::Compare { - path, - op: CompareOp::Eq, - .. - }) => { - assert_eq!(path, &vec![PathElement::Attribute("sk".to_owned())]); - } - other => panic!("expected Eq SK condition, got {other:?}"), - } -} - -#[test] -fn resolve_pk_sk_no_swap_when_correct() { - let tokens = tokenize("pk = :pk AND sk = :sk").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - - kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); -} - -#[test] -fn resolve_pk_sk_with_name_refs() { - let tokens = tokenize("#s = :sk AND #p = :pk").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - - let mut names = HashMap::new(); - names.insert("s".to_owned(), "sortkey".to_owned()); - names.insert("p".to_owned(), "partkey".to_owned()); - - kc.resolve_pk_sk("partkey", &names).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("#p".to_owned())]); -} - -#[test] -fn resolve_pk_sk_noop_for_non_eq_sk() { - // "pk = :pk AND sk > :val" — SK is not Eq, no ambiguity - let tokens = tokenize("pk = :pk AND sk > :val").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); -} - -#[test] -fn resolve_pk_sk_noop_for_single_clause() { - let tokens = tokenize("pk = :pk").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_pk_sk("pk", &HashMap::new()).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); -} - #[test] fn parse_three_clause_multipart() { // pk1 = :v1 AND pk2 = :v2 AND sk = :v3 @@ -172,87 +109,6 @@ fn reverse_comparator_maps_each_operator_and_is_involutive() { } } -#[test] -fn resolve_multipart_reclassifies() { - let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 = :v3").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let names = HashMap::new(); - kc.resolve_multipart(&["pk1", "pk2"], &["sk1"], &names) - .unwrap(); - - // After resolve_multipart, pk_path + extra_pk should have pk1 and pk2 - let pk_count = 1 + kc.extra_pk_conditions.len(); - assert_eq!(pk_count, 2); - // sk_condition should be the sk1 equality - assert!(kc.sk_condition.is_some()); -} - -#[test] -fn resolve_multipart_with_range() { - let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 > :v3").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let names = HashMap::new(); - kc.resolve_multipart(&["pk1", "pk2"], &["sk1"], &names) - .unwrap(); - - assert_eq!(1 + kc.extra_pk_conditions.len(), 2); - match &kc.sk_condition { - Some(SortKeyCondition::Compare { - op: CompareOp::Gt, .. - }) => {} - other => panic!("expected Gt SK condition, got {other:?}"), - } -} - -#[test] -fn resolve_multipart_reorders_to_schema_order() { - // Expression order: pk2, pk1, sk — reversed from key schema order [pk1, pk2] - let tokens = tokenize("pk2 = :v2 AND pk1 = :v1 AND sk = :v3").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let names = HashMap::new(); - kc.resolve_multipart(&["pk1", "pk2"], &["sk"], &names) - .unwrap(); - - // After resolve_multipart, pk_path should be pk1 (first in schema) - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); - // extra_pk_conditions should have pk2 - assert_eq!(kc.extra_pk_conditions.len(), 1); - assert_eq!( - kc.extra_pk_conditions[0].0, - vec![PathElement::Attribute("pk2".to_owned())] - ); -} - -#[test] -fn resolve_multipart_multi_range() { - // 2 HASH + 2 RANGE, all equality conditions - let tokens = tokenize("pk1 = :v1 AND pk2 = :v2 AND sk1 = :v3 AND sk2 = :v4").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let names = HashMap::new(); - kc.resolve_multipart(&["pk1", "pk2"], &["sk1", "sk2"], &names) - .unwrap(); - - // 2 PK conditions - assert_eq!(1 + kc.extra_pk_conditions.len(), 2); - // Primary SK condition is sk1 - match &kc.sk_condition { - Some(SortKeyCondition::Compare { - path, - op: CompareOp::Eq, - .. - }) => { - assert_eq!(path, &vec![PathElement::Attribute("sk1".to_owned())]); - } - other => panic!("expected Eq SK condition on sk1, got {other:?}"), - } - // Extra SK condition is sk2 - assert_eq!(kc.extra_sk_conditions.len(), 1); - assert_eq!( - kc.extra_sk_conditions[0].0, - vec![PathElement::Attribute("sk2".to_owned())] - ); -} - const NESTED_KEY_ERR: &str = "Invalid KeyConditionExpression: KeyConditionExpressions cannot have conditions on nested attributes"; #[test] @@ -424,499 +280,6 @@ fn clause_operands_reject_what_the_parser_rejects() { } } -/// The index key schema the single-HASH cases use: HASH `h`, then RANGE -/// `a`, `b`, `c`, `d`. -const ONE_HASH: [&str; 1] = ["h"]; -const FOUR_RANGE: [&str; 4] = ["a", "b", "c", "d"]; - -/// Parse `expr` and classify it against `h` + `a, b, c, d`. -fn classify_one_hash(expr: &str) -> Result { - classify_with_names(expr, &HashMap::new()) -} - -fn classify_with_names( - expr: &str, - names: &HashMap, -) -> Result { - let tokens = tokenize(expr).unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_multipart(&ONE_HASH, &FOUR_RANGE, names)?; - Ok(kc) -} - -/// The attribute names of `extra_sk_conditions`, in order. -fn extra_sk_names(kc: &KeyCondition) -> Vec { - kc.extra_sk_conditions - .iter() - .map(|(path, _)| match path.first() { - Some(PathElement::Attribute(name)) => name.clone(), - other => panic!("unexpected path {other:?}"), - }) - .collect() -} - -/// The sort-key condition's attribute and a label for its operator. -fn sk_shape(kc: &KeyCondition) -> Option<(String, &'static str)> { - let cond = kc.sk_condition.as_ref()?; - let name = match cond.path().first() { - Some(PathElement::Attribute(name)) => name.clone(), - other => panic!("unexpected path {other:?}"), - }; - let op = match cond { - SortKeyCondition::Compare { op, .. } => match op { - CompareOp::Eq => "=", - CompareOp::Ne => "<>", - CompareOp::Lt => "<", - CompareOp::Le => "<=", - CompareOp::Gt => ">", - CompareOp::Ge => ">=", - }, - SortKeyCondition::Between { .. } => "BETWEEN", - SortKeyCondition::BeginsWith { .. } => "begins_with", - }; - Some((name, op)) -} - -fn assert_range_gap(expr: &str, without_eq: &str, present: &str) { - let err = classify_one_hash(expr).unwrap_err(); - let want = format!( - "RANGE key attributes {without_eq} must have equality conditions specified in the \ - query because a condition is present on key attribute {present}" - ); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}, want {want}" - ); -} - -#[test] -fn one_hash_multi_range_hash_only_condition_is_accepted() { - let kc = classify_one_hash("h = :h").unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("h".to_owned())]); - assert!(kc.extra_pk_conditions.is_empty()); - assert!(kc.sk_condition.is_none()); - assert!(kc.extra_sk_conditions.is_empty()); -} - -#[test] -fn one_hash_multi_range_equality_prefixes_are_accepted() { - // Equalities on a leading run of the RANGE attributes, up to all four. - for (expr, extra) in [ - ("h = :h AND a = :a", vec![]), - ("h = :h AND a = :a AND b = :b", vec!["b"]), - ("h = :h AND a = :a AND b = :b AND c = :c", vec!["b", "c"]), - ( - "h = :h AND a = :a AND b = :b AND c = :c AND d = :d", - vec!["b", "c", "d"], - ), - ] { - let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); - assert_eq!( - kc.pk_path, - vec![PathElement::Attribute("h".to_owned())], - "{expr}" - ); - assert!(kc.extra_pk_conditions.is_empty(), "{expr}"); - assert_eq!(sk_shape(&kc), Some(("a".to_owned(), "=")), "{expr}"); - assert_eq!(extra_sk_names(&kc), extra, "{expr}"); - } -} - -#[test] -fn one_hash_multi_range_clause_order_is_free() { - // The defect: the first clause was taken as the partition key, so - // `b = :b AND h = :h AND a = :a` was refused as missing `h`. - for expr in [ - "b = :b AND h = :h AND a = :a", - "a = :a AND b = :b AND h = :h", - "b = :b AND a = :a AND h = :h", - ] { - let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); - assert_eq!( - kc.pk_path, - vec![PathElement::Attribute("h".to_owned())], - "{expr}" - ); - assert_eq!(sk_shape(&kc), Some(("a".to_owned(), "=")), "{expr}"); - assert_eq!(extra_sk_names(&kc), vec!["b"], "{expr}"); - } -} - -#[test] -fn one_hash_multi_range_operator_on_the_last_given_attribute_is_accepted() { - for (expr, sk, extra) in [ - ("h = :h AND a > :a", ("a", ">"), vec![]), - ("h = :h AND a = :a AND b < :b", ("b", "<"), vec!["a"]), - ( - "h = :h AND a = :a AND b = :b AND c > :c", - ("c", ">"), - vec!["a", "b"], - ), - ( - "h = :h AND a = :a AND begins_with(b, :b)", - ("b", "begins_with"), - vec!["a"], - ), - ( - "h = :h AND a = :a AND b = :b AND c = :c AND begins_with(d, :d)", - ("d", "begins_with"), - vec!["a", "b", "c"], - ), - ( - "h = :h AND a = :a AND b = :b AND c = :c AND d BETWEEN :x AND :y", - ("d", "BETWEEN"), - vec!["a", "b", "c"], - ), - ( - "c > :c AND b = :b AND h = :h AND a = :a", - ("c", ">"), - vec!["a", "b"], - ), - ] { - let kc = classify_one_hash(expr).unwrap_or_else(|e| panic!("{expr}: {e:?}")); - assert_eq!( - kc.pk_path, - vec![PathElement::Attribute("h".to_owned())], - "{expr}" - ); - assert_eq!(sk_shape(&kc), Some((sk.0.to_owned(), sk.1)), "{expr}"); - assert_eq!(extra_sk_names(&kc), extra, "{expr}"); - } -} - -#[test] -fn one_hash_multi_range_gap_is_refused() { - // A condition on a RANGE attribute needs an equality on every RANGE - // attribute before it. The defect accepted `h = :h AND b = :b` and - // returned no items. - assert_range_gap("h = :h AND b = :b", "a", "b"); - assert_range_gap("h = :h AND a = :a AND c = :c", "b", "c"); - assert_range_gap("h = :h AND a = :a AND b = :b AND d > :d", "c", "d"); -} - -#[test] -fn one_hash_multi_range_operator_before_a_later_condition_is_refused() { - assert_range_gap("h = :h AND a = :a AND b > :b AND c = :c", "b", "c"); - assert_range_gap("h = :h AND begins_with(a, :a) AND b = :b", "a", "b"); -} - -#[test] -fn one_hash_multi_range_missing_hash_is_refused() { - for expr in [ - "a = :a AND b = :b AND c = :c", - "a = :a AND b = :b", - "a = :a", - ] { - let err = classify_one_hash(expr).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "HASH key attributes h must have equality conditions specified in the query"), - "expr {expr}: got {err:?}" - ); - } -} - -/// Classify against HASH `h1`, `h2` and RANGE `r`. -fn classify_two_hash(expr: &str) -> Result { - let tokens = tokenize(expr).unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_multipart(&["h1", "h2"], &["r"], &HashMap::new())?; - Ok(kc) -} - -#[test] -fn two_hash_missing_hash_names_every_missing_attribute() { - for (expr, missing) in [ - ("h1 = :x", "h2"), - ("h2 = :x", "h1"), - ("h1 = :x AND r = :y", "h2"), - ("r = :y", "h1, h2"), - ("h1 = :x AND h2 > :y", "h2"), - ] { - let err = classify_two_hash(expr).unwrap_err(); - let want = format!( - "HASH key attributes {missing} must have equality conditions specified in the query" - ); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}" - ); - } - assert!(classify_two_hash("h1 = :x AND h2 = :y").is_ok()); - assert!(classify_two_hash("h1 = :x AND h2 = :y AND r > :z").is_ok()); -} - -#[test] -fn a_second_condition_on_one_key_attribute_is_refused() { - const WANT: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only \ - contain one condition per key"; - for expr in [ - "h = :x AND h = :y", - "h = :x AND h = :y AND a = :z", - "h = :x AND a = :y AND a = :z", - "h = :h AND a = :a AND a > :x", - "h = :h AND a > :x AND a = :a", - "h = :h AND a = :a AND b = :n AND b > :lo", - "h = :h AND h > :x", - "h = :h AND h = :y AND c = :c", - "a = :a AND a = :y", - ] { - let err = classify_one_hash(expr).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if msg == WANT), - "expr {expr}: got {err:?}" - ); - } - for expr in [ - "h1 = :x AND h1 = :y AND h2 = :z", - "h1 = :x AND h1 = :y", - "h1 = :x AND h2 = :n AND r = :r AND r > :y", - "h1 = :x AND r = :r AND r = :y", - ] { - let err = classify_two_hash(expr).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if msg == WANT), - "expr {expr}: got {err:?}" - ); - } -} - -#[test] -fn a_condition_on_a_non_key_attribute_names_the_first_uncovered_range_attribute() { - for (expr, missing) in [ - ("h = :h AND z = :z", "a"), - ("h = :h AND z = :z AND y = :y", "a"), - ("h = :h AND z > :z", "a"), - ("h = :h AND a = :a AND z = :z", "b"), - ("h = :h AND a = :a AND z > :z", "b"), - ("h = :h AND a > :a AND z = :z", "b"), - ("h = :h AND a = :a AND b = :b AND z > :z", "c"), - ("h = :h AND a = :a AND b = :b AND c = :c AND z = :z", "d"), - ] { - let err = classify_one_hash(expr).unwrap_err(); - let want = format!("Query condition missed key schema element: {missing}"); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}" - ); - } - let err = classify_two_hash("h1 = :x AND h2 = :y AND z = :z").unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Query condition missed key schema element: r")); - // A gap is reported before the non-key attribute. - let err = classify_one_hash("h = :h AND b = :b AND z = :z").unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg.starts_with("RANGE key attributes a must have equality conditions"))); - // A missing HASH attribute is reported before the non-key attribute. - let err = classify_two_hash("h1 = :x AND z = :z").unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "HASH key attributes h2 must have equality conditions specified in the query")); -} - -#[test] -fn more_conditions_than_key_attributes_are_refused_by_count() { - for (expr, n) in [ - ( - "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND z = :z", - 6, - ), - ( - "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND z > :z", - 6, - ), - ( - "h = :h AND a = :a AND b = :b AND c = :c AND d = :d AND PK = :p", - 6, - ), - ] { - let err = classify_one_hash(expr).unwrap_err(); - let want = format!( - "The number of query conditions ({n}) exceeds the number of key attributes \ - defined in the schema (5)" - ); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}" - ); - } - let err = classify_two_hash("h1 = :x AND h2 = :y AND r = :r AND z = :z").unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "The number of query conditions (4) exceeds the number of key attributes defined in the schema (3)")); -} - -#[test] -fn the_count_is_refused_before_a_missing_hash_attribute_or_a_range_gap() { - // Each count case above has every key attribute, so they also pass - // with the count check moved after the missing-HASH and RANGE-gap - // checks. These lack the HASH attribute or leave a RANGE gap. - let count = |n: usize, attrs: usize| { - format!( - "The number of query conditions ({n}) exceeds the number of key attributes \ - defined in the schema ({attrs})" - ) - }; - for expr in [ - "a = :a AND b = :b AND c = :c AND d = :d AND z1 = :z AND z2 = :y", - "h = :h AND b = :b AND c = :c AND d = :d AND z1 = :z AND z2 = :y", - ] { - let err = classify_one_hash(expr).unwrap_err(); - let want = count(6, 5); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}" - ); - } - let expr = "a = :a AND b = :b AND c = :c AND z1 = :z AND z2 = :y"; - let err = classify_two_hash(expr).unwrap_err(); - let want = count(5, 3); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "expr {expr}: got {err:?}" - ); - // The same five clauses on HASH `h` and RANGE `a`, `b`, `c`, `d` do not - // exceed its five key attributes, so the missing HASH attribute is - // reported. - let err = classify_one_hash(expr).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "HASH key attributes h must have equality conditions specified in the query"), - "expr {expr}: got {err:?}" - ); -} - -#[test] -fn one_hash_multi_range_resolves_name_references() { - let names: HashMap = [("hh", "h"), ("aa", "a"), ("bb", "b")] - .into_iter() - .map(|(k, v)| (k.to_owned(), v.to_owned())) - .collect(); - let kc = classify_with_names("#bb > :b AND #hh = :h AND #aa = :a", &names).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("#hh".to_owned())]); - assert_eq!(sk_shape(&kc), Some(("#bb".to_owned(), ">"))); - assert_eq!(extra_sk_names(&kc), vec!["#aa"]); - - let err = classify_with_names("#hh = :h AND #bb = :b", &names).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg.starts_with("RANGE key attributes a must have")), - "got {err:?}" - ); -} - -#[test] -fn one_hash_one_range_schema_is_left_unchanged() { - let tokens = tokenize("sk = :s AND pk = :p").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_multipart(&["pk"], &["sk"], &HashMap::new()) - .unwrap(); - // Still the parser's assignment; resolve_pk_sk handles this schema. - assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); -} - -#[test] -fn multi_hash_partition_key_need_not_come_first() { - // With two HASH attributes the first clause used to be checked as the - // first HASH attribute before reclassification, so this order was - // refused as missing `pk1`. - let tokens = tokenize("sk = :s AND pk1 = :a AND pk2 = :b").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_multipart(&["pk1", "pk2"], &["sk"], &HashMap::new()) - .unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk1".to_owned())]); - assert_eq!( - kc.extra_pk_conditions[0].0, - vec![PathElement::Attribute("pk2".to_owned())] - ); - assert_eq!(sk_shape(&kc), Some(("sk".to_owned(), "="))); - assert!(kc.extra_sk_conditions.is_empty()); -} - -#[test] -fn multi_hash_multi_range_operator_after_equality_keeps_both() { - // The non-equality on the second RANGE attribute is the sort-key - // condition, and the equality on the first is carried with it. - let tokens = tokenize("pk1 = :a AND pk2 = :b AND s1 = :x AND s2 > :y").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_multipart(&["pk1", "pk2"], &["s1", "s2"], &HashMap::new()) - .unwrap(); - assert_eq!(sk_shape(&kc), Some(("s2".to_owned(), ">"))); - assert_eq!(extra_sk_names(&kc), vec!["s1"]); -} - -fn key(name: &str, key_type: KeyType) -> KeySchemaElement { - KeySchemaElement { - attribute_name: name.to_owned(), - key_type, - } -} - -#[test] -fn resolve_key_schema_reads_a_multi_attribute_schema_by_name() { - // Authorization reads the partition key value from `pk_path` after this - // call, so it must name the first HASH attribute for every clause order - // the engine serves. - let two_hash = [ - key("g1", KeyType::Hash), - key("g2", KeyType::Hash), - key("gs", KeyType::Range), - ]; - let two_range = [ - key("h", KeyType::Hash), - key("a", KeyType::Range), - key("b", KeyType::Range), - ]; - for (schema, expr) in [ - (&two_hash[..], "g2 = :g AND g1 = :v AND gs = :x"), - (&two_hash[..], "gs = :x AND g1 = :v AND g2 = :g"), - (&two_hash[..], "g2 = :g AND g1 = :v AND gs > :lo"), - (&two_range[..], "a = :a AND h = :v AND b = :c"), - (&two_range[..], "b = :c AND h = :v AND a = :a"), - (&two_range[..], "b > :lo AND a = :a AND h = :v"), - (&two_range[..], "begins_with(b, :p) AND a = :a AND h = :v"), - ] { - let tokens = tokenize(expr).unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - kc.resolve_key_schema(schema, &HashMap::new()) - .unwrap_or_else(|e| panic!("{expr}: {e:?}")); - let hash = &schema[0].attribute_name; - assert_eq!( - kc.pk_path, - vec![PathElement::Attribute(hash.clone())], - "{expr}" - ); - assert_eq!(kc.pk_value, Expr::Placeholder("v".to_owned()), "{expr}"); - } -} - -#[test] -fn resolve_key_schema_checks_values_before_resolve_pk_sk() { - let schema = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; - let tokens = tokenize("sk BETWEEN :lo AND :hi AND pk = :p").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let mut checked = Vec::new(); - kc.resolve_key_schema_with(&schema, &HashMap::new(), |_, value| { - checked.push(format!("{value:?}")); - Ok(()) - }) - .unwrap(); - assert_eq!(checked.len(), 3, "{checked:?}"); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); - - let tokens = tokenize("sk = :s AND pk = :p").unwrap(); - let mut kc = parse_key_condition(&tokens).unwrap(); - let err = kc - .resolve_key_schema_with(&schema, &HashMap::new(), |_, _| { - Err(validation_err("checked")) - }) - .unwrap_err(); - assert!(matches!(&err, DynamoDbError::ValidationException(msg) if msg == "checked")); - // The failed check left the parser's assignment in place. - assert_eq!(kc.pk_path, vec![PathElement::Attribute("sk".to_owned())]); - - kc.resolve_key_schema(&schema, &HashMap::new()).unwrap(); - assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); -} - // Syntax error wording measured 2026-10-25 (us-east-1) on Query. fn kce_msg(src: &str) -> String { From cda129d06683f75a4de3a439b05e5f5fa47e1066 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:51:11 +0000 Subject: [PATCH 23/37] refactor(engine): move the tests this change added to expression_helpers.rs into their own file This is a pure move. With the tests of this round, crates/engine/src/expression_helpers.rs had 744 lines. The seven tests and three helpers this change added move to expression_helpers_order_tests.rs, loaded with `#[path]` as the start key tests are. The block runs from the operator cap placement comment to projection_syntax_error_quotes_the_source. The body is de-indented by one level and is otherwise unchanged. The tests that exist on main stay in the file, which now has 579 lines, and the same 18 tests run. --- crates/engine/src/expression_helpers.rs | 173 +---------------- .../src/expression_helpers_order_tests.rs | 177 ++++++++++++++++++ 2 files changed, 181 insertions(+), 169 deletions(-) create mode 100644 crates/engine/src/expression_helpers_order_tests.rs diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 3e4aec2b0..6baaf61be 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -473,175 +473,6 @@ mod tests { ); } - // Operator cap placement, measured 2026-10-25 (us-east-1). - - fn chain(n: usize) -> String { - vec!["#v = :v"; n].join(" OR ") - } - - /// Resolve `expr` with `#v` defined, `:v` an S, `:b` a BOOL and `:n` an N. - fn resolve(expr: &str) -> Result<(Option, ExpressionMaps), DynamoDbError> { - let names = HashMap::from([("#v".to_owned(), "v".to_owned())]); - let values = HashMap::from([ - (":v".to_owned(), AttributeValue::S("x".to_owned())), - (":b".to_owned(), AttributeValue::Bool(true)), - (":n".to_owned(), AttributeValue::N("1".to_owned())), - ]); - resolve_condition( - Some(expr), - Some(&names), - Some(&values), - None, - None, - &LimitsConfig::default(), - ) - } - - fn resolve_err(expr: &str) -> String { - match resolve(expr) { - Err(DynamoDbError::ValidationException(msg)) => msg, - other => panic!("expected ValidationException, got {other:?}"), - } - } - - #[test] - fn count_over_the_cap_is_refused_with_the_full_count() { - // 151 comparisons and 150 ORs: 301 [a30]. - assert_eq!( - resolve_err(&chain(151)), - "Invalid ConditionExpression: The expression contains too many operators; operator count: 301" - ); - // 150 comparisons and 149 ORs: 299, accepted [a30]. - assert!(resolve(&chain(150)).is_ok()); - } - - #[test] - fn placeholder_and_operand_faults_beat_the_count() { - // The service's answers of 2026-11-19 (us-east-1) on PutItem; [p17] of - // 2026-10-25 for the BOOL operand. - let rows = [ - ( - "p01", - format!("{} OR #v = :zz", chain(151)), - "An expression attribute value used in expression is not defined; attribute value: :zz", - ), - ( - "p02", - format!("{} OR #x = :v", chain(151)), - "An expression attribute name used in the document path is not defined; attribute name: #x", - ), - ( - "p03", - format!("{} OR begins_with(#v, :n)", chain(151)), - "Incorrect operand type for operator or function; operator or function: begins_with, operand type: N", - ), - ( - "p17", - format!("{} OR #v < :b", chain(150)), - "Incorrect operand type for operator or function; operator or function: <, operand type: BOOL", - ), - ]; - for (case, expr, want) in rows { - assert_eq!( - resolve_err(&expr), - format!("Invalid ConditionExpression: {want}"), - "{case}" - ); - } - } - - #[test] - fn an_undefined_value_in_a_branch_evaluation_skips_is_refused() { - // [p04] measured 2026-11-19: `attribute_not_exists(pk)` holds for an - // absent item, and the service still refuses `:zz`. - assert_eq!( - resolve_err("attribute_not_exists(pk) OR #v = :zz"), - "Invalid ConditionExpression: An expression attribute value used in expression is not defined; attribute value: :zz" - ); - } - - #[test] - fn syntax_error_beats_the_count() { - // [e04] a 300-term chain followed by ` = =`. - assert_eq!( - resolve_err(&format!("{} = =", chain(300))), - "Invalid ConditionExpression: Syntax error; token: \"=\", near: \":v = =\"" - ); - } - - #[test] - fn key_condition_count_runs_before_the_key_grammar() { - let limits = LimitsConfig::default(); - // [a62] `pk = :v OR` + 150 terms: 301, the count, not the OR refusal. - let expr = format!("pk = :v OR {}", vec!["#v = :v"; 150].join(" AND ")); - let err = parse_key_condition_expr(&expr, &limits).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid KeyConditionExpression: The expression contains too many operators; operator count: 301"), - "got {err:?}" - ); - // [a63] two conditions joined by OR under the cap: the key grammar - // answers (measured 2026-11-19 as x25). - let err = parse_key_condition_expr("pk = :v OR sk = :s", &limits).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid KeyConditionExpression: Invalid operator used in KeyConditionExpression"), - "got {err:?}" - ); - // [d23] a syntax error is reported by the key grammar in the service's words. - let err = parse_key_condition_expr("pk = :v AND", &limits).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"AND\""), - "got {err:?}" - ); - } - - #[test] - fn key_condition_syntax_errors_come_before_the_key_rules() { - // Measured 2026-11-19 (us-east-1) on Query, probe cases in the first - // column. A syntax error in the condition grammar is reported first; - // an OR or a NOT that the grammar accepts is the key rules' refusal. - let invalid = "Invalid operator used in KeyConditionExpression"; - let syntax = - |token: &str, near: &str| format!("Syntax error; token: \"{token}\", near: \"{near}\""); - let rows = [ - ("x20", "NOT pk = :p", invalid.to_owned()), - ("x21", "pk = :p AND NOT sk = :s", invalid.to_owned()), - ("k06", "NOT NOT pk = :p", invalid.to_owned()), - ("k08", "(pk = :p) OR (sk = :s)", invalid.to_owned()), - ("x22", "pk = :p AND NOT", syntax("", "NOT")), - ("x23", "pk = :p OR", syntax("", "OR")), - ("x24", "pk = :p =", syntax("=", ":p =")), - ("k01", "pk = :p sk = :s", syntax("sk", ":p sk =")), - ("k02", "pk = :p AND sk = :s sk", syntax("sk", ":s sk")), - ("k05", "pk = :p OR OR sk = :s", syntax("OR", "OR OR sk")), - ("k10", "NOT", syntax("", "NOT")), - ("k11", "pk = :p AND NOT NOT", syntax("", "NOT")), - ]; - let limits = LimitsConfig::default(); - for (case, expr, want) in rows { - let err = parse_key_condition_expr(expr, &limits).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if *msg == format!("Invalid KeyConditionExpression: {want}")), - "{case}: got {err:?}" - ); - } - } - - #[test] - fn projection_syntax_error_quotes_the_source() { - // [d27] - let limits = LimitsConfig::default(); - let err = parse_projection_expr("#v, , #v", &limits).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid ProjectionExpression: Syntax error; token: \",\", near: \", , #v\""), - "got {err:?}" - ); - } - /// Size and token limits raised so only the depth limit refuses the /// expressions below. fn raised() -> LimitsConfig { @@ -742,3 +573,7 @@ mod tests { ); } } + +#[cfg(test)] +#[path = "expression_helpers_order_tests.rs"] +mod order_tests; diff --git a/crates/engine/src/expression_helpers_order_tests.rs b/crates/engine/src/expression_helpers_order_tests.rs new file mode 100644 index 000000000..c0789ba63 --- /dev/null +++ b/crates/engine/src/expression_helpers_order_tests.rs @@ -0,0 +1,177 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The order of the checks around the operator count and the syntax +//! error, as measured on the service. + +use super::*; +use extenddb_core::limits::LimitsConfig; + +// Operator cap placement, measured 2026-10-25 (us-east-1). + +fn chain(n: usize) -> String { + vec!["#v = :v"; n].join(" OR ") +} + +/// Resolve `expr` with `#v` defined, `:v` an S, `:b` a BOOL and `:n` an N. +fn resolve(expr: &str) -> Result<(Option, ExpressionMaps), DynamoDbError> { + let names = HashMap::from([("#v".to_owned(), "v".to_owned())]); + let values = HashMap::from([ + (":v".to_owned(), AttributeValue::S("x".to_owned())), + (":b".to_owned(), AttributeValue::Bool(true)), + (":n".to_owned(), AttributeValue::N("1".to_owned())), + ]); + resolve_condition( + Some(expr), + Some(&names), + Some(&values), + None, + None, + &LimitsConfig::default(), + ) +} + +fn resolve_err(expr: &str) -> String { + match resolve(expr) { + Err(DynamoDbError::ValidationException(msg)) => msg, + other => panic!("expected ValidationException, got {other:?}"), + } +} + +#[test] +fn count_over_the_cap_is_refused_with_the_full_count() { + // 151 comparisons and 150 ORs: 301 [a30]. + assert_eq!( + resolve_err(&chain(151)), + "Invalid ConditionExpression: The expression contains too many operators; operator count: 301" + ); + // 150 comparisons and 149 ORs: 299, accepted [a30]. + assert!(resolve(&chain(150)).is_ok()); +} + +#[test] +fn placeholder_and_operand_faults_beat_the_count() { + // The service's answers of 2026-11-19 (us-east-1) on PutItem; [p17] of + // 2026-10-25 for the BOOL operand. + let rows = [ + ( + "p01", + format!("{} OR #v = :zz", chain(151)), + "An expression attribute value used in expression is not defined; attribute value: :zz", + ), + ( + "p02", + format!("{} OR #x = :v", chain(151)), + "An expression attribute name used in the document path is not defined; attribute name: #x", + ), + ( + "p03", + format!("{} OR begins_with(#v, :n)", chain(151)), + "Incorrect operand type for operator or function; operator or function: begins_with, operand type: N", + ), + ( + "p17", + format!("{} OR #v < :b", chain(150)), + "Incorrect operand type for operator or function; operator or function: <, operand type: BOOL", + ), + ]; + for (case, expr, want) in rows { + assert_eq!( + resolve_err(&expr), + format!("Invalid ConditionExpression: {want}"), + "{case}" + ); + } +} + +#[test] +fn an_undefined_value_in_a_branch_evaluation_skips_is_refused() { + // [p04] measured 2026-11-19: `attribute_not_exists(pk)` holds for an + // absent item, and the service still refuses `:zz`. + assert_eq!( + resolve_err("attribute_not_exists(pk) OR #v = :zz"), + "Invalid ConditionExpression: An expression attribute value used in expression is not defined; attribute value: :zz" + ); +} + +#[test] +fn syntax_error_beats_the_count() { + // [e04] a 300-term chain followed by ` = =`. + assert_eq!( + resolve_err(&format!("{} = =", chain(300))), + "Invalid ConditionExpression: Syntax error; token: \"=\", near: \":v = =\"" + ); +} + +#[test] +fn key_condition_count_runs_before_the_key_grammar() { + let limits = LimitsConfig::default(); + // [a62] `pk = :v OR` + 150 terms: 301, the count, not the OR refusal. + let expr = format!("pk = :v OR {}", vec!["#v = :v"; 150].join(" AND ")); + let err = parse_key_condition_expr(&expr, &limits).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid KeyConditionExpression: The expression contains too many operators; operator count: 301"), + "got {err:?}" + ); + // [a63] two conditions joined by OR under the cap: the key grammar + // answers (measured 2026-11-19 as x25). + let err = parse_key_condition_expr("pk = :v OR sk = :s", &limits).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid KeyConditionExpression: Invalid operator used in KeyConditionExpression"), + "got {err:?}" + ); + // [d23] a syntax error is reported by the key grammar in the service's words. + let err = parse_key_condition_expr("pk = :v AND", &limits).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"AND\""), + "got {err:?}" + ); +} + +#[test] +fn key_condition_syntax_errors_come_before_the_key_rules() { + // Measured 2026-11-19 (us-east-1) on Query, probe cases in the first + // column. A syntax error in the condition grammar is reported first; + // an OR or a NOT that the grammar accepts is the key rules' refusal. + let invalid = "Invalid operator used in KeyConditionExpression"; + let syntax = + |token: &str, near: &str| format!("Syntax error; token: \"{token}\", near: \"{near}\""); + let rows = [ + ("x20", "NOT pk = :p", invalid.to_owned()), + ("x21", "pk = :p AND NOT sk = :s", invalid.to_owned()), + ("k06", "NOT NOT pk = :p", invalid.to_owned()), + ("k08", "(pk = :p) OR (sk = :s)", invalid.to_owned()), + ("x22", "pk = :p AND NOT", syntax("", "NOT")), + ("x23", "pk = :p OR", syntax("", "OR")), + ("x24", "pk = :p =", syntax("=", ":p =")), + ("k01", "pk = :p sk = :s", syntax("sk", ":p sk =")), + ("k02", "pk = :p AND sk = :s sk", syntax("sk", ":s sk")), + ("k05", "pk = :p OR OR sk = :s", syntax("OR", "OR OR sk")), + ("k10", "NOT", syntax("", "NOT")), + ("k11", "pk = :p AND NOT NOT", syntax("", "NOT")), + ]; + let limits = LimitsConfig::default(); + for (case, expr, want) in rows { + let err = parse_key_condition_expr(expr, &limits).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if *msg == format!("Invalid KeyConditionExpression: {want}")), + "{case}: got {err:?}" + ); + } +} + +#[test] +fn projection_syntax_error_quotes_the_source() { + // [d27] + let limits = LimitsConfig::default(); + let err = parse_projection_expr("#v, , #v", &limits).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid ProjectionExpression: Syntax error; token: \",\", near: \", , #v\""), + "got {err:?}" + ); +} From 78cddf0797011198eacea0f7db4017a8c3bded4e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:17:16 +0000 Subject: [PATCH 24/37] refactor(engine): call validate_operator_count directly and shorten the check_parsed_condition doc `check_operator_count` passed `limits.max_expression_operators` to `validate_operator_count` and did nothing else, and it had two callers. Both callers now call `validate_operator_count`, and the wrapper is gone. The doc of `check_parsed_condition` repeated the measurements in the docs of `validate_placeholders_and_operands` and of the wrapper. It is now one sentence with links to the two checks. The TransactWriteItems sentence of the wrapper's doc moves to it with the same measurements. No answer changes. --- crates/engine/src/expression_helpers.rs | 47 ++++++++----------------- 1 file changed, 14 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 6baaf61be..bd30d2916 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -94,38 +94,15 @@ pub fn parse_condition_expr(expr: &str, limits: &LimitsConfig) -> Result: The expression contains too many operators; operator -/// count: `). +/// Check a parsed condition or filter in the service's order, after the parse +/// and before the unused placeholder check and the table lookup: +/// [`validate_placeholders_and_operands`], then [`validate_operator_count`] +/// against `limits.max_expression_operators`. /// -/// Measured 2026-10-25 (us-east-1): the check runs after the syntax, reserved -/// word, undefined placeholder and operand type checks and before the unused -/// placeholder check and the table lookup. `TransactWriteItems` counts the -/// same way, but it does not call this check (measured 2026-11-19: a Put of -/// 151, 200 or 300 `#v = :v` terms joined by OR answers 301, 399 or 599, a -/// ConditionCheck of 151 terms answers 301, and a Put of 150 terms is -/// evaluated). -/// -/// # Errors -/// -/// Returns `DynamoDbError::ValidationException` when the count is over the cap. -pub fn check_operator_count( - expr: &Expr, - kind: ExpressionKind, - limits: &LimitsConfig, -) -> Result<(), DynamoDbError> { - validate_operator_count(expr, kind, limits.max_expression_operators) -} - -/// Check a parsed condition or filter in the service's order: its placeholders -/// and operand types (see [`validate_placeholders_and_operands`]), then its -/// operator count. Measured 2026-11-19 (us-east-1) on Scan, Query, PutItem, -/// UpdateItem and DeleteItem: with 151 `#v = :v` terms joined by OR, an added -/// `OR #v = :zz` with `:zz` undefined answers the undefined value, `OR #x = -/// :v` the undefined name, `OR #v < :b` with `:b` a BOOL and `OR -/// begins_with(#v, :n)` with `:n` an N the operand type, and an unused `:u` -/// the count. +/// `TransactWriteItems` counts the same way on the service, but it does not +/// call this check (measured 2026-11-19: a Put of 151, 200 or 300 `#v = :v` +/// terms joined by OR answers 301, 399 or 599, a ConditionCheck of 151 terms +/// answers 301, and a Put of 150 terms is evaluated). /// /// # Errors /// @@ -138,7 +115,7 @@ pub fn check_parsed_condition( limits: &LimitsConfig, ) -> Result<(), DynamoDbError> { validate_placeholders_and_operands(expr, maps).map_err(|e| prefix_expression_error(e, kind))?; - check_operator_count(expr, kind, limits) + validate_operator_count(expr, kind, limits.max_expression_operators) } /// Tokenize, reserved-word check, and parse an `UpdateExpression`. @@ -317,7 +294,11 @@ pub fn parse_key_condition_expr( // condition parser reports the error in its own words. match parse_condition_from(&tokens, expr, limits.max_expression_depth) { Ok(condition) => { - check_operator_count(&condition, ExpressionKind::KeyCondition, limits)?; + validate_operator_count( + &condition, + ExpressionKind::KeyCondition, + limits.max_expression_operators, + )?; } Err(err) if is_syntax_error(&err) => return Err(err), Err(_) => {} From 61e428839dc627335f00f3d7c37910e54e4c094d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:18:50 +0000 Subject: [PATCH 25/37] fix(query): report an undefined placeholder or operand type ahead of the key condition count A KeyConditionExpression over the operator cap answered the count, even when it held an undefined placeholder or an operand of the wrong type. The service answers that fault. When the count refuses a key condition, `parse_key_condition_expr` now runs `validate_placeholders_and_operands` on it and reports the first fault the pass finds. If the pass finds no fault, the count answers as before. `handle_query` passes the expression maps it builds before the parse. A key condition under the cap does not go through the pass, so its answers do not change. Measured 2026-11-20 in us-east-1, each request sent twice with the same answer. The table has HASH `pk` and RANGE `sk`, both S, and "150 terms" is 150 `#v = :v` joined by AND: - `#x = :p AND` 150 terms, with `#x` undefined, answers `Invalid KeyConditionExpression: An expression attribute name used in the document path is not defined; attribute name: #x`. Main gives the same answer. Before this commit the branch answered `operator count: 301`, and it now answers as main and the service do. - `pk = :zz AND` 150 terms answers the undefined value `:zz`. - `pk = :p AND begins_with(sk, :n) AND` 149 terms, with `:n` an N, answers the `begins_with` operand type N. - `pk = :p AND` 150 terms `AND #y = :v` answers the undefined name `#y`. - `pk = :p AND sk < :b AND` 149 terms, with `:b` a BOOL, answers the `<` operand type BOOL. `TestChecksAheadOfTheCount::test_key_condition` sends the five requests. A unit test covers the first one. --- crates/engine/src/expression_helpers.rs | 16 ++++++-- .../src/expression_helpers_order_tests.rs | 34 +++++++++++++++-- crates/engine/src/query.rs | 3 +- tests/test_expression_operator_limits.py | 38 ++++++++++++++++++- 4 files changed, 80 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index bd30d2916..827e52392 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -267,9 +267,11 @@ pub fn parse_projection_expr( /// # Errors /// /// Returns `DynamoDbError::ValidationException` for over-size, syntax, or -/// reserved-word errors. +/// reserved-word errors, and for an undefined placeholder or an operand type +/// fault in a key condition over the operator cap. pub fn parse_key_condition_expr( expr: &str, + maps: &ExpressionMaps, limits: &LimitsConfig, ) -> Result { check_expression_size(expr, ExpressionKind::KeyCondition, limits)?; @@ -289,16 +291,22 @@ pub fn parse_key_condition_expr( // :p sk = :s` token "sk", near ":p sk ="). The count comes next: `pk = // :v OR` + 150 terms answers the count, not the operator refusal, and // 151 AND-joined equalities answer the count ahead of the - // one-condition-per-key check (measured 2026-10-25). When the + // one-condition-per-key check (measured 2026-10-25). A key condition + // over the cap that also holds an undefined placeholder or an operand + // of the wrong type answers that fault instead (measured 2026-11-20: + // `#x = :p AND` 150 terms answers the undefined `#x`). When the // condition grammar refuses the text in another way, the key // condition parser reports the error in its own words. match parse_condition_from(&tokens, expr, limits.max_expression_depth) { Ok(condition) => { - validate_operator_count( + if let Err(count) = validate_operator_count( &condition, ExpressionKind::KeyCondition, limits.max_expression_operators, - )?; + ) { + validate_placeholders_and_operands(&condition, maps)?; + return Err(count); + } } Err(err) if is_syntax_error(&err) => return Err(err), Err(_) => {} diff --git a/crates/engine/src/expression_helpers_order_tests.rs b/crates/engine/src/expression_helpers_order_tests.rs index c0789ba63..4e12fef24 100644 --- a/crates/engine/src/expression_helpers_order_tests.rs +++ b/crates/engine/src/expression_helpers_order_tests.rs @@ -103,12 +103,24 @@ fn syntax_error_beats_the_count() { ); } +/// `#v` is defined; `:v`, `:p` and `:s` are S values. +fn key_maps() -> ExpressionMaps { + let names = HashMap::from([("#v".to_owned(), "v".to_owned())]); + let values = HashMap::from([ + (":v".to_owned(), AttributeValue::S("x".to_owned())), + (":p".to_owned(), AttributeValue::S("p1".to_owned())), + (":s".to_owned(), AttributeValue::S("s1".to_owned())), + ]); + build_expression_maps(Some(&names), Some(&values)) +} + #[test] fn key_condition_count_runs_before_the_key_grammar() { let limits = LimitsConfig::default(); + let maps = key_maps(); // [a62] `pk = :v OR` + 150 terms: 301, the count, not the OR refusal. let expr = format!("pk = :v OR {}", vec!["#v = :v"; 150].join(" AND ")); - let err = parse_key_condition_expr(&expr, &limits).unwrap_err(); + let err = parse_key_condition_expr(&expr, &maps, &limits).unwrap_err(); assert!( matches!(&err, DynamoDbError::ValidationException(msg) if msg == "Invalid KeyConditionExpression: The expression contains too many operators; operator count: 301"), @@ -116,14 +128,14 @@ fn key_condition_count_runs_before_the_key_grammar() { ); // [a63] two conditions joined by OR under the cap: the key grammar // answers (measured 2026-11-19 as x25). - let err = parse_key_condition_expr("pk = :v OR sk = :s", &limits).unwrap_err(); + let err = parse_key_condition_expr("pk = :v OR sk = :s", &maps, &limits).unwrap_err(); assert!( matches!(&err, DynamoDbError::ValidationException(msg) if msg == "Invalid KeyConditionExpression: Invalid operator used in KeyConditionExpression"), "got {err:?}" ); // [d23] a syntax error is reported by the key grammar in the service's words. - let err = parse_key_condition_expr("pk = :v AND", &limits).unwrap_err(); + let err = parse_key_condition_expr("pk = :v AND", &maps, &limits).unwrap_err(); assert!( matches!(&err, DynamoDbError::ValidationException(msg) if msg == "Invalid KeyConditionExpression: Syntax error; token: \"\", near: \"AND\""), @@ -131,6 +143,19 @@ fn key_condition_count_runs_before_the_key_grammar() { ); } +#[test] +fn key_condition_placeholder_fault_beats_the_count() { + // [k21] measured 2026-11-20: `#x = :p AND` 150 terms, with `#x` + // undefined, answers the undefined name, not the count of 301. + let expr = format!("#x = :p AND {}", vec!["#v = :v"; 150].join(" AND ")); + let err = parse_key_condition_expr(&expr, &key_maps(), &LimitsConfig::default()).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid KeyConditionExpression: An expression attribute name used in the document path is not defined; attribute name: #x"), + "got {err:?}" + ); +} + #[test] fn key_condition_syntax_errors_come_before_the_key_rules() { // Measured 2026-11-19 (us-east-1) on Query, probe cases in the first @@ -154,8 +179,9 @@ fn key_condition_syntax_errors_come_before_the_key_rules() { ("k11", "pk = :p AND NOT NOT", syntax("", "NOT")), ]; let limits = LimitsConfig::default(); + let maps = key_maps(); for (case, expr, want) in rows { - let err = parse_key_condition_expr(expr, &limits).unwrap_err(); + let err = parse_key_condition_expr(expr, &maps, &limits).unwrap_err(); assert!( matches!(&err, DynamoDbError::ValidationException(msg) if *msg == format!("Invalid KeyConditionExpression: {want}")), diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index ab8183c0e..088ab7cfc 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -237,7 +237,8 @@ pub async fn handle_query( let (mut key_condition, legacy_kc_maps) = if let Some(kce_str) = input.key_condition_expression.as_deref() { - let parsed = crate::expression_helpers::parse_key_condition_expr(kce_str, &ctx.limits)?; + let parsed = + crate::expression_helpers::parse_key_condition_expr(kce_str, &maps, &ctx.limits)?; (parsed, None) } else if let Some(ref kc) = input.key_conditions { let key_schema_pairs: Vec<(String, bool)> = query_key_info diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index 8a0d98b66..d4e1132d0 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -20,8 +20,9 @@ The syntax error wording tests are in test_expression_syntax_wording.py. -Every expected text was measured against Amazon DynamoDB on 2026-10-25 or -2026-11-19 (us-east-1); the probe case id is noted on each assertion. The +Every expected text was measured against Amazon DynamoDB on 2026-10-25, +2026-11-19 or 2026-11-20 (us-east-1); the probe case id is noted on each +assertion. The write paths carry a ``1 validation error detected: `` prefix on the service that ExtendDB does not emit; those assertions compare the text after the prefix. @@ -489,6 +490,39 @@ def test_query_count_beats_an_unused_value(self, dynamodb_client, table): ) assert msg == f"Invalid FilterExpression: {TOO_MANY}301" + @pytest.mark.parametrize( + "case, kce, values, want", + [ + ("k20", "pk = :zz AND " + chain("#v = :v", 150, " AND "), {}, UNDEFINED_VALUE), + ("k21", "#x = :p AND " + chain("#v = :v", 150, " AND "), P, UNDEFINED_NAME), + ( + "k22", + "pk = :p AND begins_with(sk, :n) AND " + chain("#v = :v", 149, " AND "), + {**P, **N}, + N_PREFIX, + ), + ( + "k26", + "pk = :p AND " + chain("#v = :v", 150, " AND ") + " AND #y = :v", + P, + UNDEFINED_NAME.replace("#x", "#y"), + ), + ( + "k27", + "pk = :p AND sk < :b AND " + chain("#v = :v", 149, " AND "), + {**P, **B}, + BOOL_OPERAND, + ), + ], + ) + def test_key_condition(self, dynamodb_client, table, case, kce, values, want): + # Measured 2026-11-20: a key condition over the cap answers its + # undefined placeholder or operand type fault, not the count. + msg = _validation( + query(dynamodb_client, table, kce, ExpressionAttributeValues={**VALUES, **values}) + ) + assert msg == f"Invalid KeyConditionExpression: {want}", case + def test_write_conditions(self, dynamodb_client, table): # [p01], [p02], [p03] on PutItem; [u01] on UpdateItem; [d01] on DeleteItem. key = {"pk": {"S": "absent"}, "sk": {"S": "absent"}} From 6589e320e2ddc94e36691963d3469143100d25d0 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:19:35 +0000 Subject: [PATCH 26/37] test(partiql): check the operator cap in the translation limits test `a_translated_expression_has_no_operator_cap` repeated the setup of the test above it. Its two asserts move into `a_translated_expression_may_reach_sixteen_bytes_a_statement_character`, and this commit removes the separate test. The asserts are the same: the default cap is 300, and `translation_limits` raises it to `usize::MAX`. --- crates/engine/src/partiql/mod.rs | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/partiql/mod.rs b/crates/engine/src/partiql/mod.rs index afa7d11dc..e16ac07ba 100644 --- a/crates/engine/src/partiql/mod.rs +++ b/crates/engine/src/partiql/mod.rs @@ -463,18 +463,9 @@ mod tests { translated.max_attribute_name_bytes, classic.max_attribute_name_bytes ); - } - - #[test] - fn a_translated_expression_has_no_operator_cap() { - // The PartiQL parser counts the statement's operators; the text - // written for it is not counted again. - let classic = LimitsConfig::default(); + // The PartiQL parser counts the statement's operators instead. assert_eq!(classic.max_expression_operators, 300); - assert_eq!( - translation_limits(&classic).max_expression_operators, - usize::MAX - ); + assert_eq!(translated.max_expression_operators, usize::MAX); } #[test] From 148a4a7684ea6b21c2239306c3956156e8aad9ee Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:19:35 +0000 Subject: [PATCH 27/37] test(expression): name the Query probe cases of the rows ahead of the count The rows of `AHEAD_OF_THE_COUNT` carried only the Scan cases s01 to s04, and `test_query_filter` reported those labels for its Query requests. The Query cases of the same requests are q01, q03, q04 and q02. Each row now carries its Scan case and its Query case, and each test reports its own. --- tests/test_expression_operator_limits.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index d4e1132d0..9ba282067 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -444,28 +444,29 @@ def test_scan_query_update_keys(self, dynamodb_client_no_validation, table): U = {":u": {"S": "y"}} P = {":p": {"S": "p1"}} -# Faults the service reports ahead of the count, measured 2026-11-19 on Scan -# (s01-s04) and on Query (q01-q04) with the same answers. +# Faults the service reports ahead of the count, measured 2026-11-19 with the +# same answers on Scan and on Query. Each row names its Scan case, then its +# Query case. AHEAD_OF_THE_COUNT = [ - ("s01", chain("#v = :v", 150) + " OR #v < :b", B, BOOL_OPERAND), - ("s02", chain("#v = :v", 151) + " OR #v = :zz", {}, UNDEFINED_VALUE), - ("s03", chain("#v = :v", 151) + " OR begins_with(#v, :n)", N, N_PREFIX), - ("s04", chain("#v = :v", 151) + " OR #x = :v", {}, UNDEFINED_NAME), + ("s01", "q01", chain("#v = :v", 150) + " OR #v < :b", B, BOOL_OPERAND), + ("s02", "q03", chain("#v = :v", 151) + " OR #v = :zz", {}, UNDEFINED_VALUE), + ("s03", "q04", chain("#v = :v", 151) + " OR begins_with(#v, :n)", N, N_PREFIX), + ("s04", "q02", chain("#v = :v", 151) + " OR #x = :v", {}, UNDEFINED_NAME), ] class TestChecksAheadOfTheCount: """Undefined placeholders and operand types come before the count.""" - @pytest.mark.parametrize("case, expr, values, want", AHEAD_OF_THE_COUNT) - def test_scan_filter(self, dynamodb_client, table, case, expr, values, want): + @pytest.mark.parametrize("case, query_case, expr, values, want", AHEAD_OF_THE_COUNT) + def test_scan_filter(self, dynamodb_client, table, case, query_case, expr, values, want): msg = _validation( scan(dynamodb_client, table, expr, ExpressionAttributeValues={**VALUES, **values}) ) assert msg == f"Invalid FilterExpression: {want}", case - @pytest.mark.parametrize("case, expr, values, want", AHEAD_OF_THE_COUNT) - def test_query_filter(self, dynamodb_client, table, case, expr, values, want): + @pytest.mark.parametrize("scan_case, case, expr, values, want", AHEAD_OF_THE_COUNT) + def test_query_filter(self, dynamodb_client, table, scan_case, case, expr, values, want): msg = _validation( query( dynamodb_client, From b4260658d21bf3f4c4c3efea069e44ed9853d3be Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:19:36 +0000 Subject: [PATCH 28/37] docs(limits): list the operator cap with the expression limits docs/dynamodb-limits.md listed the expression size limits with their `LimitsConfig` fields and had no row for the operator cap. The new row gives the cap of 300, the check `validate_operator_count` and the field `LimitsConfig::max_expression_operators`. It also says where the cap applies: condition, filter and key condition expressions, and not TransactWriteItems. --- docs/dynamodb-limits.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/dynamodb-limits.md b/docs/dynamodb-limits.md index 92bfc362c..c721bbeee 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` | +| Operators and functions in an expression | 300 | Enforced | `validate_operator_count`, `LimitsConfig::max_expression_operators`; condition, filter and key condition expressions, not on TransactWriteItems | | 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 b9148ec0c6894f77b458aab9d5cba5cafbab08b2 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:34:25 +0000 Subject: [PATCH 29/37] test(expression): rewrap the module docstring of the operator limits test The paragraph on the measurement dates left "assertion. The" on a line of its own. This commit rewraps the paragraph and changes no test. --- tests/test_expression_operator_limits.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index 9ba282067..a5014e988 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -22,10 +22,9 @@ Every expected text was measured against Amazon DynamoDB on 2026-10-25, 2026-11-19 or 2026-11-20 (us-east-1); the probe case id is noted on each -assertion. The -write paths carry a ``1 validation error detected: `` prefix on the service -that ExtendDB does not emit; those assertions compare the text after the -prefix. +assertion. The write paths carry a ``1 validation error detected: `` prefix +on the service that ExtendDB does not emit; those assertions compare the +text after the prefix. Dual-target against Amazon DynamoDB and extenddb. """ From 130677b360aac3b3a30b48dca66402b0f2f3dbc0 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:23:12 +0000 Subject: [PATCH 30/37] test(expression): move the placeholder key length tests into their own file This is a pure move. tests/test_expression_operator_limits.py had 694 lines, and the placeholder key length rows are not about the operator count. TestPlaceholderKeyLength, five tests, moves to tests/test_expression_placeholder_key_length.py with the imports it uses from expression_fault_helpers. Its tests and their bodies are unchanged. The docstring of the operator limits file names the new file, and the two files have 563 and 151 lines. --- tests/test_expression_operator_limits.py | 161 ++---------------- .../test_expression_placeholder_key_length.py | 151 ++++++++++++++++ 2 files changed, 166 insertions(+), 146 deletions(-) create mode 100644 tests/test_expression_placeholder_key_length.py diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index a5014e988..b6e245e4c 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -1,30 +1,26 @@ # Copyright 2026 ExtendDB contributors # SPDX-License-Identifier: Apache-2.0 -"""Expression operator cap and placeholder key length. +"""Expression operator cap. -Two request shapes Amazon DynamoDB refuses with texts ExtendDB did not match: +Amazon DynamoDB refuses an expression with more than 300 operators: +``Invalid : The expression contains too many operators; operator +count: ``, on ConditionExpression (PutItem, UpdateItem, DeleteItem), +FilterExpression (Scan, Query) and KeyConditionExpression (Query). Every +comparison operator, AND, OR, NOT, BETWEEN, IN and function call counts one; +parentheses, paths, placeholders and list elements count zero. An undefined +placeholder and an operand of the wrong type come before the count, and so +do the Scan Limit, Segment and TotalSegments ranges. PartiQL counts the +statement, not the text it writes for it. - - an expression with more than 300 operators: - ``Invalid : The expression contains too many operators; operator - count: ``, on ConditionExpression (PutItem, UpdateItem, DeleteItem), - FilterExpression (Scan, Query) and KeyConditionExpression (Query). Every - comparison operator, AND, OR, NOT, BETWEEN, IN and function call counts - one; parentheses, paths, placeholders and list elements count zero. An - undefined placeholder and an operand of the wrong type come before the - count, and so do the Scan Limit, Segment and TotalSegments ranges. PartiQL - counts the statement, not the text it writes for it. - - an ExpressionAttributeNames or ExpressionAttributeValues key over 255 - bytes on PutItem: a ValidationException carrying ``size of key: ``, - not a SerializationException. - -The syntax error wording tests are in test_expression_syntax_wording.py. +The syntax error wording tests are in test_expression_syntax_wording.py and +the placeholder key length tests in test_expression_placeholder_key_length.py. Every expected text was measured against Amazon DynamoDB on 2026-10-25, 2026-11-19 or 2026-11-20 (us-east-1); the probe case id is noted on each -assertion. The write paths carry a ``1 validation error detected: `` prefix -on the service that ExtendDB does not emit; those assertions compare the -text after the prefix. +assertion. The write paths carry a ``1 validation error detected: `` +prefix on the service that ExtendDB does not emit; those assertions compare +the text after the prefix. Dual-target against Amazon DynamoDB and extenddb. """ @@ -298,133 +294,6 @@ def test_update_item_condition_count_beats_update_expression_faults( assert _after_prefix(msg) == f"Invalid ConditionExpression: {TOO_MANY}599", update -class TestPlaceholderKeyLength: - """A placeholder key over 255 bytes is a ValidationException with its size.""" - - @staticmethod - def _names_msg(field: str, size: int) -> str: - return ( - f"{field} contains invalid key: The expression attribute map contains " - f"a key that is too long; size of key: {size}" - ) - - def test_put_item_names_key(self, dynamodb_client_no_validation, table): - # [c01] 255 accepted (condition evaluated), 256 and 257 refused. - ok = "#" + "a" * 254 - code, _ = _error( - put(dynamodb_client_no_validation, table, f"{ok} = :v", ExpressionAttributeNames={ok: "v"}) - ) - assert code == "ConditionalCheckFailedException" - for size in (256, 257): - key = "#" + "a" * (size - 1) - msg = _validation( - put(dynamodb_client_no_validation, table, f"{key} = :v", ExpressionAttributeNames={key: "v"}) - ) - assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", size) - - def test_put_item_values_key(self, dynamodb_client_no_validation, table): - # [c02] 255 accepted, 256 and 257 refused with the size suffix. - ok = ":" + "a" * 254 - code, _ = _error( - put(dynamodb_client_no_validation, table, f"#v = {ok}", ExpressionAttributeValues={ok: {"S": "x"}}) - ) - assert code == "ConditionalCheckFailedException" - for size in (256, 257): - key = ":" + "a" * (size - 1) - msg = _validation( - put( - dynamodb_client_no_validation, - table, - f"#v = {key}", - ExpressionAttributeValues={key: {"S": "x"}}, - ) - ) - assert _after_prefix(msg) == self._names_msg("ExpressionAttributeValues", size) - - def test_put_item_key_length_is_bytes_and_checked_before_syntax( - self, dynamodb_client_no_validation, table - ): - # [c03] 127 two-byte characters: 255 bytes, passes the length check and - # fails key syntax; [c04] 128: 257 bytes; [c05] 258 bytes with an - # invalid character reports the length. - key = "#" + "\u00e9" * 127 - msg = _validation( - put(dynamodb_client_no_validation, table, "#v = :v", ExpressionAttributeNames={"#v": "v", key: "w"}) - ) - assert _after_prefix(msg) == ( - f'ExpressionAttributeNames contains invalid key: Syntax error; key: "{key}"' - ) - key = "#" + "\u00e9" * 128 - msg = _validation( - put(dynamodb_client_no_validation, table, "#v = :v", ExpressionAttributeNames={"#v": "v", key: "w"}) - ) - assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", 257) - key = "#" + "a" * 255 + "-x" - msg = _validation( - put(dynamodb_client_no_validation, table, "#v = :v", ExpressionAttributeNames={"#v": "v", key: "w"}) - ) - assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", 258) - - def test_put_item_too_long_key_beats_the_expression_checks( - self, dynamodb_client_no_validation, table - ): - # [c06] unreferenced, [c07] with a 300-term chain, [c08] with a syntax - # error, [c09] with an undefined name, [c10] with an unused value. - key = "#" + "w" * 255 - names = {"#v": "v", key: "w"} - expected = self._names_msg("ExpressionAttributeNames", 256) - for condition, extra in [ - ("#v = :v", {}), - (chain("#v = :v", 300), {}), - ("#v = = :v", {}), - ("#x = :v", {}), - ("#v = :v", {"ExpressionAttributeValues": {":v": {"S": "x"}, ":u": {"S": "y"}}}), - ]: - msg = _validation( - put(dynamodb_client_no_validation, table, condition, ExpressionAttributeNames=names, **extra) - ) - assert _after_prefix(msg) == expected, condition - - def test_scan_query_update_keys(self, dynamodb_client_no_validation, table): - # [c12] Scan names, [s10] Scan values, [s11] Query values, [s12] Query - # names: no prefix. [c13] UpdateItem names: prefix on the service. - nkey = "#" + "w" * 255 - vkey = ":" + "w" * 255 - assert _validation( - scan(dynamodb_client_no_validation, table, f"{nkey} = :v", ExpressionAttributeNames={nkey: "w"}) - ) == self._names_msg("ExpressionAttributeNames", 256) - assert _validation( - scan(dynamodb_client_no_validation, table, f"#v = {vkey}", ExpressionAttributeValues={vkey: {"S": "x"}}) - ) == self._names_msg("ExpressionAttributeValues", 256) - assert _validation( - query( - dynamodb_client_no_validation, - table, - "pk = :p", - FilterExpression=f"#v = {vkey}", - ExpressionAttributeValues={":p": {"S": "p1"}, vkey: {"S": "x"}}, - ) - ) == self._names_msg("ExpressionAttributeValues", 256) - assert _validation( - query( - dynamodb_client_no_validation, - table, - "pk = :v", - ExpressionAttributeNames={nkey: "w"}, - ) - ) == self._names_msg("ExpressionAttributeNames", 256) - msg = _validation( - lambda: dynamodb_client_no_validation.update_item( - TableName=table, - Key={"pk": {"S": "absent"}, "sk": {"S": "absent"}}, - UpdateExpression=f"SET {nkey} = :v", - ExpressionAttributeNames={nkey: "w"}, - ExpressionAttributeValues=VALUES, - ) - ) - assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", 256) - - UNDEFINED_VALUE = ( "An expression attribute value used in expression is not defined; attribute value: :zz" ) diff --git a/tests/test_expression_placeholder_key_length.py b/tests/test_expression_placeholder_key_length.py new file mode 100644 index 000000000..a4da27ee6 --- /dev/null +++ b/tests/test_expression_placeholder_key_length.py @@ -0,0 +1,151 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Placeholder key length in the expression attribute maps. + +An ExpressionAttributeNames or ExpressionAttributeValues key over 255 bytes +is a ValidationException carrying ``size of key: ``, not a +SerializationException, on PutItem as on Scan, Query and UpdateItem. The +bound is bytes of UTF-8, and it is checked before the expression checks. + +Every expected text was measured against Amazon DynamoDB on 2026-10-25, +2026-11-19, 2026-11-20 or 2026-11-23 (us-east-1); the probe case id is noted +on each assertion. The write paths carry a ``1 validation error detected: `` +prefix on the service that ExtendDB does not emit; those assertions compare +the text after the prefix. + +Dual-target against Amazon DynamoDB and extenddb. +""" + +from __future__ import annotations + +from expression_fault_helpers import ( + VALUES, _after_prefix, _error, _validation, chain, put, query, scan, table, +) + + +class TestPlaceholderKeyLength: + """A placeholder key over 255 bytes is a ValidationException with its size.""" + + @staticmethod + def _names_msg(field: str, size: int) -> str: + return ( + f"{field} contains invalid key: The expression attribute map contains " + f"a key that is too long; size of key: {size}" + ) + + def test_put_item_names_key(self, dynamodb_client_no_validation, table): + # [c01] 255 accepted (condition evaluated), 256 and 257 refused. + ok = "#" + "a" * 254 + code, _ = _error( + put(dynamodb_client_no_validation, table, f"{ok} = :v", ExpressionAttributeNames={ok: "v"}) + ) + assert code == "ConditionalCheckFailedException" + for size in (256, 257): + key = "#" + "a" * (size - 1) + msg = _validation( + put(dynamodb_client_no_validation, table, f"{key} = :v", ExpressionAttributeNames={key: "v"}) + ) + assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", size) + + def test_put_item_values_key(self, dynamodb_client_no_validation, table): + # [c02] 255 accepted, 256 and 257 refused with the size suffix. + ok = ":" + "a" * 254 + code, _ = _error( + put(dynamodb_client_no_validation, table, f"#v = {ok}", ExpressionAttributeValues={ok: {"S": "x"}}) + ) + assert code == "ConditionalCheckFailedException" + for size in (256, 257): + key = ":" + "a" * (size - 1) + msg = _validation( + put( + dynamodb_client_no_validation, + table, + f"#v = {key}", + ExpressionAttributeValues={key: {"S": "x"}}, + ) + ) + assert _after_prefix(msg) == self._names_msg("ExpressionAttributeValues", size) + + def test_put_item_key_length_is_bytes_and_checked_before_syntax( + self, dynamodb_client_no_validation, table + ): + # [c03] 127 two-byte characters: 255 bytes, passes the length check and + # fails key syntax; [c04] 128: 257 bytes; [c05] 258 bytes with an + # invalid character reports the length. + key = "#" + "\u00e9" * 127 + msg = _validation( + put(dynamodb_client_no_validation, table, "#v = :v", ExpressionAttributeNames={"#v": "v", key: "w"}) + ) + assert _after_prefix(msg) == ( + f'ExpressionAttributeNames contains invalid key: Syntax error; key: "{key}"' + ) + key = "#" + "\u00e9" * 128 + msg = _validation( + put(dynamodb_client_no_validation, table, "#v = :v", ExpressionAttributeNames={"#v": "v", key: "w"}) + ) + assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", 257) + key = "#" + "a" * 255 + "-x" + msg = _validation( + put(dynamodb_client_no_validation, table, "#v = :v", ExpressionAttributeNames={"#v": "v", key: "w"}) + ) + assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", 258) + + def test_put_item_too_long_key_beats_the_expression_checks( + self, dynamodb_client_no_validation, table + ): + # [c06] unreferenced, [c07] with a 300-term chain, [c08] with a syntax + # error, [c09] with an undefined name, [c10] with an unused value. + key = "#" + "w" * 255 + names = {"#v": "v", key: "w"} + expected = self._names_msg("ExpressionAttributeNames", 256) + for condition, extra in [ + ("#v = :v", {}), + (chain("#v = :v", 300), {}), + ("#v = = :v", {}), + ("#x = :v", {}), + ("#v = :v", {"ExpressionAttributeValues": {":v": {"S": "x"}, ":u": {"S": "y"}}}), + ]: + msg = _validation( + put(dynamodb_client_no_validation, table, condition, ExpressionAttributeNames=names, **extra) + ) + assert _after_prefix(msg) == expected, condition + + def test_scan_query_update_keys(self, dynamodb_client_no_validation, table): + # [c12] Scan names, [s10] Scan values, [s11] Query values, [s12] Query + # names: no prefix. [c13] UpdateItem names: prefix on the service. + nkey = "#" + "w" * 255 + vkey = ":" + "w" * 255 + assert _validation( + scan(dynamodb_client_no_validation, table, f"{nkey} = :v", ExpressionAttributeNames={nkey: "w"}) + ) == self._names_msg("ExpressionAttributeNames", 256) + assert _validation( + scan(dynamodb_client_no_validation, table, f"#v = {vkey}", ExpressionAttributeValues={vkey: {"S": "x"}}) + ) == self._names_msg("ExpressionAttributeValues", 256) + assert _validation( + query( + dynamodb_client_no_validation, + table, + "pk = :p", + FilterExpression=f"#v = {vkey}", + ExpressionAttributeValues={":p": {"S": "p1"}, vkey: {"S": "x"}}, + ) + ) == self._names_msg("ExpressionAttributeValues", 256) + assert _validation( + query( + dynamodb_client_no_validation, + table, + "pk = :v", + ExpressionAttributeNames={nkey: "w"}, + ) + ) == self._names_msg("ExpressionAttributeNames", 256) + msg = _validation( + lambda: dynamodb_client_no_validation.update_item( + TableName=table, + Key={"pk": {"S": "absent"}, "sk": {"S": "absent"}}, + UpdateExpression=f"SET {nkey} = :v", + ExpressionAttributeNames={nkey: "w"}, + ExpressionAttributeValues=VALUES, + ) + ) + assert _after_prefix(msg) == self._names_msg("ExpressionAttributeNames", 256) From 1c432002aaf910b82486a908d1a38e2db42e7535 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:23:12 +0000 Subject: [PATCH 31/37] fix(scan): check a Segment or TotalSegments range without its partner, and assert the range texts in full `validate_scan_ranges` checked the Segment and TotalSegments ranges only when both fields were present. A Scan with `TotalSegments: 0` and no Segment went on to the filter checks, and answered the operator count of a 151-term filter, or the missing Segment. The service answers the TotalSegments range (measured 2026-11-23 in us-east-1, twice): `1 validation error detected: Value at 'TotalSegments' failed to satisfy constraint: Member must have value greater than or equal to 1`. The comment above the call said so. Each field is now checked when it is present, in the order the service lists several faults of one request: Limit, Segment, TotalSegments. `Segment: -1` without TotalSegments answers the Segment range the same way. The texts are unchanged. TestScanRangesAheadOfTheCount gains the row s41 (151 terms, `TotalSegments: 0`), which fails on the previous production lines. Its rows now assert the full text by equality: the service's `Value at 'Limit'` and `Value at 'TotalSegments'` forms on DynamoDB, and ExtendDB's own texts on ExtendDB. --- crates/engine/src/scan.rs | 47 ++++++++++++++---------- tests/test_expression_operator_limits.py | 45 +++++++++++++++-------- 2 files changed, 57 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/scan.rs b/crates/engine/src/scan.rs index e47f06140..e90db41e9 100755 --- a/crates/engine/src/scan.rs +++ b/crates/engine/src/scan.rs @@ -520,21 +520,23 @@ pub async fn handle_scan( }) } -/// Refuse a Limit, Segment or TotalSegments value outside its range. The -/// Segment and TotalSegments ranges are checked when both are present; a -/// missing partner is reported by the pairing check in `handle_scan`. +/// Refuse a Limit, Segment or TotalSegments value outside its range. Each +/// field is checked when it is present, with or without its partner +/// (measured 2026-10-25 and 2026-11-23: `TotalSegments: 0` alone, or +/// `Segment: -1` alone, answers that field's range, not the missing +/// partner). For values inside the int32 range the service lists every +/// fault of one request in the order Limit, Segment, TotalSegments; this +/// check reports the first of them. A missing partner is reported by the +/// pairing check in `handle_scan`. fn validate_scan_ranges(input: &ScanInput) -> Result<(), DynamoDbError> { - if let (Some(seg), Some(total)) = (input.segment, input.total_segments) { - if total < 1 { - return Err(DynamoDbError::ValidationException( - "The parameter TotalSegments should be greater than or equal to 1".to_owned(), - )); - } - if total > 1_000_000 { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value '{total}' at 'totalSegments' failed to satisfy constraint: Member must have value less than or equal to 1000000" - ))); - } + if let Some(limit) = input.limit + && limit < 1 + { + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value '{limit}' at 'limit' failed to satisfy constraint: Member must have value greater than or equal to 1" + ))); + } + if let Some(seg) = input.segment { if seg < 0 { return Err(DynamoDbError::ValidationException(format!( "1 validation error detected: Value '{seg}' at 'segment' failed to satisfy constraint: Member must have value greater than or equal to 0" @@ -546,12 +548,17 @@ fn validate_scan_ranges(input: &ScanInput) -> Result<(), DynamoDbError> { ))); } } - if let Some(limit) = input.limit - && limit < 1 - { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value '{limit}' at 'limit' failed to satisfy constraint: Member must have value greater than or equal to 1" - ))); + if let Some(total) = input.total_segments { + if total < 1 { + return Err(DynamoDbError::ValidationException( + "The parameter TotalSegments should be greater than or equal to 1".to_owned(), + )); + } + if total > 1_000_000 { + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value '{total}' at 'totalSegments' failed to satisfy constraint: Member must have value less than or equal to 1000000" + ))); + } } Ok(()) } diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index b6e245e4c..d4c2c1d53 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -17,8 +17,8 @@ the placeholder key length tests in test_expression_placeholder_key_length.py. Every expected text was measured against Amazon DynamoDB on 2026-10-25, -2026-11-19 or 2026-11-20 (us-east-1); the probe case id is noted on each -assertion. The write paths carry a ``1 validation error detected: `` +2026-11-19, 2026-11-20 or 2026-11-23 (us-east-1); the probe case id is noted +on each assertion. The write paths carry a ``1 validation error detected: `` prefix on the service that ExtendDB does not emit; those assertions compare the text after the prefix. @@ -492,25 +492,42 @@ def test_the_checks_read_no_item(self, dynamodb_client, table): assert _after_prefix(_validation(request)) == f"Invalid {kind}Expression: {want}", case +# The range texts: the service's, then ExtendDB's. ExtendDB keeps its own +# wording for the three Scan ranges. +RANGE_TEXTS = { + "Limit": ( + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1", + "1 validation error detected: Value '0' at 'limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1", + ), + "TotalSegments": ( + "1 validation error detected: Value at 'TotalSegments' failed to satisfy constraint: " + "Member must have value greater than or equal to 1", + "The parameter TotalSegments should be greater than or equal to 1", + ), +} + + class TestScanRangesAheadOfTheCount: """The Scan Limit, Segment and TotalSegments ranges come first.""" @pytest.mark.parametrize( - "case, expr, values, extra", + "case, expr, values, extra, field", [ - ("s05", chain("#v = :v", 151), {}, {"Limit": 0}), - ("s16", "#v < :b", B, {"Limit": 0}), - ("s17", "#v = :zz", {}, {"Limit": 0}), - ("s22", "#v = = :v", {}, {"Limit": 0}), - ("s06", chain("#v = :v", 151), {}, {"Segment": 0, "TotalSegments": 0}), + ("s05", chain("#v = :v", 151), {}, {"Limit": 0}, "Limit"), + ("s16", "#v < :b", B, {"Limit": 0}, "Limit"), + ("s17", "#v = :zz", {}, {"Limit": 0}, "Limit"), + ("s22", "#v = = :v", {}, {"Limit": 0}, "Limit"), + ("s06", chain("#v = :v", 151), {}, {"Segment": 0, "TotalSegments": 0}, "TotalSegments"), + ("s41", chain("#v = :v", 151), {}, {"TotalSegments": 0}, "TotalSegments"), ], ) def test_range_beats_the_filter_checks( - self, dynamodb_client_no_validation, table, case, expr, values, extra + self, dynamodb_client_no_validation, table, case, expr, values, extra, field ): - # Measured 2026-11-19. The service words the range as "Value at - # 'Limit' failed to satisfy constraint: ..."; ExtendDB keeps its own - # wording, so the assertion names the parameter and the bound. + # Measured 2026-11-19, and s41 on 2026-11-23: a TotalSegments out of + # range without a Segment answers the range, not the missing partner. msg = _validation( scan( dynamodb_client_no_validation, @@ -520,9 +537,7 @@ def test_range_beats_the_filter_checks( **extra, ) ) - name = "TotalSegments" if "TotalSegments" in extra else "limit" - assert name in msg or name.capitalize() in msg, (case, msg) - assert "greater than or equal to 1" in msg, (case, msg) + assert msg == RANGE_TEXTS[field][0 if _is_real_dynamodb() else 1], (case, msg) def test_segment_pairing_comes_after_the_count(self, dynamodb_client_no_validation, table): # [s27] a Segment without TotalSegments beside 151 terms. From cd3192069cb7e276c3fb5c9e6a44948051b6cd03 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:23:12 +0000 Subject: [PATCH 32/37] refactor(expression): report a condition syntax error as a typed fault `parse_key_condition_expr` read a key condition with the condition grammar first and kept the grammar's refusal when `is_syntax_error` found `: Syntax error; token: "` in its message. The classification is now a type. The condition parser's functions return `ConditionFault`. Its `Syntax` variant is the service-worded error of a repeated or misplaced operator, keyword or path, and its `Other` variant is every other refusal. `parse_condition_classified` returns it, `parse_condition_from` flattens it to the error as before, and `parse_key_condition_expr` matches the variant. `is_syntax_error` is deleted. No answer changes: the engine's key condition order tests and the wire files pass unchanged, and a unit test checks the variant of nine refusals. --- crates/core/src/expression/mod.rs | 7 +- crates/core/src/expression/parser.rs | 121 ++++++++++++++++++--- crates/core/src/expression/syntax_error.rs | 7 -- crates/engine/src/expression_helpers.rs | 14 +-- 4 files changed, 118 insertions(+), 31 deletions(-) diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index df086a478..54db0d26a 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -39,7 +39,10 @@ pub use key_condition::{ pub use kind::ExpressionKind; pub use operand_check::validate_placeholders_and_operands; pub use operator_count::{MAX_EXPRESSION_OPERATORS, count_operators, validate_operator_count}; -pub use parser::{parse_condition, parse_condition_from, parse_condition_with_depth_limit}; +pub use parser::{ + ConditionFault, parse_condition, parse_condition_classified, parse_condition_from, + parse_condition_with_depth_limit, +}; pub use projection::{Projection, parse_projection, parse_projection_from}; pub use reserved_words::validate_no_reserved_words; pub use resolver::{ @@ -52,7 +55,7 @@ pub use search_condition::{ SearchCondition, validate_conditions_against_search_schema, validate_search_condition_expression, }; -pub use syntax_error::{is_operator_or_keyword, is_syntax_error, syntax_error, token_text}; +pub use syntax_error::{is_operator_or_keyword, syntax_error, token_text}; pub use tokenizer::{Token, tokenize, tokenize_for, tokenize_with_limit}; pub use update_evaluator::apply_update_validated; pub use update_parser::{parse_update, parse_update_from}; diff --git a/crates/core/src/expression/parser.rs b/crates/core/src/expression/parser.rs index 447e20423..1ba9bdd56 100755 --- a/crates/core/src/expression/parser.rs +++ b/crates/core/src/expression/parser.rs @@ -29,6 +29,34 @@ use super::syntax_error::{is_operator_or_keyword, syntax_error}; use super::tokenizer::Token; use crate::error::DynamoDbError; +/// Why the condition parser refused a token stream. A caller that reads a +/// key condition with the condition grammar first keeps a `Syntax` refusal +/// and leaves any other refusal to the key condition parser, which reports +/// it in its own words. +#[derive(Debug)] +pub enum ConditionFault { + /// A repeated or misplaced operator, keyword or path, worded as the + /// service words it (`Syntax error; token: "=", near: "= = :v"`). + Syntax(DynamoDbError), + /// Any other refusal: redundant parentheses, the nesting depth, a bare + /// operand, a token the grammar has no rule for. + Other(DynamoDbError), +} + +impl From for DynamoDbError { + fn from(fault: ConditionFault) -> Self { + match fault { + ConditionFault::Syntax(err) | ConditionFault::Other(err) => err, + } + } +} + +impl From for ConditionFault { + fn from(err: DynamoDbError) -> Self { + Self::Other(err) + } +} + /// Parse a condition expression token stream into an AST. /// /// # Errors @@ -63,6 +91,21 @@ pub fn parse_condition_from( source: &str, max_depth: usize, ) -> Result { + parse_condition_classified(tokens, source, max_depth).map_err(DynamoDbError::from) +} + +/// Parse as [`parse_condition_from`] does, and tell a syntax error in the +/// service's wording apart from the parser's other refusals. +/// +/// # Errors +/// +/// Returns [`ConditionFault::Syntax`] for a repeated or misplaced operator, +/// keyword or path, and [`ConditionFault::Other`] for every other refusal. +pub fn parse_condition_classified( + tokens: &[Token], + source: &str, + max_depth: usize, +) -> Result { parser_common::check_redundant_parens(tokens) .map_err(|body| validation_err(&format!("Invalid ConditionExpression: {body}")))?; let mut pos = 0; @@ -75,7 +118,7 @@ pub fn parse_condition_from( if is_operator_or_keyword(&tokens[pos]) || matches!(tokens[pos], Token::Ident(_) | Token::NameRef(_)) { - return Err(syntax_error(ExpressionKind::Condition, source, tokens, pos)); + return Err(syntax_fault(source, tokens, pos)); } return Err(validation_err(&format!( "Invalid ConditionExpression: unexpected token at position {pos}" @@ -90,7 +133,7 @@ fn parse_or( pos: &mut usize, depth: &mut usize, max_depth: usize, -) -> Result { +) -> Result { let mut left = parse_and(tokens, src, pos, depth, max_depth)?; while *pos < tokens.len() && tokens[*pos] == Token::Or { *pos += 1; @@ -106,7 +149,7 @@ fn parse_and( pos: &mut usize, depth: &mut usize, max_depth: usize, -) -> Result { +) -> Result { let mut left = parse_not(tokens, src, pos, depth, max_depth)?; while *pos < tokens.len() && tokens[*pos] == Token::And { *pos += 1; @@ -122,7 +165,7 @@ fn parse_not( pos: &mut usize, depth: &mut usize, max_depth: usize, -) -> Result { +) -> Result { if *pos < tokens.len() && tokens[*pos] == Token::Not { *pos += 1; *depth += 1; @@ -144,7 +187,7 @@ fn parse_primary( pos: &mut usize, depth: &mut usize, max_depth: usize, -) -> Result { +) -> Result { if *pos >= tokens.len() { if tokens.is_empty() { return Err(validation_err( @@ -153,7 +196,7 @@ fn parse_primary( } // Input ends where a condition is required (`#v = :v AND`): measured // 2026-10-25 as token "" with the last token as the window. - return Err(syntax_error(ExpressionKind::Condition, src, tokens, *pos)); + return Err(syntax_fault(src, tokens, *pos)); } // Parenthesized expression @@ -217,7 +260,7 @@ fn parse_primary( // "IN", near "IN IN ("; `#v IN :v` token ":v"; `#v IN` token // "", near "IN"). if tokens.get(*pos) != Some(&Token::LParen) { - return Err(syntax_error(ExpressionKind::Condition, src, tokens, *pos)); + return Err(syntax_fault(src, tokens, *pos)); } *pos += 1; let mut list = vec![parse_operand(tokens, src, pos, depth, max_depth)?]; @@ -245,10 +288,10 @@ fn parse_operand( pos: &mut usize, depth: &mut usize, max_depth: usize, -) -> Result { +) -> Result { if *pos >= tokens.len() { // Input ends where an operand is required (`#v = :v AND NOT`). - return Err(syntax_error(ExpressionKind::Condition, src, tokens, *pos)); + return Err(syntax_fault(src, tokens, *pos)); } match &tokens[*pos] { @@ -282,9 +325,7 @@ fn parse_operand( } // An operator or keyword where an operand is required (`#v = = :v`, // `#v = :v AND AND #v = :v`, `AND #v = :v`): measured 2026-10-25. - token if is_operator_or_keyword(token) => { - Err(syntax_error(ExpressionKind::Condition, src, tokens, *pos)) - } + token if is_operator_or_keyword(token) => Err(syntax_fault(src, tokens, *pos)), _ => Err(validation_err( "Invalid ConditionExpression: expected attribute path or value placeholder", )), @@ -297,7 +338,7 @@ fn parse_function_call( pos: &mut usize, depth: &mut usize, max_depth: usize, -) -> Result { +) -> Result { let name = match &tokens[*pos] { Token::Ident(n) => n.to_ascii_lowercase(), _ => { @@ -343,8 +384,13 @@ fn is_function_name(name: &str) -> bool { ) } -fn validation_err(msg: &str) -> DynamoDbError { - DynamoDbError::ValidationException(msg.to_owned()) +fn validation_err(msg: &str) -> ConditionFault { + ConditionFault::Other(DynamoDbError::ValidationException(msg.to_owned())) +} + +/// The service's syntax error at `pos`, as a [`ConditionFault::Syntax`]. +fn syntax_fault(src: &str, tokens: &[Token], pos: usize) -> ConditionFault { + ConditionFault::Syntax(syntax_error(ExpressionKind::Condition, src, tokens, pos)) } #[cfg(test)] @@ -608,4 +654,49 @@ mod tests { ); } } + + #[test] + fn the_classified_parse_tells_a_syntax_error_from_the_other_refusals() { + // The syntax variant carries the service's wording; every other + // refusal is the other variant with the parser's own text. + for (src, token, near) in [ + ("#v = = :v", "=", "= = :v"), + ("#v = :v AND", "", "AND"), + ("#v = :v #v = :v", "#v", ":v #v ="), + ("= #v = :v", "=", "= #v"), + ("#v IN :v", ":v", "IN :v"), + ] { + let fault = parse_condition_classified(&tokenize(src).unwrap(), src, 150).unwrap_err(); + let want = format!( + "Invalid ConditionExpression: Syntax error; token: \"{token}\", near: \"{near}\"" + ); + assert!( + matches!(&fault, ConditionFault::Syntax(DynamoDbError::ValidationException(msg)) + if *msg == want), + "{src}: got {fault:?}" + ); + } + for (src, text) in [ + ("((#v = :v))", "The expression has redundant parentheses;"), + ("#v", "expected comparison operator or function call"), + ("(#v = :v", "expected ')'"), + ("#v = :v, #v = :v", "unexpected token at position 3"), + ] { + let fault = parse_condition_classified(&tokenize(src).unwrap(), src, 150).unwrap_err(); + let want = format!("Invalid ConditionExpression: {text}"); + assert!( + matches!(&fault, ConditionFault::Other(DynamoDbError::ValidationException(msg)) + if *msg == want), + "{src}: got {fault:?}" + ); + } + // Depth is the other variant too, with the depth limit of the call. + let src = "NOT NOT #v = :v"; + let fault = parse_condition_classified(&tokenize(src).unwrap(), src, 1).unwrap_err(); + assert!( + matches!(&fault, ConditionFault::Other(DynamoDbError::ValidationException(msg)) + if msg == "Invalid ConditionExpression: expression nesting depth exceeded"), + "got {fault:?}" + ); + } } diff --git a/crates/core/src/expression/syntax_error.rs b/crates/core/src/expression/syntax_error.rs index b59269e31..ce1471a4c 100644 --- a/crates/core/src/expression/syntax_error.rs +++ b/crates/core/src/expression/syntax_error.rs @@ -139,13 +139,6 @@ pub fn syntax_error( )) } -/// Whether `err` is a syntax error in the service's wording, as -/// [`syntax_error`] builds it. -#[must_use] -pub fn is_syntax_error(err: &DynamoDbError) -> bool { - matches!(err, DynamoDbError::ValidationException(msg) if msg.contains(": Syntax error; token: \"")) -} - /// The window of source text around the token at `pos`: from the previous /// token to the next one, each dropped when absent. When the faulty token is /// the first one, the window starts at the start of the source, leading diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 827e52392..e09f0cdab 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -7,10 +7,10 @@ use std::collections::HashMap; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ - Expr, ExpressionKind, ExpressionMaps, KeyCondition, PathElement, Token, UpdateAction, - is_syntax_error, parse_condition_from, parse_key_condition_from, parse_projection_from, - parse_update_from, tokenize_for, tokenize_with_limit, validate_no_reserved_words, - validate_operator_count, validate_placeholders_and_operands, + ConditionFault, Expr, ExpressionKind, ExpressionMaps, KeyCondition, PathElement, Token, + UpdateAction, parse_condition_classified, parse_condition_from, parse_key_condition_from, + parse_projection_from, parse_update_from, tokenize_for, tokenize_with_limit, + validate_no_reserved_words, validate_operator_count, validate_placeholders_and_operands, }; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{AttributeValue, ConditionalOperator, ExpectedAttributeValue}; @@ -297,7 +297,7 @@ pub fn parse_key_condition_expr( // `#x = :p AND` 150 terms answers the undefined `#x`). When the // condition grammar refuses the text in another way, the key // condition parser reports the error in its own words. - match parse_condition_from(&tokens, expr, limits.max_expression_depth) { + match parse_condition_classified(&tokens, expr, limits.max_expression_depth) { Ok(condition) => { if let Err(count) = validate_operator_count( &condition, @@ -308,8 +308,8 @@ pub fn parse_key_condition_expr( return Err(count); } } - Err(err) if is_syntax_error(&err) => return Err(err), - Err(_) => {} + Err(ConditionFault::Syntax(err)) => return Err(err), + Err(ConditionFault::Other(_)) => {} } parse_key_condition_from(&tokens, expr) }) From 75505b7f7bb4fdce6f84a23d51ae680111ee4668 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:23:12 +0000 Subject: [PATCH 33/37] test(expression): add the one-condition-per-key rows and rewrite the comment on ExtendDB's check The comment on test_key_condition_count_precedes_the_key_grammar said ExtendDB has no one-condition-per-key check. The check exists since the rebase on #429, for the key attributes. The rows the comment cited are now tests, measured 2026-11-23 in us-east-1, twice each, with the same answers: - a60: `pk = :v AND` 150 `#v = :v` joined by AND answers `Invalid KeyConditionExpression: The expression contains too many operators; operator count: 301`, on the service and on ExtendDB. The count comes ahead of the one-condition-per-key check on both. - b05: the same shape with 10 terms answers `Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key` on the service, before the table lookup. ExtendDB serves it with no items. It accepts a key condition clause on an attribute outside the key schema, and its check covers the key attributes only. The row is marked as an expected failure on ExtendDB, strict, so it fails when the clause is refused. The module docstring adds the measurement date. --- tests/test_expression_operator_limits.py | 31 ++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/tests/test_expression_operator_limits.py b/tests/test_expression_operator_limits.py index d4c2c1d53..14e45d9c8 100644 --- a/tests/test_expression_operator_limits.py +++ b/tests/test_expression_operator_limits.py @@ -49,6 +49,18 @@ strict=True, ) +# ExtendDB serves a KeyConditionExpression whose second clause names an +# attribute outside the key schema, where the service refuses it. Its +# one-condition-per-key check covers the key attributes only. This change does +# not touch that check. +# TODO: remove this marker once a non-key attribute in a key condition is refused. +XFAIL_ON_EXTENDDB_NON_KEY_CONDITION = pytest.mark.xfail( + not _is_real_dynamodb(), + reason="ExtendDB serves a key condition on an attribute outside the key schema", + raises=pytest.fail.Exception, + strict=True, +) + class TestOperatorCount: """More than 300 operators is refused with the full count.""" @@ -192,10 +204,25 @@ def test_key_condition_count(self, dynamodb_client, table): def test_key_condition_count_precedes_the_key_grammar(self, dynamodb_client, table): # [a62] `pk = :v OR` + 150 terms answers the count, not the operator - # refusal. The service also runs the count ahead of its - # one-condition-per-key check (b05, a60); ExtendDB has no such check. + # refusal. [a60] `pk = :v AND` + 150 terms on one attribute answers + # the count ahead of the one-condition-per-key check, on the service + # and on ExtendDB (measured 2026-11-23). msg = _validation(query(dynamodb_client, table, "pk = :v OR " + chain("#v = :v", 150, " AND "))) assert msg == f"Invalid KeyConditionExpression: {TOO_MANY}301" + msg = _validation(query(dynamodb_client, table, "pk = :v AND " + chain("#v = :v", 150, " AND "))) + assert msg == f"Invalid KeyConditionExpression: {TOO_MANY}301" + + @XFAIL_ON_EXTENDDB_NON_KEY_CONDITION + def test_one_condition_per_key_under_the_cap(self, dynamodb_client, table): + # [b05] `pk = :v AND` + 10 terms on one attribute, 21 operators + # (measured 2026-11-23): under the cap, the service refuses the + # repeated attribute, whether or not it is a key, before the table + # lookup. + msg = _validation(query(dynamodb_client, table, "pk = :v AND " + chain("#v = :v", 10, " AND "))) + assert msg == ( + "Invalid KeyConditionExpression: KeyConditionExpressions must only " + "contain one condition per key" + ) class TestOperatorCountOrder: From 3b42c2d98c93117fafdcaf78d59ebb9bd0d4d92b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:23:12 +0000 Subject: [PATCH 34/37] docs(upgrade): add the v1.1.0 entry for the operator cap and the changed expression answers The upgrade manual lists the behaviour changes an existing deployment can see, and this change had none. The new entry at the top of "Behavior Changes by Release" states four changes: - An expression over 300 operators is refused with the service's text and count, where 1.0.0 evaluated it. `max_expression_operators` under `[limits]` raises the cap. - A repeated or misplaced operator or keyword answers the `Syntax error; token:` text in place of 1.0.0's own texts. The update expression window is built from the token positions. - A too-long or empty expression map key on PutItem answers ValidationException in place of SerializationException, and the ExpressionAttributeValues text carries the `; size of key: ` suffix. - The Scan Limit, Segment and TotalSegments ranges are checked before the expressions and the table lookup, each field on its own. The entry names who is affected and says that no catalog migration is required. --- docs/manuals/07-upgrade-manual.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index ab3b307fe..257a1f267 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -388,6 +388,17 @@ Catalog upgrades change the schema; behavior changes alter how the running serve interprets existing data or configuration. Review these before upgrading a live deployment, even when no catalog migration is required. +### v1.1.0: expressions over 300 operators are refused, and the syntax error, PutItem map key and Scan range answers change + +**What changed.** Four answers on the item operations follow DynamoDB (measured on 2026-10-25, 2026-11-19, 2026-11-20 and 2026-11-23 in us-east-1): + +- A `ConditionExpression` on PutItem, UpdateItem or DeleteItem, a `FilterExpression` on Scan or Query, or a `KeyConditionExpression` on Query with more than 300 operators gets `ValidationException` "Invalid ConditionExpression: The expression contains too many operators; operator count: 599" (the parameter name and the count follow the request). Every comparison operator, `AND`, `OR`, `NOT`, `BETWEEN`, `IN` and function call counts one; parentheses, paths, placeholders and the elements of an `IN` list count zero. 1.0.0 evaluated such an expression. The legacy `ScanFilter`, `QueryFilter` and `Expected` parameters, `UpdateExpression` and TransactWriteItems are not counted, and a PartiQL statement is counted as 1.0.0 counted it. `max_expression_operators` under `[limits]` (default 300) raises the cap. +- A repeated or misplaced operator or keyword in a condition, filter, key condition, update or projection expression gets the service's text, "Invalid ConditionExpression: Syntax error; token: \"=\", near: \"= = :v\"" for `#v = = :v`. 1.0.0 answered its own texts, such as "Invalid ConditionExpression: expected attribute path or value placeholder", and on an `UpdateExpression` it quoted a window found by searching the text for the token, which was wrong when the same text appeared earlier in the expression. +- PutItem with an `ExpressionAttributeNames` or `ExpressionAttributeValues` key over 255 bytes gets `ValidationException` "ExpressionAttributeNames contains invalid key: The expression attribute map contains a key that is too long; size of key: 256". 1.0.0 answered `SerializationException` with the same text after "Start of structure or map found where not expected: ". PutItem with an empty attribute name in `ExpressionAttributeNames` changes the same way: `ValidationException` "ExpressionAttributeNames contains invalid value: Empty attribute name for key #v", where 1.0.0 answered `SerializationException`. The `ExpressionAttributeValues` text now carries the same "; size of key: " suffix as the names text; 1.0.0 left it off. +- On Scan, a `Limit` below 1, a `Segment` outside 0 to 999999 or a `TotalSegments` outside 1 to 1000000 is refused before the filter and projection expressions are read and before the table lookup, each field on its own: `TotalSegments: 0` without `Segment` gets "The parameter TotalSegments should be greater than or equal to 1", where 1.0.0 answered the missing `Segment`, and `Limit: 0` beside a filter syntax error or a missing table gets the `Limit` text, where 1.0.0 answered the syntax error or `ResourceNotFoundException`. The texts of these three ranges are 1.0.0's. + +**Who is affected.** A client that sends an expression of more than 300 operators, which DynamoDB refuses: with 1.0.0 the request ran, with this release it gets `ValidationException` and nothing is read or written. A deployment that needs the old behaviour sets `max_expression_operators` under `[limits]` above its largest expression; DynamoDB has no such setting. A client that matches error texts: the syntax error texts and the PutItem key length error type change as listed above. No catalog migration is required, and a rollback to 1.0.0 brings back the old answers. + ### v1.0.0: Cassandra reads and writes at `LOCAL_QUORUM` **What changed.** The Cassandra backend runs its reads and writes at `LOCAL_QUORUM`. 0.1.15 ran many of them at `ONE`, the driver's default, in each area: items (the reads of GetItem, Query and Scan among them), transactions, TTL, streams, the catalog, IAM and `init`. A read with `ConsistentRead` `false` also runs at `LOCAL_QUORUM`. A lightweight transaction runs Paxos at `LOCAL_SERIAL` and commits at `LOCAL_QUORUM`. 0.1.15 ran many of its lightweight transactions at those levels already, and others, among them the admin user creation and most IAM writes, at the driver's defaults, `SERIAL` and `ONE`. Batches ran at `LOCAL_QUORUM` before and still do. No setting changes these levels (#945). From ab59fc26155f8d7688d4c4f413effe7fa7c018ce Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:23:12 +0000 Subject: [PATCH 35/37] chore(expression): drop four re-exports no caller uses, and list the operator cap in the config template `crates/core/src/expression/mod.rs` re-exported `count_operators`, `is_operator_or_keyword`, `syntax_error` and `token_text`. No code outside the module imports them: the parsers import `syntax_error` and `is_operator_or_keyword` from the module itself, and `count_operators` is called only inside `operator_count.rs`. The four names leave the `pub use` lines. `validate_operator_count` and `MAX_EXPRESSION_OPERATORS` stay. The `[limits]` section of the config file that `extenddb init` writes listed `max_expression_tokens` and `max_expression_depth` as comments and left out the new setting. It now lists `# max_expression_operators = 300` after them. --- crates/app/src/init_helpers.rs | 1 + crates/core/src/expression/mod.rs | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/app/src/init_helpers.rs b/crates/app/src/init_helpers.rs index a5d823b7f..ce91b126f 100755 --- a/crates/app/src/init_helpers.rs +++ b/crates/app/src/init_helpers.rs @@ -310,6 +310,7 @@ key_path = "{tls_key}" # max_attribute_name_bytes = 65535 # max_expression_tokens = 4096 # max_expression_depth = 150 +# max_expression_operators = 300 # per_table_max_rcu = 40000 # per_table_max_wcu = 40000 # per_account_max_rcu = 80000 diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 54db0d26a..a4e42b6ac 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -38,7 +38,7 @@ pub use key_condition::{ }; pub use kind::ExpressionKind; pub use operand_check::validate_placeholders_and_operands; -pub use operator_count::{MAX_EXPRESSION_OPERATORS, count_operators, validate_operator_count}; +pub use operator_count::{MAX_EXPRESSION_OPERATORS, validate_operator_count}; pub use parser::{ ConditionFault, parse_condition, parse_condition_classified, parse_condition_from, parse_condition_with_depth_limit, @@ -55,7 +55,6 @@ pub use search_condition::{ SearchCondition, validate_conditions_against_search_schema, validate_search_condition_expression, }; -pub use syntax_error::{is_operator_or_keyword, syntax_error, token_text}; pub use tokenizer::{Token, tokenize, tokenize_for, tokenize_with_limit}; pub use update_evaluator::apply_update_validated; pub use update_parser::{parse_update, parse_update_from}; From ae298f44db046e4e5b9373956a5faf7e571e6159 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:23:40 +0000 Subject: [PATCH 36/37] refactor(expression): move the parser tests to parser_tests.rs crates/core/src/expression/parser.rs grew to 702 lines, with the inline test module from line 396. The module moves unchanged to parser_tests.rs, which parser.rs names with #[path], as evaluator.rs and key_condition.rs name theirs. parser.rs is now 398 lines. No test changes. --- crates/core/src/expression/parser.rs | 308 +-------------------- crates/core/src/expression/parser_tests.rs | 307 ++++++++++++++++++++ 2 files changed, 309 insertions(+), 306 deletions(-) create mode 100644 crates/core/src/expression/parser_tests.rs diff --git a/crates/core/src/expression/parser.rs b/crates/core/src/expression/parser.rs index 1ba9bdd56..0058cb719 100755 --- a/crates/core/src/expression/parser.rs +++ b/crates/core/src/expression/parser.rs @@ -394,309 +394,5 @@ fn syntax_fault(src: &str, tokens: &[Token], pos: usize) -> ConditionFault { } #[cfg(test)] -mod tests { - use super::*; - use crate::expression::ast::{CompareOp, Expr, PathElement}; - use crate::expression::tokenizer::tokenize; - - fn parse(input: &str) -> Result { - let tokens = tokenize(input)?; - parse_condition(&tokens) - } - - #[test] - fn parse_simple_comparison() { - let expr = parse("price > :min").unwrap(); - assert!(matches!( - expr, - Expr::Compare { - op: CompareOp::Gt, - .. - } - )); - } - - #[test] - fn parse_and_expression() { - let expr = parse("a = :v1 AND b = :v2").unwrap(); - assert!(matches!(expr, Expr::And(_, _))); - } - - #[test] - fn parse_or_expression() { - let expr = parse("a = :v1 OR b = :v2").unwrap(); - assert!(matches!(expr, Expr::Or(_, _))); - } - - #[test] - fn parse_not_expression() { - let expr = parse("NOT a = :v").unwrap(); - assert!(matches!(expr, Expr::Not(_))); - } - - #[test] - fn parse_parenthesized_expression() { - let expr = parse("(a = :v1 OR b = :v2) AND c = :v3").unwrap(); - assert!(matches!(expr, Expr::And(_, _))); - } - - #[test] - fn parse_between_expression() { - let expr = parse("price BETWEEN :lo AND :hi").unwrap(); - assert!(matches!(expr, Expr::Between { .. })); - } - - #[test] - fn parse_in_expression() { - let expr = parse("status IN (:a, :b, :c)").unwrap(); - if let Expr::In { list, .. } = &expr { - assert_eq!(list.len(), 3); - } else { - panic!("Expected In expression"); - } - } - - #[test] - fn parse_attribute_exists() { - let expr = parse("attribute_exists(myattr)").unwrap(); - assert!(matches!(expr, Expr::Function { .. })); - } - - #[test] - fn parse_attribute_not_exists() { - let expr = parse("attribute_not_exists(#pk)").unwrap(); - if let Expr::Function { name, args } = &expr { - assert_eq!(name, "attribute_not_exists"); - assert_eq!(args.len(), 1); - } else { - panic!("Expected Function expression"); - } - } - - #[test] - fn parse_begins_with() { - let expr = parse("begins_with(#n, :prefix)").unwrap(); - if let Expr::Function { name, args } = &expr { - assert_eq!(name, "begins_with"); - assert_eq!(args.len(), 2); - } else { - panic!("Expected Function expression"); - } - } - - #[test] - fn parse_contains() { - let expr = parse("contains(tags, :tag)").unwrap(); - if let Expr::Function { name, .. } = &expr { - assert_eq!(name, "contains"); - } else { - panic!("Expected Function expression"); - } - } - - #[test] - fn parse_size_in_comparison() { - let expr = parse("size(mylist) > :limit").unwrap(); - if let Expr::Compare { left, op, .. } = &expr { - assert!(matches!(op, CompareOp::Gt)); - assert!(matches!(left.as_ref(), Expr::Function { name, .. } if name == "size")); - } else { - panic!("Expected Compare expression with size function"); - } - } - - #[test] - fn parse_nested_path() { - let expr = parse("address.city = :city").unwrap(); - if let Expr::Compare { left, .. } = &expr { - if let Expr::Path(elements) = left.as_ref() { - assert_eq!(elements.len(), 2); - assert_eq!(elements[0], PathElement::Attribute("address".into())); - assert_eq!(elements[1], PathElement::Attribute("city".into())); - } else { - panic!("Expected Path expression"); - } - } else { - panic!("Expected Compare expression"); - } - } - - #[test] - fn parse_list_index_path() { - let expr = parse("items[0] = :v").unwrap(); - if let Expr::Compare { left, .. } = &expr { - if let Expr::Path(elements) = left.as_ref() { - assert_eq!(elements.len(), 2); - assert_eq!(elements[1], PathElement::Index(0)); - } else { - panic!("Expected Path expression"); - } - } else { - panic!("Expected Compare expression"); - } - } - - #[test] - fn parse_all_comparators() { - for (input, expected_op) in [ - ("a = :v", CompareOp::Eq), - ("a <> :v", CompareOp::Ne), - ("a < :v", CompareOp::Lt), - ("a <= :v", CompareOp::Le), - ("a > :v", CompareOp::Gt), - ("a >= :v", CompareOp::Ge), - ] { - let expr = parse(input).unwrap(); - if let Expr::Compare { op, .. } = &expr { - assert_eq!(*op, expected_op, "Failed for input: {input}"); - } else { - panic!("Expected Compare for input: {input}"); - } - } - } - - #[test] - fn parse_empty_tokens_rejected() { - let err = parse_condition(&[]).unwrap_err(); - assert!(matches!(err, DynamoDbError::ValidationException(_))); - } - - #[test] - fn parse_trailing_tokens_rejected() { - // An operand after a complete condition: measured 2026-10-25 (d11, - // `#v = :v #v = :v` answers token "#v", near ":v #v ="). - let tokens = tokenize("a = :v b").unwrap(); - let err = parse_condition(&tokens).unwrap_err(); - assert!(matches!(err, DynamoDbError::ValidationException(msg) - if msg == "Invalid ConditionExpression: Syntax error; token: \"b\", near: \":v b\"")); - } - - #[test] - fn parse_depth_limit_exceeded() { - // Build deeply nested NOT NOT NOT ... a = :v - let deep = "NOT ".repeat(200) + "a = :v"; - let tokens = tokenize(&deep).unwrap(); - let err = parse_condition_with_depth_limit(&tokens, 150).unwrap_err(); - assert!( - matches!(err, DynamoDbError::ValidationException(msg) if msg.contains("depth exceeded")) - ); - } - - #[test] - fn redundant_parens_rejected() { - let cases = [ - "((a = :v))", - "(((a = :v)))", - "((a = :v AND b = :v2))", - "((NOT (a = :v)))", - "(a = :v) AND ((b = :v2))", - ]; - for expr in cases { - let tokens = tokenize(expr).unwrap(); - let err = parse_condition(&tokens).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if msg.contains("redundant parentheses")), - "Expected redundant parens error for: {expr}, got: {err:?}" - ); - } - } - - #[test] - fn valid_parens_accepted() { - let cases = [ - "(a = :v)", - "(a = :v) AND (b = :v2)", - "((a = :v) AND (b = :v2))", - "(NOT (a = :v))", - ]; - for expr in cases { - let tokens = tokenize(expr).unwrap(); - assert!( - parse_condition(&tokens).is_ok(), - "Expected valid parse for: {expr}" - ); - } - } - - #[test] - fn redundant_parens_use_canonical_message() { - for expr in [ - "((a = :v))", - "(((a = :v)))", - "((a = :v AND b = :v2))", - "((NOT (a = :v)))", - ] { - let tokens = tokenize(expr).unwrap(); - let err = parse_condition(&tokens).unwrap_err(); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) - if msg == "Invalid ConditionExpression: The expression has redundant parentheses;"), - "expr {expr}: got {err:?}" - ); - } - } - - #[test] - fn a_token_other_than_a_parenthesis_after_in_answers_the_syntax_error() { - // Measured 2026-11-19 (us-east-1), probe cases in the first column. - for (case, src, token, near) in [ - ("x17", "#v IN IN (:v)", "IN", "IN IN ("), - ("i01", "#v IN :v", ":v", "IN :v"), - ("i02", "#v IN", "", "IN"), - ] { - let err = parse_condition_from(&tokenize(src).unwrap(), src, 150).unwrap_err(); - let want = format!( - "Invalid ConditionExpression: Syntax error; token: \"{token}\", near: \"{near}\"" - ); - assert!( - matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), - "{case}: got {err:?}" - ); - } - } - - #[test] - fn the_classified_parse_tells_a_syntax_error_from_the_other_refusals() { - // The syntax variant carries the service's wording; every other - // refusal is the other variant with the parser's own text. - for (src, token, near) in [ - ("#v = = :v", "=", "= = :v"), - ("#v = :v AND", "", "AND"), - ("#v = :v #v = :v", "#v", ":v #v ="), - ("= #v = :v", "=", "= #v"), - ("#v IN :v", ":v", "IN :v"), - ] { - let fault = parse_condition_classified(&tokenize(src).unwrap(), src, 150).unwrap_err(); - let want = format!( - "Invalid ConditionExpression: Syntax error; token: \"{token}\", near: \"{near}\"" - ); - assert!( - matches!(&fault, ConditionFault::Syntax(DynamoDbError::ValidationException(msg)) - if *msg == want), - "{src}: got {fault:?}" - ); - } - for (src, text) in [ - ("((#v = :v))", "The expression has redundant parentheses;"), - ("#v", "expected comparison operator or function call"), - ("(#v = :v", "expected ')'"), - ("#v = :v, #v = :v", "unexpected token at position 3"), - ] { - let fault = parse_condition_classified(&tokenize(src).unwrap(), src, 150).unwrap_err(); - let want = format!("Invalid ConditionExpression: {text}"); - assert!( - matches!(&fault, ConditionFault::Other(DynamoDbError::ValidationException(msg)) - if *msg == want), - "{src}: got {fault:?}" - ); - } - // Depth is the other variant too, with the depth limit of the call. - let src = "NOT NOT #v = :v"; - let fault = parse_condition_classified(&tokenize(src).unwrap(), src, 1).unwrap_err(); - assert!( - matches!(&fault, ConditionFault::Other(DynamoDbError::ValidationException(msg)) - if msg == "Invalid ConditionExpression: expression nesting depth exceeded"), - "got {fault:?}" - ); - } -} +#[path = "parser_tests.rs"] +mod tests; diff --git a/crates/core/src/expression/parser_tests.rs b/crates/core/src/expression/parser_tests.rs new file mode 100644 index 000000000..a583afd27 --- /dev/null +++ b/crates/core/src/expression/parser_tests.rs @@ -0,0 +1,307 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::expression::ast::{CompareOp, Expr, PathElement}; +use crate::expression::tokenizer::tokenize; + +fn parse(input: &str) -> Result { + let tokens = tokenize(input)?; + parse_condition(&tokens) +} + +#[test] +fn parse_simple_comparison() { + let expr = parse("price > :min").unwrap(); + assert!(matches!( + expr, + Expr::Compare { + op: CompareOp::Gt, + .. + } + )); +} + +#[test] +fn parse_and_expression() { + let expr = parse("a = :v1 AND b = :v2").unwrap(); + assert!(matches!(expr, Expr::And(_, _))); +} + +#[test] +fn parse_or_expression() { + let expr = parse("a = :v1 OR b = :v2").unwrap(); + assert!(matches!(expr, Expr::Or(_, _))); +} + +#[test] +fn parse_not_expression() { + let expr = parse("NOT a = :v").unwrap(); + assert!(matches!(expr, Expr::Not(_))); +} + +#[test] +fn parse_parenthesized_expression() { + let expr = parse("(a = :v1 OR b = :v2) AND c = :v3").unwrap(); + assert!(matches!(expr, Expr::And(_, _))); +} + +#[test] +fn parse_between_expression() { + let expr = parse("price BETWEEN :lo AND :hi").unwrap(); + assert!(matches!(expr, Expr::Between { .. })); +} + +#[test] +fn parse_in_expression() { + let expr = parse("status IN (:a, :b, :c)").unwrap(); + if let Expr::In { list, .. } = &expr { + assert_eq!(list.len(), 3); + } else { + panic!("Expected In expression"); + } +} + +#[test] +fn parse_attribute_exists() { + let expr = parse("attribute_exists(myattr)").unwrap(); + assert!(matches!(expr, Expr::Function { .. })); +} + +#[test] +fn parse_attribute_not_exists() { + let expr = parse("attribute_not_exists(#pk)").unwrap(); + if let Expr::Function { name, args } = &expr { + assert_eq!(name, "attribute_not_exists"); + assert_eq!(args.len(), 1); + } else { + panic!("Expected Function expression"); + } +} + +#[test] +fn parse_begins_with() { + let expr = parse("begins_with(#n, :prefix)").unwrap(); + if let Expr::Function { name, args } = &expr { + assert_eq!(name, "begins_with"); + assert_eq!(args.len(), 2); + } else { + panic!("Expected Function expression"); + } +} + +#[test] +fn parse_contains() { + let expr = parse("contains(tags, :tag)").unwrap(); + if let Expr::Function { name, .. } = &expr { + assert_eq!(name, "contains"); + } else { + panic!("Expected Function expression"); + } +} + +#[test] +fn parse_size_in_comparison() { + let expr = parse("size(mylist) > :limit").unwrap(); + if let Expr::Compare { left, op, .. } = &expr { + assert!(matches!(op, CompareOp::Gt)); + assert!(matches!(left.as_ref(), Expr::Function { name, .. } if name == "size")); + } else { + panic!("Expected Compare expression with size function"); + } +} + +#[test] +fn parse_nested_path() { + let expr = parse("address.city = :city").unwrap(); + if let Expr::Compare { left, .. } = &expr { + if let Expr::Path(elements) = left.as_ref() { + assert_eq!(elements.len(), 2); + assert_eq!(elements[0], PathElement::Attribute("address".into())); + assert_eq!(elements[1], PathElement::Attribute("city".into())); + } else { + panic!("Expected Path expression"); + } + } else { + panic!("Expected Compare expression"); + } +} + +#[test] +fn parse_list_index_path() { + let expr = parse("items[0] = :v").unwrap(); + if let Expr::Compare { left, .. } = &expr { + if let Expr::Path(elements) = left.as_ref() { + assert_eq!(elements.len(), 2); + assert_eq!(elements[1], PathElement::Index(0)); + } else { + panic!("Expected Path expression"); + } + } else { + panic!("Expected Compare expression"); + } +} + +#[test] +fn parse_all_comparators() { + for (input, expected_op) in [ + ("a = :v", CompareOp::Eq), + ("a <> :v", CompareOp::Ne), + ("a < :v", CompareOp::Lt), + ("a <= :v", CompareOp::Le), + ("a > :v", CompareOp::Gt), + ("a >= :v", CompareOp::Ge), + ] { + let expr = parse(input).unwrap(); + if let Expr::Compare { op, .. } = &expr { + assert_eq!(*op, expected_op, "Failed for input: {input}"); + } else { + panic!("Expected Compare for input: {input}"); + } + } +} + +#[test] +fn parse_empty_tokens_rejected() { + let err = parse_condition(&[]).unwrap_err(); + assert!(matches!(err, DynamoDbError::ValidationException(_))); +} + +#[test] +fn parse_trailing_tokens_rejected() { + // An operand after a complete condition: measured 2026-10-25 (d11, + // `#v = :v #v = :v` answers token "#v", near ":v #v ="). + let tokens = tokenize("a = :v b").unwrap(); + let err = parse_condition(&tokens).unwrap_err(); + assert!(matches!(err, DynamoDbError::ValidationException(msg) + if msg == "Invalid ConditionExpression: Syntax error; token: \"b\", near: \":v b\"")); +} + +#[test] +fn parse_depth_limit_exceeded() { + // Build deeply nested NOT NOT NOT ... a = :v + let deep = "NOT ".repeat(200) + "a = :v"; + let tokens = tokenize(&deep).unwrap(); + let err = parse_condition_with_depth_limit(&tokens, 150).unwrap_err(); + assert!( + matches!(err, DynamoDbError::ValidationException(msg) if msg.contains("depth exceeded")) + ); +} + +#[test] +fn redundant_parens_rejected() { + let cases = [ + "((a = :v))", + "(((a = :v)))", + "((a = :v AND b = :v2))", + "((NOT (a = :v)))", + "(a = :v) AND ((b = :v2))", + ]; + for expr in cases { + let tokens = tokenize(expr).unwrap(); + let err = parse_condition(&tokens).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if msg.contains("redundant parentheses")), + "Expected redundant parens error for: {expr}, got: {err:?}" + ); + } +} + +#[test] +fn valid_parens_accepted() { + let cases = [ + "(a = :v)", + "(a = :v) AND (b = :v2)", + "((a = :v) AND (b = :v2))", + "(NOT (a = :v))", + ]; + for expr in cases { + let tokens = tokenize(expr).unwrap(); + assert!( + parse_condition(&tokens).is_ok(), + "Expected valid parse for: {expr}" + ); + } +} + +#[test] +fn redundant_parens_use_canonical_message() { + for expr in [ + "((a = :v))", + "(((a = :v)))", + "((a = :v AND b = :v2))", + "((NOT (a = :v)))", + ] { + let tokens = tokenize(expr).unwrap(); + let err = parse_condition(&tokens).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) + if msg == "Invalid ConditionExpression: The expression has redundant parentheses;"), + "expr {expr}: got {err:?}" + ); + } +} + +#[test] +fn a_token_other_than_a_parenthesis_after_in_answers_the_syntax_error() { + // Measured 2026-11-19 (us-east-1), probe cases in the first column. + for (case, src, token, near) in [ + ("x17", "#v IN IN (:v)", "IN", "IN IN ("), + ("i01", "#v IN :v", ":v", "IN :v"), + ("i02", "#v IN", "", "IN"), + ] { + let err = parse_condition_from(&tokenize(src).unwrap(), src, 150).unwrap_err(); + let want = format!( + "Invalid ConditionExpression: Syntax error; token: \"{token}\", near: \"{near}\"" + ); + assert!( + matches!(&err, DynamoDbError::ValidationException(msg) if *msg == want), + "{case}: got {err:?}" + ); + } +} + +#[test] +fn the_classified_parse_tells_a_syntax_error_from_the_other_refusals() { + // The syntax variant carries the service's wording; every other + // refusal is the other variant with the parser's own text. + for (src, token, near) in [ + ("#v = = :v", "=", "= = :v"), + ("#v = :v AND", "", "AND"), + ("#v = :v #v = :v", "#v", ":v #v ="), + ("= #v = :v", "=", "= #v"), + ("#v IN :v", ":v", "IN :v"), + ] { + let fault = parse_condition_classified(&tokenize(src).unwrap(), src, 150).unwrap_err(); + let want = format!( + "Invalid ConditionExpression: Syntax error; token: \"{token}\", near: \"{near}\"" + ); + assert!( + matches!(&fault, ConditionFault::Syntax(DynamoDbError::ValidationException(msg)) + if *msg == want), + "{src}: got {fault:?}" + ); + } + for (src, text) in [ + ("((#v = :v))", "The expression has redundant parentheses;"), + ("#v", "expected comparison operator or function call"), + ("(#v = :v", "expected ')'"), + ("#v = :v, #v = :v", "unexpected token at position 3"), + ] { + let fault = parse_condition_classified(&tokenize(src).unwrap(), src, 150).unwrap_err(); + let want = format!("Invalid ConditionExpression: {text}"); + assert!( + matches!(&fault, ConditionFault::Other(DynamoDbError::ValidationException(msg)) + if *msg == want), + "{src}: got {fault:?}" + ); + } + // Depth is the other variant too, with the depth limit of the call. + let src = "NOT NOT #v = :v"; + let fault = parse_condition_classified(&tokenize(src).unwrap(), src, 1).unwrap_err(); + assert!( + matches!(&fault, ConditionFault::Other(DynamoDbError::ValidationException(msg)) + if msg == "Invalid ConditionExpression: expression nesting depth exceeded"), + "got {fault:?}" + ); +} From ee1d541683a07c88ab78fa4d3f37e620a3c65682 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:23:40 +0000 Subject: [PATCH 37/37] docs(upgrade): remove max_expression_operators before a rollback to 1.0.0 The v1.1.0 entry said that a rollback to 1.0.0 brings back the old answers. A configuration that sets max_expression_operators, as the entry suggests for the old behaviour, stops a 1.0.0 binary at start: LimitsConfig in 1.0.0 refuses unknown fields. The entry now says to remove the key before such a rollback. --- docs/manuals/07-upgrade-manual.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 257a1f267..bc4b9c26d 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -397,7 +397,7 @@ deployment, even when no catalog migration is required. - PutItem with an `ExpressionAttributeNames` or `ExpressionAttributeValues` key over 255 bytes gets `ValidationException` "ExpressionAttributeNames contains invalid key: The expression attribute map contains a key that is too long; size of key: 256". 1.0.0 answered `SerializationException` with the same text after "Start of structure or map found where not expected: ". PutItem with an empty attribute name in `ExpressionAttributeNames` changes the same way: `ValidationException` "ExpressionAttributeNames contains invalid value: Empty attribute name for key #v", where 1.0.0 answered `SerializationException`. The `ExpressionAttributeValues` text now carries the same "; size of key: " suffix as the names text; 1.0.0 left it off. - On Scan, a `Limit` below 1, a `Segment` outside 0 to 999999 or a `TotalSegments` outside 1 to 1000000 is refused before the filter and projection expressions are read and before the table lookup, each field on its own: `TotalSegments: 0` without `Segment` gets "The parameter TotalSegments should be greater than or equal to 1", where 1.0.0 answered the missing `Segment`, and `Limit: 0` beside a filter syntax error or a missing table gets the `Limit` text, where 1.0.0 answered the syntax error or `ResourceNotFoundException`. The texts of these three ranges are 1.0.0's. -**Who is affected.** A client that sends an expression of more than 300 operators, which DynamoDB refuses: with 1.0.0 the request ran, with this release it gets `ValidationException` and nothing is read or written. A deployment that needs the old behaviour sets `max_expression_operators` under `[limits]` above its largest expression; DynamoDB has no such setting. A client that matches error texts: the syntax error texts and the PutItem key length error type change as listed above. No catalog migration is required, and a rollback to 1.0.0 brings back the old answers. +**Who is affected.** A client that sends an expression of more than 300 operators, which DynamoDB refuses: with 1.0.0 the request ran, with this release it gets `ValidationException` and nothing is read or written. A deployment that needs the old behaviour sets `max_expression_operators` under `[limits]` above its largest expression; DynamoDB has no such setting. A client that matches error texts: the syntax error texts and the PutItem key length error type change as listed above. No catalog migration is required, and a rollback to 1.0.0 brings back the old answers. Remove `max_expression_operators` from `[limits]` before such a rollback: 1.0.0 refuses to start with a configuration that holds the key. ### v1.0.0: Cassandra reads and writes at `LOCAL_QUORUM`