Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
75a783b
fix(expression): refuse a document path of more than 32 elements
LeeroyHannigan Oct 29, 2026
5b64ffd
test(expression): document path length limit and its order
LeeroyHannigan Oct 29, 2026
ea464eb
fix(expression): value nesting after mixed parameters and Item numbers
LeeroyHannigan Oct 29, 2026
8549bc0
test(expression): mixed parameters and Item numbers before value nesting
LeeroyHannigan Oct 29, 2026
69e6415
Merge #399's head 5646709c6 into fix/document-path-length-on-399
LeeroyHannigan Nov 12, 2026
d508588
fix(expression): check a projection path's overlap before the next path
LeeroyHannigan Nov 12, 2026
617ab86
fix(transact): check an Update's condition before its UpdateExpression
LeeroyHannigan Nov 12, 2026
91060d0
fix(put): check the Item's numbers and nesting before the condition
LeeroyHannigan Nov 12, 2026
d98748b
fix(query): check key condition references and path lengths in one pass
LeeroyHannigan Nov 12, 2026
4cacd55
fix(expression): build the BETWEEN bounds sentence only for a fault
LeeroyHannigan Nov 12, 2026
ad68185
docs(expression): state the key condition order and drop a run label
LeeroyHannigan Nov 12, 2026
3626544
refactor(query): reuse the semantic walk's reference checks for keys
LeeroyHannigan Nov 12, 2026
375c1ad
docs(expression): split the long sentences in the new comments
LeeroyHannigan Nov 12, 2026
519f200
refactor(put): check the Item's numbers and nesting once
LeeroyHannigan Nov 12, 2026
dea363e
Merge fix/transact-validation-order into fix/document-path-length-on-399
LeeroyHannigan Nov 16, 2026
7029242
fix(put): run the Item and value checks once, at their position from …
LeeroyHannigan Nov 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 40 additions & 23 deletions crates/core/src/expression/evaluator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,29 +55,10 @@ pub fn evaluate_condition(
let val = resolve_to_value(operand, item, maps)?;
let lo = resolve_to_value(low, item, maps)?;
let hi = resolve_to_value(high, item, maps)?;
// DynamoDB validates bounds when both are literal placeholders
if matches!(low.as_ref(), Expr::Placeholder(_))
&& matches!(high.as_ref(), Expr::Placeholder(_))
&& let (Some(l), Some(h)) = (lo.as_deref(), hi.as_deref())
{
let l_type = attribute_type_code(l);
let h_type = attribute_type_code(h);
if l_type != h_type {
return Err(DynamoDbError::ValidationException(format!(
"Invalid ConditionExpression: The BETWEEN operator requires same data type for lower and upper bounds; lower bound operand: AttributeValue: {{{}}}, upper bound operand: AttributeValue: {{{}}}",
format_attribute_value(l),
format_attribute_value(h)
)));
}
let lpn = placeholder_numeric(low, maps);
let hpn = placeholder_numeric(high, maps);
if compare_values(l, h, CompareOp::Gt, lpn, hpn) {
return Err(DynamoDbError::ValidationException(format!(
"Invalid ConditionExpression: The BETWEEN operator requires upper bound to be greater than or equal to lower bound; lower bound operand: AttributeValue: {{{}}}, upper bound operand: AttributeValue: {{{}}}",
format_attribute_value(l),
format_attribute_value(h)
)));
}
if let Some(msg) = between_bounds_fault(low, high, maps) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No test fails with this call removed. Without it, PutItem with Expected: {n: {ComparisonOperator: BETWEEN, AttributeValueList: [{N: "5"}, {N: "1"}]}} answers ConditionalCheckFailedException where this head answers ValidationException.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4cacd55. A unit test calls evaluate_condition with bounds out of order, and a wire test sends your Expected BETWEEN on PutItem.

return Err(DynamoDbError::ValidationException(format!(
"Invalid ConditionExpression: {msg}"
)));
}
match (&val, &lo, &hi) {
(Some(v), Some(l), Some(h)) => {
Expand Down Expand Up @@ -129,6 +110,42 @@ fn resolve_to_value<'a>(
}
}

/// The service's sentence when both BETWEEN bounds are placeholders and they
/// differ in type or the lower is above the upper, without the `Invalid
/// <Kind>: ` label. The service checks this at request time, whatever the
/// item (measured 2026-10-26). The evaluator calls this for every item, so
/// the sentence is built only when the bounds are at fault.
pub(crate) fn between_bounds_fault(
low: &Expr,
high: &Expr,
maps: &ExpressionMaps,
) -> Option<String> {
let (Expr::Placeholder(l_name), Expr::Placeholder(h_name)) = (low, high) else {
return None;
};
let (Some(l), Some(h)) = (maps.values.get(l_name), maps.values.get(h_name)) else {
return None;
};
let requirement = if attribute_type_code(l) != attribute_type_code(h) {
"same data type for lower and upper bounds"
} else if compare_values(
l,
h,
CompareOp::Gt,
placeholder_numeric(low, maps),
placeholder_numeric(high, maps),
) {
"upper bound to be greater than or equal to lower bound"
} else {
return None;
};
Some(format!(
"The BETWEEN operator requires {requirement}; lower bound operand: AttributeValue: {{{}}}, upper bound operand: AttributeValue: {{{}}}",
format_attribute_value(l),
format_attribute_value(h)
))
}

/// Look up a pre-parsed number for a placeholder expression.
///
/// Returns `None` if the expression is not a placeholder or has no pre-parsed
Expand Down
38 changes: 38 additions & 0 deletions crates/core/src/expression/evaluator_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,44 @@ fn between_out_of_range() {
assert!(!eval("age BETWEEN :lo AND :hi", &item, HashMap::new(), values).unwrap());
}

/// Bounds of different types or with the lower above the upper are refused
/// whatever the item holds. A legacy `Expected` condition reaches the
/// evaluator without the semantic walk, so this is its only bounds check.
/// Measured 2026-11-12: PutItem with `Expected` `n BETWEEN [5, 1]` answers
/// ValidationException on a missing and on an existing item.
#[test]
fn between_bounds_at_fault_are_refused_for_every_item() {
let bounds = |lo: AttributeValue, hi: AttributeValue| {
HashMap::from([("lo".to_owned(), lo), ("hi".to_owned(), hi)])
};
for (values, want) in [
(
bounds(AttributeValue::N("5".into()), AttributeValue::N("1".into())),
"Invalid ConditionExpression: The BETWEEN operator requires upper bound to be \
greater than or equal to lower bound; lower bound operand: AttributeValue: {N:5}, \
upper bound operand: AttributeValue: {N:1}",
),
(
bounds(AttributeValue::N("1".into()), AttributeValue::S("a".into())),
"Invalid ConditionExpression: The BETWEEN operator requires same data type for \
lower and upper bounds; lower bound operand: AttributeValue: {N:1}, upper bound \
operand: AttributeValue: {S:a}",
),
] {
for item in [simple_item(), BTreeMap::new()] {
match eval(
"age BETWEEN :lo AND :hi",
&item,
HashMap::new(),
values.clone(),
) {
Err(DynamoDbError::ValidationException(msg)) => assert_eq!(msg, want),
other => panic!("{want}: {other:?}"),
}
}
}
}

#[test]
fn in_expression_match() {
let item = simple_item();
Expand Down
68 changes: 64 additions & 4 deletions crates/core/src/expression/key_condition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use super::ast::{CompareOp, Expr, PathElement};
use super::parser_common;
use super::resolver::ExpressionMaps;
use super::tokenizer::Token;
use crate::error::DynamoDbError;
use crate::types::{
Expand Down Expand Up @@ -530,8 +531,32 @@ impl SortKeyCondition {
///
/// Returns `ValidationException` for syntax errors or unsupported constructs.
pub fn parse_key_condition(tokens: &[Token]) -> Result<KeyCondition, DynamoDbError> {
let mut clauses = parse_clauses(tokens)?;
classify_clauses(parse_clauses(tokens, None)?)
}

/// [`parse_key_condition`] for a request. Once the expression parses, one pass
/// in text order checks every `#name` and `:value` reference against `maps`
/// and every document path's length. The pass runs before the
/// nested-attribute refusal and the clause shapes.
///
/// Measured 2026-11-12 (us-east-1): `pk = :nope AND <33 elements> = :s`
/// answers the undefined `:nope`. `<33 elements> = :s AND pk = :nope` and
/// `pk = :p AND <33 elements> = :nope` answer the length.
/// `#m.#k = :s AND #zz = :p` answers the undefined `#zz`, and `pk < :nope`
/// the undefined `:nope`.
///
/// # Errors
///
/// Returns `ValidationException` for the errors of [`parse_key_condition`],
/// an undefined reference and a path of more than 32 elements.
pub fn parse_key_condition_with_maps(
tokens: &[Token],
maps: &ExpressionMaps,
) -> Result<KeyCondition, DynamoDbError> {
classify_clauses(parse_clauses(tokens, Some(maps))?)
}

fn classify_clauses(mut clauses: Vec<RawClause>) -> Result<KeyCondition, DynamoDbError> {
match clauses.len() {
1 => classify_single(clauses.remove(0)),
2 => classify_pair(clauses.remove(0), clauses.remove(0)),
Expand All @@ -555,7 +580,7 @@ pub fn parse_key_condition(tokens: &[Token]) -> Result<KeyCondition, DynamoDbErr
pub fn key_condition_clause_operands(
tokens: &[Token],
) -> Result<Vec<KeyClauseOperand>, DynamoDbError> {
Ok(parse_clauses(tokens)?
Ok(parse_clauses(tokens, None)?
.into_iter()
.filter_map(|clause| match clause {
RawClause::Eq(path, value) => Some(KeyClauseOperand {
Expand Down Expand Up @@ -589,7 +614,12 @@ pub struct KeyClauseOperand {

/// Parse a `KeyConditionExpression` token stream into its AND-ed clauses,
/// before any of them is read as the partition or the sort key condition.
fn parse_clauses(tokens: &[Token]) -> Result<Vec<RawClause>, DynamoDbError> {
/// With `maps`, the references and path lengths are checked once the clauses
/// parse (see [`check_references`]).
fn parse_clauses(
tokens: &[Token],
maps: Option<&ExpressionMaps>,
) -> Result<Vec<RawClause>, DynamoDbError> {
parser_common::check_redundant_parens(tokens)
.map_err(|body| validation_err(&format!("Invalid KeyConditionExpression: {body}")))?;

Expand Down Expand Up @@ -625,16 +655,46 @@ fn parse_clauses(tokens: &[Token]) -> Result<Vec<RawClause>, DynamoDbError> {
));
}

if let Some(maps) = maps {
check_references(tokens, maps)?;
}

// A key condition may only reference a top-level key attribute. Any document
// path (`attr.sub` or `attr[i]`) on a key is rejected, matching Amazon
// DynamoDB. Runs after the reserved-word check and before key-schema checks.
// DynamoDB. Runs after the reserved-word check, the references and the
// path lengths, and before key-schema checks.
for clause in &clauses {
reject_nested_key_path(raw_clause_path(clause))?;
}

Ok(clauses)
}

/// Refuse the first `#name` or `:value` reference that `maps` does not define
/// and the first document path of more than 32 elements. One pass in text
/// order checks each path's names, then its length, with the semantic walk's
/// checks.
fn check_references(tokens: &[Token], maps: &ExpressionMaps) -> Result<(), DynamoDbError> {
use super::semantics::{check_path_refs, check_value_defined};
let kind = super::ExpressionKind::KeyCondition;
let mut pos = 0;
while pos < tokens.len() {
match &tokens[pos] {
Token::Placeholder(value) => {
check_value_defined(value, maps, kind)?;
pos += 1;
}
// A function name such as `begins_with` is not a path.
Token::Ident(_) if tokens.get(pos + 1) == Some(&Token::LParen) => pos += 1,
Token::Ident(_) | Token::NameRef(_) => {
check_path_refs(&parser_common::parse_path(tokens, &mut pos)?, maps, kind)?;
}
_ => pos += 1,
}
}
Ok(())
}

/// The attribute-side path of a raw clause.
fn raw_clause_path(clause: &RawClause) -> &[PathElement] {
match clause {
Expand Down
4 changes: 3 additions & 1 deletion crates/core/src/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod key_condition;
mod kind;
mod parser;
mod parser_common;
mod path_length;
mod projection;
mod reserved_words;
mod resolver;
Expand All @@ -29,10 +30,11 @@ pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only}
pub use evaluator::{compare_orderable, evaluate_condition};
pub use key_condition::{
KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands,
parse_key_condition,
parse_key_condition, parse_key_condition_with_maps,
};
pub use kind::ExpressionKind;
pub use parser::{parse_condition, parse_condition_with_depth_limit};
pub use path_length::MAX_DOCUMENT_PATH_ELEMENTS;
pub use projection::{Projection, parse_projection};
pub use reserved_words::validate_no_reserved_words;
pub use resolver::{
Expand Down
Loading
Loading