Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
29229c2
fix(expressions): validate requests in the service's order and with i…
LeeroyHannigan Oct 31, 2026
aef6e1b
fix(expressions): keep the legacy filter operand-type checks, clarify…
LeeroyHannigan Oct 31, 2026
475465a
fix(expressions): refuse legacy filter operand types with the service…
LeeroyHannigan Oct 31, 2026
90fdc32
fix(expressions): validate legacy conditions with the service's rules…
LeeroyHannigan Oct 31, 2026
68dcd0a
fix(engine): order transaction ConsumedCapacity by table creation time
LeeroyHannigan Oct 31, 2026
217b5f9
fix(storage-mongodb): keep milliseconds on the catalog creation time
LeeroyHannigan Oct 31, 2026
b7ba331
docs: state the transaction capacity tie rule per backend
LeeroyHannigan Oct 31, 2026
ac76c66
refactor(core): split the expression semantic pass by rule family
LeeroyHannigan Oct 31, 2026
964f3c3
refactor(core): move the update-parser tests into their own file
LeeroyHannigan Oct 31, 2026
bf75dc7
style: remove two em dashes from comments this branch added
LeeroyHannigan Oct 31, 2026
af5f681
fix(transact): report four per-item checks where the service does
LeeroyHannigan Oct 31, 2026
d28de7a
fix(query): name the first undefined key condition reference
LeeroyHannigan Oct 31, 2026
52aad21
fix(expressions): answer four checks as the service does
LeeroyHannigan Oct 31, 2026
2c6d37b
docs: correct four comments, pin the sorted unused key list
LeeroyHannigan Oct 31, 2026
d45765d
fix(transact): apply the value nesting limits as the service does
LeeroyHannigan Oct 31, 2026
cbb04f0
fix(scan): report Segment and TotalSegments mismatches after the expr…
LeeroyHannigan Oct 31, 2026
1454cc9
docs: state what the Scan comment, the helpers header and the nesting…
LeeroyHannigan Oct 31, 2026
6f12515
Merge origin/main into fix/transact-validation-order
LeeroyHannigan Nov 5, 2026
5646709
Merge origin/main into fix/transact-validation-order
LeeroyHannigan Nov 9, 2026
ba4ae3d
Merge origin/main into fix/transact-validation-order
LeeroyHannigan Nov 14, 2026
7e04892
test: set creation_date_time in two TableKeyInfo literals from main
LeeroyHannigan Nov 14, 2026
a0f2a6b
fix(expressions): read BETWEEN bound numbers through number_value
LeeroyHannigan Nov 14, 2026
39ad6cd
fix(expressions): name the DELETE typeSet for a DELETE operand of the…
LeeroyHannigan Nov 16, 2026
1700595
Merge origin/main into fix/transact-validation-order
LeeroyHannigan Nov 16, 2026
2e1fa32
fix(expressions): pass the depth limit to the update section parse
LeeroyHannigan Nov 16, 2026
29f6669
test(expressions): pin the depth limit for calls of any name
LeeroyHannigan Nov 16, 2026
cd50250
fix(expressions): refuse a call by name past the depth limit
LeeroyHannigan Nov 19, 2026
63c2ba9
Merge branch 'main' into fix/transact-validation-order
LeeroyHannigan Nov 20, 2026
2d137cc
Merge branch 'main' into fix/transact-validation-order
LeeroyHannigan Nov 23, 2026
7efa519
Merge origin/main into fix/transact-validation-order
LeeroyHannigan Nov 24, 2026
a942b74
Merge origin/main into fix/transact-validation-order
LeeroyHannigan Nov 24, 2026
cdafc6f
Merge origin/main into fix/transact-validation-order
LeeroyHannigan Nov 24, 2026
5ee0b6d
fix(engine): allow the PartiQL-only helpers to be unused without partiql
LeeroyHannigan Nov 24, 2026
5a2facf
Merge origin/main into fix/transact-validation-order
LeeroyHannigan Nov 25, 2026
1a93ee2
test: set creation_date_time in the TableKeyInfo literal of #544's ga…
LeeroyHannigan Nov 25, 2026
1fbf065
Merge origin/main into fix/transact-validation-order
LeeroyHannigan Dec 3, 2026
caf3462
test: pass the expression maps to the key condition parse in #481's t…
LeeroyHannigan Dec 3, 2026
edb464c
docs(upgrade): add the v1.2.0 entry for the expression and transactio…
LeeroyHannigan Dec 3, 2026
beafa78
Merge origin/main into fix/transact-validation-order
LeeroyHannigan Dec 4, 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
61 changes: 55 additions & 6 deletions crates/core/src/expression/depth_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

//! The nesting depth limit of the update and condition parsers: an
//! expression nested past `max_depth` is refused, and one nested far past it
//! is refused on a thread with a small stack instead of overflowing it.
//! is refused on a thread with a small stack instead of overflowing it. A
//! call refused by name is refused with the name refusal past the limit too.

use super::parser::parse_condition_with_depth_limit;
use super::test_timeout::within_10_s;
Expand All @@ -22,6 +23,7 @@ const SMALL_STACK: usize = 1 << 20;

const UPDATE_TOO_DEEP: &str = "Invalid UpdateExpression: expression nesting depth exceeded";
const CONDITION_TOO_DEEP: &str = "Invalid ConditionExpression: expression nesting depth exceeded";
const UPDATE_NO_FOO: &str = "Invalid UpdateExpression: Invalid function name; function: foo";

/// `SET qty = (qty + (qty + ... :v))` with `levels` groups.
fn nested_groups(levels: usize) -> String {
Expand Down Expand Up @@ -73,13 +75,12 @@ fn message(result: Result<(), DynamoDbError>) -> String {
}
}

/// `update` or `condition`.
type Parse = fn(&str) -> Result<(), DynamoDbError>;

/// Run `parse` on `expr` on a thread with [`SMALL_STACK`], failing the test
/// after 10 seconds.
fn on_small_stack(
what: &'static str,
expr: String,
parse: fn(&str) -> Result<(), DynamoDbError>,
) -> Result<(), DynamoDbError> {
fn on_small_stack(what: &'static str, expr: String, parse: Parse) -> Result<(), DynamoDbError> {
within_10_s(what, move || {
std::thread::Builder::new()
.stack_size(SMALL_STACK)
Expand Down Expand Up @@ -163,3 +164,51 @@ fn condition_far_past_the_limit_is_refused_without_overflowing_the_stack() {
CONDITION_TOO_DEEP
);
}

/// Past the limit, a call the service refuses by name answers the name
/// refusal, as the service does at 151, 200 and 300 calls (measured
/// 2026-11-19, two sends each). `size` in a condition, and `if_not_exists`
/// and `list_append` in a SET value, keep the depth error.
#[test]
fn calls_refused_by_name_past_the_limit_answer_the_name_refusal() {
let past = LIMIT + 1;
let rows: [(&'static str, Parse, String, &str); 5] = [
(
"151 foo calls in a condition",
condition,
format!("{}a{} = :v", "foo(".repeat(past), ")".repeat(past)),
"Invalid ConditionExpression: Invalid function name; function: foo",
),
(
"50,000 f calls in a condition",
condition,
format!("{}x{}", "f(".repeat(FAR), ")".repeat(FAR)),
"Invalid ConditionExpression: Invalid function name; function: f",
),
(
"151 foo calls in a SET",
update,
format!("SET a = {}:v{}", "foo(".repeat(past), ")".repeat(past)),
UPDATE_NO_FOO,
),
(
"50,000 foo calls in a SET",
update,
format!("SET qty = {}:v{}", "foo(".repeat(FAR), ")".repeat(FAR)),
UPDATE_NO_FOO,
),
(
"151 size calls in a SET",
update,
format!("SET a = {}:v{}", "size(".repeat(past), ")".repeat(past)),
"Invalid UpdateExpression: The function is not allowed in an update expression; function: size",
),
];
for (what, parse, expr, expected) in rows {
assert_eq!(
message(on_small_stack(what, expr, parse)),
expected,
"{what}"
);
}
}
17 changes: 17 additions & 0 deletions crates/core/src/expression/evaluator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,23 @@ fn placeholder_numeric<'a>(expr: &Expr, maps: &'a ExpressionMaps) -> Option<Pars
}
}

/// Order two values of the same orderable type: `S` and `B` bytewise, `N`
/// numerically. Returns `None` for any other pair (different types, or a type
/// with no order), and for an `N` that is not a number the service can store.
#[must_use]
pub fn compare_orderable(left: &AttributeValue, right: &AttributeValue) -> Option<Ordering> {
match (left, right) {
(AttributeValue::S(l), AttributeValue::S(r)) => Some(l.cmp(r)),
(AttributeValue::B(l), AttributeValue::B(r)) => Some(l.cmp(r)),
(AttributeValue::N(l), AttributeValue::N(r)) => {
let l = number_value(l)?;
let r = number_value(r)?;
Some(l.cmp(&r))
}
_ => None,
}
}

/// One side of a numeric comparison as a decimal: the placeholder's
/// pre-parsed value when there is one, else `n` read with [`number_value`].
/// `None` when the number is not one the service can store.
Expand Down
10 changes: 10 additions & 0 deletions crates/core/src/expression/evaluator_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,16 @@ fn a_number_with_millions_of_digits_is_not_parsed() {
assert!(!eval_within_10_s("n > :v", item, values).unwrap());
}

/// A legacy `BETWEEN` bound with millions of trailing zeros is read through
/// the number check, at its value, and not parsed as written.
#[test]
fn a_bound_with_millions_of_trailing_zeros_compares_at_its_value() {
let long = AttributeValue::N(format!("1.{}", "0".repeat(2_000_000)));
let one = AttributeValue::N("1".to_owned());
let order = within_10_s("a long bound", move || compare_orderable(&long, &one));
assert_eq!(order, Some(Ordering::Equal));
}

/// A placeholder refused when the maps are built stays refused: a filter
/// does not read its text again for each item it compares.
#[test]
Expand Down
11 changes: 9 additions & 2 deletions crates/core/src/expression/key_condition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -810,12 +810,19 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result<RawClause
));
}

// begins_with(path, :val)
// begins_with(path, :val). The name is matched as written. Any other
// identifier followed by `(` is refused with the text the service gives
// it, which depends on the name (see `key_condition_function_refusal`).
if let Token::Ident(name) = &tokens[*pos]
&& name.eq_ignore_ascii_case("begins_with")
&& *pos + 1 < tokens.len()
&& tokens[*pos + 1] == Token::LParen
{
if name != "begins_with" {
return Err(validation_err(&format!(
"Invalid KeyConditionExpression: {}",
super::semantics::key_condition_function_refusal(name)
)));
}
*pos += 1; // skip function name
parser_common::expect_token(tokens, pos, &Token::LParen, "(", "KeyConditionExpression")?;
let path = parse_key_operand_path(tokens, pos)?;
Expand Down
23 changes: 22 additions & 1 deletion crates/core/src/expression/kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,32 @@ pub fn check_expression_size(
expr: &str,
kind: ExpressionKind,
limits: &LimitsConfig,
) -> Result<(), DynamoDbError> {
check_expression_size_with(expr, kind, limits, kind.size_error_includes_length())
}

/// `check_expression_size` with the length suffix decided by the caller.
///
/// Amazon DynamoDB appends ` expression size: N` for a `ConditionExpression`
/// inside a transaction and for a Scan `FilterExpression`, and omits it for a
/// `ConditionExpression` on PutItem, UpdateItem, or DeleteItem and for a Query
/// `FilterExpression` (measured 2026-10-14). The suffix is therefore a property
/// of the operation, not of the expression kind alone.
///
/// # Errors
///
/// Returns `DynamoDbError::ValidationException` when the expression is over
/// the configured byte limit.
pub fn check_expression_size_with(
expr: &str,
kind: ExpressionKind,
limits: &LimitsConfig,
include_length: bool,
) -> Result<(), DynamoDbError> {
if expr.len() > limits.max_expression_length_bytes {
let mut msg =
format!("Invalid {kind}: Expression size has exceeded the maximum allowed size;");
if kind.size_error_includes_length() {
if include_length {
use std::fmt::Write as _;
let _ = write!(msg, " expression size: {}", expr.len());
}
Expand Down
17 changes: 11 additions & 6 deletions crates/core/src/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,32 +23,37 @@ mod search_condition;
#[cfg(feature = "search-inequality-filters")]
pub mod search_filter;
pub mod search_params;
mod semantics;
#[cfg(test)]
mod test_timeout;
mod tokenizer;
mod update_evaluator;
mod update_parser;

pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only};
pub use evaluator::evaluate_condition;
pub use evaluator::{compare_orderable, evaluate_condition};
pub use key_condition::{
KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands,
parse_key_condition,
};
pub use kind::{ExpressionKind, check_expression_size};
pub use kind::{ExpressionKind, check_expression_size, check_expression_size_with};
pub use parser::{parse_condition, parse_condition_with_depth_limit};
pub use projection::{Projection, parse_projection};
pub use reserved_words::validate_no_reserved_words;
pub use resolver::{
ExpressionMaps, collect_key_condition_refs, collect_value_placeholders, resolve_element_name,
resolve_name_ref, resolve_path, validate_begins_with_operands, validate_expression_param_usage,
validate_ordering_operand_types, validate_unused_attributes,
ExpressionMaps, attribute_type_code, collect_key_condition_refs, collect_value_placeholders,
resolve_element_name, resolve_name_ref, resolve_path, validate_begins_with_operands,
validate_expression_param_usage, validate_ordering_operand_types, validate_unused_attributes,
validate_update_paths_disjoint,
};
pub use search_condition::{
MAX_INLINE_FILTER_CONDITIONS, MAX_PARTITION_KEY_CONDITIONS, MAX_SEARCH_CONDITIONS,
SearchCondition, search_condition_name_refs, validate_conditions_against_search_schema,
validate_search_condition_expression,
};
pub use semantics::{validate_condition_semantics, validate_update_semantics};
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};
pub use update_parser::{
ParsedUpdate, UpdateSection, parse_update, parse_update_from, parse_update_sections,
};
107 changes: 75 additions & 32 deletions crates/core/src/expression/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,15 @@
//! function_call → function_name '(' operand ( ',' operand )* ')'
//! ```
//!
//! A parenthesized condition, a `NOT` and a `size` call read as an operand
//! each nest one level, up to `max_depth`.
//! A parenthesized condition, a `NOT` and a function call read as an operand
//! each nest one level, up to `max_depth`. A function call that is the
//! condition itself nests none. Past `max_depth`, a call the semantic pass
//! refuses by name is refused with that message, not the depth error.

use super::ast::{CompareOp, Expr};
use super::kind::ExpressionKind;
use super::parser_common;
use super::semantics::check_condition_call_name;
use super::tokenizer::Token;
use crate::error::DynamoDbError;

Expand Down Expand Up @@ -136,19 +140,24 @@ fn parse_primary(
return Ok(expr);
}

// Try function call: ident followed by '('
if let Token::Ident(name) = &tokens[*pos] {
let fn_name_lower = name.to_ascii_lowercase();
if is_function_name(&fn_name_lower)
&& *pos + 1 < tokens.len()
&& tokens[*pos + 1] == Token::LParen
{
return parse_function_call(tokens, pos, depth, max_depth);
}
}

// Operand — then check for comparator, BETWEEN, or IN
let left = parse_operand(tokens, pos, depth, max_depth)?;
// Operand (a path, a placeholder, or a function call), then a comparator,
// BETWEEN, or IN. A function call with nothing after it is the condition
// itself. This pass checks grammar only: whether that function may stand
// alone, whether its name exists, and how many operands it takes are
// checked afterwards by `validate_condition_semantics`, over the whole
// parsed tree. Amazon DynamoDB reports every syntax error before any
// semantic error, so `foo(pk) AND` is reported as the syntax error at the
// end, not as the unknown function name that comes first in the text.
// Deferring the semantic checks here gives the same precedence.
//
// `parse_operand` counts a function call as one nesting level. A call
// that is the condition itself is not an operand and nests no level, so
// it is parsed here directly.
let left = if is_condition_call(tokens, *pos) {
parse_function_call(tokens, pos, depth, max_depth)?
} else {
parse_operand(tokens, pos, depth, max_depth)?
};

if *pos < tokens.len() {
if let Some(op) = try_comparator(&tokens[*pos]) {
Expand Down Expand Up @@ -191,6 +200,10 @@ fn parse_primary(
}
}

if matches!(left, Expr::Function { .. }) {
return Ok(left);
}

// Bare operand is not a valid condition on its own
Err(validation_err(
"Invalid ConditionExpression: expected comparison operator or function call",
Expand All @@ -216,13 +229,14 @@ fn parse_operand(
Ok(expr)
}
Token::Ident(name) => {
// size(path) is a function that returns a value, usable as an operand
if name.eq_ignore_ascii_case("size")
&& *pos + 1 < tokens.len()
&& tokens[*pos + 1] == Token::LParen
{
// A function call, `size(path)` or any other name, nests one
// level. Its name is checked by `validate_condition_semantics`,
// except past the limit, where that pass never runs and the name
// is checked here (see `depth_tests.rs`).
if *pos + 1 < tokens.len() && tokens[*pos + 1] == Token::LParen {
*depth += 1;
if *depth > max_depth {
check_condition_call_name(name, true, ExpressionKind::Condition)?;
return Err(validation_err(
"Invalid ConditionExpression: expression nesting depth exceeded",
));
Expand Down Expand Up @@ -251,7 +265,7 @@ fn parse_function_call(
max_depth: usize,
) -> Result<Expr, DynamoDbError> {
let name = match &tokens[*pos] {
Token::Ident(n) => n.to_ascii_lowercase(),
Token::Ident(n) => n.clone(),
_ => {
return Err(validation_err(
"Invalid ConditionExpression: expected function name",
Expand All @@ -262,13 +276,22 @@ fn parse_function_call(

parser_common::expect_token(tokens, pos, &Token::LParen, "(", "ConditionExpression")?;

let mut args = Vec::new();
if *pos < tokens.len() && tokens[*pos] != Token::RParen {
// The grammar requires at least one operand between the parentheses. A
// call with an empty operand list, `foo()` or `attribute_exists()`, is a
// grammar error on the service, reported at the `)` with the text below,
// before the function name or its operand count is looked at (measured
// 2026-10-14 and again 2026-10-23, where `attribute_exists()` and `foo()`
// both answered this text; `begins_with(pk)` with one operand is instead
// the semantic operand-count error from `validate_condition_semantics`).
if *pos < tokens.len() && tokens[*pos] == Token::RParen {
return Err(validation_err(
"Invalid ConditionExpression: Syntax error; token: \")\", near: \"()\"",
));
}
let mut args = vec![parse_operand(tokens, pos, depth, max_depth)?];
while *pos < tokens.len() && tokens[*pos] == Token::Comma {
*pos += 1;
args.push(parse_operand(tokens, pos, depth, max_depth)?);
while *pos < tokens.len() && tokens[*pos] == Token::Comma {
*pos += 1;
args.push(parse_operand(tokens, pos, depth, max_depth)?);
}
}

parser_common::expect_token(tokens, pos, &Token::RParen, ")", "ConditionExpression")?;
Expand All @@ -288,11 +311,31 @@ fn try_comparator(token: &Token) -> Option<CompareOp> {
}
}

fn is_function_name(name: &str) -> bool {
matches!(
name,
"attribute_exists" | "attribute_not_exists" | "attribute_type" | "begins_with" | "contains"
)
/// Whether the tokens at `pos` start a function call with no comparator,
/// `BETWEEN` or `IN` after its closing parenthesis, that is, a call that is
/// the condition itself and not an operand.
fn is_condition_call(tokens: &[Token], pos: usize) -> bool {
if !matches!(tokens.get(pos), Some(Token::Ident(_)))
|| tokens.get(pos + 1) != Some(&Token::LParen)
{
return false;
}
let mut open = 0_usize;
for (i, token) in tokens.iter().enumerate().skip(pos + 1) {
match token {
Token::LParen => open += 1,
Token::RParen => {
open -= 1;
if open == 0 {
return !tokens.get(i + 1).is_some_and(|next| {
try_comparator(next).is_some() || matches!(next, Token::Between | Token::In)
});
}
}
_ => {}
}
}
false
}

fn validation_err(msg: &str) -> DynamoDbError {
Expand Down
Loading
Loading