From 4a2d3828a1906345bf530231f1d65babba9c6040 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 31 Oct 2026 19:05:54 +0000 Subject: [PATCH 01/29] fix(query): reject a KeyConditionExpression with two conditions on one key A key condition that named the same key attribute twice was served. For `pk = :a AND pk = :b` the parser took the first equality as the partition key condition and the second as the sort key condition, so on a table with pk HASH and sk RANGE the request returned the items in partition `:a` whose sort key equalled `:b`. The same hole accepted two conditions on the sort key, including BETWEEN or begins_with paired with another sort key condition. DynamoDB rejects all of these with "Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key" (measured 2026-10-24, us-east-1). It resolves every `#name` and `:value` reference before it looks for the duplicate, so an undefined name or value is reported first, and it reports the duplicate ahead of the key value type check and the unused-value check (measured 2026-10-31). parse_key_condition_with_maps takes the request's expression attribute names and values. After the parser's own checks, and before any clause is classified, it refuses two conditions on one key attribute, written with plain names or through `#name` references. When there is a duplicate it reports an undefined `#name` and then an undefined `:value` first. A key condition without a duplicate takes the same path as before. The engine's Query handler parses through it, and the server's LeadingKeys extraction runs the same check through key_condition_clause_operands, so a duplicate leaves dynamodb:LeadingKeys absent whichever way it is written. Fixes #430 --- crates/core/src/expression/key_condition.rs | 442 +++++++++++++++++- crates/core/src/expression/mod.rs | 2 +- crates/engine/src/expression_helpers.rs | 121 ++++- crates/engine/src/query.rs | 7 +- crates/server/src/leading_keys.rs | 29 +- crates/server/src/leading_keys/tests.rs | 52 ++- tests/test_fgac_leading_keys.py | 52 ++- tests/test_query_key_condition_one_per_key.py | 318 +++++++++++++ 8 files changed, 962 insertions(+), 61 deletions(-) create mode 100644 tests/test_query_key_condition_one_per_key.py diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index edaa1f8e5..211aa3729 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -389,7 +389,9 @@ impl KeyCondition { /// 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. + /// HASH attribute. Both parse with [`parse_key_condition_with_maps`], + /// which refuses a second condition on one key attribute before this runs, + /// so a duplicate is reported ahead of `value_check`. /// /// # Errors /// @@ -462,6 +464,75 @@ impl KeyCondition { } } +/// The service's message when a `KeyConditionExpression` carries more than one +/// condition on the same key attribute. Measured 2026-10-24 (us-east-1). +const ONE_CONDITION_PER_KEY_ERR: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key"; + +/// Refuse a key condition with more than one condition on one key attribute. +/// +/// Two clauses name the same attribute when their paths resolve to the same +/// name through `names`, whether each is written as a plain name or as a +/// `#name` reference. Two clauses on one `#name` reference name the same +/// attribute whether or not `names` defines it. DynamoDB allows one condition +/// per key attribute, on the partition key and on the sort key alike, whatever +/// the operators are (measured 2026-10-24). +/// +/// The service resolves every `#name` and `:value` reference before it looks +/// for a duplicate (measured 2026-10-31), so when a duplicate is found an +/// undefined `#name` in any clause is reported first, then an undefined +/// `:value`, each with the service's text. A key condition without a duplicate +/// passes, and the checks that follow report its undefined references. +fn reject_duplicate_key_attrs( + clauses: &[RawClause], + names: &std::collections::HashMap, + values: &std::collections::HashMap, +) -> Result<(), DynamoDbError> { + let mut seen: Vec<&str> = Vec::with_capacity(clauses.len()); + let mut duplicated = false; + for clause in clauses { + let Some(PathElement::Attribute(name)) = raw_clause_path(clause).first() else { + continue; + }; + // An undefined reference keeps its `#`, which no plain name carries. + let attr = match name.strip_prefix('#') { + Some(reference) => names.get(reference).map_or(name.as_str(), String::as_str), + None => name.as_str(), + }; + if seen.contains(&attr) { + duplicated = true; + break; + } + seen.push(attr); + } + if !duplicated { + return Ok(()); + } + for clause in clauses { + if let Some(PathElement::Attribute(name)) = raw_clause_path(clause).first() + && let Some(reference) = name.strip_prefix('#') + && !names.contains_key(reference) + { + return Err(validation_err(&format!( + "Invalid KeyConditionExpression: An expression attribute name used in the \ + document path is not defined; attribute name: #{reference}" + ))); + } + } + for clause in clauses { + for value in raw_clause_values(clause) { + if let Expr::Placeholder(placeholder) = value + && !values.contains_key(placeholder) + { + return Err(validation_err(&format!( + "Invalid KeyConditionExpression: An expression attribute value used in \ + expression is not defined; attribute value: :{placeholder}" + ))); + } + } + } + Err(validation_err(ONE_CONDITION_PER_KEY_ERR)) +} + /// Resolve a path's top-level attribute name, handling `#name` references. fn resolve_path_attr( path: &[PathElement], @@ -526,12 +597,49 @@ impl SortKeyCondition { /// Supports multi-part keys: up to 8 AND-ed clauses (4 HASH + 4 RANGE). /// Rejects OR, NOT, and unsupported functions. /// +/// This does not look for a second condition on one key attribute, which +/// needs the request's `ExpressionAttributeNames` and +/// `ExpressionAttributeValues`. A request's key condition is parsed with +/// [`parse_key_condition_with_maps`]. +/// /// # Errors /// /// Returns `ValidationException` for syntax errors or unsupported constructs. pub fn parse_key_condition(tokens: &[Token]) -> Result { - let mut clauses = parse_clauses(tokens)?; + classify_clauses(parse_clauses(tokens)?) +} + +/// [`parse_key_condition`] with the request's `ExpressionAttributeNames` +/// (`names`, keyed without the leading `#`) and `ExpressionAttributeValues` +/// (`values`, keyed without the leading `:`; only which placeholders are +/// defined is read). +/// +/// After the parser's own checks, and before any clause is read as the +/// partition or the sort key condition, this refuses a key condition with more +/// than one condition on one key attribute, written with plain names or +/// through `#name` references. When there is such a duplicate, an undefined +/// `#name` and then an undefined `:value` are reported ahead of it, as the +/// service reports them. The engine reads a `Query` key condition through +/// this, and authorization runs the same check through +/// [`key_condition_clause_operands`]. +/// +/// # Errors +/// +/// As [`parse_key_condition`], plus `ValidationException` for a second +/// condition on one key attribute. +pub fn parse_key_condition_with_maps( + tokens: &[Token], + names: &std::collections::HashMap, + values: &std::collections::HashMap, +) -> Result { + let clauses = parse_clauses(tokens)?; + reject_duplicate_key_attrs(&clauses, names, values)?; + classify_clauses(clauses) +} +/// Read the parsed clauses as a partition key condition and sort key +/// conditions. +fn classify_clauses(mut clauses: Vec) -> Result { match clauses.len() { 1 => classify_single(clauses.remove(0)), 2 => classify_pair(clauses.remove(0), clauses.remove(0)), @@ -548,14 +656,24 @@ pub fn parse_key_condition(tokens: &[Token]) -> Result( tokens: &[Token], + names: &std::collections::HashMap, + values: &std::collections::HashMap, ) -> Result, DynamoDbError> { - Ok(parse_clauses(tokens)? + let clauses = parse_clauses(tokens)?; + reject_duplicate_key_attrs(&clauses, names, values)?; + Ok(clauses .into_iter() .filter_map(|clause| match clause { RawClause::Eq(path, value) => Some(KeyClauseOperand { @@ -645,6 +763,15 @@ fn raw_clause_path(clause: &RawClause) -> &[PathElement] { } } +/// The value operands of a raw clause, in the order they are written. +fn raw_clause_values(clause: &RawClause) -> Vec<&Expr> { + match clause { + RawClause::Eq(_, value) | RawClause::Compare(_, _, value) => vec![value], + RawClause::Between(_, low, high) => vec![low, high], + RawClause::BeginsWith(_, prefix) => vec![prefix], + } +} + /// Reject any key path that is not a single top-level attribute. /// /// `parse_path` always emits an `Attribute` (or `#name`) as element 0, so a path @@ -998,6 +1125,7 @@ fn validation_err(msg: &str) -> DynamoDbError { mod tests { use super::*; use crate::expression::tokenize; + use crate::types::AttributeValue; use std::collections::HashMap; #[test] @@ -1355,17 +1483,14 @@ mod tests { "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 = + key_condition_clause_operands(&tokens, &HashMap::new(), &values_of(expr)).unwrap(); let got: Vec<(String, String, bool)> = got .into_iter() .map(|clause| { @@ -1404,7 +1529,7 @@ mod tests { continue; }; assert!( - key_condition_clause_operands(&tokens).is_err(), + key_condition_clause_operands(&tokens, &HashMap::new(), &no_values()).is_err(), "expr {expr} should be rejected" ); } @@ -1902,4 +2027,297 @@ mod tests { kc.resolve_key_schema(&schema, &HashMap::new()).unwrap(); assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); } + + const UNDEFINED_NAME_U: &str = "Invalid KeyConditionExpression: An expression attribute \ + name used in the document path is not defined; attribute \ + name: #u"; + const TYPE_ERR: &str = "One or more parameter values were invalid: Condition parameter \ + type does not match schema type"; + + /// No `ExpressionAttributeValues`. + fn no_values() -> HashMap { + HashMap::new() + } + + /// `ExpressionAttributeValues` that define every placeholder of `expr`, + /// keyed without the leading `:`. + fn values_of(expr: &str) -> HashMap { + tokenize(expr) + .unwrap() + .into_iter() + .filter_map(|token| match token { + Token::Placeholder(name) => Some((name, AttributeValue::S("v".to_owned()))), + _ => None, + }) + .collect() + } + + /// `ExpressionAttributeNames` from `(reference, attribute)` pairs, keyed + /// without the leading `#`. + fn names_of(pairs: &[(&str, &str)]) -> HashMap { + pairs + .iter() + .map(|(reference, attr)| ((*reference).to_owned(), (*attr).to_owned())) + .collect() + } + + /// Parse `expr` as the engine parses a request's key condition, with every + /// placeholder defined. + fn parse_request( + expr: &str, + names: &HashMap, + ) -> Result { + let tokens = tokenize(expr).unwrap(); + parse_key_condition_with_maps(&tokens, names, &values_of(expr)) + } + + fn assert_refused( + result: Result, + want: &str, + expr: &str, + ) { + match result { + Err(DynamoDbError::ValidationException(msg)) => assert_eq!(msg, want, "expr {expr}"), + other => panic!("expr {expr}: got {other:?}"), + } + } + + /// A second condition on a key attribute, written with plain names or + /// through a `#name` reference, is refused before the clauses are handed + /// to authorization, so the LeadingKeys path reads no partition operand + /// from such a request. + #[test] + fn clause_operands_reject_duplicate_key_attribute() { + let names = names_of(&[("p", "pk"), ("s", "sk")]); + for expr in [ + "pk = :a AND pk = :b", + "#p = :a AND pk = :b", + "pk = :u AND pk > :v", + "#p = :u AND pk > :v", + "pk > :v AND sk = :s AND sk = :t", + "pk > :v AND #s = :s AND sk = :t", + ] { + let tokens = tokenize(expr).unwrap(); + assert_refused( + key_condition_clause_operands(&tokens, &names, &values_of(expr)), + ONE_CONDITION_PER_KEY_ERR, + expr, + ); + } + } + + #[test] + fn duplicate_condition_on_one_key_attribute_rejected() { + // Measured 2026-10-24 (us-east-1): every one of these shapes answers + // the one-condition-per-key message, whatever the operators are and + // whichever key attribute is named twice. + for expr in [ + "pk = :a AND pk = :b", + "pk = :a AND pk = :a", + "pk = :a AND pk = :b AND sk = :c", + "pk = :a AND pk > :b", + "pk > :b AND pk = :a", + ":a = pk AND pk = :b", + "(pk = :a) AND (pk = :b)", + "pk = :a AND sk = :b AND sk = :c", + "pk = :a AND sk = :b AND sk = :b", + "pk = :a AND sk BETWEEN :b AND :c AND sk = :b", + "pk = :a AND sk BETWEEN :b AND :c AND begins_with(sk, :b)", + "pk = :a AND begins_with(sk, :b) AND sk = :c", + "pk = :a AND sk > :b AND sk < :c", + "pk = :a AND begins_with(sk, :b) AND begins_with(sk, :c)", + "pk = :a AND pk = :b AND sk = :b AND sk = :c", + "sk = :b AND sk = :c", + ] { + assert_refused( + parse_request(expr, &HashMap::new()), + ONE_CONDITION_PER_KEY_ERR, + expr, + ); + } + } + + #[test] + fn duplicate_condition_through_name_reference_rejected() { + // `#p` and `pk` name the same attribute once `#p` is resolved, on a + // single-attribute key schema and a multi-attribute one alike. + let names = names_of(&[("p", "pk"), ("hh", "h")]); + for expr in ["#p = :a AND pk = :b", "#hh = :x AND h = :y AND a = :z"] { + assert_refused(parse_request(expr, &names), ONE_CONDITION_PER_KEY_ERR, expr); + } + } + + #[test] + fn duplicate_condition_through_two_name_references_rejected() { + let names = names_of(&[("p", "pk"), ("q", "pk")]); + let expr = "#p = :a AND #q = :b"; + assert_refused(parse_request(expr, &names), ONE_CONDITION_PER_KEY_ERR, expr); + } + + #[test] + fn duplicate_condition_on_sort_key_through_name_reference_rejected() { + let names = names_of(&[("s", "sk")]); + let expr = "pk = :a AND #s = :b AND sk = :c"; + assert_refused(parse_request(expr, &names), ONE_CONDITION_PER_KEY_ERR, expr); + } + + /// With a duplicate present, an undefined `#name` anywhere in the + /// expression is reported first. Measured 2026-10-24 for + /// `#u = :a AND #u = :b` and 2026-10-31 for the next three; the + /// multi-attribute form is not measured. + #[test] + fn undefined_name_reported_ahead_of_duplicate() { + for expr in [ + "#u = :a AND #u = :b", + "#u = :a AND #u > :b", + "#u = :a AND sk = :b AND sk = :c", + "pk = :a AND pk = :b AND #u = :c", + "h = :a AND h = :b AND #u = :c", + ] { + assert_refused(parse_request(expr, &HashMap::new()), UNDEFINED_NAME_U, expr); + } + // Without a duplicate the parse passes, and `resolve_pk_sk` reports + // the name. + let mut kc = parse_request("#u = :a AND sk = :b", &HashMap::new()).unwrap(); + assert_refused( + kc.resolve_pk_sk("pk", &HashMap::new()), + UNDEFINED_NAME_U, + "#u = :a AND sk = :b", + ); + } + + /// With a duplicate present, an undefined `:value` is reported ahead of it + /// (measured 2026-10-31: `pk = :a AND pk = :b` without + /// `ExpressionAttributeValues` answers the undefined-value message for + /// `:a`). Which of an undefined name and an undefined value the service + /// reports first is not measured; the name is checked first here. + #[test] + fn undefined_value_reported_ahead_of_duplicate() { + let undefined = |value: &str| { + format!( + "Invalid KeyConditionExpression: An expression attribute value used in \ + expression is not defined; attribute value: :{value}" + ) + }; + let tokens = tokenize("pk = :a AND pk = :b").unwrap(); + assert_refused( + parse_key_condition_with_maps(&tokens, &HashMap::new(), &no_values()), + &undefined("a"), + "pk = :a AND pk = :b", + ); + let tokens = tokenize("pk = :a AND pk = :missing").unwrap(); + assert_refused( + parse_key_condition_with_maps(&tokens, &HashMap::new(), &values_of("pk = :a")), + &undefined("missing"), + "pk = :a AND pk = :missing", + ); + let tokens = tokenize("pk = :a AND pk = :b AND #u = :c").unwrap(); + assert_refused( + parse_key_condition_with_maps(&tokens, &HashMap::new(), &no_values()), + UNDEFINED_NAME_U, + "pk = :a AND pk = :b AND #u = :c", + ); + // Without a duplicate the parse does not read the values. + let tokens = tokenize("pk = :a AND sk = :b").unwrap(); + assert!(parse_key_condition_with_maps(&tokens, &HashMap::new(), &no_values()).is_ok()); + } + + /// The duplicate is reported by the parse, so it comes ahead of the key + /// value type check that `resolve_key_schema_with` runs and of the engine's + /// unused-value check, whichever way it is spelled (measured 2026-10-31: + /// `pk = :a AND pk = :n`, `#p = :a AND pk = :n` and + /// `pk = :a AND #s = :b AND sk = :n` with `:n` a number on an S key, and + /// `pk = :a AND pk = :b` with an unused `:z`, answer the + /// one-condition-per-key message; `pk = :n` alone answers the type). + #[test] + fn duplicate_reported_ahead_of_type_and_unused_value_checks() { + let schema = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; + let names = names_of(&[("p", "pk"), ("s", "sk")]); + let values: HashMap = [ + ("a", AttributeValue::S("alice".to_owned())), + ("b", AttributeValue::S("bob".to_owned())), + ("n", AttributeValue::N("1".to_owned())), + ("z", AttributeValue::S("zed".to_owned())), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect(); + for expr in [ + "pk = :a AND pk = :n", + "#p = :a AND pk = :n", + "pk = :a AND #s = :b AND sk = :n", + "pk = :a AND pk = :b", + ] { + let tokens = tokenize(expr).unwrap(); + assert_refused( + parse_key_condition_with_maps(&tokens, &names, &values), + ONE_CONDITION_PER_KEY_ERR, + expr, + ); + } + let tokens = tokenize("pk = :n").unwrap(); + let mut kc = parse_key_condition_with_maps(&tokens, &names, &values).unwrap(); + assert_refused( + kc.resolve_key_schema_with(&schema, &names, |_, value| match value { + Expr::Placeholder(name) if name == "n" => Err(validation_err(TYPE_ERR)), + _ => Ok(()), + }), + TYPE_ERR, + "pk = :n", + ); + } + + #[test] + fn nested_path_reported_ahead_of_duplicate() { + // Measured 2026-10-24: both of these answer their own message, not the + // one-condition-per-key message. + assert_refused( + parse_request("pk = :a AND pk.foo = :b", &HashMap::new()), + NESTED_KEY_ERR, + "pk = :a AND pk.foo = :b", + ); + assert_refused( + parse_request("((pk = :a)) AND (pk = :b)", &HashMap::new()), + "Invalid KeyConditionExpression: The expression has redundant parentheses;", + "((pk = :a)) AND (pk = :b)", + ); + } + + #[test] + fn distinct_key_attributes_accepted_after_duplicate_check() { + // One condition per key attribute passes the check and resolves under + // the key schema the engine reads it with: the check is per attribute + // name, not per clause count. + let names = names_of(&[("p", "pk"), ("s", "sk")]); + let pk_sk = [key("pk", KeyType::Hash), key("sk", KeyType::Range)]; + let two_hash = [ + key("pk1", KeyType::Hash), + key("pk2", KeyType::Hash), + key("sk", KeyType::Range), + ]; + let two_by_two = [ + key("pk1", KeyType::Hash), + key("pk2", KeyType::Hash), + key("sk1", KeyType::Range), + key("sk2", KeyType::Range), + ]; + for (schema, expr) in [ + (&pk_sk[..], "pk = :a"), + (&pk_sk[..], "pk = :a AND sk = :b"), + (&pk_sk[..], "sk = :b AND pk = :a"), + (&pk_sk[..], "pk = :a AND sk BETWEEN :b AND :c"), + (&pk_sk[..], "pk = :a AND begins_with(sk, :b)"), + (&pk_sk[..], "#p = :a AND #s = :b"), + (&two_hash[..], "pk1 = :a AND pk2 = :b AND sk = :c"), + ( + &two_by_two[..], + "pk1 = :a AND pk2 = :b AND sk1 = :c AND sk2 = :d", + ), + ] { + let mut kc = parse_request(expr, &names) + .unwrap_or_else(|err| panic!("expr {expr} should parse: {err:?}")); + kc.resolve_key_schema(schema, &names) + .unwrap_or_else(|err| panic!("expr {expr} should resolve: {err:?}")); + } + } } diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index c9f8e207b..28061f18c 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -26,7 +26,7 @@ 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_with_maps, }; pub use kind::ExpressionKind; pub use parser::{parse_condition, parse_condition_with_depth_limit}; diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 913333015..9a5dc0f65 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_with_depth_limit, parse_key_condition_with_maps, parse_projection, + parse_update_from, tokenize_for, tokenize_with_limit, validate_no_reserved_words, + validate_ordering_operand_types, }; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{AttributeValue, ConditionalOperator, ExpectedAttributeValue}; @@ -237,14 +238,19 @@ pub fn parse_projection_expr( /// Size-check, tokenize, reserved-word check, and parse a `KeyConditionExpression`. /// +/// `maps` holds the request's `ExpressionAttributeNames` and +/// `ExpressionAttributeValues`, which the parse reads to refuse a second +/// condition on one key attribute. +/// /// Errors carry the `KeyConditionExpression` prefix, matching Amazon `DynamoDB`. /// /// # Errors /// /// Returns `DynamoDbError::ValidationException` for over-size, syntax, or -/// reserved-word errors. +/// reserved-word errors, and for a second condition on one key attribute. pub fn parse_key_condition_expr( expr: &str, + maps: &ExpressionMaps, limits: &LimitsConfig, ) -> Result { check_expression_size(expr, ExpressionKind::KeyCondition, limits)?; @@ -257,7 +263,7 @@ pub fn parse_key_condition_expr( if limits.enforce_reserved_keywords { validate_no_reserved_words(&tokens)?; } - parse_key_condition(&tokens) + parse_key_condition_with_maps(&tokens, &maps.names, &maps.values) }) .map_err(|e| prefix_expression_error(e, ExpressionKind::KeyCondition)) } @@ -407,4 +413,111 @@ mod tests { "got {err:?}" ); } + + /// A key condition request and the message it answers: the expression, + /// its `#`-prefixed names, its `:`-prefixed values (`None` for no + /// `ExpressionAttributeValues`) and the expected message. + type KceCase = ( + &'static str, + Vec<(&'static str, &'static str)>, + Option>, + &'static str, + ); + + /// Parse `expr` as `Query` does, with `#`-prefixed `names` and + /// `:`-prefixed `values` as a request carries them. + fn parse_kce( + expr: &str, + names: &[(&str, &str)], + values: Option<&[(&str, AttributeValue)]>, + ) -> Result { + let names: HashMap = names + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(); + let values: Option> = values.map(|vs| { + vs.iter() + .map(|(k, v)| ((*k).to_owned(), v.clone())) + .collect() + }); + let maps = build_expression_maps(Some(&names), values.as_ref()); + parse_key_condition_expr(expr, &maps, &LimitsConfig::default()) + } + + /// The order of the one-condition-per-key check through the engine's + /// entry point, on the requests measured 2026-10-31 (table `pk` S HASH, + /// `sk` S RANGE). The key value type check and the unused-value check + /// run after this parse. + #[test] + fn key_condition_duplicate_check_order_matches_the_service() { + const ONE_PER_KEY: &str = "Invalid KeyConditionExpression: KeyConditionExpressions \ + must only contain one condition per key"; + const UNDEFINED_U: &str = "Invalid KeyConditionExpression: An expression attribute \ + name used in the document path is not defined; attribute \ + name: #u"; + const UNDEFINED_A: &str = "Invalid KeyConditionExpression: An expression attribute \ + value used in expression is not defined; attribute value: :a"; + let s = |v: &str| AttributeValue::S(v.to_owned()); + let n = AttributeValue::N("1".to_owned()); + let abc = [(":a", s("alice")), (":b", s("bob")), (":c", s("carol"))]; + let cases: Vec = vec![ + ( + "pk = :a AND pk = :b", + vec![], + Some(abc[..2].to_vec()), + ONE_PER_KEY, + ), + ( + "#p = :a AND pk = :n", + vec![("#p", "pk")], + Some(vec![(":a", s("alice")), (":n", n.clone())]), + ONE_PER_KEY, + ), + ( + "pk = :a AND #s = :b AND sk = :n", + vec![("#s", "sk")], + Some(vec![ + (":a", s("alice")), + (":b", s("bob")), + (":n", n.clone()), + ]), + ONE_PER_KEY, + ), + ( + "#u = :a AND sk = :b AND sk = :c", + vec![], + Some(abc.to_vec()), + UNDEFINED_U, + ), + ( + "pk = :a AND pk = :b AND #u = :c", + vec![], + Some(abc.to_vec()), + UNDEFINED_U, + ), + ("pk = :a AND pk = :b", vec![], None, UNDEFINED_A), + ( + "pk = :a AND pk = :b", + vec![], + Some(vec![(":a", s("alice")), (":b", s("bob")), (":z", s("zed"))]), + ONE_PER_KEY, + ), + ( + "#u = :a AND #u > :b", + vec![], + Some(abc[..2].to_vec()), + UNDEFINED_U, + ), + ]; + for (expr, names, values, want) in cases { + let got = parse_kce(expr, &names, values.as_deref()); + assert!( + matches!(&got, Err(DynamoDbError::ValidationException(msg)) if msg == want), + "expr {expr}: got {got:?}" + ); + } + // Without a duplicate the parse leaves the value to the later checks. + let got = parse_kce("pk = :n", &[], Some(&[(":n", n)])); + assert!(got.is_ok(), "pk = :n: got {got:?}"); + } } diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 848f5fdbb..1ed90459b 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -237,7 +237,12 @@ 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)?; + // The parse refuses a second condition on one key attribute, after + // the expression's `#name` and `:value` references are checked and + // before the clauses are classified, which is where the service + // reports it (measured 2026-10-31). + 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/crates/server/src/leading_keys.rs b/crates/server/src/leading_keys.rs index 0f2577985..46cc90af3 100644 --- a/crates/server/src/leading_keys.rs +++ b/crates/server/src/leading_keys.rs @@ -63,7 +63,7 @@ use std::collections::HashMap; use extenddb_core::expression::{ - Expr, PathElement, Token, key_condition_clause_operands, parse_key_condition, + Expr, PathElement, Token, key_condition_clause_operands, parse_key_condition_with_maps, tokenize_with_limit, }; use extenddb_core::types::{KeySchemaElement, KeyType, TableKeyInfo}; @@ -268,8 +268,11 @@ fn query_leading_keys(input: &Value, key_info: &TableKeyInfo, max_tokens: usize) if let Some(kce) = input.get("KeyConditionExpression").and_then(Value::as_str) { let tokens = tokenize_with_limit(kce, max_tokens).ok()?; - // The clauses that name the partition attribute, as written. - let pk_clauses: Vec<_> = key_condition_clause_operands(&tokens) + // The clauses that name the partition attribute. A key condition with + // a second condition on one key attribute, written with plain names + // or through a `#name` reference, is refused here with the check the + // engine runs, so it leaves the key absent whatever its operators. + let pk_clauses: Vec<_> = key_condition_clause_operands(&tokens, &names, &values) .ok()? .into_iter() .filter(|clause| resolve_attr_name(&clause.path, &names).as_deref() == Some(pk_attr)) @@ -278,21 +281,17 @@ fn query_leading_keys(input: &Value, key_info: &TableKeyInfo, max_tokens: usize) // engine reads it. When the engine's classification refuses the // condition (a missing HASH attribute on a multi-attribute key schema, // for one) or the value cannot be read here (an `N` that is not a - // number, a placeholder with no value), the key stays absent and no - // other clause's operand is bound in its place: the equality, not the - // other clause, names the partition. + // number, a placeholder with no value), the key stays absent. if pk_clauses.iter().any(|clause| clause.equality) { return equality_pk_value(&tokens, key_schema, pk_attr, &names, &values); } - // Exactly one clause names the partition key, under an operator the - // engine rejects, such as `pk > :v`. The service binds LeadingKeys to - // that operand and evaluates the policy before it rejects the shape, - // so a principal fenced away from the value gets AccessDeniedException + // The one clause on the partition key uses an operator the engine + // rejects, such as `pk > :v`. The service binds LeadingKeys to that + // operand and evaluates the policy before it rejects the shape, so a + // principal fenced away from the value gets AccessDeniedException // while one fenced to it gets the shape's ValidationException - // (measured 2026-10-21 for `pk > :v`). A condition that does not - // parse, one that names no partition clause, and one with two - // non-equality partition clauses (which value the service binds for - // that shape is not measured) leave the key absent. + // (measured 2026-10-21 for `pk > :v`). A condition that does not parse + // and one that names no partition clause leave the key absent. let [clause] = pk_clauses.as_slice() else { return None; }; @@ -348,7 +347,7 @@ fn equality_pk_value( names: &HashMap, values: &HashMap, ) -> Option { - let mut kc = parse_key_condition(tokens).ok()?; + let mut kc = parse_key_condition_with_maps(tokens, names, values).ok()?; // Assign every clause to its key attribute with the engine's own // classification: by name on a multi-attribute key schema, where the // first HASH attribute is the one LeadingKeys names, and by diff --git a/crates/server/src/leading_keys/tests.rs b/crates/server/src/leading_keys/tests.rs index c81e3baaa..9936f1e6d 100644 --- a/crates/server/src/leading_keys/tests.rs +++ b/crates/server/src/leading_keys/tests.rs @@ -622,11 +622,10 @@ fn query_between_on_the_partition_key_is_absent() { assert_eq!(r, None); } -/// An equality on the partition key decides the key, even when its value -/// cannot be read and another clause names the partition key: the other -/// clause's operand is never bound in its place. With `:u = {"N": "bob"}` -/// (not a number) the key stays absent, as on main, rather than becoming -/// `alice`. +/// An equality on the partition key and a second clause on the partition key +/// name the partition key twice, so the duplicate check refuses the condition +/// and the key stays absent: the other clause's operand (`alice`) is never +/// bound, whether the equality's value can be read or not. #[test] fn query_unreadable_partition_equality_binds_no_other_clause() { for (kce, u) in [ @@ -634,6 +633,7 @@ fn query_unreadable_partition_equality_binds_no_other_clause() { ("pk > :v AND pk = :u", json!({"N": "bob"})), ("#p = :u AND pk > :v", json!({"N": "bob"})), ("pk = :u AND begins_with(pk, :v)", json!({"N": "1e"})), + ("pk = :u AND pk > :v", json!({"S": "bob"})), ] { let input = json!({ "TableName": "t", @@ -644,18 +644,40 @@ fn query_unreadable_partition_equality_binds_no_other_clause() { let r = single_table_leading_keys(&input, "Query", Some(&main_table()), MAX_TOKENS); assert_eq!(r, None, "{kce}"); } - // A readable equality keeps its own value with another partition clause. - let input = json!({ - "TableName": "t", - "KeyConditionExpression": "pk = :u AND pk > :v", - "ExpressionAttributeValues": {":u": {"S": "bob"}, ":v": {"S": "alice"}}, - }); - let r = single_table_leading_keys(&input, "Query", Some(&main_table()), MAX_TOKENS); - assert_ne!(r, Some(vec!["alice".to_owned()])); } -/// Two non-equality clauses on the partition key: which operand the service -/// binds is not measured, so neither is bound, in either clause order. +/// A second condition on one key attribute, written with plain names or +/// through a `#name` reference, leaves the key absent, including when the +/// only partition clause is a non-equality whose operand would otherwise be +/// bound. The engine refuses all of these. +#[test] +fn query_duplicate_key_condition_leaves_the_key_absent() { + for kce in [ + "pk = :a AND pk = :b", + "#p = :a AND pk = :b", + "pk = :a AND sk = :b AND sk = :c", + "pk = :a AND #s = :b AND sk = :c", + "pk > :a AND sk = :b AND sk = :c", + "pk > :a AND #s = :b AND sk = :c", + ] { + let input = json!({ + "TableName": "t", + "KeyConditionExpression": kce, + "ExpressionAttributeNames": {"#p": "pk", "#s": "sk"}, + "ExpressionAttributeValues": { + ":a": {"S": "alice"}, + ":b": {"S": "bob"}, + ":c": {"S": "carol"}, + }, + }); + let r = single_table_leading_keys(&input, "Query", Some(&main_table()), MAX_TOKENS); + assert_eq!(r, None, "{kce}"); + } +} + +/// Two non-equality clauses on the partition key name it twice, so the +/// duplicate check refuses the condition and neither operand is bound, in +/// either clause order. #[test] fn query_two_non_equality_partition_clauses_bind_nothing() { for kce in [ diff --git a/tests/test_fgac_leading_keys.py b/tests/test_fgac_leading_keys.py index 905fcd1f1..ee3882909 100644 --- a/tests/test_fgac_leading_keys.py +++ b/tests/test_fgac_leading_keys.py @@ -96,6 +96,12 @@ def _denied(exc: ClientError) -> bool: return exc.value.response["Error"]["Code"] == "AccessDeniedException" +ONE_PER_KEY = ( + "Invalid KeyConditionExpression: " + "KeyConditionExpressions must only contain one condition per key" +) + + # The values a Query on the multi-attribute key table may name; each query # carries only the ones its key condition uses. _MK_VALUES = {":v": {"S": OWN}, ":g": {"S": "blue"}, ":x": {"S": "x1"}, @@ -371,12 +377,31 @@ def test_scan_denied_under_for_any_value(self, table): c.scan(TableName=table) assert _denied(e) - # -- An equality on the partition key decides the key ------------------ + # -- A second clause on the partition key binds nothing ---------------- def test_unreadable_partition_equality_does_not_bind_another_clause(self, table): - # An equality on the partition key decides the key. When its value - # cannot be read (`:u = {"N": "bob"}`), a second clause naming the - # fenced value must not be bound in its place. + # An equality on the partition key and a second clause on it name the + # partition key twice, so the duplicate check leaves + # dynamodb:LeadingKeys absent and the fenced value in the second + # clause (`:v`) is never bound. A principal allowed everything gets + # the one-condition-per-key error. A policy that needs a LeadingKeys + # value denies the request, whether the equality's value can be read + # (`:u = {"S": "bob"}`) or not (`:u = {"N": "bob"}`, refused either + # way). + kces = ("pk = :u AND pk > :v", "pk > :v AND pk = :u") + readable = {":u": {"S": OTHER}, ":v": {"S": OWN}} + unreadable = {":u": {"N": OTHER}, ":v": {"S": OWN}} + owner = self._user_client([("all", { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}], + })]) + for kce in kces: + with pytest.raises(ClientError) as e: + owner.query(TableName=table, KeyConditionExpression=kce, + ExpressionAttributeValues=readable) + err = e.value.response["Error"] + assert err["Code"] == "ValidationException", kce + assert err["Message"] == ONE_PER_KEY, kce for form in ("ForAnyValue", "ForAllValues+Null"): if form == "ForAnyValue": policy = self._leading_keys_policy("ForAnyValue", [OWN], table) @@ -385,15 +410,16 @@ def test_unreadable_partition_equality_does_not_bind_another_clause(self, table) stmt = policy["Statement"][0] stmt["Condition"]["Null"] = {"dynamodb:LeadingKeys": "false"} c = self._user_client([("lk", policy)]) - for kce in ("pk = :u AND pk > :v", "pk > :v AND pk = :u"): - try: - got = c.query( - TableName=table, KeyConditionExpression=kce, - ExpressionAttributeValues={":u": {"N": OTHER}, ":v": {"S": OWN}}) - except ClientError: - continue - parts = {it["pk"]["S"] for it in got["Items"]} - assert OTHER not in parts, (form, kce, parts) + for kce in kces: + with pytest.raises(ClientError) as e: + c.query(TableName=table, KeyConditionExpression=kce, + ExpressionAttributeValues=readable) + assert _denied(e), (form, kce) + with pytest.raises(ClientError) as e: + c.query(TableName=table, KeyConditionExpression=kce, + ExpressionAttributeValues=unreadable) + assert e.value.response["Error"]["Code"] in ( + "AccessDeniedException", "ValidationException"), (form, kce) def test_non_equality_partition_with_sort_clause_is_refused(self, table): # The fix binds the partition operand of these shapes; the engine still diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py new file mode 100644 index 000000000..3aa118c86 --- /dev/null +++ b/tests/test_query_key_condition_one_per_key.py @@ -0,0 +1,318 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""A KeyConditionExpression carries one condition per key attribute. + +Amazon DynamoDB rejects a key condition that names the same key attribute twice, +on the partition key and on the sort key alike, whatever the operators are: + + ValidationException: Invalid KeyConditionExpression: KeyConditionExpressions + must only contain one condition per key + +Measured 2026-10-24T00:27:56Z and 00:30:39Z in us-east-1 on a table with +pk (S) HASH and sk (S) RANGE. Issue #430. + +The order against undefined references, the key value type check and an +unused value was measured 2026-10-31T17:37Z in us-east-1 on a table with the +same key schema, two samples each: an undefined #name anywhere in the +expression and an undefined :value are reported ahead of the duplicate, and the +duplicate is reported ahead of the type check and the unused-value check. + +Dual-target against Amazon DynamoDB and extenddb. +""" + +from __future__ import annotations + +import pytest +from botocore.exceptions import ClientError + +from conftest import scoped_table + +ONE_PER_KEY = ( + "Invalid KeyConditionExpression: " + "KeyConditionExpressions must only contain one condition per key" +) +NESTED = ( + "Invalid KeyConditionExpression: " + "KeyConditionExpressions cannot have conditions on nested attributes" +) +REDUNDANT_PARENS = ( + "Invalid KeyConditionExpression: The expression has redundant parentheses;" +) +UNDEFINED_NAME = ( + "An expression attribute name used in the document path is not defined; " + "attribute name: #u" +) +UNDEFINED_NAME_EXACT = "Invalid KeyConditionExpression: " + UNDEFINED_NAME +UNDEFINED_VALUE_A = ( + "Invalid KeyConditionExpression: An expression attribute value used in " + "expression is not defined; attribute value: :a" +) + +A = {"S": "alice"} +B = {"S": "bob"} +C = {"S": "carol"} +N1 = {"N": "1"} + + +@pytest.fixture(scope="class") +def range_table(dynamodb_client): + """pk (S) HASH, sk (S) RANGE, holding alice/bob and alice/carol.""" + 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: + for sk in ("bob", "carol"): + dynamodb_client.put_item( + TableName=name, Item={"pk": {"S": "alice"}, "sk": {"S": sk}} + ) + yield name + + +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"] + + +class TestOneConditionPerKey: + """Every measured duplicate shape, and the shapes that keep their own error.""" + + @pytest.mark.parametrize( + ("expr", "values"), + [ + # The shape in the issue: a second equality on the partition key is + # served on extenddb before the fix, reading :b as a sort key value. + ("pk = :a AND pk = :b", {":a": A, ":b": B}), + ("pk = :a AND pk = :a", {":a": A}), + ("pk = :a AND pk = :b AND sk = :c", {":a": A, ":b": B, ":c": C}), + ("pk = :a AND pk > :b", {":a": A, ":b": B}), + ("pk > :b AND pk = :a", {":a": A, ":b": B}), + (":a = pk AND pk = :b", {":a": A, ":b": B}), + ("(pk = :a) AND (pk = :b)", {":a": A, ":b": B}), + ], + ) + def test_duplicate_partition_key_condition( + self, dynamodb_client, range_table, expr, values + ): + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression=expr, + ExpressionAttributeValues=values, + ) + ) + assert code == "ValidationException" + assert msg == ONE_PER_KEY + + @pytest.mark.parametrize( + ("expr", "values"), + [ + ("pk = :a AND sk = :b AND sk = :c", {":a": A, ":b": B, ":c": C}), + ("pk = :a AND sk = :b AND sk = :b", {":a": A, ":b": B}), + ( + "pk = :a AND sk BETWEEN :b AND :c AND sk = :b", + {":a": A, ":b": B, ":c": C}, + ), + ( + "pk = :a AND sk BETWEEN :b AND :c AND begins_with(sk, :b)", + {":a": A, ":b": B, ":c": C}, + ), + ("pk = :a AND begins_with(sk, :b) AND sk = :c", {":a": A, ":b": B, ":c": C}), + ("pk = :a AND sk > :b AND sk < :c", {":a": A, ":b": B, ":c": C}), + ( + "pk = :a AND begins_with(sk, :b) AND begins_with(sk, :c)", + {":a": A, ":b": B, ":c": C}, + ), + ("pk = :a AND pk = :b AND sk = :b AND sk = :c", {":a": A, ":b": B, ":c": C}), + # No partition key condition at all: the duplicate is reported + # ahead of the missing key schema element. + ("sk = :b AND sk = :c", {":b": B, ":c": C}), + ], + ) + def test_duplicate_sort_key_condition( + self, dynamodb_client, range_table, expr, values + ): + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression=expr, + ExpressionAttributeValues=values, + ) + ) + assert code == "ValidationException" + assert msg == ONE_PER_KEY + + @pytest.mark.parametrize( + ("expr", "values", "names"), + [ + ("#p = :a AND pk = :b", {":a": A, ":b": B}, {"#p": "pk"}), + ("#p = :a AND #q = :b", {":a": A, ":b": B}, {"#p": "pk", "#q": "pk"}), + ( + "pk = :a AND #s = :b AND sk = :c", + {":a": A, ":b": B, ":c": C}, + {"#s": "sk"}, + ), + ], + ) + def test_duplicate_through_name_reference( + self, dynamodb_client, range_table, expr, values, names + ): + """An #name alias resolving to the same attribute is a duplicate.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression=expr, + ExpressionAttributeValues=values, + ExpressionAttributeNames=names, + ) + ) + assert code == "ValidationException" + assert msg == ONE_PER_KEY + + def test_distinct_key_conditions_still_served(self, dynamodb_client, range_table): + """One condition per key attribute, in either order, returns rows.""" + pk_only = dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a", + ExpressionAttributeValues={":a": A}, + ) + assert pk_only["Count"] == 2 + + pk_and_sk = dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a AND sk = :b", + ExpressionAttributeValues={":a": A, ":b": B}, + ) + assert pk_and_sk["Count"] == 1 + + sk_first = dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="sk = :b AND pk = :a", + ExpressionAttributeValues={":a": A, ":b": B}, + ) + assert sk_first["Count"] == 1 + + sk_range = dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a AND sk BETWEEN :b AND :c", + ExpressionAttributeValues={":a": A, ":b": B, ":c": C}, + ) + assert sk_range["Count"] == 2 + + def test_nested_path_reported_ahead_of_duplicate( + self, dynamodb_client, range_table + ): + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a AND pk.foo = :b", + ExpressionAttributeValues={":a": A, ":b": B}, + ) + ) + assert code == "ValidationException" + assert msg == NESTED + + def test_redundant_parens_reported_ahead_of_duplicate( + self, dynamodb_client, range_table + ): + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="((pk = :a)) AND (pk = :b)", + ExpressionAttributeValues={":a": A, ":b": B}, + ) + ) + assert code == "ValidationException" + assert msg == REDUNDANT_PARENS + + def test_undefined_name_reported_ahead_of_duplicate( + self, dynamodb_client, range_table + ): + """Two conditions on an undefined #name: the name is reported.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="#u = :a AND #u = :b", + ExpressionAttributeValues={":a": A, ":b": B}, + ) + ) + assert code == "ValidationException" + assert UNDEFINED_NAME in msg + + +class TestDuplicateCheckOrder: + """Where the duplicate is reported against the other checks (2026-10-31).""" + + @pytest.mark.parametrize( + ("expr", "values"), + [ + ("#u = :a AND sk = :b AND sk = :c", {":a": A, ":b": B, ":c": C}), + ("pk = :a AND pk = :b AND #u = :c", {":a": A, ":b": B, ":c": C}), + ("#u = :a AND #u > :b", {":a": A, ":b": B}), + ], + ) + def test_undefined_name_in_any_clause_reported_ahead_of_duplicate( + self, dynamodb_client, range_table, expr, values + ): + """No ExpressionAttributeNames: the undefined #u is reported.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression=expr, + ExpressionAttributeValues=values, + ) + ) + assert code == "ValidationException" + assert msg == UNDEFINED_NAME_EXACT + + def test_undefined_value_reported_ahead_of_duplicate( + self, dynamodb_client, range_table + ): + """No ExpressionAttributeValues: the first undefined value is reported.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a AND pk = :b", + ) + ) + assert code == "ValidationException" + assert msg == UNDEFINED_VALUE_A + + @pytest.mark.parametrize( + ("expr", "values", "names"), + [ + # A number on the S key: the duplicate is reported ahead of the + # key value type check, in either spelling. + ("#p = :a AND pk = :n", {":a": A, ":n": N1}, {"#p": "pk"}), + ( + "pk = :a AND #s = :b AND sk = :n", + {":a": A, ":b": B, ":n": N1}, + {"#s": "sk"}, + ), + # An unused value: the duplicate is reported ahead of the + # unused-value check. + ("pk = :a AND pk = :b", {":a": A, ":b": B, ":z": {"S": "zed"}}, None), + ], + ) + def test_duplicate_reported_ahead_of_value_checks( + self, dynamodb_client, range_table, expr, values, names + ): + kwargs = { + "TableName": range_table, + "KeyConditionExpression": expr, + "ExpressionAttributeValues": values, + } + if names is not None: + kwargs["ExpressionAttributeNames"] = names + code, msg = _error(lambda: dynamodb_client.query(**kwargs)) + assert code == "ValidationException" + assert msg == ONE_PER_KEY From cc8d19272a02a521b4e7cdb5792da57b485f5cee Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:15:43 +0000 Subject: [PATCH 02/29] fix(auth): keep the LeadingKeys binding for a duplicate key condition The branch made authorization run the one-condition-per-key check, so a key condition with two conditions on one key attribute left dynamodb:LeadingKeys absent. Main bound the partition equality's value for such a condition. Which value the service binds for it is not measured. This restores main's binding: crates/server/src/leading_keys.rs is main's code again, and key_condition_clause_operands takes the tokens alone, as on main. The answers differ for `pk = :own AND sk = :b AND sk = :c`. With main's binding, a principal fenced to `own` by ForAnyValue:StringEquals reaches the engine and gets the one-condition-per-key ValidationException. With the key absent, it got AccessDeniedException. A unit test in leading_keys/tests.rs and a wire test in tests/test_fgac_leading_keys.py pin main's answer. The engine refuses every such key condition, so it reads no item either way. --- crates/core/src/expression/key_condition.rs | 74 +++++++-------------- crates/server/src/leading_keys.rs | 29 ++++---- crates/server/src/leading_keys/tests.rs | 47 +++++++------ tests/test_fgac_leading_keys.py | 34 +++++++--- 4 files changed, 90 insertions(+), 94 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 211aa3729..5a063af5d 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -389,9 +389,10 @@ impl KeyCondition { /// 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. Both parse with [`parse_key_condition_with_maps`], - /// which refuses a second condition on one key attribute before this runs, - /// so a duplicate is reported ahead of `value_check`. + /// HASH attribute. The engine parses with + /// [`parse_key_condition_with_maps`], which refuses a second condition on + /// one key attribute before this runs, so a duplicate is reported ahead of + /// `value_check`. /// /// # Errors /// @@ -597,10 +598,12 @@ impl SortKeyCondition { /// Supports multi-part keys: up to 8 AND-ed clauses (4 HASH + 4 RANGE). /// Rejects OR, NOT, and unsupported functions. /// -/// This does not look for a second condition on one key attribute, which -/// needs the request's `ExpressionAttributeNames` and -/// `ExpressionAttributeValues`. A request's key condition is parsed with -/// [`parse_key_condition_with_maps`]. +/// This does not refuse a second condition on one key attribute, which needs +/// the request's `ExpressionAttributeNames` and `ExpressionAttributeValues`. +/// The engine parses a request's key condition with +/// [`parse_key_condition_with_maps`]. Authorization parses with this when it +/// finds the partition key value for `dynamodb:LeadingKeys`, which keeps the +/// value it bound for such a condition before the engine refused it. /// /// # Errors /// @@ -620,8 +623,7 @@ pub fn parse_key_condition(tokens: &[Token]) -> Result) -> Result( +/// Returns `ValidationException` for the same syntax errors and unsupported +/// constructs [`parse_key_condition`] rejects before it classifies clauses. +pub fn key_condition_clause_operands( tokens: &[Token], - names: &std::collections::HashMap, - values: &std::collections::HashMap, ) -> Result, DynamoDbError> { - let clauses = parse_clauses(tokens)?; - reject_duplicate_key_attrs(&clauses, names, values)?; - Ok(clauses + Ok(parse_clauses(tokens)? .into_iter() .filter_map(|clause| match clause { RawClause::Eq(path, value) => Some(KeyClauseOperand { @@ -1483,14 +1480,17 @@ mod tests { "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, &HashMap::new(), &values_of(expr)).unwrap(); + let got = key_condition_clause_operands(&tokens).unwrap(); let got: Vec<(String, String, bool)> = got .into_iter() .map(|clause| { @@ -1529,7 +1529,7 @@ mod tests { continue; }; assert!( - key_condition_clause_operands(&tokens, &HashMap::new(), &no_values()).is_err(), + key_condition_clause_operands(&tokens).is_err(), "expr {expr} should be rejected" ); } @@ -2082,30 +2082,6 @@ mod tests { } } - /// A second condition on a key attribute, written with plain names or - /// through a `#name` reference, is refused before the clauses are handed - /// to authorization, so the LeadingKeys path reads no partition operand - /// from such a request. - #[test] - fn clause_operands_reject_duplicate_key_attribute() { - let names = names_of(&[("p", "pk"), ("s", "sk")]); - for expr in [ - "pk = :a AND pk = :b", - "#p = :a AND pk = :b", - "pk = :u AND pk > :v", - "#p = :u AND pk > :v", - "pk > :v AND sk = :s AND sk = :t", - "pk > :v AND #s = :s AND sk = :t", - ] { - let tokens = tokenize(expr).unwrap(); - assert_refused( - key_condition_clause_operands(&tokens, &names, &values_of(expr)), - ONE_CONDITION_PER_KEY_ERR, - expr, - ); - } - } - #[test] fn duplicate_condition_on_one_key_attribute_rejected() { // Measured 2026-10-24 (us-east-1): every one of these shapes answers diff --git a/crates/server/src/leading_keys.rs b/crates/server/src/leading_keys.rs index 60e7df075..3a6c733b7 100644 --- a/crates/server/src/leading_keys.rs +++ b/crates/server/src/leading_keys.rs @@ -63,7 +63,7 @@ use std::collections::HashMap; use extenddb_core::expression::{ - Expr, PathElement, Token, key_condition_clause_operands, parse_key_condition_with_maps, + Expr, PathElement, Token, key_condition_clause_operands, parse_key_condition, tokenize_with_limit, }; use extenddb_core::types::{KeySchemaElement, KeyType, TableKeyInfo}; @@ -268,11 +268,8 @@ fn query_leading_keys(input: &Value, key_info: &TableKeyInfo, max_tokens: usize) if let Some(kce) = input.get("KeyConditionExpression").and_then(Value::as_str) { let tokens = tokenize_with_limit(kce, max_tokens).ok()?; - // The clauses that name the partition attribute. A key condition with - // a second condition on one key attribute, written with plain names - // or through a `#name` reference, is refused here with the check the - // engine runs, so it leaves the key absent whatever its operators. - let pk_clauses: Vec<_> = key_condition_clause_operands(&tokens, &names, &values) + // The clauses that name the partition attribute, as written. + let pk_clauses: Vec<_> = key_condition_clause_operands(&tokens) .ok()? .into_iter() .filter(|clause| resolve_attr_name(&clause.path, &names).as_deref() == Some(pk_attr)) @@ -281,17 +278,21 @@ fn query_leading_keys(input: &Value, key_info: &TableKeyInfo, max_tokens: usize) // engine reads it. When the engine's classification refuses the // condition (a missing HASH attribute on a multi-attribute key schema, // for one) or the value cannot be read here (an `N` that is not a - // number, a placeholder with no value), the key stays absent. + // number, a placeholder with no value), the key stays absent and no + // other clause's operand is bound in its place: the equality, not the + // other clause, names the partition. if pk_clauses.iter().any(|clause| clause.equality) { return equality_pk_value(&tokens, key_schema, pk_attr, &names, &values); } - // The one clause on the partition key uses an operator the engine - // rejects, such as `pk > :v`. The service binds LeadingKeys to that - // operand and evaluates the policy before it rejects the shape, so a - // principal fenced away from the value gets AccessDeniedException + // Exactly one clause names the partition key, under an operator the + // engine rejects, such as `pk > :v`. The service binds LeadingKeys to + // that operand and evaluates the policy before it rejects the shape, + // so a principal fenced away from the value gets AccessDeniedException // while one fenced to it gets the shape's ValidationException - // (measured 2026-10-21 for `pk > :v`). A condition that does not parse - // and one that names no partition clause leave the key absent. + // (measured 2026-10-21 for `pk > :v`). A condition that does not + // parse, one that names no partition clause, and one with two + // non-equality partition clauses (which value the service binds for + // that shape is not measured) leave the key absent. let [clause] = pk_clauses.as_slice() else { return None; }; @@ -347,7 +348,7 @@ fn equality_pk_value( names: &HashMap, values: &HashMap, ) -> Option { - let mut kc = parse_key_condition_with_maps(tokens, names, values).ok()?; + let mut kc = parse_key_condition(tokens).ok()?; // Assign every clause to its key attribute with the engine's own // classification: by name on a multi-attribute key schema, where the // first HASH attribute is the one LeadingKeys names, and by diff --git a/crates/server/src/leading_keys/tests.rs b/crates/server/src/leading_keys/tests.rs index 9936f1e6d..e942824a9 100644 --- a/crates/server/src/leading_keys/tests.rs +++ b/crates/server/src/leading_keys/tests.rs @@ -622,10 +622,11 @@ fn query_between_on_the_partition_key_is_absent() { assert_eq!(r, None); } -/// An equality on the partition key and a second clause on the partition key -/// name the partition key twice, so the duplicate check refuses the condition -/// and the key stays absent: the other clause's operand (`alice`) is never -/// bound, whether the equality's value can be read or not. +/// An equality on the partition key decides the key, even when its value +/// cannot be read and another clause names the partition key: the other +/// clause's operand is never bound in its place. With `:u = {"N": "bob"}` +/// (not a number) the key stays absent, as on main, rather than becoming +/// `alice`. #[test] fn query_unreadable_partition_equality_binds_no_other_clause() { for (kce, u) in [ @@ -633,7 +634,6 @@ fn query_unreadable_partition_equality_binds_no_other_clause() { ("pk > :v AND pk = :u", json!({"N": "bob"})), ("#p = :u AND pk > :v", json!({"N": "bob"})), ("pk = :u AND begins_with(pk, :v)", json!({"N": "1e"})), - ("pk = :u AND pk > :v", json!({"S": "bob"})), ] { let input = json!({ "TableName": "t", @@ -644,40 +644,43 @@ fn query_unreadable_partition_equality_binds_no_other_clause() { let r = single_table_leading_keys(&input, "Query", Some(&main_table()), MAX_TOKENS); assert_eq!(r, None, "{kce}"); } + // A readable equality keeps its own value with another partition clause. + let input = json!({ + "TableName": "t", + "KeyConditionExpression": "pk = :u AND pk > :v", + "ExpressionAttributeValues": {":u": {"S": "bob"}, ":v": {"S": "alice"}}, + }); + let r = single_table_leading_keys(&input, "Query", Some(&main_table()), MAX_TOKENS); + assert_ne!(r, Some(vec!["alice".to_owned()])); } -/// A second condition on one key attribute, written with plain names or -/// through a `#name` reference, leaves the key absent, including when the -/// only partition clause is a non-equality whose operand would otherwise be -/// bound. The engine refuses all of these. +/// A second condition on one key attribute keeps the partition equality's +/// value, so a principal fenced to `own` reaches the engine, which refuses the +/// key condition, and one fenced away from it is denied. The engine refuses +/// every such key condition; which value the service binds for one is not +/// measured. #[test] -fn query_duplicate_key_condition_leaves_the_key_absent() { +fn query_duplicate_key_condition_binds_the_partition_equality() { for kce in [ - "pk = :a AND pk = :b", - "#p = :a AND pk = :b", - "pk = :a AND sk = :b AND sk = :c", - "pk = :a AND #s = :b AND sk = :c", - "pk > :a AND sk = :b AND sk = :c", - "pk > :a AND #s = :b AND sk = :c", + "pk = :own AND sk = :b AND sk = :c", + "pk = :own AND pk = :b", ] { let input = json!({ "TableName": "t", "KeyConditionExpression": kce, - "ExpressionAttributeNames": {"#p": "pk", "#s": "sk"}, "ExpressionAttributeValues": { - ":a": {"S": "alice"}, + ":own": {"S": "own"}, ":b": {"S": "bob"}, ":c": {"S": "carol"}, }, }); let r = single_table_leading_keys(&input, "Query", Some(&main_table()), MAX_TOKENS); - assert_eq!(r, None, "{kce}"); + assert_eq!(r, Some(vec!["own".to_owned()]), "{kce}"); } } -/// Two non-equality clauses on the partition key name it twice, so the -/// duplicate check refuses the condition and neither operand is bound, in -/// either clause order. +/// Two non-equality clauses on the partition key: which operand the service +/// binds is not measured, so neither is bound, in either clause order. #[test] fn query_two_non_equality_partition_clauses_bind_nothing() { for kce in [ diff --git a/tests/test_fgac_leading_keys.py b/tests/test_fgac_leading_keys.py index ee3882909..2dcd94155 100644 --- a/tests/test_fgac_leading_keys.py +++ b/tests/test_fgac_leading_keys.py @@ -377,17 +377,15 @@ def test_scan_denied_under_for_any_value(self, table): c.scan(TableName=table) assert _denied(e) - # -- A second clause on the partition key binds nothing ---------------- + # -- A second clause on the partition key ------------------------------ def test_unreadable_partition_equality_does_not_bind_another_clause(self, table): - # An equality on the partition key and a second clause on it name the - # partition key twice, so the duplicate check leaves - # dynamodb:LeadingKeys absent and the fenced value in the second - # clause (`:v`) is never bound. A principal allowed everything gets - # the one-condition-per-key error. A policy that needs a LeadingKeys - # value denies the request, whether the equality's value can be read - # (`:u = {"S": "bob"}`) or not (`:u = {"N": "bob"}`, refused either - # way). + # An equality on the partition key decides dynamodb:LeadingKeys, and + # the fenced value in the second clause (`:v`) is never bound in its + # place. A principal allowed everything gets the one-condition-per-key + # error. A policy fenced to `:v`'s value denies the request, whether + # the equality's value can be read (`:u = {"S": "bob"}`, bound) or not + # (`:u = {"N": "bob"}`, absent, and refused either way). kces = ("pk = :u AND pk > :v", "pk > :v AND pk = :u") readable = {":u": {"S": OTHER}, ":v": {"S": OWN}} unreadable = {":u": {"N": OTHER}, ":v": {"S": OWN}} @@ -421,6 +419,24 @@ def test_unreadable_partition_equality_does_not_bind_another_clause(self, table) assert e.value.response["Error"]["Code"] in ( "AccessDeniedException", "ValidationException"), (form, kce) + def test_duplicate_sort_key_condition_binds_the_partition_equality(self, table): + # A second condition on the sort key leaves dynamodb:LeadingKeys bound + # to the partition equality's value, so a principal fenced to that + # value reaches the engine and gets the one-condition-per-key error. + # With the key absent, the same principal would get + # AccessDeniedException. Which value the service binds for a key + # condition with two conditions on one key attribute is not measured. + c = self._user_client([("lk", self._leading_keys_policy( + "ForAnyValue", [OWN], table))]) + with pytest.raises(ClientError) as e: + c.query(TableName=table, + KeyConditionExpression="pk = :own AND sk = :b AND sk = :c", + ExpressionAttributeValues={":own": {"S": OWN}, ":b": {"S": "x"}, + ":c": {"S": "y"}}) + err = e.value.response["Error"] + assert err["Code"] == "ValidationException" + assert err["Message"] == ONE_PER_KEY + def test_non_equality_partition_with_sort_clause_is_refused(self, table): # The fix binds the partition operand of these shapes; the engine still # refuses them, so no partition is read whatever authorization binds. From 8b4967235f97792d39111073af77c81e95c3072a Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:24:29 +0000 Subject: [PATCH 03/29] fix(core): check key condition references in the order they are written parse_key_condition_with_maps reported an undefined reference only when the key condition also had a second condition on one key attribute. It checked every #name before any :value. Without a duplicate, the classifier reported an undefined #name later. An undefined :value reached the storage query builders, which refused it without the `Invalid KeyConditionExpression: ` prefix. The parse now takes the request's ExpressionMaps and checks, after the grammar and before any clause is classified: 1. Every #name and :value reference, once, in the order the expression is written. The first undefined one is refused with the prefix, with or without a duplicate. The engine's unused name and value check runs after the parse, so an undefined reference comes first. 2. A begins_with operand that is not a string or a binary value. 3. A second condition on one key attribute. `<>` and `contains` are parsed as clauses and refused after these checks, with the messages they had. Measured in us-east-1 on 10 and 11 Nov 2026, two sends each, the same answer both times: - `pk = :q AND #u = :c` with no maps answers `:q`. - `sk = :b AND pk = :a` with no values answers `:b`. - `pk = :a AND pk = :b AND #u = :c` with no maps answers `:a`. The core test that expected `#u` for this request now expects `:a`. - `pk = :q AND pk = :b AND #u = :c` with `:b` and `:c` defined answers `:q`. - `#u = :a AND #u = :b` with no maps answers `#u`. - `pk = :a AND sk = :missing` with an unused `:extra` answers `:missing`, and `pk = :v` or `#k = :v` with an unused name or value answers the undefined reference. - `pk = :a AND pk <> :b` and `pk = :a AND contains(pk, :b)` answer the one-condition-per-key message. - `pk = :a AND begins_with(sk, :n) AND sk = :b` with `:n` a number answers "Incorrect operand type for operator or function; operator or function: begins_with, operand type: N". Without a duplicate, the begins_with operand check now also runs ahead of the key value type check. The service's order for that request is not measured. The undefined name message has one copy in key_condition.rs, and the undefined value message comes from ExpressionMaps::resolve_value_for. --- crates/core/src/expression/key_condition.rs | 436 ++++++++++++-------- crates/engine/src/expression_helpers.rs | 7 +- crates/engine/src/query.rs | 9 +- 3 files changed, 263 insertions(+), 189 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 5a063af5d..00edea21f 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -15,10 +15,12 @@ use super::ast::{CompareOp, Expr, PathElement}; use super::parser_common; +use super::resolver::{ExpressionMaps, attribute_type_code}; use super::tokenizer::Token; use crate::error::DynamoDbError; use crate::types::{ - KeySchemaElement, KeyType, hash_key_elements, is_multipart_key_schema, range_key_elements, + AttributeValue, 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. @@ -81,12 +83,10 @@ impl KeyCondition { 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}" - )) - })? + names + .get(ref_name) + .map(String::as_str) + .ok_or_else(|| undefined_name_err(ref_name))? } else { name.as_str() } @@ -469,69 +469,88 @@ impl KeyCondition { /// condition on the same key attribute. Measured 2026-10-24 (us-east-1). const ONE_CONDITION_PER_KEY_ERR: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key"; +/// The service's message for a `#name` reference that +/// `ExpressionAttributeNames` does not define. +fn undefined_name_err(reference: &str) -> DynamoDbError { + validation_err(&format!( + "Invalid KeyConditionExpression: An expression attribute name used in the document \ + path is not defined; attribute name: #{reference}" + )) +} + +/// Refuse the first `#name` or `:value` reference that `maps` does not define, +/// in the order the expression is written, names and values alike. +/// +/// Measured 2026-11-10 and 2026-11-11 (us-east-1): the service names the +/// first undefined reference in text order (`pk = :q AND #u = :c` with no +/// maps answers `:q`; `#u = :a AND #u = :b` answers `#u`), with or without a +/// second condition on one key attribute, and ahead of an unused name or +/// value. +fn check_references(tokens: &[Token], maps: &ExpressionMaps) -> Result<(), DynamoDbError> { + for token in tokens { + match token { + Token::NameRef(name) if !maps.names.contains_key(name) => { + return Err(undefined_name_err(name)); + } + Token::Placeholder(placeholder) => { + maps.resolve_value_for(placeholder, "KeyConditionExpression")?; + } + _ => {} + } + } + Ok(()) +} + +/// Refuse a `begins_with` operand that is not a string or a binary value. +/// +/// Measured 2026-11-11 (us-east-1): `pk = :a AND begins_with(sk, :n) AND +/// sk = :b` with `:n` a number answers this ahead of the one-condition-per-key +/// message. +fn check_begins_with_operands( + clauses: &[RawClause], + maps: &ExpressionMaps, +) -> Result<(), DynamoDbError> { + for clause in clauses { + if let RawClause::BeginsWith(_, Expr::Placeholder(placeholder)) = clause + && let Some(value) = maps.values.get(placeholder) + && !matches!(value, AttributeValue::S(_) | AttributeValue::B(_)) + { + return Err(validation_err(&format!( + "Invalid KeyConditionExpression: Incorrect operand type for operator or \ + function; operator or function: begins_with, operand type: {}", + attribute_type_code(value) + ))); + } + } + Ok(()) +} + /// Refuse a key condition with more than one condition on one key attribute. /// /// Two clauses name the same attribute when their paths resolve to the same /// name through `names`, whether each is written as a plain name or as a -/// `#name` reference. Two clauses on one `#name` reference name the same -/// attribute whether or not `names` defines it. DynamoDB allows one condition -/// per key attribute, on the partition key and on the sort key alike, whatever -/// the operators are (measured 2026-10-24). -/// -/// The service resolves every `#name` and `:value` reference before it looks -/// for a duplicate (measured 2026-10-31), so when a duplicate is found an -/// undefined `#name` in any clause is reported first, then an undefined -/// `:value`, each with the service's text. A key condition without a duplicate -/// passes, and the checks that follow report its undefined references. -fn reject_duplicate_key_attrs( +/// `#name` reference. DynamoDB allows one condition per key attribute, on the +/// partition key and on the sort key alike, whatever the operators are +/// (measured 2026-10-24, and 2026-11-11 for `<>` and `contains`). +fn reject_duplicate_key_attrs( clauses: &[RawClause], names: &std::collections::HashMap, - values: &std::collections::HashMap, ) -> Result<(), DynamoDbError> { let mut seen: Vec<&str> = Vec::with_capacity(clauses.len()); - let mut duplicated = false; for clause in clauses { let Some(PathElement::Attribute(name)) = raw_clause_path(clause).first() else { continue; }; - // An undefined reference keeps its `#`, which no plain name carries. let attr = match name.strip_prefix('#') { Some(reference) => names.get(reference).map_or(name.as_str(), String::as_str), None => name.as_str(), }; if seen.contains(&attr) { - duplicated = true; - break; + return Err(validation_err(ONE_CONDITION_PER_KEY_ERR)); } seen.push(attr); } - if !duplicated { - return Ok(()); - } - for clause in clauses { - if let Some(PathElement::Attribute(name)) = raw_clause_path(clause).first() - && let Some(reference) = name.strip_prefix('#') - && !names.contains_key(reference) - { - return Err(validation_err(&format!( - "Invalid KeyConditionExpression: An expression attribute name used in the \ - document path is not defined; attribute name: #{reference}" - ))); - } - } - for clause in clauses { - for value in raw_clause_values(clause) { - if let Expr::Placeholder(placeholder) = value - && !values.contains_key(placeholder) - { - return Err(validation_err(&format!( - "Invalid KeyConditionExpression: An expression attribute value used in \ - expression is not defined; attribute value: :{placeholder}" - ))); - } - } - } - Err(validation_err(ONE_CONDITION_PER_KEY_ERR)) + Ok(()) } /// Resolve a path's top-level attribute name, handling `#name` references. @@ -542,12 +561,10 @@ fn resolve_path_attr( 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}" - )) - }) + names + .get(ref_name) + .cloned() + .ok_or_else(|| undefined_name_err(ref_name)) } else { Ok(name.clone()) } @@ -612,36 +629,38 @@ pub fn parse_key_condition(tokens: &[Token]) -> Result`, `contains`) is refused after these. The +/// engine reads a `Query` key condition through this. /// /// # Errors /// -/// As [`parse_key_condition`], plus `ValidationException` for a second -/// condition on one key attribute. -pub fn parse_key_condition_with_maps( +/// As [`parse_key_condition`], plus `ValidationException` for each of the +/// faults above. +pub fn parse_key_condition_with_maps( tokens: &[Token], - names: &std::collections::HashMap, - values: &std::collections::HashMap, + maps: &ExpressionMaps, ) -> Result { let clauses = parse_clauses(tokens)?; - reject_duplicate_key_attrs(&clauses, names, values)?; + check_references(tokens, maps)?; + check_begins_with_operands(&clauses, maps)?; + reject_duplicate_key_attrs(&clauses, &maps.names)?; classify_clauses(clauses) } /// Read the parsed clauses as a partition key condition and sort key -/// conditions. +/// conditions, after refusing the first clause whose operator a key condition +/// does not support. fn classify_clauses(mut clauses: Vec) -> Result { + refuse_unsupported_clauses(&clauses)?; match clauses.len() { 1 => classify_single(clauses.remove(0)), 2 => classify_pair(clauses.remove(0), clauses.remove(0)), @@ -649,6 +668,18 @@ fn classify_clauses(mut clauses: Vec) -> Result Result<(), DynamoDbError> { + match clauses.iter().find_map(|clause| match clause { + RawClause::Unsupported(_, message) => Some(*message), + _ => None, + }) { + Some(message) => Err(validation_err(message)), + None => Ok(()), + } +} + /// The attribute path and single value operand of each clause of a /// `KeyConditionExpression`, and whether the clause compares by equality. /// @@ -670,7 +701,9 @@ fn classify_clauses(mut clauses: Vec) -> Result Result, DynamoDbError> { - Ok(parse_clauses(tokens)? + let clauses = parse_clauses(tokens)?; + refuse_unsupported_clauses(&clauses)?; + Ok(clauses .into_iter() .filter_map(|clause| match clause { RawClause::Eq(path, value) => Some(KeyClauseOperand { @@ -685,7 +718,7 @@ pub fn key_condition_clause_operands( equality: false, }) } - RawClause::Between(..) => None, + RawClause::Between(..) | RawClause::Unsupported(..) => None, }) .collect()) } @@ -756,16 +789,8 @@ fn raw_clause_path(clause: &RawClause) -> &[PathElement] { RawClause::Eq(path, _) | RawClause::Compare(path, _, _) | RawClause::Between(path, _, _) - | RawClause::BeginsWith(path, _) => path, - } -} - -/// The value operands of a raw clause, in the order they are written. -fn raw_clause_values(clause: &RawClause) -> Vec<&Expr> { - match clause { - RawClause::Eq(_, value) | RawClause::Compare(_, _, value) => vec![value], - RawClause::Between(_, low, high) => vec![low, high], - RawClause::BeginsWith(_, prefix) => vec![prefix], + | RawClause::BeginsWith(path, _) + | RawClause::Unsupported(path, _) => path, } } @@ -789,6 +814,11 @@ enum RawClause { Compare(Vec, CompareOp, Expr), Between(Vec, Expr, Expr), BeginsWith(Vec, Expr), + /// A clause whose operator a key condition does not support, with the + /// message it is refused with. It stays a clause until a second + /// condition on its attribute has been looked for, which the service + /// reports first. + Unsupported(Vec, &'static str), } enum KeyOperand { @@ -822,7 +852,7 @@ fn classify_pair(a: RawClause, b: RawClause) -> Result) -> Result) -> Result SortKeyCondition { - match clause { +/// The sort key condition a clause becomes. [`classify_clauses`] refuses an +/// unsupported clause before any clause reaches this. +fn raw_to_sk(clause: RawClause) -> Result { + Ok(match clause { RawClause::Eq(path, value) => SortKeyCondition::Compare { path, op: CompareOp::Eq, @@ -898,7 +930,8 @@ fn raw_to_sk(clause: RawClause) -> SortKeyCondition { RawClause::Compare(path, op, value) => SortKeyCondition::Compare { path, op, value }, RawClause::Between(path, low, high) => SortKeyCondition::Between { path, low, high }, RawClause::BeginsWith(path, prefix) => SortKeyCondition::BeginsWith { path, prefix }, - } + RawClause::Unsupported(_, message) => return Err(validation_err(message)), + }) } fn parse_key_clause(tokens: &[Token], pos: &mut usize) -> Result { @@ -931,19 +964,25 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result Result path, KeyOperand::Value(value) => { - let op = try_comparator(&tokens[*pos]).ok_or_else(|| { - validation_err("Invalid KeyConditionExpression: expected comparison operator") - })?; - // DynamoDB rejects <> in KeyConditionExpression — only =, <, <=, >, >= - // are valid key condition operators. - if op == CompareOp::Ne { - return Err(validation_err( - "Invalid KeyConditionExpression: Unsupported operator on KeyCondition: NE", - )); - } + let op = try_comparator(&tokens[*pos]) + .ok_or_else(|| validation_err(EXPECTED_COMPARISON_OPERATOR))?; *pos += 1; let path = parse_key_operand_path(tokens, pos)?; + if op == CompareOp::Ne { + return Ok(RawClause::Unsupported(path, NE_UNSUPPORTED)); + } // Key conditions are stored path-first, so reverse the operator when // the source expression puts the value placeholder on the left. let op = reverse_comparator(op); @@ -993,27 +1027,34 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result in KeyConditionExpression — only =, <, <=, >, >= - // are valid key condition operators. - if op == CompareOp::Ne { - return Err(validation_err( - "Invalid KeyConditionExpression: Unsupported operator on KeyCondition: NE", - )); - } + let op = + try_comparator(&tokens[*pos]).ok_or_else(|| validation_err(EXPECTED_COMPARISON_OPERATOR))?; *pos += 1; let value = parse_key_value(tokens, pos)?; - if op == CompareOp::Eq { + if op == CompareOp::Ne { + Ok(RawClause::Unsupported(path, NE_UNSUPPORTED)) + } else if op == CompareOp::Eq { Ok(RawClause::Eq(path, value)) } else { Ok(RawClause::Compare(path, op, value)) } } +/// A key condition allows `=`, `<`, `<=`, `>` and `>=`, and refuses `<>` with +/// this. A second condition on the same attribute is reported first +/// (measured 2026-11-11: `pk = :a AND pk <> :b` answers the +/// one-condition-per-key message). +const NE_UNSUPPORTED: &str = "Invalid KeyConditionExpression: Unsupported operator on KeyCondition: NE"; + +/// The refusal of a clause with no comparison operator, and of a `contains` +/// clause. A second condition on the same attribute is reported ahead of +/// `contains` (measured 2026-11-11: `pk = :a AND contains(pk, :b)` answers +/// the one-condition-per-key message). +const EXPECTED_COMPARISON_OPERATOR: &str = + "Invalid KeyConditionExpression: expected comparison operator"; + fn parse_key_operand(tokens: &[Token], pos: &mut usize) -> Result { if *pos >= tokens.len() { return Err(validation_err( @@ -2028,9 +2069,6 @@ mod tests { assert_eq!(kc.pk_path, vec![PathElement::Attribute("pk".to_owned())]); } - const UNDEFINED_NAME_U: &str = "Invalid KeyConditionExpression: An expression attribute \ - name used in the document path is not defined; attribute \ - name: #u"; const TYPE_ERR: &str = "One or more parameter values were invalid: Condition parameter \ type does not match schema type"; @@ -2061,16 +2099,30 @@ mod tests { .collect() } - /// Parse `expr` as the engine parses a request's key condition, with every - /// placeholder defined. - fn parse_request( + /// Parse `expr` as the engine parses a request's key condition. + fn parse_with( expr: &str, names: &HashMap, + values: &HashMap, ) -> Result { let tokens = tokenize(expr).unwrap(); - parse_key_condition_with_maps(&tokens, names, &values_of(expr)) + parse_key_condition_with_maps(&tokens, &ExpressionMaps::new(names.clone(), values.clone())) + } + + /// [`parse_with`] with every placeholder of `expr` defined. + fn parse_request( + expr: &str, + names: &HashMap, + ) -> Result { + parse_with(expr, names, &values_of(expr)) } + fn undefined_value(value: &str) -> String { + format!( + "Invalid KeyConditionExpression: An expression attribute value used in \ + expression is not defined; attribute value: :{value}" + ) + } fn assert_refused( result: Result, want: &str, @@ -2137,67 +2189,59 @@ mod tests { assert_refused(parse_request(expr, &names), ONE_CONDITION_PER_KEY_ERR, expr); } - /// With a duplicate present, an undefined `#name` anywhere in the - /// expression is reported first. Measured 2026-10-24 for - /// `#u = :a AND #u = :b` and 2026-10-31 for the next three; the - /// multi-attribute form is not measured. + /// The first undefined reference in the order the expression is written is + /// reported, a `#name` or a `:value`, with or without a duplicate. + /// Measured 2026-10-24 for `#u = :a AND #u = :b`, 2026-10-31 for the + /// duplicates with `#u` the only undefined reference, and 2026-11-11 for + /// the rest (us-east-1, two sends each). The multi-attribute form is not + /// measured. #[test] - fn undefined_name_reported_ahead_of_duplicate() { - for expr in [ - "#u = :a AND #u = :b", - "#u = :a AND #u > :b", - "#u = :a AND sk = :b AND sk = :c", - "pk = :a AND pk = :b AND #u = :c", - "h = :a AND h = :b AND #u = :c", + fn first_undefined_reference_in_text_order_is_reported() { + let none = HashMap::new(); + for (expr, values, want) in [ + // Every placeholder defined, `#u` the only undefined reference. + ("#u = :a AND #u = :b", values_of("#u = :a AND #u = :b"), "#u"), + ("#u = :a AND #u > :b", values_of("#u = :a AND #u > :b"), "#u"), + ( + "#u = :a AND sk = :b AND sk = :c", + values_of("#u = :a AND sk = :b AND sk = :c"), + "#u", + ), + ( + "pk = :a AND pk = :b AND #u = :c", + values_of("pk = :a AND pk = :b AND #u = :c"), + "#u", + ), + ( + "h = :a AND h = :b AND #u = :c", + values_of("h = :a AND h = :b AND #u = :c"), + "#u", + ), + // No maps, or only some values: the first in text order. + ("#u = :a AND #u = :b", no_values(), "#u"), + ("pk = :q AND #u = :c", no_values(), ":q"), + ("sk = :b AND pk = :a", no_values(), ":b"), + ("pk = :b AND pk = :a", no_values(), ":b"), + ("pk = :a AND pk = :b AND #u = :c", no_values(), ":a"), + ( + "pk = :q AND pk = :b AND #u = :c", + values_of(":b :c"), + ":q", + ), + ("pk = :a AND pk = :missing", values_of(":a"), ":missing"), + ("#k = :v", no_values(), "#k"), + ("pk = :v", no_values(), ":v"), ] { - assert_refused(parse_request(expr, &HashMap::new()), UNDEFINED_NAME_U, expr); + let want = match want.strip_prefix('#') { + Some(name) => format!( + "Invalid KeyConditionExpression: An expression attribute name used in the \ + document path is not defined; attribute name: #{name}" + ), + None => undefined_value(&want[1..]), + }; + assert_refused(parse_with(expr, &none, &values), &want, expr); } - // Without a duplicate the parse passes, and `resolve_pk_sk` reports - // the name. - let mut kc = parse_request("#u = :a AND sk = :b", &HashMap::new()).unwrap(); - assert_refused( - kc.resolve_pk_sk("pk", &HashMap::new()), - UNDEFINED_NAME_U, - "#u = :a AND sk = :b", - ); - } - - /// With a duplicate present, an undefined `:value` is reported ahead of it - /// (measured 2026-10-31: `pk = :a AND pk = :b` without - /// `ExpressionAttributeValues` answers the undefined-value message for - /// `:a`). Which of an undefined name and an undefined value the service - /// reports first is not measured; the name is checked first here. - #[test] - fn undefined_value_reported_ahead_of_duplicate() { - let undefined = |value: &str| { - format!( - "Invalid KeyConditionExpression: An expression attribute value used in \ - expression is not defined; attribute value: :{value}" - ) - }; - let tokens = tokenize("pk = :a AND pk = :b").unwrap(); - assert_refused( - parse_key_condition_with_maps(&tokens, &HashMap::new(), &no_values()), - &undefined("a"), - "pk = :a AND pk = :b", - ); - let tokens = tokenize("pk = :a AND pk = :missing").unwrap(); - assert_refused( - parse_key_condition_with_maps(&tokens, &HashMap::new(), &values_of("pk = :a")), - &undefined("missing"), - "pk = :a AND pk = :missing", - ); - let tokens = tokenize("pk = :a AND pk = :b AND #u = :c").unwrap(); - assert_refused( - parse_key_condition_with_maps(&tokens, &HashMap::new(), &no_values()), - UNDEFINED_NAME_U, - "pk = :a AND pk = :b AND #u = :c", - ); - // Without a duplicate the parse does not read the values. - let tokens = tokenize("pk = :a AND sk = :b").unwrap(); - assert!(parse_key_condition_with_maps(&tokens, &HashMap::new(), &no_values()).is_ok()); } - /// The duplicate is reported by the parse, so it comes ahead of the key /// value type check that `resolve_key_schema_with` runs and of the engine's /// unused-value check, whichever way it is spelled (measured 2026-10-31: @@ -2224,15 +2268,13 @@ mod tests { "pk = :a AND #s = :b AND sk = :n", "pk = :a AND pk = :b", ] { - let tokens = tokenize(expr).unwrap(); assert_refused( - parse_key_condition_with_maps(&tokens, &names, &values), + parse_with(expr, &names, &values), ONE_CONDITION_PER_KEY_ERR, expr, ); } - let tokens = tokenize("pk = :n").unwrap(); - let mut kc = parse_key_condition_with_maps(&tokens, &names, &values).unwrap(); + let mut kc = parse_with("pk = :n", &names, &values).unwrap(); assert_refused( kc.resolve_key_schema_with(&schema, &names, |_, value| match value { Expr::Placeholder(name) if name == "n" => Err(validation_err(TYPE_ERR)), @@ -2243,6 +2285,36 @@ mod tests { ); } + /// `<>` and `contains` are refused after the duplicate check, and a + /// `begins_with` operand that is not a string or a binary value before it + /// (measured 2026-11-11, us-east-1, two sends each). Without a duplicate, + /// `<>` and `contains` keep the messages they had. + #[test] + fn operators_and_operands_around_the_duplicate_check() { + const BEGINS_WITH_N: &str = "Invalid KeyConditionExpression: Incorrect operand type \ + for operator or function; operator or function: \ + begins_with, operand type: N"; + let mut values = values_of(":a :b :c"); + values.insert("n".to_owned(), AttributeValue::N("1".to_owned())); + let none = HashMap::new(); + for (expr, want) in [ + ("pk = :a AND pk <> :b", ONE_CONDITION_PER_KEY_ERR), + ("pk = :a AND contains(pk, :b)", ONE_CONDITION_PER_KEY_ERR), + ("pk = :a AND begins_with(sk, :n) AND sk = :b", BEGINS_WITH_N), + ("pk = :a AND sk <> :b", NE_UNSUPPORTED), + ("pk = :a AND :b <> sk", NE_UNSUPPORTED), + ("pk = :a AND contains(sk, :b)", EXPECTED_COMPARISON_OPERATOR), + ] { + assert_refused(parse_with(expr, &none, &values), want, expr); + } + // The map-less parse authorization reads refuses them too. + for expr in ["pk = :a AND pk <> :b", "pk = :a AND contains(pk, :b)"] { + let tokens = tokenize(expr).unwrap(); + assert!(parse_key_condition(&tokens).is_err(), "expr {expr}"); + assert!(key_condition_clause_operands(&tokens).is_err(), "expr {expr}"); + } + } + #[test] fn nested_path_reported_ahead_of_duplicate() { // Measured 2026-10-24: both of these answer their own message, not the diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 9a5dc0f65..4f891710c 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -239,7 +239,8 @@ pub fn parse_projection_expr( /// Size-check, tokenize, reserved-word check, and parse a `KeyConditionExpression`. /// /// `maps` holds the request's `ExpressionAttributeNames` and -/// `ExpressionAttributeValues`, which the parse reads to refuse a second +/// `ExpressionAttributeValues`. The parse reads them to refuse an undefined +/// reference, a `begins_with` operand of the wrong type and a second /// condition on one key attribute. /// /// Errors carry the `KeyConditionExpression` prefix, matching Amazon `DynamoDB`. @@ -247,7 +248,7 @@ pub fn parse_projection_expr( /// # Errors /// /// Returns `DynamoDbError::ValidationException` for over-size, syntax, or -/// reserved-word errors, and for a second condition on one key attribute. +/// reserved-word errors, and for the faults above. pub fn parse_key_condition_expr( expr: &str, maps: &ExpressionMaps, @@ -263,7 +264,7 @@ pub fn parse_key_condition_expr( if limits.enforce_reserved_keywords { validate_no_reserved_words(&tokens)?; } - parse_key_condition_with_maps(&tokens, &maps.names, &maps.values) + parse_key_condition_with_maps(&tokens, maps) }) .map_err(|e| prefix_expression_error(e, ExpressionKind::KeyCondition)) } diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 38b74bd23..ee5074f4f 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -237,10 +237,11 @@ pub async fn handle_query( let (mut key_condition, legacy_kc_maps) = if let Some(kce_str) = input.key_condition_expression.as_deref() { - // The parse refuses a second condition on one key attribute, after - // the expression's `#name` and `:value` references are checked and - // before the clauses are classified, which is where the service - // reports it (measured 2026-10-31). + // The parse refuses, in this order, the first undefined `#name` or + // `:value` in the order the expression is written, a `begins_with` + // operand of the wrong type and a second condition on one key + // attribute, before the clauses are classified (measured 2026-10-31 + // and 2026-11-11). let parsed = crate::expression_helpers::parse_key_condition_expr(kce_str, &maps, &ctx.limits)?; (parsed, None) From 822c472e23b0fae3c3d506a9258b66a4074d02ab Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:42:19 +0000 Subject: [PATCH 04/29] fix(query): refuse a duplicate key condition where the service does The branch refused a key condition with two conditions on one key attribute after the table, index, ConsistentRead and Select checks. It refused it ahead of the FilterExpression checks. The service runs both the other way round. Measured in us-east-1 on 11 Nov 2026, two sends each, the same answer both times. The table has pk (S) HASH, sk (S) RANGE and a KEYS_ONLY global secondary index on g (S). The key condition is `pk = :a AND pk = :b`: - A missing table, IndexName `nope`, ConsistentRead on the index, Select `BOGUS` and Select `ALL_ATTRIBUTES` on the index each answer the one-condition-per-key message. - A FilterExpression `#q = :a` with `#q` undefined, `foo = :zz` with `:zz` undefined, `begins_with(foo, :n)` with `:n` a number, `name = :a` (a reserved word) and `zz = = :a` each answer the filter's own message. handle_query now parses the key condition right after deserialization. When the parse answers the one-condition-per-key message, the filter's grammar, reserved word, reference and operand type checks run. The first fault they find is returned, and otherwise the duplicate. Any other fault of the parse is reported further down, where it was. An invalid Select is left out of the typed input and its error is returned after this check. The parse result is used further down, so the key condition is parsed once. tests/test_query_key_condition_one_per_key.py pins the measured rows. Its table gets the KEYS_ONLY index. For `zz = = :a` the test compares the expression the error names. ExtendDB words its filter syntax errors differently from the service. --- crates/core/src/expression/key_condition.rs | 2 +- crates/core/src/expression/mod.rs | 4 +- crates/engine/src/query.rs | 100 +++++++++++---- tests/test_query_key_condition_one_per_key.py | 118 +++++++++++++++++- 4 files changed, 199 insertions(+), 25 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 00edea21f..62b142e2f 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -467,7 +467,7 @@ impl KeyCondition { /// The service's message when a `KeyConditionExpression` carries more than one /// condition on the same key attribute. Measured 2026-10-24 (us-east-1). -const ONE_CONDITION_PER_KEY_ERR: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key"; +pub const ONE_CONDITION_PER_KEY_ERR: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key"; /// The service's message for a `#name` reference that /// `ExpressionAttributeNames` does not define. diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 479cadc94..9e7b682fc 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -25,8 +25,8 @@ mod update_parser; pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only}; pub use evaluator::evaluate_condition; pub use key_condition::{ - KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands, - parse_key_condition, parse_key_condition_with_maps, + KeyClauseOperand, KeyCondition, ONE_CONDITION_PER_KEY_ERR, SortKeyCondition, + key_condition_clause_operands, parse_key_condition, parse_key_condition_with_maps, }; pub use kind::ExpressionKind; pub use parser::{parse_condition, parse_condition_with_depth_limit}; diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index ee5074f4f..3e5b5d284 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -9,7 +9,9 @@ use serde_json::Value; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::PathElement; -use extenddb_core::expression::{ExpressionKind, ExpressionMaps, Projection}; +use extenddb_core::expression::{ + ExpressionKind, ExpressionMaps, ONE_CONDITION_PER_KEY_ERR, Projection, +}; use extenddb_core::types::{ IndexType, KeyType, QueryInput, QueryOutput, Select, TableKeyInfo, VECTOR_INDEX_QUERY_NOT_SUPPORTED, @@ -44,7 +46,7 @@ use crate::{DispatchMetrics, DispatchResult}; /// Returns `DynamoDbError` for validation failures, missing tables, or storage errors. #[allow(clippy::cast_possible_wrap)] // item counts won't exceed i64::MAX pub async fn handle_query( - body: Value, + mut body: Value, ctx: &OperationContext, ) -> Result { // Pre-scanned before typed deserialization, sequentially: Query stops at @@ -60,7 +62,11 @@ pub async fn handle_query( clause: crate::EnumClause::Named("returnConsumedCapacity"), }], )?; - crate::validate_enum_fields( + // A second condition on one key attribute is reported ahead of an invalid + // Select (measured 2026-11-11: `pk = :a AND pk = :b` with Select `BOGUS` + // answers the duplicate), so an invalid Select is left out of the typed + // input and its error waits for that check below. + let select_check = crate::validate_enum_fields( &body, &[crate::EnumField { json_name: "Select", @@ -72,9 +78,44 @@ pub async fn handle_query( ], clause: crate::EnumClause::Named("select"), }], - )?; + ); + if select_check.is_err() + && let Some(fields) = body.as_object_mut() + { + fields.remove("Select"); + } let input: QueryInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; + // Build expression maps from request (used for expression-based parameters) + let maps = build_expression_maps( + input.expression_attribute_names.as_ref(), + input.expression_attribute_values.as_ref(), + ); + + // The key condition is parsed here because the service reports a second + // condition on one key attribute ahead of the Select, table, index and + // ConsistentRead checks (measured 2026-11-11: with `pk = :a AND pk = :b`, + // Select `BOGUS`, a missing table, IndexName `nope`, ConsistentRead on a + // GSI and Select `ALL_ATTRIBUTES` on a KEYS_ONLY GSI each answer the + // duplicate). The FilterExpression's own faults come first. Any other + // fault of the parse is reported further down. + let key_condition_parse = input + .key_condition_expression + .as_deref() + .map(|kce| crate::expression_helpers::parse_key_condition_expr(kce, &maps, &ctx.limits)); + if let Some(Err(DynamoDbError::ValidationException(msg))) = &key_condition_parse + && msg == ONE_CONDITION_PER_KEY_ERR + { + refuse_filter_faults( + input.filter_expression.as_deref(), + input.expression_attribute_names.as_ref(), + &maps, + &ctx.limits, + )?; + return Err(DynamoDbError::ValidationException(msg.clone())); + } + select_check?; + // P118: Fetch key_info first so we can use table_id for index lookup. let key_info = ctx .table_key_info(&input.table_name) @@ -199,12 +240,6 @@ pub async fn handle_query( // the expression-parameter-usage checks (matching real DynamoDB). reject_empty_key_condition_expression(input.key_condition_expression.as_deref())?; - // Build expression maps from request (used for expression-based parameters) - let maps = build_expression_maps( - input.expression_attribute_names.as_ref(), - input.expression_attribute_values.as_ref(), - ); - // Reject EAN/EAV supplied with no expression that references them. Legacy // KeyConditions does not count as an expression. Query emits no values suffix. let has_kce = input @@ -234,17 +269,13 @@ pub async fn handle_query( )?; // Parse KeyConditionExpression or desugar legacy KeyConditions - let (mut key_condition, legacy_kc_maps) = if let Some(kce_str) = - input.key_condition_expression.as_deref() - { - // The parse refuses, in this order, the first undefined `#name` or - // `:value` in the order the expression is written, a `begins_with` - // operand of the wrong type and a second condition on one key - // attribute, before the clauses are classified (measured 2026-10-31 - // and 2026-11-11). - let parsed = - crate::expression_helpers::parse_key_condition_expr(kce_str, &maps, &ctx.limits)?; - (parsed, None) + let (mut key_condition, legacy_kc_maps) = if let Some(parsed) = key_condition_parse { + // Parsed above. The parse refuses, in this order, the first undefined + // `#name` or `:value` in the order the expression is written, a + // `begins_with` operand of the wrong type and a second condition on + // one key attribute, before the clauses are classified (measured + // 2026-10-31 and 2026-11-11). + (parsed?, None) } else if let Some(ref kc) = input.key_conditions { let key_schema_pairs: Vec<(String, bool)> = query_key_info .key_schema @@ -703,6 +734,33 @@ fn refuse_begins_with_on_number( Ok(()) } +/// Refuse a `FilterExpression` fault that the service reports ahead of a +/// second condition on one key attribute. +/// +/// Measured 2026-11-11 (us-east-1), with `pk = :a AND pk = :b`: a filter +/// syntax error, a reserved word, an undefined `#name` or `:value`, and a +/// number in `begins_with` each answer the filter's own message. This runs +/// only for a key condition with that duplicate. +fn refuse_filter_faults( + filter: Option<&str>, + names: Option<&HashMap>, + maps: &ExpressionMaps, + limits: &extenddb_core::limits::LimitsConfig, +) -> Result<(), DynamoDbError> { + let Some(filter) = parse_optional_filter(filter, limits)? else { + return Ok(()); + }; + validate_name_refs_in_expr(&filter, names, ExpressionKind::Filter)?; + let mut placeholders = Vec::new(); + extenddb_core::expression::collect_value_placeholders(&filter, &mut placeholders); + for placeholder in &placeholders { + maps.resolve_value_for(placeholder, ExpressionKind::Filter.as_str())?; + } + extenddb_core::expression::validate_begins_with_operands(&filter, maps) + .and_then(|()| extenddb_core::expression::validate_ordering_operand_types(&filter, maps)) + .map_err(|e| crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter)) +} + /// Validate that all `#name` references in an expression AST are defined. fn validate_name_refs_in_expr( expr: &extenddb_core::expression::Expr, diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index 3aa118c86..b58baf589 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -18,6 +18,13 @@ expression and an undefined :value are reported ahead of the duplicate, and the duplicate is reported ahead of the type check and the unused-value check. +The order against the FilterExpression and the table, index, ConsistentRead +and Select checks was measured 2026-11-11T09:43Z in us-east-1 on a table with +the same key schema and a KEYS_ONLY global secondary index on g (S), two +sends each: a FilterExpression fault is reported ahead of the duplicate, and +the duplicate ahead of a missing table, an unknown index, ConsistentRead on +the index, an invalid Select and Select ALL_ATTRIBUTES on the index. + Dual-target against Amazon DynamoDB and extenddb. """ @@ -55,19 +62,31 @@ N1 = {"N": "1"} +KEYS_ONLY_INDEX = "g-keys" + + @pytest.fixture(scope="class") def range_table(dynamodb_client): - """pk (S) HASH, sk (S) RANGE, holding alice/bob and alice/carol.""" + """pk (S) HASH, sk (S) RANGE, holding alice/bob and alice/carol, with a + KEYS_ONLY global secondary index on g (S).""" with scoped_table( dynamodb_client, attribute_definitions=[ {"AttributeName": "pk", "AttributeType": "S"}, {"AttributeName": "sk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"}, ], key_schema=[ {"AttributeName": "pk", "KeyType": "HASH"}, {"AttributeName": "sk", "KeyType": "RANGE"}, ], + GlobalSecondaryIndexes=[ + { + "IndexName": KEYS_ONLY_INDEX, + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "KEYS_ONLY"}, + } + ], ) as name: for sk in ("bob", "carol"): dynamodb_client.put_item( @@ -316,3 +335,100 @@ def test_duplicate_reported_ahead_of_value_checks( code, msg = _error(lambda: dynamodb_client.query(**kwargs)) assert code == "ValidationException" assert msg == ONE_PER_KEY + + +class TestDuplicateAheadOfRequestChecks: + """Where the duplicate is reported against the FilterExpression and the + table, index, ConsistentRead and Select checks (2026-11-11).""" + + @pytest.mark.parametrize( + ("filter_expr", "values", "want"), + [ + ( + "#q = :a", + {":a": A, ":b": B}, + "Invalid FilterExpression: An expression attribute name used in " + "the document path is not defined; attribute name: #q", + ), + ( + "foo = :zz", + {":a": A, ":b": B}, + "Invalid FilterExpression: An expression attribute value used in " + "expression is not defined; attribute value: :zz", + ), + ( + "begins_with(foo, :n)", + {":a": A, ":b": B, ":n": N1}, + "Invalid FilterExpression: Incorrect operand type for operator or " + "function; operator or function: begins_with, operand type: N", + ), + ( + "name = :a", + {":a": A, ":b": B}, + "Invalid FilterExpression: Attribute name is a reserved keyword; " + "reserved keyword: name", + ), + ], + ids=["undefined-name", "undefined-value", "begins-with-number", "reserved-word"], + ) + def test_filter_fault_reported_ahead_of_duplicate( + self, dynamodb_client, range_table, filter_expr, values, want + ): + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a AND pk = :b", + FilterExpression=filter_expr, + ExpressionAttributeValues=values, + ) + ) + assert code == "ValidationException" + assert msg == want + + def test_filter_syntax_error_reported_ahead_of_duplicate( + self, dynamodb_client, range_table + ): + """The service answers `Invalid FilterExpression: Syntax error; token: + "=", near: "= = :a"`; extenddb words its syntax errors differently, so + only the expression the error names is compared.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a AND pk = :b", + FilterExpression="zz = = :a", + ExpressionAttributeValues={":a": A, ":b": B}, + ) + ) + assert code == "ValidationException" + assert msg.startswith("Invalid FilterExpression: "), msg + + @pytest.mark.parametrize( + ("kwargs", "on_index"), + [ + ({"TableName": "extenddb-test-484-no-such-table"}, False), + ({"IndexName": "nope"}, False), + ({"IndexName": KEYS_ONLY_INDEX, "ConsistentRead": True}, True), + ({"Select": "BOGUS"}, False), + ({"IndexName": KEYS_ONLY_INDEX, "Select": "ALL_ATTRIBUTES"}, True), + ], + ids=[ + "missing-table", + "unknown-index", + "consistent-read-on-gsi", + "invalid-select", + "all-attributes-on-keys-only-gsi", + ], + ) + def test_duplicate_reported_ahead_of_table_index_and_select_checks( + self, dynamodb_client, range_table, kwargs, on_index + ): + key = "g" if on_index else "pk" + request = { + "TableName": range_table, + "KeyConditionExpression": f"{key} = :a AND {key} = :b", + "ExpressionAttributeValues": {":a": A, ":b": B}, + **kwargs, + } + code, msg = _error(lambda: dynamodb_client.query(**request)) + assert code == "ValidationException" + assert msg == ONE_PER_KEY From ef09b476f015bf3bd5ccb3258e9351c988557304 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:42:57 +0000 Subject: [PATCH 05/29] test(query): compare the exact undefined name message test_undefined_name_reported_ahead_of_duplicate checked that the message contained the undefined name text. It passed on a message without the `Invalid KeyConditionExpression: ` prefix. It now compares the whole message with UNDEFINED_NAME_EXACT. That is the service's text for `#u = :a AND #u = :b` with no ExpressionAttributeNames, measured in us-east-1 on 24 Oct 2026. --- tests/test_query_key_condition_one_per_key.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index b58baf589..b0f86f5e7 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -46,11 +46,10 @@ REDUNDANT_PARENS = ( "Invalid KeyConditionExpression: The expression has redundant parentheses;" ) -UNDEFINED_NAME = ( - "An expression attribute name used in the document path is not defined; " - "attribute name: #u" +UNDEFINED_NAME_EXACT = ( + "Invalid KeyConditionExpression: An expression attribute name used in the " + "document path is not defined; attribute name: #u" ) -UNDEFINED_NAME_EXACT = "Invalid KeyConditionExpression: " + UNDEFINED_NAME UNDEFINED_VALUE_A = ( "Invalid KeyConditionExpression: An expression attribute value used in " "expression is not defined; attribute value: :a" @@ -265,7 +264,7 @@ def test_undefined_name_reported_ahead_of_duplicate( ) ) assert code == "ValidationException" - assert UNDEFINED_NAME in msg + assert msg == UNDEFINED_NAME_EXACT class TestDuplicateCheckOrder: From f910fa554a7585ab51bf3cd652e981a3e85e5550 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:44:12 +0000 Subject: [PATCH 06/29] test(query): pin the measured reference and operator order on the wire tests/test_query_key_condition_one_per_key.py gets the requests behind the reference order and operator change, each with the service's answer: - The first undefined reference in the order the expression is written, a #name or a :value, with or without a duplicate. Measured in us-east-1 on 11 Nov 2026. - An undefined reference ahead of an unused name or value (measured on 10 and 11 Nov 2026). The 10 Nov rows were sent to a table keyed on pk (S) alone. The test table also has sk (S) as its sort key, and none of these requests names it. - `pk = :a AND pk <> :b` and `pk = :a AND contains(pk, :b)` answer the one-condition-per-key message (measured on 11 Nov 2026). - `pk = :a AND begins_with(sk, :n) AND sk = :b` with `:n` a number answers the begins_with operand type message (measured on 11 Nov 2026). Every send in both runs got the same answer twice. --- tests/test_query_key_condition_one_per_key.py | 83 ++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index b0f86f5e7..420a3bb54 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -23,7 +23,13 @@ the same key schema and a KEYS_ONLY global secondary index on g (S), two sends each: a FilterExpression fault is reported ahead of the duplicate, and the duplicate ahead of a missing table, an unknown index, ConsistentRead on -the index, an invalid Select and Select ALL_ATTRIBUTES on the index. +the index, an invalid Select and Select ALL_ATTRIBUTES on the index. In the +same run the first undefined reference in the order the expression is written +was reported, a #name or a :value, with or without a duplicate; `<>` and +`contains` beside a duplicate answered the duplicate; and a number in +begins_with answered its operand type error ahead of it. On 2026-11-10 an +undefined reference was reported ahead of an unused name or value, on a table +keyed on pk (S) alone. Dual-target against Amazon DynamoDB and extenddb. """ @@ -431,3 +437,78 @@ def test_duplicate_reported_ahead_of_table_index_and_select_checks( code, msg = _error(lambda: dynamodb_client.query(**request)) assert code == "ValidationException" assert msg == ONE_PER_KEY + + +def _undefined(reference: str) -> str: + """The service's message for an undefined `#name` or `:value`.""" + if reference.startswith("#"): + return ( + "Invalid KeyConditionExpression: An expression attribute name used in " + f"the document path is not defined; attribute name: {reference}" + ) + return ( + "Invalid KeyConditionExpression: An expression attribute value used in " + f"expression is not defined; attribute value: {reference}" + ) + + +class TestReferenceAndOperatorOrder: + """Which undefined reference is reported, and the operators beside a + duplicate (2026-11-10 and 2026-11-11).""" + + @pytest.mark.parametrize( + ("expr", "names", "values", "undefined"), + [ + ("pk = :q AND #u = :c", None, None, ":q"), + ("sk = :b AND pk = :a", None, None, ":b"), + ("pk = :a AND sk = :missing", None, {":a": A, ":extra": B}, ":missing"), + ("pk = :a AND pk = :b AND #u = :c", None, None, ":a"), + ("pk = :q AND pk = :b AND #u = :c", None, {":b": B, ":c": C}, ":q"), + ("#u = :a AND #u = :b", None, None, "#u"), + ("pk = :b AND pk = :a", None, None, ":b"), + # Measured 2026-11-10 on a table keyed on pk (S) alone; each + # request also carries an unused name or value. + ("pk = :v", None, {":w": A}, ":v"), + ("#k = :v", None, {":v": A, ":w": B}, "#k"), + ("#k = :v", {"#j": "pk"}, {":v": A}, "#k"), + ("pk = :v", {"#j": "pk"}, {":w": A}, ":v"), + ("#k = :v", None, {":w": A}, "#k"), + ], + ) + def test_first_undefined_reference_in_text_order_is_reported( + self, dynamodb_client, range_table, expr, names, values, undefined + ): + kwargs = {"TableName": range_table, "KeyConditionExpression": expr} + if names is not None: + kwargs["ExpressionAttributeNames"] = names + if values is not None: + kwargs["ExpressionAttributeValues"] = values + code, msg = _error(lambda: dynamodb_client.query(**kwargs)) + assert code == "ValidationException" + assert msg == _undefined(undefined) + + @pytest.mark.parametrize( + ("expr", "values", "want"), + [ + ("pk = :a AND pk <> :b", {":a": A, ":b": B}, ONE_PER_KEY), + ("pk = :a AND contains(pk, :b)", {":a": A, ":b": B}, ONE_PER_KEY), + ( + "pk = :a AND begins_with(sk, :n) AND sk = :b", + {":a": A, ":b": B, ":n": N1}, + "Invalid KeyConditionExpression: Incorrect operand type for operator " + "or function; operator or function: begins_with, operand type: N", + ), + ], + ) + def test_operators_beside_a_duplicate( + self, dynamodb_client, range_table, expr, values, want + ): + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression=expr, + ExpressionAttributeValues=values, + ) + ) + assert code == "ValidationException" + assert msg == want From 968d084e2acd097ec6c46761b11052b4b6101d76 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:45:22 +0000 Subject: [PATCH 07/29] refactor(core): mark the classifier's duplicate check as the map-less guard resolve_multipart_with refused a second condition on one key attribute with its own copy of the message. The engine never reaches that branch with a duplicate, since parse_key_condition_with_maps refuses one before the clauses are classified. Authorization still parses with the map-less parse_key_condition when it finds dynamodb:LeadingKeys, and keeps the binding it had for such a condition. On a multi-attribute key schema the branch is what refuses the duplicate there. The branch stays, with a comment that says so, and returns ONE_CONDITION_PER_KEY_ERR. No answer changes. --- crates/core/src/expression/key_condition.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 62b142e2f..6e5df35a0 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -241,9 +241,11 @@ impl KeyCondition { .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). + // One condition per key attribute. The engine parses a request's key + // condition with `parse_key_condition_with_maps`, which refuses a + // second condition on one key attribute before this runs. This guards + // the map-less `parse_key_condition`, which authorization reads for + // `dynamodb:LeadingKeys`. 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) @@ -251,11 +253,7 @@ impl KeyCondition { || 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(), - )); + return Err(validation_err(ONE_CONDITION_PER_KEY_ERR)); } // More conditions than key attributes (measured 2026-10-21: the count From a6c9fdf5b66503eddd281bb5f295248f821ba10e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:47:37 +0000 Subject: [PATCH 08/29] test(engine): keep two rows in the key condition parse test key_condition_duplicate_check_order_matches_the_service repeated eight order rows that the core tests and the wire file already cover. What it adds is that parse_key_condition_expr passes the request's maps to the parse, with the `#` and `:` keys a request carries. Two rows show that: `#p = :a AND pk = :b` with `#p` defined as pk answers the one-condition-per-key message, and `pk = :a AND pk = :b AND #u = :c` answers the undefined name message for `#u`. The test is renamed key_condition_parse_reads_the_request_maps, and the file is 74 lines shorter. --- crates/engine/src/expression_helpers.rs | 114 +++++------------------- 1 file changed, 20 insertions(+), 94 deletions(-) diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 4f891710c..05396c1b8 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -415,110 +415,36 @@ mod tests { ); } - /// A key condition request and the message it answers: the expression, - /// its `#`-prefixed names, its `:`-prefixed values (`None` for no - /// `ExpressionAttributeValues`) and the expected message. - type KceCase = ( - &'static str, - Vec<(&'static str, &'static str)>, - Option>, - &'static str, - ); - - /// Parse `expr` as `Query` does, with `#`-prefixed `names` and - /// `:`-prefixed `values` as a request carries them. - fn parse_kce( - expr: &str, - names: &[(&str, &str)], - values: Option<&[(&str, AttributeValue)]>, - ) -> Result { - let names: HashMap = names - .iter() - .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) - .collect(); - let values: Option> = values.map(|vs| { - vs.iter() - .map(|(k, v)| ((*k).to_owned(), v.clone())) - .collect() - }); - let maps = build_expression_maps(Some(&names), values.as_ref()); - parse_key_condition_expr(expr, &maps, &LimitsConfig::default()) - } - - /// The order of the one-condition-per-key check through the engine's - /// entry point, on the requests measured 2026-10-31 (table `pk` S HASH, - /// `sk` S RANGE). The key value type check and the unused-value check - /// run after this parse. + /// `parse_key_condition_expr` reads the request's `ExpressionAttributeNames` + /// and `ExpressionAttributeValues`, keyed with `#` and `:` as a request + /// carries them: a duplicate written through `#p` and an undefined `#u` + /// each answer the service's message. The core tests cover the other + /// rows. #[test] - fn key_condition_duplicate_check_order_matches_the_service() { - const ONE_PER_KEY: &str = "Invalid KeyConditionExpression: KeyConditionExpressions \ - must only contain one condition per key"; - const UNDEFINED_U: &str = "Invalid KeyConditionExpression: An expression attribute \ - name used in the document path is not defined; attribute \ - name: #u"; - const UNDEFINED_A: &str = "Invalid KeyConditionExpression: An expression attribute \ - value used in expression is not defined; attribute value: :a"; - let s = |v: &str| AttributeValue::S(v.to_owned()); - let n = AttributeValue::N("1".to_owned()); - let abc = [(":a", s("alice")), (":b", s("bob")), (":c", s("carol"))]; - let cases: Vec = vec![ - ( - "pk = :a AND pk = :b", - vec![], - Some(abc[..2].to_vec()), - ONE_PER_KEY, - ), - ( - "#p = :a AND pk = :n", - vec![("#p", "pk")], - Some(vec![(":a", s("alice")), (":n", n.clone())]), - ONE_PER_KEY, - ), - ( - "pk = :a AND #s = :b AND sk = :n", - vec![("#s", "sk")], - Some(vec![ - (":a", s("alice")), - (":b", s("bob")), - (":n", n.clone()), - ]), - ONE_PER_KEY, - ), + fn key_condition_parse_reads_the_request_maps() { + let names: HashMap = [("#p".to_owned(), "pk".to_owned())].into(); + let values: HashMap = [":a", ":b", ":c"] + .into_iter() + .map(|k| (k.to_owned(), AttributeValue::S("v".to_owned()))) + .collect(); + let maps = build_expression_maps(Some(&names), Some(&values)); + for (expr, want) in [ ( - "#u = :a AND sk = :b AND sk = :c", - vec![], - Some(abc.to_vec()), - UNDEFINED_U, + "#p = :a AND pk = :b", + "Invalid KeyConditionExpression: KeyConditionExpressions must only contain \ + one condition per key", ), ( "pk = :a AND pk = :b AND #u = :c", - vec![], - Some(abc.to_vec()), - UNDEFINED_U, - ), - ("pk = :a AND pk = :b", vec![], None, UNDEFINED_A), - ( - "pk = :a AND pk = :b", - vec![], - Some(vec![(":a", s("alice")), (":b", s("bob")), (":z", s("zed"))]), - ONE_PER_KEY, - ), - ( - "#u = :a AND #u > :b", - vec![], - Some(abc[..2].to_vec()), - UNDEFINED_U, + "Invalid KeyConditionExpression: An expression attribute name used in the \ + document path is not defined; attribute name: #u", ), - ]; - for (expr, names, values, want) in cases { - let got = parse_kce(expr, &names, values.as_deref()); + ] { + let got = parse_key_condition_expr(expr, &maps, &LimitsConfig::default()); assert!( matches!(&got, Err(DynamoDbError::ValidationException(msg)) if msg == want), "expr {expr}: got {got:?}" ); } - // Without a duplicate the parse leaves the value to the later checks. - let got = parse_kce("pk = :n", &[], Some(&[(":n", n)])); - assert!(got.is_ok(), "pk = :n: got {got:?}"); } } From 1f722e062e3cc73f9033348b63725b2860704552 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:48:55 +0000 Subject: [PATCH 09/29] style: apply rustfmt to the key condition and LeadingKeys changes Earlier commits on this branch left five spots unformatted. cargo +1.97.0 fmt --all rewraps a statement, a constant, three test table rows and an assertion in key_condition.rs. It also joins one loop header in leading_keys/tests.rs. No code changes. --- crates/core/src/expression/key_condition.rs | 30 +++++++++++++-------- crates/server/src/leading_keys/tests.rs | 5 +--- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 6e5df35a0..73f0d7660 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -1025,8 +1025,8 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result Result :b` answers the /// one-condition-per-key message). -const NE_UNSUPPORTED: &str = "Invalid KeyConditionExpression: Unsupported operator on KeyCondition: NE"; +const NE_UNSUPPORTED: &str = + "Invalid KeyConditionExpression: Unsupported operator on KeyCondition: NE"; /// The refusal of a clause with no comparison operator, and of a `contains` /// clause. A second condition on the same attribute is reported ahead of @@ -2198,8 +2199,16 @@ mod tests { let none = HashMap::new(); for (expr, values, want) in [ // Every placeholder defined, `#u` the only undefined reference. - ("#u = :a AND #u = :b", values_of("#u = :a AND #u = :b"), "#u"), - ("#u = :a AND #u > :b", values_of("#u = :a AND #u > :b"), "#u"), + ( + "#u = :a AND #u = :b", + values_of("#u = :a AND #u = :b"), + "#u", + ), + ( + "#u = :a AND #u > :b", + values_of("#u = :a AND #u > :b"), + "#u", + ), ( "#u = :a AND sk = :b AND sk = :c", values_of("#u = :a AND sk = :b AND sk = :c"), @@ -2221,11 +2230,7 @@ mod tests { ("sk = :b AND pk = :a", no_values(), ":b"), ("pk = :b AND pk = :a", no_values(), ":b"), ("pk = :a AND pk = :b AND #u = :c", no_values(), ":a"), - ( - "pk = :q AND pk = :b AND #u = :c", - values_of(":b :c"), - ":q", - ), + ("pk = :q AND pk = :b AND #u = :c", values_of(":b :c"), ":q"), ("pk = :a AND pk = :missing", values_of(":a"), ":missing"), ("#k = :v", no_values(), "#k"), ("pk = :v", no_values(), ":v"), @@ -2309,7 +2314,10 @@ mod tests { for expr in ["pk = :a AND pk <> :b", "pk = :a AND contains(pk, :b)"] { let tokens = tokenize(expr).unwrap(); assert!(parse_key_condition(&tokens).is_err(), "expr {expr}"); - assert!(key_condition_clause_operands(&tokens).is_err(), "expr {expr}"); + assert!( + key_condition_clause_operands(&tokens).is_err(), + "expr {expr}" + ); } } diff --git a/crates/server/src/leading_keys/tests.rs b/crates/server/src/leading_keys/tests.rs index e942824a9..a898dd9d7 100644 --- a/crates/server/src/leading_keys/tests.rs +++ b/crates/server/src/leading_keys/tests.rs @@ -661,10 +661,7 @@ fn query_unreadable_partition_equality_binds_no_other_clause() { /// measured. #[test] fn query_duplicate_key_condition_binds_the_partition_equality() { - for kce in [ - "pk = :own AND sk = :b AND sk = :c", - "pk = :own AND pk = :b", - ] { + for kce in ["pk = :own AND sk = :b AND sk = :c", "pk = :own AND pk = :b"] { let input = json!({ "TableName": "t", "KeyConditionExpression": kce, From c8bbdd050ef2fa9859f813087754a6f5391db009 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:40:04 +0000 Subject: [PATCH 10/29] fix(query): check the request's parameters ahead of a duplicate key condition The branch refused a key condition with two conditions on one key attribute right after deserialization. That put the refusal ahead of the checks main runs before the key condition parse. Those checks are Limit, the mixing of expression and non-expression parameters and an empty KeyConditionExpression. Then come expression names and values with no expression, and ConditionalOperator without a QueryFilter. Measured in us-east-1 on 11 Nov 2026, two sends each, the same answer both times, with `pk = :a AND pk = :b`: - ConditionalOperator `AND` and no QueryFilter answers "Can not use both expression and non-expression parameters in the same request: Non-expression parameters: {ConditionalOperator} Expression parameters: {KeyConditionExpression}". - KeyConditions beside the expression answers the same message with `{KeyConditions}`. These checks move into check_request_parameters, in main's order. A request with a duplicate runs them before its filter checks and the duplicate refusal. Any other request runs them where main did, after the table, index, ConsistentRead and Select checks. The duplicate stays ahead of those four (measured on 11 Nov 2026). The Limit order is not measured, since the SDK refuses Limit 0 before it sends the request. Limit keeps main's place ahead of the parse. The branch also checked an invalid Select after a body that does not deserialize, where main checked it before. Main's order is back: when the body does not deserialize, an invalid Select is reported first. tests/test_query_key_condition_one_per_key.py pins the two measured messages. --- crates/engine/src/query.rs | 171 ++++++++++-------- tests/test_query_key_condition_one_per_key.py | 35 ++++ 2 files changed, 134 insertions(+), 72 deletions(-) diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 3e5b5d284..448cce564 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -84,7 +84,15 @@ pub async fn handle_query( { fields.remove("Select"); } - let input: QueryInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; + // An invalid Select still comes ahead of a body that does not + // deserialize, as it did when it was checked before deserialization. + let input: QueryInput = match serde_json::from_value(body) { + Ok(input) => input, + Err(err) => { + select_check?; + return Err(crate::deserialize_error(err)); + } + }; // Build expression maps from request (used for expression-based parameters) let maps = build_expression_maps( @@ -97,8 +105,11 @@ pub async fn handle_query( // ConsistentRead checks (measured 2026-11-11: with `pk = :a AND pk = :b`, // Select `BOGUS`, a missing table, IndexName `nope`, ConsistentRead on a // GSI and Select `ALL_ATTRIBUTES` on a KEYS_ONLY GSI each answer the - // duplicate). The FilterExpression's own faults come first. Any other - // fault of the parse is reported further down. + // duplicate). The checks of the request's parameters that come before the + // parse, and the FilterExpression's own faults, are reported first + // (measured 2026-11-11: ConditionalOperator, or KeyConditions, beside the + // expression answers the parameter mixing error). Any other fault of the + // parse is reported further down. let key_condition_parse = input .key_condition_expression .as_deref() @@ -106,6 +117,7 @@ pub async fn handle_query( if let Some(Err(DynamoDbError::ValidationException(msg))) = &key_condition_parse && msg == ONE_CONDITION_PER_KEY_ERR { + check_request_parameters(&input)?; refuse_filter_faults( input.filter_expression.as_deref(), input.expression_attribute_names.as_ref(), @@ -178,14 +190,7 @@ pub async fn handle_query( validate_query_select_index_support(input.select, index_info.as_ref())?; } - // Validate Limit >= 1 (REQ-QUERY-001) - if let Some(limit) = input.limit - && limit < 1 - { - return Err(DynamoDbError::ValidationException( - "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1".to_owned(), - )); - } + check_request_parameters(&input)?; // For index queries, build a key_info that reflects the index's key schema // so the storage layer uses the correct SK column for the index table. @@ -207,67 +212,6 @@ pub async fn handle_query( key_info.clone() }; - // --- Legacy vs expression mutual exclusivity checks --- - let kce_present = input.key_condition_expression.is_some(); - let has_kc = input.key_conditions.as_ref().is_some_and(|m| !m.is_empty()); - let has_fe = input.filter_expression.is_some(); - let has_qf = input.query_filter.as_ref().is_some_and(|m| !m.is_empty()); - let has_pe = input.projection_expression.is_some(); - let has_atg = input - .attributes_to_get - .as_ref() - .is_some_and(|a| !a.is_empty()); - let has_cond_op = input.conditional_operator.is_some(); - - // KeyConditions legitimately combines with FilterExpression and - // ProjectionExpression, so it joins the mixing check only when - // KeyConditionExpression is also present. - extenddb_core::validation::validate_no_expression_param_mixing( - &[ - ("AttributesToGet", has_atg), - ("QueryFilter", has_qf), - ("ConditionalOperator", has_cond_op), - ("KeyConditions", has_kc && kce_present), - ], - &[ - ("ProjectionExpression", has_pe), - ("FilterExpression", has_fe), - ("KeyConditionExpression", kce_present), - ], - )?; - - // An explicitly empty KeyConditionExpression is rejected up front, before - // the expression-parameter-usage checks (matching real DynamoDB). - reject_empty_key_condition_expression(input.key_condition_expression.as_deref())?; - - // Reject EAN/EAV supplied with no expression that references them. Legacy - // KeyConditions does not count as an expression. Query emits no values suffix. - let has_kce = input - .key_condition_expression - .as_ref() - .is_some_and(|s| !s.is_empty()); - let has_filter_expr = input - .filter_expression - .as_ref() - .is_some_and(|s| !s.is_empty()); - let has_proj_expr = input - .projection_expression - .as_ref() - .is_some_and(|s| !s.is_empty()); - extenddb_core::expression::validate_expression_param_usage( - input.expression_attribute_names.as_ref(), - has_kce || has_filter_expr || has_proj_expr, - input.expression_attribute_values.as_ref(), - has_kce || has_filter_expr, - &[], - )?; - - // ConditionalOperator requires a QueryFilter with two or more conditions. - extenddb_core::validation::validate_conditional_operator_usage( - has_cond_op, - input.query_filter.as_ref().map_or(0, HashMap::len), - )?; - // Parse KeyConditionExpression or desugar legacy KeyConditions let (mut key_condition, legacy_kc_maps) = if let Some(parsed) = key_condition_parse { // Parsed above. The parse refuses, in this order, the first undefined @@ -734,6 +678,89 @@ fn refuse_begins_with_on_number( Ok(()) } +/// The checks of a request's parameters that run before the key condition +/// parse, in this order: `Limit`, the mixing of expression and non-expression +/// parameters, an empty `KeyConditionExpression`, `ExpressionAttributeNames` +/// and `ExpressionAttributeValues` with no expression that uses them, and +/// `ConditionalOperator` without a `QueryFilter` of two or more conditions. +/// +/// `handle_query` runs these after the table, index, `ConsistentRead` and +/// `Select` checks, and, for a key condition with a second condition on one +/// key attribute, ahead of them and ahead of that refusal (measured +/// 2026-11-11: `pk = :a AND pk = :b` with `ConditionalOperator` `AND` and no +/// `QueryFilter`, or with `KeyConditions`, answers the mixing error). +fn check_request_parameters(input: &QueryInput) -> Result<(), DynamoDbError> { + // Validate Limit >= 1 (REQ-QUERY-001) + if let Some(limit) = input.limit + && limit < 1 + { + return Err(DynamoDbError::ValidationException( + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1".to_owned(), + )); + } + + // --- Legacy vs expression mutual exclusivity checks --- + let kce_present = input.key_condition_expression.is_some(); + let has_kc = input.key_conditions.as_ref().is_some_and(|m| !m.is_empty()); + let has_fe = input.filter_expression.is_some(); + let has_qf = input.query_filter.as_ref().is_some_and(|m| !m.is_empty()); + let has_pe = input.projection_expression.is_some(); + let has_atg = input + .attributes_to_get + .as_ref() + .is_some_and(|a| !a.is_empty()); + let has_cond_op = input.conditional_operator.is_some(); + + // KeyConditions legitimately combines with FilterExpression and + // ProjectionExpression, so it joins the mixing check only when + // KeyConditionExpression is also present. + extenddb_core::validation::validate_no_expression_param_mixing( + &[ + ("AttributesToGet", has_atg), + ("QueryFilter", has_qf), + ("ConditionalOperator", has_cond_op), + ("KeyConditions", has_kc && kce_present), + ], + &[ + ("ProjectionExpression", has_pe), + ("FilterExpression", has_fe), + ("KeyConditionExpression", kce_present), + ], + )?; + + // An explicitly empty KeyConditionExpression is rejected up front, before + // the expression-parameter-usage checks (matching real DynamoDB). + reject_empty_key_condition_expression(input.key_condition_expression.as_deref())?; + + // Reject EAN/EAV supplied with no expression that references them. Legacy + // KeyConditions does not count as an expression. Query emits no values suffix. + let has_kce = input + .key_condition_expression + .as_ref() + .is_some_and(|s| !s.is_empty()); + let has_filter_expr = input + .filter_expression + .as_ref() + .is_some_and(|s| !s.is_empty()); + let has_proj_expr = input + .projection_expression + .as_ref() + .is_some_and(|s| !s.is_empty()); + extenddb_core::expression::validate_expression_param_usage( + input.expression_attribute_names.as_ref(), + has_kce || has_filter_expr || has_proj_expr, + input.expression_attribute_values.as_ref(), + has_kce || has_filter_expr, + &[], + )?; + + // ConditionalOperator requires a QueryFilter with two or more conditions. + extenddb_core::validation::validate_conditional_operator_usage( + has_cond_op, + input.query_filter.as_ref().map_or(0, HashMap::len), + ) +} + /// Refuse a `FilterExpression` fault that the service reports ahead of a /// second condition on one key attribute. /// diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index 420a3bb54..9fec1f6a8 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -438,6 +438,41 @@ def test_duplicate_reported_ahead_of_table_index_and_select_checks( assert code == "ValidationException" assert msg == ONE_PER_KEY + @pytest.mark.parametrize( + ("kwargs", "non_expression"), + [ + ({"ConditionalOperator": "AND"}, "ConditionalOperator"), + ( + { + "KeyConditions": { + "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [A]} + } + }, + "KeyConditions", + ), + ], + ids=["conditional-operator", "key-conditions"], + ) + def test_parameter_mixing_reported_ahead_of_duplicate( + self, dynamodb_client, range_table, kwargs, non_expression + ): + """Measured 2026-11-11T11:23Z: a non-expression parameter beside the + expression answers the mixing error, not the duplicate.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a AND pk = :b", + ExpressionAttributeValues={":a": A, ":b": B}, + **kwargs, + ) + ) + assert code == "ValidationException" + assert msg == ( + "Can not use both expression and non-expression parameters in the same " + f"request: Non-expression parameters: {{{non_expression}}} Expression " + "parameters: {KeyConditionExpression}" + ) + def _undefined(reference: str) -> str: """The service's message for an undefined `#name` or `:value`.""" From 9f5c7437fc6a3f70ccc79a1c8288c7e0838ad28e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:43:12 +0000 Subject: [PATCH 11/29] fix(core): keep the parser's refusal for other <> and contains shapes The reference order change parsed every `<>` and `contains(...)` clause to its end and refused it after the duplicate check. A clause of another shape then got a different message from the one main gave. Main answers "expected comparison operator" for `pk = :a AND contains(sk)`. The branch answered "expected ','", and `pk = :a AND sk <> sk2` answered the placeholder message in place of "Unsupported operator on KeyCondition: NE". No measurement covers those texts. Only three shapes now wait for the duplicate check: `name <> :value`, `:value <> name` and `contains(name, :value)`, with one top-level attribute and the measured lowercase spelling. Measured in us-east-1 on 11 Nov 2026, these answer an undefined name or the duplicate first. Any other `<>` or `contains` clause is refused where the parser meets it, with main's message. The service answers `pk = :a AND contains(sk)` with "Incorrect number of operands for operator or function; operator or function: contains, number of operands: 1" (measured on 11 Nov 2026). This change keeps main's text for it. A core test covers the shapes. --- crates/core/src/expression/key_condition.rs | 110 +++++++++++++++++--- 1 file changed, 96 insertions(+), 14 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 73f0d7660..54a711204 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -962,25 +962,40 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result { + single_attribute_path(attr) + } + _ => None, + }; + let Some(path) = path else { + return Err(validation_err(EXPECTED_COMPARISON_OPERATOR)); + }; + *pos += 6; + return Ok(RawClause::Unsupported(path, EXPECTED_COMPARISON_OPERATOR)); } // path op :value | :value op path | path BETWEEN :lo AND :hi @@ -999,10 +1014,16 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result name` with one top-level attribute is refused once a + // second condition on that attribute has been looked for. Any + // other `<>` clause is refused here, as before. if op == CompareOp::Ne { - return Ok(RawClause::Unsupported(path, NE_UNSUPPORTED)); + return match parse_key_operand_path(tokens, pos) { + Ok(path) if path.len() == 1 => Ok(RawClause::Unsupported(path, NE_UNSUPPORTED)), + _ => Err(validation_err(NE_UNSUPPORTED)), + }; } + let path = parse_key_operand_path(tokens, pos)?; // Key conditions are stored path-first, so reverse the operator when // the source expression puts the value placeholder on the left. let op = reverse_comparator(op); @@ -1029,17 +1050,38 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result :value` with one top-level attribute is refused once a second + // condition on that attribute has been looked for. Any other `<>` clause + // is refused here, as before. + if op == CompareOp::Ne { + return match tokens.get(*pos) { + Some(Token::Placeholder(_)) if path.len() == 1 => { + *pos += 1; + Ok(RawClause::Unsupported(path, NE_UNSUPPORTED)) + } + _ => Err(validation_err(NE_UNSUPPORTED)), + }; + } + let value = parse_key_value(tokens, pos)?; - if op == CompareOp::Ne { - Ok(RawClause::Unsupported(path, NE_UNSUPPORTED)) - } else if op == CompareOp::Eq { + if op == CompareOp::Eq { Ok(RawClause::Eq(path, value)) } else { Ok(RawClause::Compare(path, op, value)) } } +/// The path of a `#name` or plain attribute token, or `None` for any other +/// token. +fn single_attribute_path(token: &Token) -> Option> { + match token { + Token::Ident(name) => Some(vec![PathElement::Attribute(name.clone())]), + Token::NameRef(name) => Some(vec![PathElement::Attribute(format!("#{name}"))]), + _ => None, + } +} + /// A key condition allows `=`, `<`, `<=`, `>` and `>=`, and refuses `<>` with /// this. A second condition on the same attribute is reported first /// (measured 2026-11-11: `pk = :a AND pk <> :b` answers the @@ -2321,6 +2363,46 @@ mod tests { } } + /// Only `name <> :value`, `:value <> name` and `contains(name, :value)`, + /// with one top-level attribute, wait for the duplicate check. Any other + /// `<>` or `contains` clause is refused where the parser meets it, with + /// the message it gave before, ahead of a duplicate. The service's text + /// for these shapes differs and is not changed here (measured 2026-11-11 + /// for `pk = :a AND contains(sk)`). + #[test] + fn other_ne_and_contains_clauses_keep_their_refusal() { + let values = values_of(":a :b :c"); + let none = HashMap::new(); + for (expr, want) in [ + ("pk = :a AND contains(sk)", EXPECTED_COMPARISON_OPERATOR), + ("pk = :a AND contains(pk)", EXPECTED_COMPARISON_OPERATOR), + ( + "pk = :a AND contains(sk, :b, :c)", + EXPECTED_COMPARISON_OPERATOR, + ), + ("pk = :a AND contains(:b, sk)", EXPECTED_COMPARISON_OPERATOR), + ("pk = :a AND contains(sk, sk)", EXPECTED_COMPARISON_OPERATOR), + ( + "pk = :a AND contains(pk.x, :b)", + EXPECTED_COMPARISON_OPERATOR, + ), + ("pk = :a AND CONTAINS(pk, :b)", EXPECTED_COMPARISON_OPERATOR), + ("pk = :a AND pk <> pk", NE_UNSUPPORTED), + ("pk = :a AND pk.x <> :b", NE_UNSUPPORTED), + ("pk = :a AND :b <> pk.x", NE_UNSUPPORTED), + ("pk = :a AND :b <> :c", NE_UNSUPPORTED), + ] { + assert_refused(parse_with(expr, &none, &values), want, expr); + } + // A `<>` with nothing after it. + let tokens = tokenize("pk = :a AND pk <>").unwrap(); + assert_refused( + parse_key_condition_with_maps(&tokens, &ExpressionMaps::new(none, values)), + NE_UNSUPPORTED, + "pk = :a AND pk <>", + ); + } + #[test] fn nested_path_reported_ahead_of_duplicate() { // Measured 2026-10-24: both of these answer their own message, not the From a056da22489fee8c8f1d000935bf5d483c869527 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:45:26 +0000 Subject: [PATCH 12/29] test(query): pin the measured operator and operand order on the wire tests/test_query_key_condition_one_per_key.py gets the rows measured in us-east-1 on 11 Nov 2026, two sends each, the same answer both times: - `pk = :a AND begins_with(sk, :n)` with `:n` a number and no duplicate answers the begins_with operand type message. - `pk = :a AND sk <> :b AND #u = :c` and `pk = :a AND contains(sk, :b) AND #u = :c` with no names answer the undefined name message for `#u`. - `pk = :a AND sk <> :b AND sk = :c` and `pk = :a AND contains(sk, :b) AND sk = :c` answer the one-condition-per-key message. - `pk = :a AND sk <> :b AND` answers a syntax error. ExtendDB words its syntax errors differently, so the test checks the prefix and that the operator is not named. The begins_with operand type message becomes a module constant, and the module docstring lists the new measurements. --- tests/test_query_key_condition_one_per_key.py | 73 ++++++++++++++++++- 1 file changed, 70 insertions(+), 3 deletions(-) diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index 9fec1f6a8..6ecd04585 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -29,7 +29,12 @@ `contains` beside a duplicate answered the duplicate; and a number in begins_with answered its operand type error ahead of it. On 2026-11-10 an undefined reference was reported ahead of an unused name or value, on a table -keyed on pk (S) alone. +keyed on pk (S) alone. At 11:22Z and 11:23Z the same day, on the table with +the index: ConditionalOperator or KeyConditions beside the expression +answered the parameter mixing error ahead of the duplicate; an undefined name, +a later syntax error and a duplicate on sk were each reported ahead of `<>` +and contains; and a number in begins_with answered its operand type error +without a duplicate too. Dual-target against Amazon DynamoDB and extenddb. """ @@ -60,6 +65,10 @@ "Invalid KeyConditionExpression: An expression attribute value used in " "expression is not defined; attribute value: :a" ) +BEGINS_WITH_N = ( + "Invalid KeyConditionExpression: Incorrect operand type for operator or " + "function; operator or function: begins_with, operand type: N" +) A = {"S": "alice"} B = {"S": "bob"} @@ -530,8 +539,15 @@ def test_first_undefined_reference_in_text_order_is_reported( ( "pk = :a AND begins_with(sk, :n) AND sk = :b", {":a": A, ":b": B, ":n": N1}, - "Invalid KeyConditionExpression: Incorrect operand type for operator " - "or function; operator or function: begins_with, operand type: N", + BEGINS_WITH_N, + ), + # Measured 2026-11-11T11:23Z: `<>` or contains beside a second + # condition on sk. + ("pk = :a AND sk <> :b AND sk = :c", {":a": A, ":b": B, ":c": C}, ONE_PER_KEY), + ( + "pk = :a AND contains(sk, :b) AND sk = :c", + {":a": A, ":b": B, ":c": C}, + ONE_PER_KEY, ), ], ) @@ -547,3 +563,54 @@ def test_operators_beside_a_duplicate( ) assert code == "ValidationException" assert msg == want + + @pytest.mark.parametrize( + ("expr", "values", "want"), + [ + # A number in begins_with on an S sort key, with no duplicate: the + # operand type, not the key value type. + ("pk = :a AND begins_with(sk, :n)", {":a": A, ":n": N1}, BEGINS_WITH_N), + # An undefined name beside `<>` or contains: the name. + ( + "pk = :a AND sk <> :b AND #u = :c", + {":a": A, ":b": B, ":c": C}, + _undefined("#u"), + ), + ( + "pk = :a AND contains(sk, :b) AND #u = :c", + {":a": A, ":b": B, ":c": C}, + _undefined("#u"), + ), + ], + ) + def test_operators_and_operands_without_a_duplicate( + self, dynamodb_client, range_table, expr, values, want + ): + """Measured 2026-11-11T11:22Z.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression=expr, + ExpressionAttributeValues=values, + ) + ) + assert code == "ValidationException" + assert msg == want + + def test_syntax_error_after_ne_reported_ahead_of_it( + self, dynamodb_client, range_table + ): + """Measured 2026-11-11T11:23Z: the service answers `Invalid + KeyConditionExpression: Syntax error; token: "", near: "AND"`. + extenddb words its syntax errors differently, so the test checks + that a syntax error is reported and not the operator.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a AND sk <> :b AND", + ExpressionAttributeValues={":a": A, ":b": B}, + ) + ) + assert code == "ValidationException" + assert msg.startswith("Invalid KeyConditionExpression: "), msg + assert "operator" not in msg, msg From 5ea180d0ecb57e03e176a940e9a80d419eb5bca6 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:59:38 +0000 Subject: [PATCH 13/29] fix(query): check parameters, then the filter, then the key condition handle_query now checks every Query in the order the service does. First come the request's parameters, then every FilterExpression fault, then every KeyConditionExpression fault. The Select, table, index and ConsistentRead checks come after these. The branch used this order only for a key condition with two conditions on one key attribute. Any other key condition fault came after the table, and the filter was checked after the key condition. Measured in us-east-1 on 11 Nov 2026, two sends each, the same answer both times. The table has pk (S) HASH, sk (S) RANGE and a KEYS_ONLY global secondary index on g (S): - An undefined filter `#q` or a filter syntax error answers ahead of an undefined key condition `:missing`. An undefined filter `#q` or `:zz` answers ahead of an undefined key condition `#s`. An undefined filter `#q` answers ahead of a number in begins_with and ahead of a trailing AND in the key condition. - With a valid filter, the undefined key condition `:missing` answers. - ConditionalOperator beside `pk = :a` answers the parameter mixing error with a missing table, IndexName `nope`, Select `BOGUS` and ConsistentRead on the index. - An undefined filter `#q` answers ahead of the same four. With ConditionalOperator, the mixing error answers first and lists `{FilterExpression, KeyConditionExpression}`. - `pk = :a` with FilterExpression `foo = :zz` and `:zz` undefined is refused on a partition with no items. check_request_parameters keeps the mixing, empty key condition, parameter usage and ConditionalOperator checks. It now runs right after deserialization. The Limit check is back where main had it, after the Select, table, index and ConsistentRead checks, since its order is not measured. parse_filter_expression replaces the duplicate-only filter check and runs for every request with a FilterExpression. It checks the grammar, names, operand types and then values, in main's order, and returns the parsed filter for the read. The key condition is parsed after it, and any fault of the parse is returned at once. ONE_CONDITION_PER_KEY_ERR is private again. tests/test_query_key_condition_one_per_key.py pins each measured row. For the filter syntax error the test compares the `Invalid FilterExpression: ` prefix, since ExtendDB words its syntax errors differently. --- crates/core/src/expression/key_condition.rs | 2 +- crates/core/src/expression/mod.rs | 4 +- crates/engine/src/query.rs | 152 ++++++++--------- tests/test_query_key_condition_one_per_key.py | 159 ++++++++++++++++++ 4 files changed, 229 insertions(+), 88 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 54a711204..15ba81b77 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -465,7 +465,7 @@ impl KeyCondition { /// The service's message when a `KeyConditionExpression` carries more than one /// condition on the same key attribute. Measured 2026-10-24 (us-east-1). -pub const ONE_CONDITION_PER_KEY_ERR: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key"; +const ONE_CONDITION_PER_KEY_ERR: &str = "Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key"; /// The service's message for a `#name` reference that /// `ExpressionAttributeNames` does not define. diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 9e7b682fc..479cadc94 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -25,8 +25,8 @@ mod update_parser; pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only}; pub use evaluator::evaluate_condition; pub use key_condition::{ - KeyClauseOperand, KeyCondition, ONE_CONDITION_PER_KEY_ERR, SortKeyCondition, - key_condition_clause_operands, parse_key_condition, parse_key_condition_with_maps, + KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands, + parse_key_condition, parse_key_condition_with_maps, }; pub use kind::ExpressionKind; pub use parser::{parse_condition, parse_condition_with_depth_limit}; diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 448cce564..9f44ab2f4 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -9,9 +9,7 @@ use serde_json::Value; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::PathElement; -use extenddb_core::expression::{ - ExpressionKind, ExpressionMaps, ONE_CONDITION_PER_KEY_ERR, Projection, -}; +use extenddb_core::expression::{ExpressionKind, ExpressionMaps, Projection}; use extenddb_core::types::{ IndexType, KeyType, QueryInput, QueryOutput, Select, TableKeyInfo, VECTOR_INDEX_QUERY_NOT_SUPPORTED, @@ -62,10 +60,12 @@ pub async fn handle_query( clause: crate::EnumClause::Named("returnConsumedCapacity"), }], )?; - // A second condition on one key attribute is reported ahead of an invalid - // Select (measured 2026-11-11: `pk = :a AND pk = :b` with Select `BOGUS` - // answers the duplicate), so an invalid Select is left out of the typed - // input and its error waits for that check below. + // The service checks Select after the request's parameters, its + // FilterExpression and its KeyConditionExpression (measured 2026-11-11: + // with Select `BOGUS`, a parameter mixing error, an undefined filter + // `#name` and a second condition on one key attribute each answer + // first), so an invalid Select is left out of the typed input and its + // error waits for those checks below. let select_check = crate::validate_enum_fields( &body, &[crate::EnumField { @@ -100,32 +100,22 @@ pub async fn handle_query( input.expression_attribute_values.as_ref(), ); - // The key condition is parsed here because the service reports a second - // condition on one key attribute ahead of the Select, table, index and - // ConsistentRead checks (measured 2026-11-11: with `pk = :a AND pk = :b`, - // Select `BOGUS`, a missing table, IndexName `nope`, ConsistentRead on a - // GSI and Select `ALL_ATTRIBUTES` on a KEYS_ONLY GSI each answer the - // duplicate). The checks of the request's parameters that come before the - // parse, and the FilterExpression's own faults, are reported first - // (measured 2026-11-11: ConditionalOperator, or KeyConditions, beside the - // expression answers the parameter mixing error). Any other fault of the - // parse is reported further down. - let key_condition_parse = input + // The service checks a Query in this order (measured 2026-11-11 in + // us-east-1): the request's parameters, then every FilterExpression + // fault, then every KeyConditionExpression fault, then Select, the table, + // the index and ConsistentRead. A parameter mixing error answers ahead of + // a filter fault, and ahead of a missing table, IndexName `nope`, Select + // `BOGUS` and ConsistentRead on a GSI. A filter fault answers ahead of an + // undefined key condition reference, a key condition syntax error, a + // number in `begins_with` and those four. A key condition fault answers + // ahead of those four. Limit stays below, where it was checked before. + check_request_parameters(&input)?; + let filter_expression = parse_filter_expression(&input, &maps, &ctx.limits)?; + let key_condition_expression = input .key_condition_expression .as_deref() - .map(|kce| crate::expression_helpers::parse_key_condition_expr(kce, &maps, &ctx.limits)); - if let Some(Err(DynamoDbError::ValidationException(msg))) = &key_condition_parse - && msg == ONE_CONDITION_PER_KEY_ERR - { - check_request_parameters(&input)?; - refuse_filter_faults( - input.filter_expression.as_deref(), - input.expression_attribute_names.as_ref(), - &maps, - &ctx.limits, - )?; - return Err(DynamoDbError::ValidationException(msg.clone())); - } + .map(|kce| crate::expression_helpers::parse_key_condition_expr(kce, &maps, &ctx.limits)) + .transpose()?; select_check?; // P118: Fetch key_info first so we can use table_id for index lookup. @@ -190,7 +180,14 @@ pub async fn handle_query( validate_query_select_index_support(input.select, index_info.as_ref())?; } - check_request_parameters(&input)?; + // Validate Limit >= 1 (REQ-QUERY-001) + if let Some(limit) = input.limit + && limit < 1 + { + return Err(DynamoDbError::ValidationException( + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1".to_owned(), + )); + } // For index queries, build a key_info that reflects the index's key schema // so the storage layer uses the correct SK column for the index table. @@ -213,13 +210,9 @@ pub async fn handle_query( }; // Parse KeyConditionExpression or desugar legacy KeyConditions - let (mut key_condition, legacy_kc_maps) = if let Some(parsed) = key_condition_parse { - // Parsed above. The parse refuses, in this order, the first undefined - // `#name` or `:value` in the order the expression is written, a - // `begins_with` operand of the wrong type and a second condition on - // one key attribute, before the clauses are classified (measured - // 2026-10-31 and 2026-11-11). - (parsed?, None) + let (mut key_condition, legacy_kc_maps) = if let Some(parsed) = key_condition_expression { + // Parsed and checked above, after the FilterExpression. + (parsed, None) } else if let Some(ref kc) = input.key_conditions { let key_schema_pairs: Vec<(String, bool)> = query_key_info .key_schema @@ -316,23 +309,15 @@ pub async fn handle_query( } } - // Parse FilterExpression or desugar legacy QueryFilter - let (filter, filter_maps) = if let Some(ref qf) = input.query_filter { - if qf.is_empty() { - ( - parse_optional_filter(input.filter_expression.as_deref(), &ctx.limits)?, - None, - ) - } else { + // Desugar a legacy QueryFilter. A FilterExpression was parsed and checked + // above; the parameter mixing check refuses a request with both. + let (filter, filter_maps) = match input.query_filter { + Some(ref qf) if !qf.is_empty() => { let cond_op = input.conditional_operator.unwrap_or_default(); let (expr, fmaps) = desugar_filter(qf, cond_op)?; (Some(expr), Some(fmaps)) } - } else { - ( - parse_optional_filter(input.filter_expression.as_deref(), &ctx.limits)?, - None, - ) + _ => (filter_expression, None), }; // Validate #name references in filter are defined in ExpressionAttributeNames @@ -678,27 +663,19 @@ fn refuse_begins_with_on_number( Ok(()) } -/// The checks of a request's parameters that run before the key condition -/// parse, in this order: `Limit`, the mixing of expression and non-expression -/// parameters, an empty `KeyConditionExpression`, `ExpressionAttributeNames` -/// and `ExpressionAttributeValues` with no expression that uses them, and +/// The checks of a request's parameters, in main's order: the mixing of +/// expression and non-expression parameters, an empty +/// `KeyConditionExpression`, `ExpressionAttributeNames` and +/// `ExpressionAttributeValues` with no expression that uses them, and /// `ConditionalOperator` without a `QueryFilter` of two or more conditions. /// -/// `handle_query` runs these after the table, index, `ConsistentRead` and -/// `Select` checks, and, for a key condition with a second condition on one -/// key attribute, ahead of them and ahead of that refusal (measured -/// 2026-11-11: `pk = :a AND pk = :b` with `ConditionalOperator` `AND` and no -/// `QueryFilter`, or with `KeyConditions`, answers the mixing error). +/// `handle_query` runs these first, ahead of the `FilterExpression`, the +/// `KeyConditionExpression` and the `Select`, table, index and +/// `ConsistentRead` checks (measured 2026-11-11: `ConditionalOperator` `AND` +/// beside `pk = :a` answers the mixing error with a missing table, IndexName +/// `nope`, Select `BOGUS`, ConsistentRead on a GSI or an undefined filter +/// `#name`, and beside `pk = :a AND pk = :b`). fn check_request_parameters(input: &QueryInput) -> Result<(), DynamoDbError> { - // Validate Limit >= 1 (REQ-QUERY-001) - if let Some(limit) = input.limit - && limit < 1 - { - return Err(DynamoDbError::ValidationException( - "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1".to_owned(), - )); - } - // --- Legacy vs expression mutual exclusivity checks --- let kce_present = input.key_condition_expression.is_some(); let has_kc = input.key_conditions.as_ref().is_some_and(|m| !m.is_empty()); @@ -761,31 +738,36 @@ fn check_request_parameters(input: &QueryInput) -> Result<(), DynamoDbError> { ) } -/// Refuse a `FilterExpression` fault that the service reports ahead of a -/// second condition on one key attribute. +/// Parse the request's `FilterExpression` and refuse its faults, before the +/// key condition is parsed and the table is read. /// -/// Measured 2026-11-11 (us-east-1), with `pk = :a AND pk = :b`: a filter -/// syntax error, a reserved word, an undefined `#name` or `:value`, and a -/// number in `begins_with` each answer the filter's own message. This runs -/// only for a key condition with that duplicate. -fn refuse_filter_faults( - filter: Option<&str>, - names: Option<&HashMap>, +/// The checks run in main's order: grammar and reserved words, undefined +/// `#name` references, `begins_with` and ordering operand types, then +/// undefined `:value` references. Measured 2026-11-11 (us-east-1): an +/// undefined filter `#name`, an undefined filter `:value` and a filter syntax +/// error each answer ahead of a key condition fault, and an undefined filter +/// `:value` is refused on a partition with no items. +fn parse_filter_expression( + input: &QueryInput, maps: &ExpressionMaps, limits: &extenddb_core::limits::LimitsConfig, -) -> Result<(), DynamoDbError> { - let Some(filter) = parse_optional_filter(filter, limits)? else { - return Ok(()); +) -> Result, DynamoDbError> { + let Some(filter) = parse_optional_filter(input.filter_expression.as_deref(), limits)? else { + return Ok(None); }; + let names = input.expression_attribute_names.as_ref(); validate_name_refs_in_expr(&filter, names, ExpressionKind::Filter)?; + extenddb_core::expression::validate_begins_with_operands(&filter, maps) + .and_then(|()| extenddb_core::expression::validate_ordering_operand_types(&filter, maps)) + .map_err(|e| { + crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter) + })?; let mut placeholders = Vec::new(); extenddb_core::expression::collect_value_placeholders(&filter, &mut placeholders); for placeholder in &placeholders { maps.resolve_value_for(placeholder, ExpressionKind::Filter.as_str())?; } - extenddb_core::expression::validate_begins_with_operands(&filter, maps) - .and_then(|()| extenddb_core::expression::validate_ordering_operand_types(&filter, maps)) - .map_err(|e| crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter)) + Ok(Some(filter)) } /// Validate that all `#name` references in an expression AST are defined. diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index 6ecd04585..391037933 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -36,6 +36,12 @@ and contains; and a number in begins_with answered its operand type error without a duplicate too. +The order of a Query's checks without a duplicate was measured +2026-11-11T12:42Z to 12:44Z in us-east-1 on the table with the index, two +sends each: the parameter mixing error first, then every FilterExpression +fault, then every KeyConditionExpression fault, then Select, the table, the +index and ConsistentRead. + Dual-target against Amazon DynamoDB and extenddb. """ @@ -614,3 +620,156 @@ def test_syntax_error_after_ne_reported_ahead_of_it( assert code == "ValidationException" assert msg.startswith("Invalid KeyConditionExpression: "), msg assert "operator" not in msg, msg + + +FILTER_UNDEFINED_Q = ( + "Invalid FilterExpression: An expression attribute name used in the " + "document path is not defined; attribute name: #q" +) +FILTER_UNDEFINED_ZZ = ( + "Invalid FilterExpression: An expression attribute value used in " + "expression is not defined; attribute value: :zz" +) +EMPTY_PARTITION = {"S": "p484-empty"} + + +def _mixing(*expression_parameters: str) -> str: + return ( + "Can not use both expression and non-expression parameters in the same " + "request: Non-expression parameters: {ConditionalOperator} Expression " + f"parameters: {{{', '.join(expression_parameters)}}}" + ) + + +class TestQueryCheckOrder: + """The order of a Query's checks without a duplicate (2026-11-11T12:42Z to + 12:44Z): parameters, then the FilterExpression, then the + KeyConditionExpression, then Select, the table, the index and + ConsistentRead.""" + + @pytest.mark.parametrize( + ("kce", "values", "filter_expr", "want"), + [ + # F1: an undefined key condition value beside an undefined filter + # name. + ("pk = :a AND sk = :missing", {":a": A}, "#q = :a", FILTER_UNDEFINED_Q), + # F1c, F1d: an undefined key condition name beside an undefined + # filter name or value. + ("pk = :a AND #s = :b", {":a": A, ":b": B}, "#q = :a", FILTER_UNDEFINED_Q), + ("pk = :a AND #s = :b", {":a": A, ":b": B}, "foo = :zz", FILTER_UNDEFINED_ZZ), + # F1e: a valid filter, so the key condition value answers. + ( + "pk = :a AND sk = :missing", + {":a": A}, + "foo = :a", + "Invalid KeyConditionExpression: An expression attribute value used " + "in expression is not defined; attribute value: :missing", + ), + # F1f: a number in begins_with on the S sort key. + ( + "pk = :a AND begins_with(sk, :n)", + {":a": A, ":n": N1}, + "#q = :a", + FILTER_UNDEFINED_Q, + ), + # F1g: a key condition syntax error (a trailing AND). + ("pk = :a AND", {":a": A}, "#q = :a", FILTER_UNDEFINED_Q), + ], + ids=["F1", "F1c", "F1d", "F1e", "F1f", "F1g"], + ) + def test_filter_fault_reported_ahead_of_key_condition_fault( + self, dynamodb_client, range_table, kce, values, filter_expr, want + ): + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression=kce, + ExpressionAttributeValues=values, + FilterExpression=filter_expr, + ) + ) + assert code == "ValidationException" + assert msg == want + + def test_filter_syntax_error_reported_ahead_of_key_condition_value( + self, dynamodb_client, range_table + ): + """F1b. The service answers `Invalid FilterExpression: Syntax error; + token: "=", near: "= = :a"`; extenddb words its syntax errors + differently, so the prefix is compared.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a AND sk = :missing", + ExpressionAttributeValues={":a": A}, + FilterExpression="zz = = :a", + ) + ) + assert code == "ValidationException" + assert msg.startswith("Invalid FilterExpression: "), msg + + @pytest.mark.parametrize( + ("kwargs", "on_index", "want"), + [ + # F2a to F2d: the mixing error ahead of each. + ( + {"TableName": "extenddb-test-484-no-such-table", "ConditionalOperator": "AND"}, + False, + _mixing("KeyConditionExpression"), + ), + ({"IndexName": "nope", "ConditionalOperator": "AND"}, False, _mixing("KeyConditionExpression")), + ({"Select": "BOGUS", "ConditionalOperator": "AND"}, False, _mixing("KeyConditionExpression")), + ( + {"IndexName": KEYS_ONLY_INDEX, "ConsistentRead": True, "ConditionalOperator": "AND"}, + True, + _mixing("KeyConditionExpression"), + ), + # H1 to H4: an undefined filter name ahead of each. + ( + {"TableName": "extenddb-test-484-no-such-table", "FilterExpression": "#q = :a"}, + False, + FILTER_UNDEFINED_Q, + ), + ({"IndexName": "nope", "FilterExpression": "#q = :a"}, False, FILTER_UNDEFINED_Q), + ({"Select": "BOGUS", "FilterExpression": "#q = :a"}, False, FILTER_UNDEFINED_Q), + ( + {"IndexName": KEYS_ONLY_INDEX, "ConsistentRead": True, "FilterExpression": "#q = :a"}, + True, + FILTER_UNDEFINED_Q, + ), + # H5: the mixing error ahead of an undefined filter name. + ( + {"ConditionalOperator": "AND", "FilterExpression": "#q = :a"}, + False, + _mixing("FilterExpression", "KeyConditionExpression"), + ), + ], + ids=["F2a", "F2b", "F2c", "F2d", "H1", "H2", "H3", "H4", "H5"], + ) + def test_parameter_and_filter_checks_reported_ahead_of_request_checks( + self, dynamodb_client, range_table, kwargs, on_index, want + ): + request = { + "TableName": range_table, + "KeyConditionExpression": "g = :a" if on_index else "pk = :a", + "ExpressionAttributeValues": {":a": A}, + **kwargs, + } + code, msg = _error(lambda: dynamodb_client.query(**request)) + assert code == "ValidationException" + assert msg == want + + def test_undefined_filter_value_refused_on_an_empty_partition( + self, dynamodb_client, range_table + ): + """F3: refused before any item is read.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a", + ExpressionAttributeValues={":a": EMPTY_PARTITION}, + FilterExpression="foo = :zz", + ) + ) + assert code == "ValidationException" + assert msg == FILTER_UNDEFINED_ZZ From b13ec53216137214a9c0121b22accfed335654cc Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:37:34 +0000 Subject: [PATCH 14/29] fix(query): check Limit ahead of every other Query check handle_query checked Limit after the parameter, filter and key condition checks and after the table, index, ConsistentRead and Select checks. The Limit check now runs right after deserialization, ahead of the parameter checks. Measured in us-east-1 on 11 Nov 2026, two sends each, the same answer both times. The SDK's own checks were off, so Limit 0 reached the service. Limit 0 gets the Limit refusal in each of these requests: - alone - beside a key condition syntax error (a trailing AND) - beside `pk = :a AND pk = :b` - beside a filter `#q` with no ExpressionAttributeNames - beside ConditionalOperator, which is a parameter mixing error - on a missing table - beside Select `BOGUS` The refusal reads "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1". ExtendDB's text for Limit is the same. The same run measured four rows this branch already answers, and tests/test_query_key_condition_one_per_key.py now pins them: - `begins_with(pk, :n)` with `:n` a number answers "Invalid KeyConditionExpression: Incorrect operand type for operator or function; operator or function: begins_with, operand type: N". - On a missing table, ExpressionAttributeValues beside legacy KeyConditions answers "ExpressionAttributeValues can only be specified when using expressions". - On a missing table, an empty KeyConditionExpression answers "Invalid KeyConditionExpression: The expression can not be empty;". - On a missing table, ConditionalOperator with legacy KeyConditions and no QueryFilter answers "ConditionalOperator cannot be used without Filter or Expected". The Limit tests use the conftest client fixture that has the SDK's checks off. --- crates/engine/src/query.rs | 59 +++++---- tests/test_query_key_condition_one_per_key.py | 113 +++++++++++++++++- 2 files changed, 145 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 9f44ab2f4..6d796ff88 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -60,10 +60,10 @@ pub async fn handle_query( clause: crate::EnumClause::Named("returnConsumedCapacity"), }], )?; - // The service checks Select after the request's parameters, its + // The service checks Select after Limit, the request's parameters, its // FilterExpression and its KeyConditionExpression (measured 2026-11-11: - // with Select `BOGUS`, a parameter mixing error, an undefined filter - // `#name` and a second condition on one key attribute each answer + // with Select `BOGUS`, Limit 0, a parameter mixing error, an undefined + // filter `#name` and a second condition on one key attribute each answer // first), so an invalid Select is left out of the typed input and its // error waits for those checks below. let select_check = crate::validate_enum_fields( @@ -94,6 +94,19 @@ pub async fn handle_query( } }; + // Validate Limit >= 1 (REQ-QUERY-001). The service checks Limit ahead of + // every other fault measured (2026-11-11, us-east-1: Limit 0 answers this + // beside a key condition syntax error, a second condition on one key + // attribute, an undefined filter `#name`, a parameter mixing error, a + // missing table and Select `BOGUS`). + if let Some(limit) = input.limit + && limit < 1 + { + return Err(DynamoDbError::ValidationException( + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1".to_owned(), + )); + } + // Build expression maps from request (used for expression-based parameters) let maps = build_expression_maps( input.expression_attribute_names.as_ref(), @@ -101,14 +114,14 @@ pub async fn handle_query( ); // The service checks a Query in this order (measured 2026-11-11 in - // us-east-1): the request's parameters, then every FilterExpression - // fault, then every KeyConditionExpression fault, then Select, the table, - // the index and ConsistentRead. A parameter mixing error answers ahead of - // a filter fault, and ahead of a missing table, IndexName `nope`, Select - // `BOGUS` and ConsistentRead on a GSI. A filter fault answers ahead of an - // undefined key condition reference, a key condition syntax error, a - // number in `begins_with` and those four. A key condition fault answers - // ahead of those four. Limit stays below, where it was checked before. + // us-east-1): Limit, then the request's parameters, then every + // FilterExpression fault, then every KeyConditionExpression fault, then + // Select, the table, the index and ConsistentRead. A parameter check + // answers ahead of a filter fault, and ahead of a missing table, + // IndexName `nope`, Select `BOGUS` and ConsistentRead on a GSI. A filter + // fault answers ahead of an undefined key condition reference, a key + // condition syntax error, a number in `begins_with` and those four. A key + // condition fault answers ahead of those four. check_request_parameters(&input)?; let filter_expression = parse_filter_expression(&input, &maps, &ctx.limits)?; let key_condition_expression = input @@ -180,15 +193,6 @@ pub async fn handle_query( validate_query_select_index_support(input.select, index_info.as_ref())?; } - // Validate Limit >= 1 (REQ-QUERY-001) - if let Some(limit) = input.limit - && limit < 1 - { - return Err(DynamoDbError::ValidationException( - "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1".to_owned(), - )); - } - // For index queries, build a key_info that reflects the index's key schema // so the storage layer uses the correct SK column for the index table. let query_key_info = if let Some(ref idx) = index_info { @@ -669,12 +673,15 @@ fn refuse_begins_with_on_number( /// `ExpressionAttributeValues` with no expression that uses them, and /// `ConditionalOperator` without a `QueryFilter` of two or more conditions. /// -/// `handle_query` runs these first, ahead of the `FilterExpression`, the -/// `KeyConditionExpression` and the `Select`, table, index and -/// `ConsistentRead` checks (measured 2026-11-11: `ConditionalOperator` `AND` -/// beside `pk = :a` answers the mixing error with a missing table, IndexName -/// `nope`, Select `BOGUS`, ConsistentRead on a GSI or an undefined filter -/// `#name`, and beside `pk = :a AND pk = :b`). +/// `handle_query` runs these right after the `Limit` check, ahead of the +/// `FilterExpression`, the `KeyConditionExpression` and the `Select`, table, +/// index and `ConsistentRead` checks (measured 2026-11-11: `ConditionalOperator` +/// `AND` beside `pk = :a` answers the mixing error with a missing table, +/// IndexName `nope`, Select `BOGUS`, ConsistentRead on a GSI or an undefined +/// filter `#name`, and beside `pk = :a AND pk = :b`; on a missing table, +/// `ExpressionAttributeValues` beside legacy `KeyConditions`, an empty +/// `KeyConditionExpression` and `ConditionalOperator` without a `QueryFilter` +/// each answer their own message). fn check_request_parameters(input: &QueryInput) -> Result<(), DynamoDbError> { // --- Legacy vs expression mutual exclusivity checks --- let kce_present = input.key_condition_expression.is_some(); diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index 391037933..67c165d96 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -40,7 +40,9 @@ 2026-11-11T12:42Z to 12:44Z in us-east-1 on the table with the index, two sends each: the parameter mixing error first, then every FilterExpression fault, then every KeyConditionExpression fault, then Select, the table, the -index and ConsistentRead. +index and ConsistentRead. At 13:26Z, with the SDK's own checks off, Limit 0 +answered its own message ahead of every other fault sent beside it, and the +other parameter checks answered ahead of a missing table. Dual-target against Amazon DynamoDB and extenddb. """ @@ -773,3 +775,112 @@ def test_undefined_filter_value_refused_on_an_empty_partition( ) assert code == "ValidationException" assert msg == FILTER_UNDEFINED_ZZ + + +LIMIT_ZERO = ( + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1" +) +MISSING_TABLE = "extenddb-test-484-no-such-table" +LEGACY_PK = {"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [A]}} + + +class TestLimitAndParameterChecksFirst: + """Limit and the other parameter checks against the rest (2026-11-11T13:26Z).""" + + @pytest.mark.parametrize( + ("kwargs", "missing_table"), + [ + ({"KeyConditionExpression": "pk = :a", "ExpressionAttributeValues": {":a": A}}, False), + ( + {"KeyConditionExpression": "pk = :a AND", "ExpressionAttributeValues": {":a": A}}, + False, + ), + ( + { + "KeyConditionExpression": "pk = :a AND pk = :b", + "ExpressionAttributeValues": {":a": A, ":b": B}, + }, + False, + ), + ( + { + "KeyConditionExpression": "pk = :a", + "ExpressionAttributeValues": {":a": A}, + "FilterExpression": "#q = :a", + }, + False, + ), + ( + { + "KeyConditionExpression": "pk = :a", + "ExpressionAttributeValues": {":a": A}, + "ConditionalOperator": "AND", + }, + False, + ), + ({"KeyConditionExpression": "pk = :a", "ExpressionAttributeValues": {":a": A}}, True), + ( + { + "KeyConditionExpression": "pk = :a", + "ExpressionAttributeValues": {":a": A}, + "Select": "BOGUS", + }, + False, + ), + ], + ids=["L1", "L2", "L3", "L4", "L5", "L6", "L7"], + ) + def test_limit_zero_reported_first( + self, dynamodb_client_no_validation, range_table, kwargs, missing_table + ): + """Limit 0 answers its own message ahead of a key condition syntax + error, a duplicate, a filter fault, a parameter mixing error, a + missing table and Select BOGUS. The SDK refuses Limit 0 before it + sends the request, so this client has its checks off.""" + code, msg = _error( + lambda: dynamodb_client_no_validation.query( + TableName=MISSING_TABLE if missing_table else range_table, + Limit=0, + **kwargs, + ) + ) + assert code == "ValidationException" + assert msg == LIMIT_ZERO + + def test_begins_with_number_on_the_partition_key(self, dynamodb_client, range_table): + """P1: the operand type, ahead of the partition key equality rule.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="begins_with(pk, :n)", + ExpressionAttributeValues={":n": N1}, + ) + ) + assert code == "ValidationException" + assert msg == BEGINS_WITH_N + + @pytest.mark.parametrize( + ("kwargs", "want"), + [ + ( + {"KeyConditions": LEGACY_PK, "ExpressionAttributeValues": {":a": A}}, + "ExpressionAttributeValues can only be specified when using expressions", + ), + ( + {"KeyConditionExpression": ""}, + "Invalid KeyConditionExpression: The expression can not be empty;", + ), + ( + {"KeyConditions": LEGACY_PK, "ConditionalOperator": "AND"}, + "ConditionalOperator cannot be used without Filter or Expected", + ), + ], + ids=["M1", "M2", "M3"], + ) + def test_parameter_check_reported_ahead_of_a_missing_table( + self, dynamodb_client, kwargs, want + ): + code, msg = _error(lambda: dynamodb_client.query(TableName=MISSING_TABLE, **kwargs)) + assert code == "ValidationException" + assert msg == want From c560e41c5f5d27380d009317aa5b0062f68a3990 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:49:43 +0000 Subject: [PATCH 15/29] test(query): add the non-key and hash-only duplicate cases tests/test_query_key_condition_one_per_key.py gets two tests in TestOneConditionPerKey: - test_duplicate_condition_on_a_non_key_attribute sends `pk = :a AND zz = :b AND zz = :c` to the table with pk (S) HASH and sk (S) RANGE. zz is not a key attribute. - test_duplicate_partition_key_condition_on_a_hash_only_table sends `pk = :a AND pk = :b` to a table keyed on pk (S) alone. A class-scoped hash_table fixture creates that table and deletes it after the class. Measured in us-east-1 on 11 Nov 2026 at 14:39 UTC, two sends each, the same answer both times. Both requests answer 400 ValidationException with "Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key". Each test compares the whole message with ONE_PER_KEY. The module docstring adds the 14:39 run. Signed-off-by: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> --- tests/test_query_key_condition_one_per_key.py | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index 67c165d96..5dbd30ced 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -42,7 +42,10 @@ fault, then every KeyConditionExpression fault, then Select, the table, the index and ConsistentRead. At 13:26Z, with the SDK's own checks off, Limit 0 answered its own message ahead of every other fault sent beside it, and the -other parameter checks answered ahead of a missing table. +other parameter checks answered ahead of a missing table. At 14:39Z, two +conditions on a non-key attribute, and two conditions on the partition key of +a table keyed on pk (S) alone, each answered the one-condition-per-key +message. Dual-target against Amazon DynamoDB and extenddb. """ @@ -117,6 +120,13 @@ def range_table(dynamodb_client): yield name +@pytest.fixture(scope="class") +def hash_table(dynamodb_client): + """pk (S) HASH and no sort key.""" + with scoped_table(dynamodb_client) as name: + yield name + + def _error(func) -> tuple[str, str]: with pytest.raises(ClientError) as exc_info: func() @@ -219,6 +229,35 @@ def test_duplicate_through_name_reference( assert code == "ValidationException" assert msg == ONE_PER_KEY + def test_duplicate_condition_on_a_non_key_attribute( + self, dynamodb_client, range_table + ): + """Measured 2026-11-11T14:39Z: two conditions on zz, which is not a key + attribute, answer the duplicate too.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=range_table, + KeyConditionExpression="pk = :a AND zz = :b AND zz = :c", + ExpressionAttributeValues={":a": A, ":b": B, ":c": C}, + ) + ) + assert code == "ValidationException" + assert msg == ONE_PER_KEY + + def test_duplicate_partition_key_condition_on_a_hash_only_table( + self, dynamodb_client, hash_table + ): + """Measured 2026-11-11T14:39Z on a table keyed on pk (S) alone.""" + code, msg = _error( + lambda: dynamodb_client.query( + TableName=hash_table, + KeyConditionExpression="pk = :a AND pk = :b", + ExpressionAttributeValues={":a": A, ":b": B}, + ) + ) + assert code == "ValidationException" + assert msg == ONE_PER_KEY + def test_distinct_key_conditions_still_served(self, dynamodb_client, range_table): """One condition per key attribute, in either order, returns rows.""" pk_only = dynamodb_client.query( From 52a90f6efe4978508150768007d185406d7a9f09 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:10:09 +0000 Subject: [PATCH 16/29] refactor(query): shorten comments and skip repeated filter checks handle_query checked a FilterExpression's #name references and its begins_with and ordering operand types in parse_filter_expression, then checked the filter again after the key condition. The second pass now runs only where its input differs from the first: - The #name check runs again only for a desugared legacy QueryFilter. desugar_filter keeps each attribute name as a path, so an attribute named "#x" reads as an undefined reference and the check refuses it. - The operand check runs again only when legacy KeyConditions or a QueryFilter add values to the request's ExpressionAttributeValues. It reads the merged values, as before. Beside a KeyConditionExpression, the merged values are the request's own, which parse_filter_expression has already checked. A new helper, check_filter_operand_types, holds the two operand checks. parse_filter_expression and the second pass both call it. The comments on the Select hold, the Limit check and the check order now state the rule and the measurement date in one sentence each. So do the doc comments of check_request_parameters and parse_filter_expression. The wire tests in tests/test_query_key_condition_one_per_key.py cover the cases they listed. No answer changes. The 93 tests in tests/test_query_key_condition_one_per_key.py pass, and 85 requests sent twice to a server built before and after this change get the same answers. Signed-off-by: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> --- crates/engine/src/query.rs | 86 ++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 51 deletions(-) diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 6d796ff88..2c805b90b 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -60,12 +60,10 @@ pub async fn handle_query( clause: crate::EnumClause::Named("returnConsumedCapacity"), }], )?; - // The service checks Select after Limit, the request's parameters, its - // FilterExpression and its KeyConditionExpression (measured 2026-11-11: - // with Select `BOGUS`, Limit 0, a parameter mixing error, an undefined - // filter `#name` and a second condition on one key attribute each answer - // first), so an invalid Select is left out of the typed input and its - // error waits for those checks below. + // The service checks Select after Limit, the request's parameters, the + // FilterExpression and the KeyConditionExpression (measured 2026-11-11), + // so an invalid Select is left out of the typed input and its error waits + // for those checks below. let select_check = crate::validate_enum_fields( &body, &[crate::EnumField { @@ -95,10 +93,7 @@ pub async fn handle_query( }; // Validate Limit >= 1 (REQ-QUERY-001). The service checks Limit ahead of - // every other fault measured (2026-11-11, us-east-1: Limit 0 answers this - // beside a key condition syntax error, a second condition on one key - // attribute, an undefined filter `#name`, a parameter mixing error, a - // missing table and Select `BOGUS`). + // every other fault measured (2026-11-11, us-east-1). if let Some(limit) = input.limit && limit < 1 { @@ -116,12 +111,7 @@ pub async fn handle_query( // The service checks a Query in this order (measured 2026-11-11 in // us-east-1): Limit, then the request's parameters, then every // FilterExpression fault, then every KeyConditionExpression fault, then - // Select, the table, the index and ConsistentRead. A parameter check - // answers ahead of a filter fault, and ahead of a missing table, - // IndexName `nope`, Select `BOGUS` and ConsistentRead on a GSI. A filter - // fault answers ahead of an undefined key condition reference, a key - // condition syntax error, a number in `begins_with` and those four. A key - // condition fault answers ahead of those four. + // Select, the table, the index and ConsistentRead. check_request_parameters(&input)?; let filter_expression = parse_filter_expression(&input, &maps, &ctx.limits)?; let key_condition_expression = input @@ -324,10 +314,11 @@ pub async fn handle_query( _ => (filter_expression, None), }; - // Validate #name references in filter are defined in ExpressionAttributeNames - if let Some(ref filter_expr) = filter { + // A desugared QueryFilter's paths: a legacy attribute name that starts with + // `#` reads as a reference. A FilterExpression's were checked when parsed. + if let (Some(f), Some(_)) = (&filter, &filter_maps) { let names = input.expression_attribute_names.as_ref(); - validate_name_refs_in_expr(filter_expr, names, ExpressionKind::Filter)?; + validate_name_refs_in_expr(f, names, ExpressionKind::Filter)?; } // Parse ProjectionExpression or desugar legacy AttributesToGet @@ -448,14 +439,13 @@ 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 { - extenddb_core::expression::validate_begins_with_operands(f, &combined_maps).map_err( - |e| crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter), - )?; - extenddb_core::expression::validate_ordering_operand_types(f, &combined_maps).map_err( - |e| crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter), - )?; + // The filter's operand types against the values legacy KeyConditions or a + // QueryFilter add. A FilterExpression was checked against the request's own + // values when it was parsed. + if let Some(f) = &filter + && (filter_maps.is_some() || legacy_kc_maps.is_some()) + { + check_filter_operand_types(f, &combined_maps)?; } // Validate ExclusiveStartKey matches the key schema @@ -667,21 +657,14 @@ fn refuse_begins_with_on_number( Ok(()) } -/// The checks of a request's parameters, in main's order: the mixing of +/// The checks of a request's parameters, in this order: the mixing of /// expression and non-expression parameters, an empty /// `KeyConditionExpression`, `ExpressionAttributeNames` and /// `ExpressionAttributeValues` with no expression that uses them, and /// `ConditionalOperator` without a `QueryFilter` of two or more conditions. /// -/// `handle_query` runs these right after the `Limit` check, ahead of the -/// `FilterExpression`, the `KeyConditionExpression` and the `Select`, table, -/// index and `ConsistentRead` checks (measured 2026-11-11: `ConditionalOperator` -/// `AND` beside `pk = :a` answers the mixing error with a missing table, -/// IndexName `nope`, Select `BOGUS`, ConsistentRead on a GSI or an undefined -/// filter `#name`, and beside `pk = :a AND pk = :b`; on a missing table, -/// `ExpressionAttributeValues` beside legacy `KeyConditions`, an empty -/// `KeyConditionExpression` and `ConditionalOperator` without a `QueryFilter` -/// each answer their own message). +/// `handle_query` runs these after the `Limit` check and ahead of every other +/// check (measured 2026-11-11). fn check_request_parameters(input: &QueryInput) -> Result<(), DynamoDbError> { // --- Legacy vs expression mutual exclusivity checks --- let kce_present = input.key_condition_expression.is_some(); @@ -745,15 +728,10 @@ fn check_request_parameters(input: &QueryInput) -> Result<(), DynamoDbError> { ) } -/// Parse the request's `FilterExpression` and refuse its faults, before the -/// key condition is parsed and the table is read. -/// -/// The checks run in main's order: grammar and reserved words, undefined -/// `#name` references, `begins_with` and ordering operand types, then -/// undefined `:value` references. Measured 2026-11-11 (us-east-1): an -/// undefined filter `#name`, an undefined filter `:value` and a filter syntax -/// error each answer ahead of a key condition fault, and an undefined filter -/// `:value` is refused on a partition with no items. +/// Parse the request's `FilterExpression` and refuse its faults before the key +/// condition is parsed and the table is read: grammar and reserved words, +/// undefined `#name` references, operand types, then undefined `:value` +/// references (measured 2026-11-11, us-east-1). fn parse_filter_expression( input: &QueryInput, maps: &ExpressionMaps, @@ -764,11 +742,7 @@ fn parse_filter_expression( }; let names = input.expression_attribute_names.as_ref(); validate_name_refs_in_expr(&filter, names, ExpressionKind::Filter)?; - extenddb_core::expression::validate_begins_with_operands(&filter, maps) - .and_then(|()| extenddb_core::expression::validate_ordering_operand_types(&filter, maps)) - .map_err(|e| { - crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter) - })?; + check_filter_operand_types(&filter, maps)?; let mut placeholders = Vec::new(); extenddb_core::expression::collect_value_placeholders(&filter, &mut placeholders); for placeholder in &placeholders { @@ -777,6 +751,16 @@ fn parse_filter_expression( Ok(Some(filter)) } +/// Refuse a `begins_with` or ordering operand of the wrong type in a filter. +fn check_filter_operand_types( + filter: &extenddb_core::expression::Expr, + maps: &ExpressionMaps, +) -> Result<(), DynamoDbError> { + extenddb_core::expression::validate_begins_with_operands(filter, maps) + .and_then(|()| extenddb_core::expression::validate_ordering_operand_types(filter, maps)) + .map_err(|e| crate::expression_helpers::prefix_expression_error(e, ExpressionKind::Filter)) +} + /// Validate that all `#name` references in an expression AST are defined. fn validate_name_refs_in_expr( expr: &extenddb_core::expression::Expr, From 9733e94b831158c25f8db38449ce910193add54b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:32:41 +0000 Subject: [PATCH 17/29] test(query): rewrite the one-per-key tests as tables of rows tests/test_query_key_condition_one_per_key.py keeps each measured request as one row: an id, the Query's parameters and the service's answer. Each of the six classes holds a ROWS list and one test_refused that sends every row. The 27 test functions, each with its own query call, become 7, and the file goes from 925 lines to 422. Helpers build the parameters (_q) and the undefined-reference and mixing messages (_undefined, _mixing), and compare the answer (_refused). The module docstring states the table each date ran on, and each class docstring gives its dates. The rows are the old tests' requests and answers, one for one. A harness recorded what each test sends and asserts. It found the same 96 queries in both files, with the same client and the same expectations. test_distinct_key_conditions_still_served sent four queries in one test and now has four cases, so the file collects 96 tests where it collected 93. In crates/core/src/expression/key_condition.rs, the four duplicate_condition_* unit tests and nested_path_reported_ahead_of_duplicate become one table in duplicate_condition_on_one_key_attribute_rejected. The table has a column for the #name definitions and a column for the answer. It holds the 22 expressions and answers the five tests checked. Each row defines only the names its expression uses. No production code changes, and no answer changes. Signed-off-by: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> --- crates/core/src/expression/key_condition.rs | 112 +- tests/test_query_key_condition_one_per_key.py | 1149 +++++------------ 2 files changed, 369 insertions(+), 892 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 15ba81b77..b8f9c8785 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -2175,61 +2175,57 @@ mod tests { } } + /// A second condition on one key attribute, on the partition key or the + /// sort key, written with plain names or through `#name` references and + /// whatever the operators, answers the one-condition-per-key message; a + /// nested path and redundant parentheses keep their own (measured + /// 2026-10-24, us-east-1). #[test] fn duplicate_condition_on_one_key_attribute_rejected() { - // Measured 2026-10-24 (us-east-1): every one of these shapes answers - // the one-condition-per-key message, whatever the operators are and - // whichever key attribute is named twice. - for expr in [ - "pk = :a AND pk = :b", - "pk = :a AND pk = :a", - "pk = :a AND pk = :b AND sk = :c", - "pk = :a AND pk > :b", - "pk > :b AND pk = :a", - ":a = pk AND pk = :b", - "(pk = :a) AND (pk = :b)", - "pk = :a AND sk = :b AND sk = :c", - "pk = :a AND sk = :b AND sk = :b", - "pk = :a AND sk BETWEEN :b AND :c AND sk = :b", - "pk = :a AND sk BETWEEN :b AND :c AND begins_with(sk, :b)", - "pk = :a AND begins_with(sk, :b) AND sk = :c", - "pk = :a AND sk > :b AND sk < :c", - "pk = :a AND begins_with(sk, :b) AND begins_with(sk, :c)", - "pk = :a AND pk = :b AND sk = :b AND sk = :c", - "sk = :b AND sk = :c", - ] { - assert_refused( - parse_request(expr, &HashMap::new()), - ONE_CONDITION_PER_KEY_ERR, - expr, - ); - } - } - - #[test] - fn duplicate_condition_through_name_reference_rejected() { - // `#p` and `pk` name the same attribute once `#p` is resolved, on a - // single-attribute key schema and a multi-attribute one alike. - let names = names_of(&[("p", "pk"), ("hh", "h")]); - for expr in ["#p = :a AND pk = :b", "#hh = :x AND h = :y AND a = :z"] { - assert_refused(parse_request(expr, &names), ONE_CONDITION_PER_KEY_ERR, expr); + const REDUNDANT_PARENS: &str = + "Invalid KeyConditionExpression: The expression has redundant parentheses;"; + let dup = ONE_CONDITION_PER_KEY_ERR; + // The expression, its `#name` definitions and the answer. + type Case<'a> = (&'a str, &'a [(&'a str, &'a str)], &'a str); + let cases: &[Case<'_>] = &[ + ("pk = :a AND pk = :b", &[], dup), + ("pk = :a AND pk = :a", &[], dup), + ("pk = :a AND pk = :b AND sk = :c", &[], dup), + ("pk = :a AND pk > :b", &[], dup), + ("pk > :b AND pk = :a", &[], dup), + (":a = pk AND pk = :b", &[], dup), + ("(pk = :a) AND (pk = :b)", &[], dup), + ("pk = :a AND sk = :b AND sk = :c", &[], dup), + ("pk = :a AND sk = :b AND sk = :b", &[], dup), + ("pk = :a AND sk BETWEEN :b AND :c AND sk = :b", &[], dup), + ( + "pk = :a AND sk BETWEEN :b AND :c AND begins_with(sk, :b)", + &[], + dup, + ), + ("pk = :a AND begins_with(sk, :b) AND sk = :c", &[], dup), + ("pk = :a AND sk > :b AND sk < :c", &[], dup), + ( + "pk = :a AND begins_with(sk, :b) AND begins_with(sk, :c)", + &[], + dup, + ), + ("pk = :a AND pk = :b AND sk = :b AND sk = :c", &[], dup), + ("sk = :b AND sk = :c", &[], dup), + // `#p` and `pk` name one attribute once `#p` is resolved, on a + // single-attribute key schema and a multi-attribute one alike. + ("#p = :a AND pk = :b", &[("p", "pk")], dup), + ("#hh = :x AND h = :y AND a = :z", &[("hh", "h")], dup), + ("#p = :a AND #q = :b", &[("p", "pk"), ("q", "pk")], dup), + ("pk = :a AND #s = :b AND sk = :c", &[("s", "sk")], dup), + ("pk = :a AND pk.foo = :b", &[], NESTED_KEY_ERR), + ("((pk = :a)) AND (pk = :b)", &[], REDUNDANT_PARENS), + ]; + for (expr, names, want) in cases { + assert_refused(parse_request(expr, &names_of(names)), want, expr); } } - #[test] - fn duplicate_condition_through_two_name_references_rejected() { - let names = names_of(&[("p", "pk"), ("q", "pk")]); - let expr = "#p = :a AND #q = :b"; - assert_refused(parse_request(expr, &names), ONE_CONDITION_PER_KEY_ERR, expr); - } - - #[test] - fn duplicate_condition_on_sort_key_through_name_reference_rejected() { - let names = names_of(&[("s", "sk")]); - let expr = "pk = :a AND #s = :b AND sk = :c"; - assert_refused(parse_request(expr, &names), ONE_CONDITION_PER_KEY_ERR, expr); - } - /// The first undefined reference in the order the expression is written is /// reported, a `#name` or a `:value`, with or without a duplicate. /// Measured 2026-10-24 for `#u = :a AND #u = :b`, 2026-10-31 for the @@ -2403,22 +2399,6 @@ mod tests { ); } - #[test] - fn nested_path_reported_ahead_of_duplicate() { - // Measured 2026-10-24: both of these answer their own message, not the - // one-condition-per-key message. - assert_refused( - parse_request("pk = :a AND pk.foo = :b", &HashMap::new()), - NESTED_KEY_ERR, - "pk = :a AND pk.foo = :b", - ); - assert_refused( - parse_request("((pk = :a)) AND (pk = :b)", &HashMap::new()), - "Invalid KeyConditionExpression: The expression has redundant parentheses;", - "((pk = :a)) AND (pk = :b)", - ); - } - #[test] fn distinct_key_attributes_accepted_after_duplicate_check() { // One condition per key attribute passes the check and resolves under diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index 5dbd30ced..5467421b7 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -3,49 +3,20 @@ """A KeyConditionExpression carries one condition per key attribute. -Amazon DynamoDB rejects a key condition that names the same key attribute twice, -on the partition key and on the sort key alike, whatever the operators are: +Amazon DynamoDB refuses a key condition that names the same key attribute +twice, on the partition key and on the sort key alike, whatever the operators +are (issue #430): ValidationException: Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key -Measured 2026-10-24T00:27:56Z and 00:30:39Z in us-east-1 on a table with -pk (S) HASH and sk (S) RANGE. Issue #430. - -The order against undefined references, the key value type check and an -unused value was measured 2026-10-31T17:37Z in us-east-1 on a table with the -same key schema, two samples each: an undefined #name anywhere in the -expression and an undefined :value are reported ahead of the duplicate, and the -duplicate is reported ahead of the type check and the unused-value check. - -The order against the FilterExpression and the table, index, ConsistentRead -and Select checks was measured 2026-11-11T09:43Z in us-east-1 on a table with -the same key schema and a KEYS_ONLY global secondary index on g (S), two -sends each: a FilterExpression fault is reported ahead of the duplicate, and -the duplicate ahead of a missing table, an unknown index, ConsistentRead on -the index, an invalid Select and Select ALL_ATTRIBUTES on the index. In the -same run the first undefined reference in the order the expression is written -was reported, a #name or a :value, with or without a duplicate; `<>` and -`contains` beside a duplicate answered the duplicate; and a number in -begins_with answered its operand type error ahead of it. On 2026-11-10 an -undefined reference was reported ahead of an unused name or value, on a table -keyed on pk (S) alone. At 11:22Z and 11:23Z the same day, on the table with -the index: ConditionalOperator or KeyConditions beside the expression -answered the parameter mixing error ahead of the duplicate; an undefined name, -a later syntax error and a duplicate on sk were each reported ahead of `<>` -and contains; and a number in begins_with answered its operand type error -without a duplicate too. - -The order of a Query's checks without a duplicate was measured -2026-11-11T12:42Z to 12:44Z in us-east-1 on the table with the index, two -sends each: the parameter mixing error first, then every FilterExpression -fault, then every KeyConditionExpression fault, then Select, the table, the -index and ConsistentRead. At 13:26Z, with the SDK's own checks off, Limit 0 -answered its own message ahead of every other fault sent beside it, and the -other parameter checks answered ahead of a missing table. At 14:39Z, two -conditions on a non-key attribute, and two conditions on the partition key of -a table keyed on pk (S) alone, each answered the one-condition-per-key -message. +Every row below is a request and the answer the service gave it in us-east-1, +on the date in its class's docstring. The 2026-10-24 and 2026-10-31 rows ran on +a table with pk (S) HASH and sk (S) RANGE, and the 2026-11-11 rows from 09:43Z +to 12:44Z on such a table with a KEYS_ONLY global secondary index on g (S). The +2026-11-10 rows and J2 ran on a table keyed on pk (S) alone. Where the +service's text differs from extenddb's by wording alone (syntax errors), the +row compares the prefix. Dual-target against Amazon DynamoDB and extenddb. """ @@ -65,29 +36,88 @@ "Invalid KeyConditionExpression: " "KeyConditionExpressions cannot have conditions on nested attributes" ) -REDUNDANT_PARENS = ( - "Invalid KeyConditionExpression: The expression has redundant parentheses;" -) -UNDEFINED_NAME_EXACT = ( - "Invalid KeyConditionExpression: An expression attribute name used in the " - "document path is not defined; attribute name: #u" -) -UNDEFINED_VALUE_A = ( - "Invalid KeyConditionExpression: An expression attribute value used in " - "expression is not defined; attribute value: :a" -) +REDUNDANT_PARENS = "Invalid KeyConditionExpression: The expression has redundant parentheses;" BEGINS_WITH_N = ( "Invalid KeyConditionExpression: Incorrect operand type for operator or " "function; operator or function: begins_with, operand type: N" ) +FILTER_BEGINS_WITH_N = ( + "Invalid FilterExpression: Incorrect operand type for operator or " + "function; operator or function: begins_with, operand type: N" +) +FILTER_RESERVED_NAME = ( + "Invalid FilterExpression: Attribute name is a reserved keyword; reserved keyword: name" +) +LIMIT_ZERO = ( + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1" +) +# A prefix match: the service words its syntax errors differently from extenddb. +KCE_PREFIX = "Invalid KeyConditionExpression: " +FILTER_PREFIX = "Invalid FilterExpression: " A = {"S": "alice"} B = {"S": "bob"} C = {"S": "carol"} N1 = {"N": "1"} +VALUES = {"a": A, "b": B, "c": C, "n": N1, "z": {"S": "zed"}, "v": A, "w": B, "extra": B} +GSI = "g-keys" +HASH = "hash-table" # stands for the hash_table fixture in a row's TableName +MISSING_TABLE = "extenddb-test-484-no-such-table" +LEGACY_PK = {"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [A]}} + + +def _undefined(reference: str, expression: str = "KeyConditionExpression") -> str: + """The service's message for an undefined `#name` or `:value`.""" + if reference.startswith("#"): + return ( + f"Invalid {expression}: An expression attribute name used in the " + f"document path is not defined; attribute name: {reference}" + ) + return ( + f"Invalid {expression}: An expression attribute value used in " + f"expression is not defined; attribute value: {reference}" + ) + + +def _mixing(non_expression: str, *expression: str) -> str: + return ( + "Can not use both expression and non-expression parameters in the same " + f"request: Non-expression parameters: {{{non_expression}}} Expression " + f"parameters: {{{', '.join(expression)}}}" + ) -KEYS_ONLY_INDEX = "g-keys" +def _q(kce: str | None = None, values=None, names: dict | None = None, **kwargs) -> dict: + """A Query's parameters. `values` names the entries of VALUES to define, + as "a b n", or is the ExpressionAttributeValues dict itself.""" + request = dict(kwargs) + if kce is not None: + request["KeyConditionExpression"] = kce + if isinstance(values, str): + values = {f":{k}": VALUES[k] for k in values.split()} + if values: + request["ExpressionAttributeValues"] = values + if names: + request["ExpressionAttributeNames"] = names + return request + + +def _refused(client, table: str, request: dict, want: str) -> None: + """Send the Query against `table` and compare the ValidationException's + text with `want`, or its prefix when `want` is one. With KCE_PREFIX the + text must also not contain "operator".""" + request = {"TableName": table, **request} + with pytest.raises(ClientError) as exc_info: + client.query(**request) + err = exc_info.value.response["Error"] + assert err["Code"] == "ValidationException", err + if want in (KCE_PREFIX, FILTER_PREFIX): + assert err["Message"].startswith(want), err["Message"] + if want == KCE_PREFIX: + assert "operator" not in err["Message"], err["Message"] + else: + assert err["Message"] == want @pytest.fixture(scope="class") @@ -107,16 +137,14 @@ def range_table(dynamodb_client): ], GlobalSecondaryIndexes=[ { - "IndexName": KEYS_ONLY_INDEX, + "IndexName": GSI, "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], "Projection": {"ProjectionType": "KEYS_ONLY"}, } ], ) as name: for sk in ("bob", "carol"): - dynamodb_client.put_item( - TableName=name, Item={"pk": {"S": "alice"}, "sk": {"S": sk}} - ) + dynamodb_client.put_item(TableName=name, Item={"pk": {"S": "alice"}, "sk": {"S": sk}}) yield name @@ -127,799 +155,268 @@ def hash_table(dynamodb_client): yield name -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"] - - class TestOneConditionPerKey: - """Every measured duplicate shape, and the shapes that keep their own error.""" - - @pytest.mark.parametrize( - ("expr", "values"), - [ - # The shape in the issue: a second equality on the partition key is - # served on extenddb before the fix, reading :b as a sort key value. - ("pk = :a AND pk = :b", {":a": A, ":b": B}), - ("pk = :a AND pk = :a", {":a": A}), - ("pk = :a AND pk = :b AND sk = :c", {":a": A, ":b": B, ":c": C}), - ("pk = :a AND pk > :b", {":a": A, ":b": B}), - ("pk > :b AND pk = :a", {":a": A, ":b": B}), - (":a = pk AND pk = :b", {":a": A, ":b": B}), - ("(pk = :a) AND (pk = :b)", {":a": A, ":b": B}), - ], - ) - def test_duplicate_partition_key_condition( - self, dynamodb_client, range_table, expr, values - ): - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression=expr, - ExpressionAttributeValues=values, - ) - ) - assert code == "ValidationException" - assert msg == ONE_PER_KEY - - @pytest.mark.parametrize( - ("expr", "values"), - [ - ("pk = :a AND sk = :b AND sk = :c", {":a": A, ":b": B, ":c": C}), - ("pk = :a AND sk = :b AND sk = :b", {":a": A, ":b": B}), - ( - "pk = :a AND sk BETWEEN :b AND :c AND sk = :b", - {":a": A, ":b": B, ":c": C}, - ), - ( - "pk = :a AND sk BETWEEN :b AND :c AND begins_with(sk, :b)", - {":a": A, ":b": B, ":c": C}, - ), - ("pk = :a AND begins_with(sk, :b) AND sk = :c", {":a": A, ":b": B, ":c": C}), - ("pk = :a AND sk > :b AND sk < :c", {":a": A, ":b": B, ":c": C}), - ( - "pk = :a AND begins_with(sk, :b) AND begins_with(sk, :c)", - {":a": A, ":b": B, ":c": C}, - ), - ("pk = :a AND pk = :b AND sk = :b AND sk = :c", {":a": A, ":b": B, ":c": C}), - # No partition key condition at all: the duplicate is reported - # ahead of the missing key schema element. - ("sk = :b AND sk = :c", {":b": B, ":c": C}), - ], - ) - def test_duplicate_sort_key_condition( - self, dynamodb_client, range_table, expr, values - ): - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression=expr, - ExpressionAttributeValues=values, - ) - ) - assert code == "ValidationException" - assert msg == ONE_PER_KEY + """Every measured duplicate shape (2026-10-24, and 2026-11-11 for J1 and + J2), the shapes that keep their own error, and the distinct conditions + that are served.""" + + ROWS = [ + ("pk = :a AND pk = :b", _q("pk = :a AND pk = :b", "a b"), ONE_PER_KEY), + ("pk = :a AND pk = :a", _q("pk = :a AND pk = :a", "a"), ONE_PER_KEY), + ("pk twice, sk", _q("pk = :a AND pk = :b AND sk = :c", "a b c"), ONE_PER_KEY), + ("pk = :a AND pk > :b", _q("pk = :a AND pk > :b", "a b"), ONE_PER_KEY), + ("pk > :b AND pk = :a", _q("pk > :b AND pk = :a", "a b"), ONE_PER_KEY), + (":a = pk AND pk = :b", _q(":a = pk AND pk = :b", "a b"), ONE_PER_KEY), + ("(pk = :a) AND (pk = :b)", _q("(pk = :a) AND (pk = :b)", "a b"), ONE_PER_KEY), + ("sk = :b AND sk = :c", _q("pk = :a AND sk = :b AND sk = :c", "a b c"), ONE_PER_KEY), + ("sk = :b AND sk = :b", _q("pk = :a AND sk = :b AND sk = :b", "a b"), ONE_PER_KEY), + ("BETWEEN and =", _q("pk = :a AND sk BETWEEN :b AND :c AND sk = :b", "a b c"), ONE_PER_KEY), + ( + "BETWEEN and begins_with", + _q("pk = :a AND sk BETWEEN :b AND :c AND begins_with(sk, :b)", "a b c"), + ONE_PER_KEY, + ), + ( + "begins_with and =", + _q("pk = :a AND begins_with(sk, :b) AND sk = :c", "a b c"), + ONE_PER_KEY, + ), + ("> and <", _q("pk = :a AND sk > :b AND sk < :c", "a b c"), ONE_PER_KEY), + ( + "begins_with twice", + _q("pk = :a AND begins_with(sk, :b) AND begins_with(sk, :c)", "a b c"), + ONE_PER_KEY, + ), + ( + "pk twice, sk twice", + _q("pk = :a AND pk = :b AND sk = :b AND sk = :c", "a b c"), + ONE_PER_KEY, + ), + # No partition key condition: the duplicate comes ahead of the missing key. + ("sk twice, no pk", _q("sk = :b AND sk = :c", "b c"), ONE_PER_KEY), + ("#p = :a AND pk = :b", _q("#p = :a AND pk = :b", "a b", {"#p": "pk"}), ONE_PER_KEY), + ("#p and #q", _q("#p = :a AND #q = :b", "a b", {"#p": "pk", "#q": "pk"}), ONE_PER_KEY), + ("#s and sk", _q("pk = :a AND #s = :b AND sk = :c", "a b c", {"#s": "sk"}), ONE_PER_KEY), + ("J1 non-key attribute twice", _q("pk = :a AND zz = :b AND zz = :c", "a b c"), ONE_PER_KEY), + ("J2 hash-only table", _q("pk = :a AND pk = :b", "a b", TableName=HASH), ONE_PER_KEY), + ("nested path first", _q("pk = :a AND pk.foo = :b", "a b"), NESTED), + ("redundant parentheses first", _q("((pk = :a)) AND (pk = :b)", "a b"), REDUNDANT_PARENS), + ("undefined #u first", _q("#u = :a AND #u = :b", "a b"), _undefined("#u")), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, range_table, hash_table, row): + _, request, want = row + if request.get("TableName") == HASH: + request = {**request, "TableName": hash_table} + _refused(dynamodb_client, range_table, request, want) @pytest.mark.parametrize( - ("expr", "values", "names"), + ("kce", "values", "count"), [ - ("#p = :a AND pk = :b", {":a": A, ":b": B}, {"#p": "pk"}), - ("#p = :a AND #q = :b", {":a": A, ":b": B}, {"#p": "pk", "#q": "pk"}), - ( - "pk = :a AND #s = :b AND sk = :c", - {":a": A, ":b": B, ":c": C}, - {"#s": "sk"}, - ), + ("pk = :a", "a", 2), + ("pk = :a AND sk = :b", "a b", 1), + ("sk = :b AND pk = :a", "a b", 1), + ("pk = :a AND sk BETWEEN :b AND :c", "a b c", 2), ], ) - def test_duplicate_through_name_reference( - self, dynamodb_client, range_table, expr, values, names - ): - """An #name alias resolving to the same attribute is a duplicate.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression=expr, - ExpressionAttributeValues=values, - ExpressionAttributeNames=names, - ) - ) - assert code == "ValidationException" - assert msg == ONE_PER_KEY - - def test_duplicate_condition_on_a_non_key_attribute( - self, dynamodb_client, range_table - ): - """Measured 2026-11-11T14:39Z: two conditions on zz, which is not a key - attribute, answer the duplicate too.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a AND zz = :b AND zz = :c", - ExpressionAttributeValues={":a": A, ":b": B, ":c": C}, - ) - ) - assert code == "ValidationException" - assert msg == ONE_PER_KEY - - def test_duplicate_partition_key_condition_on_a_hash_only_table( - self, dynamodb_client, hash_table - ): - """Measured 2026-11-11T14:39Z on a table keyed on pk (S) alone.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=hash_table, - KeyConditionExpression="pk = :a AND pk = :b", - ExpressionAttributeValues={":a": A, ":b": B}, - ) - ) - assert code == "ValidationException" - assert msg == ONE_PER_KEY - - def test_distinct_key_conditions_still_served(self, dynamodb_client, range_table): - """One condition per key attribute, in either order, returns rows.""" - pk_only = dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a", - ExpressionAttributeValues={":a": A}, - ) - assert pk_only["Count"] == 2 - - pk_and_sk = dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a AND sk = :b", - ExpressionAttributeValues={":a": A, ":b": B}, - ) - assert pk_and_sk["Count"] == 1 - - sk_first = dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="sk = :b AND pk = :a", - ExpressionAttributeValues={":a": A, ":b": B}, - ) - assert sk_first["Count"] == 1 - - sk_range = dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a AND sk BETWEEN :b AND :c", - ExpressionAttributeValues={":a": A, ":b": B, ":c": C}, - ) - assert sk_range["Count"] == 2 - - def test_nested_path_reported_ahead_of_duplicate( - self, dynamodb_client, range_table - ): - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a AND pk.foo = :b", - ExpressionAttributeValues={":a": A, ":b": B}, - ) - ) - assert code == "ValidationException" - assert msg == NESTED - - def test_redundant_parens_reported_ahead_of_duplicate( - self, dynamodb_client, range_table - ): - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="((pk = :a)) AND (pk = :b)", - ExpressionAttributeValues={":a": A, ":b": B}, - ) - ) - assert code == "ValidationException" - assert msg == REDUNDANT_PARENS - - def test_undefined_name_reported_ahead_of_duplicate( - self, dynamodb_client, range_table + def test_distinct_key_conditions_still_served( + self, dynamodb_client, range_table, kce, values, count ): - """Two conditions on an undefined #name: the name is reported.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="#u = :a AND #u = :b", - ExpressionAttributeValues={":a": A, ":b": B}, - ) - ) - assert code == "ValidationException" - assert msg == UNDEFINED_NAME_EXACT + got = dynamodb_client.query(TableName=range_table, **_q(kce, values)) + assert got["Count"] == count class TestDuplicateCheckOrder: - """Where the duplicate is reported against the other checks (2026-10-31).""" - - @pytest.mark.parametrize( - ("expr", "values"), - [ - ("#u = :a AND sk = :b AND sk = :c", {":a": A, ":b": B, ":c": C}), - ("pk = :a AND pk = :b AND #u = :c", {":a": A, ":b": B, ":c": C}), - ("#u = :a AND #u > :b", {":a": A, ":b": B}), - ], - ) - def test_undefined_name_in_any_clause_reported_ahead_of_duplicate( - self, dynamodb_client, range_table, expr, values - ): - """No ExpressionAttributeNames: the undefined #u is reported.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression=expr, - ExpressionAttributeValues=values, - ) - ) - assert code == "ValidationException" - assert msg == UNDEFINED_NAME_EXACT - - def test_undefined_value_reported_ahead_of_duplicate( - self, dynamodb_client, range_table - ): - """No ExpressionAttributeValues: the first undefined value is reported.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a AND pk = :b", - ) - ) - assert code == "ValidationException" - assert msg == UNDEFINED_VALUE_A - - @pytest.mark.parametrize( - ("expr", "values", "names"), - [ - # A number on the S key: the duplicate is reported ahead of the - # key value type check, in either spelling. - ("#p = :a AND pk = :n", {":a": A, ":n": N1}, {"#p": "pk"}), - ( - "pk = :a AND #s = :b AND sk = :n", - {":a": A, ":b": B, ":n": N1}, - {"#s": "sk"}, - ), - # An unused value: the duplicate is reported ahead of the - # unused-value check. - ("pk = :a AND pk = :b", {":a": A, ":b": B, ":z": {"S": "zed"}}, None), - ], - ) - def test_duplicate_reported_ahead_of_value_checks( - self, dynamodb_client, range_table, expr, values, names - ): - kwargs = { - "TableName": range_table, - "KeyConditionExpression": expr, - "ExpressionAttributeValues": values, - } - if names is not None: - kwargs["ExpressionAttributeNames"] = names - code, msg = _error(lambda: dynamodb_client.query(**kwargs)) - assert code == "ValidationException" - assert msg == ONE_PER_KEY + """The duplicate against undefined references, the key value type check + and an unused value (2026-10-31).""" + + ROWS = [ + ("#u in clause 1", _q("#u = :a AND sk = :b AND sk = :c", "a b c"), _undefined("#u")), + ("#u in clause 3", _q("pk = :a AND pk = :b AND #u = :c", "a b c"), _undefined("#u")), + ("#u twice, >", _q("#u = :a AND #u > :b", "a b"), _undefined("#u")), + ("no values", _q("pk = :a AND pk = :b"), _undefined(":a")), + # A number on the S key: the duplicate comes ahead of the type check. + ("#p and pk, :n", _q("#p = :a AND pk = :n", "a n", {"#p": "pk"}), ONE_PER_KEY), + ( + "#s and sk, :n", + _q("pk = :a AND #s = :b AND sk = :n", "a b n", {"#s": "sk"}), + ONE_PER_KEY, + ), + ("unused :z", _q("pk = :a AND pk = :b", "a b z"), ONE_PER_KEY), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, range_table, row): + _, request, want = row + _refused(dynamodb_client, range_table, request, want) class TestDuplicateAheadOfRequestChecks: - """Where the duplicate is reported against the FilterExpression and the - table, index, ConsistentRead and Select checks (2026-11-11).""" - - @pytest.mark.parametrize( - ("filter_expr", "values", "want"), - [ - ( - "#q = :a", - {":a": A, ":b": B}, - "Invalid FilterExpression: An expression attribute name used in " - "the document path is not defined; attribute name: #q", - ), - ( - "foo = :zz", - {":a": A, ":b": B}, - "Invalid FilterExpression: An expression attribute value used in " - "expression is not defined; attribute value: :zz", - ), - ( - "begins_with(foo, :n)", - {":a": A, ":b": B, ":n": N1}, - "Invalid FilterExpression: Incorrect operand type for operator or " - "function; operator or function: begins_with, operand type: N", - ), - ( - "name = :a", - {":a": A, ":b": B}, - "Invalid FilterExpression: Attribute name is a reserved keyword; " - "reserved keyword: name", - ), - ], - ids=["undefined-name", "undefined-value", "begins-with-number", "reserved-word"], - ) - def test_filter_fault_reported_ahead_of_duplicate( - self, dynamodb_client, range_table, filter_expr, values, want - ): - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a AND pk = :b", - FilterExpression=filter_expr, - ExpressionAttributeValues=values, - ) - ) - assert code == "ValidationException" - assert msg == want - - def test_filter_syntax_error_reported_ahead_of_duplicate( - self, dynamodb_client, range_table - ): - """The service answers `Invalid FilterExpression: Syntax error; token: - "=", near: "= = :a"`; extenddb words its syntax errors differently, so - only the expression the error names is compared.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a AND pk = :b", - FilterExpression="zz = = :a", - ExpressionAttributeValues={":a": A, ":b": B}, - ) - ) - assert code == "ValidationException" - assert msg.startswith("Invalid FilterExpression: "), msg - - @pytest.mark.parametrize( - ("kwargs", "on_index"), - [ - ({"TableName": "extenddb-test-484-no-such-table"}, False), - ({"IndexName": "nope"}, False), - ({"IndexName": KEYS_ONLY_INDEX, "ConsistentRead": True}, True), - ({"Select": "BOGUS"}, False), - ({"IndexName": KEYS_ONLY_INDEX, "Select": "ALL_ATTRIBUTES"}, True), - ], - ids=[ - "missing-table", - "unknown-index", - "consistent-read-on-gsi", - "invalid-select", - "all-attributes-on-keys-only-gsi", - ], - ) - def test_duplicate_reported_ahead_of_table_index_and_select_checks( - self, dynamodb_client, range_table, kwargs, on_index - ): - key = "g" if on_index else "pk" - request = { - "TableName": range_table, - "KeyConditionExpression": f"{key} = :a AND {key} = :b", - "ExpressionAttributeValues": {":a": A, ":b": B}, - **kwargs, - } - code, msg = _error(lambda: dynamodb_client.query(**request)) - assert code == "ValidationException" - assert msg == ONE_PER_KEY - - @pytest.mark.parametrize( - ("kwargs", "non_expression"), - [ - ({"ConditionalOperator": "AND"}, "ConditionalOperator"), - ( - { - "KeyConditions": { - "pk": {"ComparisonOperator": "EQ", "AttributeValueList": [A]} - } - }, - "KeyConditions", - ), - ], - ids=["conditional-operator", "key-conditions"], - ) - def test_parameter_mixing_reported_ahead_of_duplicate( - self, dynamodb_client, range_table, kwargs, non_expression - ): - """Measured 2026-11-11T11:23Z: a non-expression parameter beside the - expression answers the mixing error, not the duplicate.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a AND pk = :b", - ExpressionAttributeValues={":a": A, ":b": B}, - **kwargs, - ) - ) - assert code == "ValidationException" - assert msg == ( - "Can not use both expression and non-expression parameters in the same " - f"request: Non-expression parameters: {{{non_expression}}} Expression " - "parameters: {KeyConditionExpression}" - ) - - -def _undefined(reference: str) -> str: - """The service's message for an undefined `#name` or `:value`.""" - if reference.startswith("#"): - return ( - "Invalid KeyConditionExpression: An expression attribute name used in " - f"the document path is not defined; attribute name: {reference}" - ) - return ( - "Invalid KeyConditionExpression: An expression attribute value used in " - f"expression is not defined; attribute value: {reference}" - ) + """The duplicate against the FilterExpression (A), the table, index, + ConsistentRead and Select checks (B) and parameter mixing (E8, E9), + measured 2026-11-11T09:43Z and 11:23Z.""" + + DUP = "pk = :a AND pk = :b" + ROWS = [ + ("A1", _q(DUP, "a b", FilterExpression="#q = :a"), _undefined("#q", "FilterExpression")), + ("A2", _q(DUP, "a b", FilterExpression="foo = :zz"), _undefined(":zz", "FilterExpression")), + ("A3", _q(DUP, "a b n", FilterExpression="begins_with(foo, :n)"), FILTER_BEGINS_WITH_N), + ("A4", _q(DUP, "a b", FilterExpression="name = :a"), FILTER_RESERVED_NAME), + ("A5", _q(DUP, "a b", FilterExpression="zz = = :a"), FILTER_PREFIX), + ("B1", _q(DUP, "a b", TableName=MISSING_TABLE), ONE_PER_KEY), + ("B2", _q(DUP, "a b", IndexName="nope"), ONE_PER_KEY), + ("B3", _q("g = :a AND g = :b", "a b", IndexName=GSI, ConsistentRead=True), ONE_PER_KEY), + ("B4", _q(DUP, "a b", Select="BOGUS"), ONE_PER_KEY), + ("B5", _q("g = :a AND g = :b", "a b", IndexName=GSI, Select="ALL_ATTRIBUTES"), ONE_PER_KEY), + ( + "E8", + _q(DUP, "a b", ConditionalOperator="AND"), + _mixing("ConditionalOperator", "KeyConditionExpression"), + ), + ( + "E9", + _q(DUP, "a b", KeyConditions=LEGACY_PK), + _mixing("KeyConditions", "KeyConditionExpression"), + ), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, range_table, row): + _, request, want = row + _refused(dynamodb_client, range_table, request, want) class TestReferenceAndOperatorOrder: - """Which undefined reference is reported, and the operators beside a - duplicate (2026-11-10 and 2026-11-11).""" - - @pytest.mark.parametrize( - ("expr", "names", "values", "undefined"), - [ - ("pk = :q AND #u = :c", None, None, ":q"), - ("sk = :b AND pk = :a", None, None, ":b"), - ("pk = :a AND sk = :missing", None, {":a": A, ":extra": B}, ":missing"), - ("pk = :a AND pk = :b AND #u = :c", None, None, ":a"), - ("pk = :q AND pk = :b AND #u = :c", None, {":b": B, ":c": C}, ":q"), - ("#u = :a AND #u = :b", None, None, "#u"), - ("pk = :b AND pk = :a", None, None, ":b"), - # Measured 2026-11-10 on a table keyed on pk (S) alone; each - # request also carries an unused name or value. - ("pk = :v", None, {":w": A}, ":v"), - ("#k = :v", None, {":v": A, ":w": B}, "#k"), - ("#k = :v", {"#j": "pk"}, {":v": A}, "#k"), - ("pk = :v", {"#j": "pk"}, {":w": A}, ":v"), - ("#k = :v", None, {":w": A}, "#k"), - ], - ) - def test_first_undefined_reference_in_text_order_is_reported( - self, dynamodb_client, range_table, expr, names, values, undefined - ): - kwargs = {"TableName": range_table, "KeyConditionExpression": expr} - if names is not None: - kwargs["ExpressionAttributeNames"] = names - if values is not None: - kwargs["ExpressionAttributeValues"] = values - code, msg = _error(lambda: dynamodb_client.query(**kwargs)) - assert code == "ValidationException" - assert msg == _undefined(undefined) - - @pytest.mark.parametrize( - ("expr", "values", "want"), - [ - ("pk = :a AND pk <> :b", {":a": A, ":b": B}, ONE_PER_KEY), - ("pk = :a AND contains(pk, :b)", {":a": A, ":b": B}, ONE_PER_KEY), - ( - "pk = :a AND begins_with(sk, :n) AND sk = :b", - {":a": A, ":b": B, ":n": N1}, - BEGINS_WITH_N, - ), - # Measured 2026-11-11T11:23Z: `<>` or contains beside a second - # condition on sk. - ("pk = :a AND sk <> :b AND sk = :c", {":a": A, ":b": B, ":c": C}, ONE_PER_KEY), - ( - "pk = :a AND contains(sk, :b) AND sk = :c", - {":a": A, ":b": B, ":c": C}, - ONE_PER_KEY, - ), - ], - ) - def test_operators_beside_a_duplicate( - self, dynamodb_client, range_table, expr, values, want - ): - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression=expr, - ExpressionAttributeValues=values, - ) - ) - assert code == "ValidationException" - assert msg == want - - @pytest.mark.parametrize( - ("expr", "values", "want"), - [ - # A number in begins_with on an S sort key, with no duplicate: the - # operand type, not the key value type. - ("pk = :a AND begins_with(sk, :n)", {":a": A, ":n": N1}, BEGINS_WITH_N), - # An undefined name beside `<>` or contains: the name. - ( - "pk = :a AND sk <> :b AND #u = :c", - {":a": A, ":b": B, ":c": C}, - _undefined("#u"), - ), - ( - "pk = :a AND contains(sk, :b) AND #u = :c", - {":a": A, ":b": B, ":c": C}, - _undefined("#u"), - ), - ], - ) - def test_operators_and_operands_without_a_duplicate( - self, dynamodb_client, range_table, expr, values, want - ): - """Measured 2026-11-11T11:22Z.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression=expr, - ExpressionAttributeValues=values, - ) - ) - assert code == "ValidationException" - assert msg == want - - def test_syntax_error_after_ne_reported_ahead_of_it( - self, dynamodb_client, range_table - ): - """Measured 2026-11-11T11:23Z: the service answers `Invalid - KeyConditionExpression: Syntax error; token: "", near: "AND"`. - extenddb words its syntax errors differently, so the test checks - that a syntax error is reported and not the operator.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a AND sk <> :b AND", - ExpressionAttributeValues={":a": A, ":b": B}, - ) - ) - assert code == "ValidationException" - assert msg.startswith("Invalid KeyConditionExpression: "), msg - assert "operator" not in msg, msg - - -FILTER_UNDEFINED_Q = ( - "Invalid FilterExpression: An expression attribute name used in the " - "document path is not defined; attribute name: #q" -) -FILTER_UNDEFINED_ZZ = ( - "Invalid FilterExpression: An expression attribute value used in " - "expression is not defined; attribute value: :zz" -) -EMPTY_PARTITION = {"S": "p484-empty"} - - -def _mixing(*expression_parameters: str) -> str: - return ( - "Can not use both expression and non-expression parameters in the same " - "request: Non-expression parameters: {ConditionalOperator} Expression " - f"parameters: {{{', '.join(expression_parameters)}}}" - ) + """The first undefined reference in the order the expression is written + (C, 2026-11-11, and the 2026-11-10 rows on a table keyed on pk alone), and + `<>`, `contains` and `begins_with` with and without a duplicate (D, E, + 2026-11-11).""" + + ROWS = [ + ("C1", _q("pk = :q AND #u = :c"), _undefined(":q")), + ("C2", _q("sk = :b AND pk = :a"), _undefined(":b")), + ("C3", _q("pk = :a AND sk = :missing", "a extra"), _undefined(":missing")), + ("C4", _q("pk = :a AND pk = :b AND #u = :c"), _undefined(":a")), + ("C5", _q("pk = :q AND pk = :b AND #u = :c", "b c"), _undefined(":q")), + ("C6", _q("#u = :a AND #u = :b"), _undefined("#u")), + ("C7", _q("pk = :b AND pk = :a"), _undefined(":b")), + # 2026-11-10: each request also carries an unused name or value. + ("10 Nov unused :w", _q("pk = :v", {":w": A}), _undefined(":v")), + ("10 Nov #k, unused :w", _q("#k = :v", "v w"), _undefined("#k")), + ("10 Nov #k, unused #j", _q("#k = :v", "v", {"#j": "pk"}), _undefined("#k")), + ("10 Nov unused #j and :w", _q("pk = :v", {":w": A}, {"#j": "pk"}), _undefined(":v")), + ("10 Nov #k, only :w", _q("#k = :v", {":w": A}), _undefined("#k")), + ("D1", _q("pk = :a AND pk <> :b", "a b"), ONE_PER_KEY), + ("D2", _q("pk = :a AND contains(pk, :b)", "a b"), ONE_PER_KEY), + ("D3", _q("pk = :a AND begins_with(sk, :n) AND sk = :b", "a b n"), BEGINS_WITH_N), + ("E11", _q("pk = :a AND sk <> :b AND sk = :c", "a b c"), ONE_PER_KEY), + ("E12", _q("pk = :a AND contains(sk, :b) AND sk = :c", "a b c"), ONE_PER_KEY), + ("E1", _q("pk = :a AND begins_with(sk, :n)", "a n"), BEGINS_WITH_N), + ("E2", _q("pk = :a AND sk <> :b AND #u = :c", "a b c"), _undefined("#u")), + ("E3", _q("pk = :a AND contains(sk, :b) AND #u = :c", "a b c"), _undefined("#u")), + # The service answers a syntax error; the prefix match also checks that + # the operator is not what is reported. + ("E10", _q("pk = :a AND sk <> :b AND", "a b"), KCE_PREFIX), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, range_table, row): + _, request, want = row + _refused(dynamodb_client, range_table, request, want) class TestQueryCheckOrder: """The order of a Query's checks without a duplicate (2026-11-11T12:42Z to 12:44Z): parameters, then the FilterExpression, then the KeyConditionExpression, then Select, the table, the index and - ConsistentRead.""" - - @pytest.mark.parametrize( - ("kce", "values", "filter_expr", "want"), - [ - # F1: an undefined key condition value beside an undefined filter - # name. - ("pk = :a AND sk = :missing", {":a": A}, "#q = :a", FILTER_UNDEFINED_Q), - # F1c, F1d: an undefined key condition name beside an undefined - # filter name or value. - ("pk = :a AND #s = :b", {":a": A, ":b": B}, "#q = :a", FILTER_UNDEFINED_Q), - ("pk = :a AND #s = :b", {":a": A, ":b": B}, "foo = :zz", FILTER_UNDEFINED_ZZ), - # F1e: a valid filter, so the key condition value answers. - ( - "pk = :a AND sk = :missing", - {":a": A}, - "foo = :a", - "Invalid KeyConditionExpression: An expression attribute value used " - "in expression is not defined; attribute value: :missing", - ), - # F1f: a number in begins_with on the S sort key. - ( - "pk = :a AND begins_with(sk, :n)", - {":a": A, ":n": N1}, - "#q = :a", - FILTER_UNDEFINED_Q, - ), - # F1g: a key condition syntax error (a trailing AND). - ("pk = :a AND", {":a": A}, "#q = :a", FILTER_UNDEFINED_Q), - ], - ids=["F1", "F1c", "F1d", "F1e", "F1f", "F1g"], - ) - def test_filter_fault_reported_ahead_of_key_condition_fault( - self, dynamodb_client, range_table, kce, values, filter_expr, want - ): - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression=kce, - ExpressionAttributeValues=values, - FilterExpression=filter_expr, - ) - ) - assert code == "ValidationException" - assert msg == want - - def test_filter_syntax_error_reported_ahead_of_key_condition_value( - self, dynamodb_client, range_table - ): - """F1b. The service answers `Invalid FilterExpression: Syntax error; - token: "=", near: "= = :a"`; extenddb words its syntax errors - differently, so the prefix is compared.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a AND sk = :missing", - ExpressionAttributeValues={":a": A}, - FilterExpression="zz = = :a", - ) - ) - assert code == "ValidationException" - assert msg.startswith("Invalid FilterExpression: "), msg - - @pytest.mark.parametrize( - ("kwargs", "on_index", "want"), - [ - # F2a to F2d: the mixing error ahead of each. - ( - {"TableName": "extenddb-test-484-no-such-table", "ConditionalOperator": "AND"}, - False, - _mixing("KeyConditionExpression"), - ), - ({"IndexName": "nope", "ConditionalOperator": "AND"}, False, _mixing("KeyConditionExpression")), - ({"Select": "BOGUS", "ConditionalOperator": "AND"}, False, _mixing("KeyConditionExpression")), - ( - {"IndexName": KEYS_ONLY_INDEX, "ConsistentRead": True, "ConditionalOperator": "AND"}, - True, - _mixing("KeyConditionExpression"), - ), - # H1 to H4: an undefined filter name ahead of each. - ( - {"TableName": "extenddb-test-484-no-such-table", "FilterExpression": "#q = :a"}, - False, - FILTER_UNDEFINED_Q, - ), - ({"IndexName": "nope", "FilterExpression": "#q = :a"}, False, FILTER_UNDEFINED_Q), - ({"Select": "BOGUS", "FilterExpression": "#q = :a"}, False, FILTER_UNDEFINED_Q), - ( - {"IndexName": KEYS_ONLY_INDEX, "ConsistentRead": True, "FilterExpression": "#q = :a"}, - True, - FILTER_UNDEFINED_Q, - ), - # H5: the mixing error ahead of an undefined filter name. - ( - {"ConditionalOperator": "AND", "FilterExpression": "#q = :a"}, - False, - _mixing("FilterExpression", "KeyConditionExpression"), - ), - ], - ids=["F2a", "F2b", "F2c", "F2d", "H1", "H2", "H3", "H4", "H5"], - ) - def test_parameter_and_filter_checks_reported_ahead_of_request_checks( - self, dynamodb_client, range_table, kwargs, on_index, want - ): - request = { - "TableName": range_table, - "KeyConditionExpression": "g = :a" if on_index else "pk = :a", - "ExpressionAttributeValues": {":a": A}, - **kwargs, - } - code, msg = _error(lambda: dynamodb_client.query(**request)) - assert code == "ValidationException" - assert msg == want - - def test_undefined_filter_value_refused_on_an_empty_partition( - self, dynamodb_client, range_table - ): - """F3: refused before any item is read.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="pk = :a", - ExpressionAttributeValues={":a": EMPTY_PARTITION}, - FilterExpression="foo = :zz", - ) - ) - assert code == "ValidationException" - assert msg == FILTER_UNDEFINED_ZZ - - -LIMIT_ZERO = ( - "1 validation error detected: Value at 'Limit' failed to satisfy constraint: " - "Member must have value greater than or equal to 1" -) -MISSING_TABLE = "extenddb-test-484-no-such-table" -LEGACY_PK = {"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [A]}} + ConsistentRead. F3 is an undefined filter value on a partition with no + items.""" + + Q = "#q = :a" + CO = {"ConditionalOperator": "AND"} + UNDEFINED_Q = _undefined("#q", "FilterExpression") + MIXING = _mixing("ConditionalOperator", "KeyConditionExpression") + ROWS = [ + ("F1", _q("pk = :a AND sk = :missing", "a", FilterExpression=Q), UNDEFINED_Q), + ("F1b", _q("pk = :a AND sk = :missing", "a", FilterExpression="zz = = :a"), FILTER_PREFIX), + ("F1c", _q("pk = :a AND #s = :b", "a b", FilterExpression=Q), UNDEFINED_Q), + ( + "F1d", + _q("pk = :a AND #s = :b", "a b", FilterExpression="foo = :zz"), + _undefined(":zz", "FilterExpression"), + ), + ( + "F1e", + _q("pk = :a AND sk = :missing", "a", FilterExpression="foo = :a"), + _undefined(":missing"), + ), + ("F1f", _q("pk = :a AND begins_with(sk, :n)", "a n", FilterExpression=Q), UNDEFINED_Q), + ("F1g", _q("pk = :a AND", "a", FilterExpression=Q), UNDEFINED_Q), + ("F2a", _q("pk = :a", "a", TableName=MISSING_TABLE, **CO), MIXING), + ("F2b", _q("pk = :a", "a", IndexName="nope", **CO), MIXING), + ("F2c", _q("pk = :a", "a", Select="BOGUS", **CO), MIXING), + ("F2d", _q("g = :a", "a", IndexName=GSI, ConsistentRead=True, **CO), MIXING), + ("H1", _q("pk = :a", "a", TableName=MISSING_TABLE, FilterExpression=Q), UNDEFINED_Q), + ("H2", _q("pk = :a", "a", IndexName="nope", FilterExpression=Q), UNDEFINED_Q), + ("H3", _q("pk = :a", "a", Select="BOGUS", FilterExpression=Q), UNDEFINED_Q), + ( + "H4", + _q("g = :a", "a", IndexName=GSI, ConsistentRead=True, FilterExpression=Q), + UNDEFINED_Q, + ), + ( + "H5", + _q("pk = :a", "a", FilterExpression=Q, **CO), + _mixing("ConditionalOperator", "FilterExpression", "KeyConditionExpression"), + ), + ( + "F3", + _q("pk = :a", {":a": {"S": "p484-empty"}}, FilterExpression="foo = :zz"), + _undefined(":zz", "FilterExpression"), + ), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, range_table, row): + _, request, want = row + _refused(dynamodb_client, range_table, request, want) class TestLimitAndParameterChecksFirst: - """Limit and the other parameter checks against the rest (2026-11-11T13:26Z).""" - - @pytest.mark.parametrize( - ("kwargs", "missing_table"), - [ - ({"KeyConditionExpression": "pk = :a", "ExpressionAttributeValues": {":a": A}}, False), - ( - {"KeyConditionExpression": "pk = :a AND", "ExpressionAttributeValues": {":a": A}}, - False, - ), - ( - { - "KeyConditionExpression": "pk = :a AND pk = :b", - "ExpressionAttributeValues": {":a": A, ":b": B}, - }, - False, - ), - ( - { - "KeyConditionExpression": "pk = :a", - "ExpressionAttributeValues": {":a": A}, - "FilterExpression": "#q = :a", - }, - False, - ), - ( - { - "KeyConditionExpression": "pk = :a", - "ExpressionAttributeValues": {":a": A}, - "ConditionalOperator": "AND", - }, - False, - ), - ({"KeyConditionExpression": "pk = :a", "ExpressionAttributeValues": {":a": A}}, True), - ( - { - "KeyConditionExpression": "pk = :a", - "ExpressionAttributeValues": {":a": A}, - "Select": "BOGUS", - }, - False, - ), - ], - ids=["L1", "L2", "L3", "L4", "L5", "L6", "L7"], - ) - def test_limit_zero_reported_first( - self, dynamodb_client_no_validation, range_table, kwargs, missing_table - ): - """Limit 0 answers its own message ahead of a key condition syntax - error, a duplicate, a filter fault, a parameter mixing error, a - missing table and Select BOGUS. The SDK refuses Limit 0 before it - sends the request, so this client has its checks off.""" - code, msg = _error( - lambda: dynamodb_client_no_validation.query( - TableName=MISSING_TABLE if missing_table else range_table, - Limit=0, - **kwargs, - ) - ) - assert code == "ValidationException" - assert msg == LIMIT_ZERO - - def test_begins_with_number_on_the_partition_key(self, dynamodb_client, range_table): - """P1: the operand type, ahead of the partition key equality rule.""" - code, msg = _error( - lambda: dynamodb_client.query( - TableName=range_table, - KeyConditionExpression="begins_with(pk, :n)", - ExpressionAttributeValues={":n": N1}, - ) - ) - assert code == "ValidationException" - assert msg == BEGINS_WITH_N - - @pytest.mark.parametrize( - ("kwargs", "want"), - [ - ( - {"KeyConditions": LEGACY_PK, "ExpressionAttributeValues": {":a": A}}, - "ExpressionAttributeValues can only be specified when using expressions", - ), - ( - {"KeyConditionExpression": ""}, - "Invalid KeyConditionExpression: The expression can not be empty;", - ), - ( - {"KeyConditions": LEGACY_PK, "ConditionalOperator": "AND"}, - "ConditionalOperator cannot be used without Filter or Expected", - ), - ], - ids=["M1", "M2", "M3"], - ) - def test_parameter_check_reported_ahead_of_a_missing_table( - self, dynamodb_client, kwargs, want - ): - code, msg = _error(lambda: dynamodb_client.query(TableName=MISSING_TABLE, **kwargs)) - assert code == "ValidationException" - assert msg == want + """Limit 0 ahead of every other fault (L), begins_with on the partition + key (P1) and the parameter checks ahead of a missing table (M), measured + 2026-11-11T13:26Z. The SDK refuses Limit 0 before it sends the request, so + the L rows use the client with its checks off.""" + + ROWS = [ + ("L1", _q("pk = :a", "a", Limit=0), LIMIT_ZERO), + ("L2", _q("pk = :a AND", "a", Limit=0), LIMIT_ZERO), + ("L3", _q("pk = :a AND pk = :b", "a b", Limit=0), LIMIT_ZERO), + ("L4", _q("pk = :a", "a", FilterExpression="#q = :a", Limit=0), LIMIT_ZERO), + ("L5", _q("pk = :a", "a", ConditionalOperator="AND", Limit=0), LIMIT_ZERO), + ("L6", _q("pk = :a", "a", TableName=MISSING_TABLE, Limit=0), LIMIT_ZERO), + ("L7", _q("pk = :a", "a", Select="BOGUS", Limit=0), LIMIT_ZERO), + ("P1", _q("begins_with(pk, :n)", "n"), BEGINS_WITH_N), + ( + "M1", + _q(None, "a", TableName=MISSING_TABLE, KeyConditions=LEGACY_PK), + "ExpressionAttributeValues can only be specified when using expressions", + ), + ( + "M2", + _q("", TableName=MISSING_TABLE), + "Invalid KeyConditionExpression: The expression can not be empty;", + ), + ( + "M3", + _q(None, TableName=MISSING_TABLE, KeyConditions=LEGACY_PK, ConditionalOperator="AND"), + "ConditionalOperator cannot be used without Filter or Expected", + ), + ] + + @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) + def test_refused(self, dynamodb_client, dynamodb_client_no_validation, range_table, row): + _, request, want = row + client = dynamodb_client_no_validation if "Limit" in request else dynamodb_client + _refused(client, range_table, request, want) From e86363916194931cbbb9604c23a2fc22dc6669b9 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:01:56 +0000 Subject: [PATCH 18/29] refactor(query): read and check a Query body in one function handle_query starts with lines that read the body and check it before it reads the table. These lines move to check_request, in the new file crates/engine/src/query/request_checks.rs. They are the ReturnConsumedCapacity and Select checks, the deserialization, the Limit check, the parameter checks, and the parse of the FilterExpression and the KeyConditionExpression. handle_query calls check_request. The moved lines do not change, except that check_request gets the limits as a parameter. The next commit calls check_request from authorization. query.rs goes from 864 to 801 lines. --- crates/engine/src/query.rs | 87 +++-------------- crates/engine/src/query/request_checks.rs | 109 ++++++++++++++++++++++ 2 files changed, 121 insertions(+), 75 deletions(-) create mode 100644 crates/engine/src/query/request_checks.rs diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 2c805b90b..5edf802b9 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -19,7 +19,7 @@ use extenddb_storage::error::StorageError; use crate::OperationContext; use crate::capacity_helpers; use crate::create_table::storage_err_to_dynamo; -use crate::expression_helpers::{build_expression_maps, parse_optional_filter}; +use crate::expression_helpers::parse_optional_filter; use crate::index_helpers::{ VectorIndexReadRefusal, classify_unresolved_index_read, combined_lek_key_schema, validate_query_select_index_support, @@ -33,6 +33,10 @@ use crate::start_key::{ }; use crate::{DispatchMetrics, DispatchResult}; +mod request_checks; + +use request_checks::CheckedRequest; + /// Handle a `Query` request. /// /// Parses `KeyConditionExpression`, queries the storage layer, applies @@ -44,82 +48,15 @@ use crate::{DispatchMetrics, DispatchResult}; /// Returns `DynamoDbError` for validation failures, missing tables, or storage errors. #[allow(clippy::cast_possible_wrap)] // item counts won't exceed i64::MAX pub async fn handle_query( - mut body: Value, + body: Value, ctx: &OperationContext, ) -> Result { - // Pre-scanned before typed deserialization, sequentially: Query stops at - // the FIRST invalid enum, checking ReturnConsumedCapacity ahead of Select. - // Measured 2026-08-24 (us-east-1): both invalid answers "1 validation - // error detected" naming returnConsumedCapacity alone. (Scan is the - // opposite on both counts: it aggregates, select-first; see handle_scan.) - crate::validate_enum_fields( - &body, - &[crate::EnumField { - json_name: "ReturnConsumedCapacity", - valid: &["INDEXES", "TOTAL", "NONE"], - clause: crate::EnumClause::Named("returnConsumedCapacity"), - }], - )?; - // The service checks Select after Limit, the request's parameters, the - // FilterExpression and the KeyConditionExpression (measured 2026-11-11), - // so an invalid Select is left out of the typed input and its error waits - // for those checks below. - let select_check = crate::validate_enum_fields( - &body, - &[crate::EnumField { - json_name: "Select", - valid: &[ - "SPECIFIC_ATTRIBUTES", - "COUNT", - "ALL_ATTRIBUTES", - "ALL_PROJECTED_ATTRIBUTES", - ], - clause: crate::EnumClause::Named("select"), - }], - ); - if select_check.is_err() - && let Some(fields) = body.as_object_mut() - { - fields.remove("Select"); - } - // An invalid Select still comes ahead of a body that does not - // deserialize, as it did when it was checked before deserialization. - let input: QueryInput = match serde_json::from_value(body) { - Ok(input) => input, - Err(err) => { - select_check?; - return Err(crate::deserialize_error(err)); - } - }; - - // Validate Limit >= 1 (REQ-QUERY-001). The service checks Limit ahead of - // every other fault measured (2026-11-11, us-east-1). - if let Some(limit) = input.limit - && limit < 1 - { - return Err(DynamoDbError::ValidationException( - "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1".to_owned(), - )); - } - - // Build expression maps from request (used for expression-based parameters) - let maps = build_expression_maps( - input.expression_attribute_names.as_ref(), - input.expression_attribute_values.as_ref(), - ); - - // The service checks a Query in this order (measured 2026-11-11 in - // us-east-1): Limit, then the request's parameters, then every - // FilterExpression fault, then every KeyConditionExpression fault, then - // Select, the table, the index and ConsistentRead. - check_request_parameters(&input)?; - let filter_expression = parse_filter_expression(&input, &maps, &ctx.limits)?; - let key_condition_expression = input - .key_condition_expression - .as_deref() - .map(|kce| crate::expression_helpers::parse_key_condition_expr(kce, &maps, &ctx.limits)) - .transpose()?; - select_check?; + let CheckedRequest { + input, + maps, + filter_expression, + key_condition_expression, + } = request_checks::check_request(body, &ctx.limits)?; // P118: Fetch key_info first so we can use table_id for index lookup. let key_info = ctx diff --git a/crates/engine/src/query/request_checks.rs b/crates/engine/src/query/request_checks.rs new file mode 100644 index 000000000..0669349f2 --- /dev/null +++ b/crates/engine/src/query/request_checks.rs @@ -0,0 +1,109 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The checks `handle_query` makes on a request before it reads the table. + +use serde_json::Value; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::expression::{Expr, ExpressionMaps, KeyCondition}; +use extenddb_core::limits::LimitsConfig; +use extenddb_core::types::QueryInput; + +use super::{check_request_parameters, parse_filter_expression}; +use crate::expression_helpers::build_expression_maps; + +/// A `Query` request read from its body, with its expressions parsed. +pub(super) struct CheckedRequest { + pub(super) input: QueryInput, + pub(super) maps: ExpressionMaps, + pub(super) filter_expression: Option, + pub(super) key_condition_expression: Option, +} + +/// Read a `Query` body and refuse its faults that come before the table is +/// read, in the order the service reports them. +pub(super) fn check_request( + mut body: Value, + limits: &LimitsConfig, +) -> Result { + // Pre-scanned before typed deserialization, sequentially: Query stops at + // the FIRST invalid enum, checking ReturnConsumedCapacity ahead of Select. + // Measured 2026-08-24 (us-east-1): both invalid answers "1 validation + // error detected" naming returnConsumedCapacity alone. (Scan is the + // opposite on both counts: it aggregates, select-first; see handle_scan.) + crate::validate_enum_fields( + &body, + &[crate::EnumField { + json_name: "ReturnConsumedCapacity", + valid: &["INDEXES", "TOTAL", "NONE"], + clause: crate::EnumClause::Named("returnConsumedCapacity"), + }], + )?; + // The service checks Select after Limit, the request's parameters, the + // FilterExpression and the KeyConditionExpression (measured 2026-11-11), + // so an invalid Select is left out of the typed input and its error waits + // for those checks below. + let select_check = crate::validate_enum_fields( + &body, + &[crate::EnumField { + json_name: "Select", + valid: &[ + "SPECIFIC_ATTRIBUTES", + "COUNT", + "ALL_ATTRIBUTES", + "ALL_PROJECTED_ATTRIBUTES", + ], + clause: crate::EnumClause::Named("select"), + }], + ); + if select_check.is_err() + && let Some(fields) = body.as_object_mut() + { + fields.remove("Select"); + } + // An invalid Select still comes ahead of a body that does not + // deserialize, as it did when it was checked before deserialization. + let input: QueryInput = match serde_json::from_value(body) { + Ok(input) => input, + Err(err) => { + select_check?; + return Err(crate::deserialize_error(err)); + } + }; + + // Validate Limit >= 1 (REQ-QUERY-001). The service checks Limit ahead of + // every other fault measured (2026-11-11, us-east-1). + if let Some(limit) = input.limit + && limit < 1 + { + return Err(DynamoDbError::ValidationException( + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: Member must have value greater than or equal to 1".to_owned(), + )); + } + + // Build expression maps from request (used for expression-based parameters) + let maps = build_expression_maps( + input.expression_attribute_names.as_ref(), + input.expression_attribute_values.as_ref(), + ); + + // The service checks a Query in this order (measured 2026-11-11 in + // us-east-1): Limit, then the request's parameters, then every + // FilterExpression fault, then every KeyConditionExpression fault, then + // Select, the table, the index and ConsistentRead. + check_request_parameters(&input)?; + let filter_expression = parse_filter_expression(&input, &maps, limits)?; + let key_condition_expression = input + .key_condition_expression + .as_deref() + .map(|kce| crate::expression_helpers::parse_key_condition_expr(kce, &maps, limits)) + .transpose()?; + select_check?; + Ok(CheckedRequest { + input, + maps, + filter_expression, + key_condition_expression, + }) +} From e3e1da1305212aee475c6118cdb941bc6bbbb74b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:21:18 +0000 Subject: [PATCH 19/29] fix(server): refuse a duplicate key condition before the IAM decision DynamoDB refuses a Query whose KeyConditionExpression has more than one condition on one key attribute before it evaluates the caller's policy. On us-east-1, on 19 Nov, 9 key condition shapes went twice to the table owner and to 6 roles. Four roles had a dynamodb:LeadingKeys condition: - ForAnyValue:StringEquals on the first partition value - ForAnyValue:StringEquals on the second partition value - ForAllValues:StringEquals on a third value, without a Null guard - ForAllValues:StringEquals on the first value, with a Null guard One role had no Allow for dynamodb:Query, and one had a Deny on it. All 126 requests got the same ValidationException: Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key The service reports some faults ahead of the duplicate. Three were sent with a duplicate to every principal: Limit 0, an undefined name in the FilterExpression, and an undefined name in the key condition. Every principal got the fault. Before this change, authorization ran first, so a principal whose condition excluded the value of the partition key equality got AccessDeniedException. authorize_request now calls refuse_duplicate_key_condition for a Query before the IAM decision. The function looks for a key attribute that the key condition names twice (has_duplicate_key_condition, through the request's ExpressionAttributeNames). When it finds one, it runs check_request and returns its error, so every principal gets the answer the table owner gets. Other requests go on to the IAM decision as before. The check reads nothing from the table. The leading_keys unit test that pinned the value bound for a duplicate is removed, because authorization no longer binds a value for one. The wire tests expect the one-condition-per-key message for every principal. --- crates/core/src/expression/key_condition.rs | 24 +++- crates/core/src/expression/mod.rs | 4 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/query.rs | 1 + crates/engine/src/query/request_checks.rs | 123 +++++++++++++++++++- crates/server/src/leading_keys/tests.rs | 22 ---- crates/server/src/request_helpers.rs | 7 ++ tests/test_fgac_leading_keys.py | 85 +++++++++----- 8 files changed, 208 insertions(+), 60 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index b8f9c8785..0606a2dd9 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -616,9 +616,9 @@ impl SortKeyCondition { /// This does not refuse a second condition on one key attribute, which needs /// the request's `ExpressionAttributeNames` and `ExpressionAttributeValues`. /// The engine parses a request's key condition with -/// [`parse_key_condition_with_maps`]. Authorization parses with this when it -/// finds the partition key value for `dynamodb:LeadingKeys`, which keeps the -/// value it bound for such a condition before the engine refused it. +/// [`parse_key_condition_with_maps`]. Authorization refuses a second condition +/// on one key attribute first ([`has_duplicate_key_condition`]), and parses +/// with this when it finds the partition key value for `dynamodb:LeadingKeys`. /// /// # Errors /// @@ -627,6 +627,19 @@ pub fn parse_key_condition(tokens: &[Token]) -> Result, +) -> bool { + parse_clauses(tokens).is_ok_and(|clauses| reject_duplicate_key_attrs(&clauses, names).is_err()) +} + /// [`parse_key_condition`] with the request's `ExpressionAttributeNames` and /// `ExpressionAttributeValues`. /// @@ -688,9 +701,8 @@ fn refuse_unsupported_clauses(clauses: &[RawClause]) -> Result<(), DynamoDbError /// since it names no single value for the attribute. /// /// Like [`parse_key_condition`], this does not refuse a second condition on -/// one key attribute, so authorization binds `dynamodb:LeadingKeys` for such a -/// condition as it did before the engine refused it. Which value the service -/// binds for it is not measured. +/// one key attribute. Authorization refuses such a condition before it reads +/// this ([`has_duplicate_key_condition`]). /// /// # Errors /// diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 35189baef..0302e1bad 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -29,8 +29,8 @@ mod update_parser; pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only}; pub use evaluator::evaluate_condition; pub use key_condition::{ - KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands, - parse_key_condition, parse_key_condition_with_maps, + KeyClauseOperand, KeyCondition, SortKeyCondition, has_duplicate_key_condition, + key_condition_clause_operands, parse_key_condition, parse_key_condition_with_maps, }; pub use kind::ExpressionKind; pub use parser::{parse_condition, parse_condition_with_depth_limit}; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 637fbc154..26553062c 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -73,7 +73,7 @@ pub use import_export::{handle_export_table, handle_import_table}; pub use item_authorizer::{ItemAccess, ItemAuthorization, ItemAuthorizer}; pub use list_tables::handle_list_tables; pub use put_item::handle_put_item; -pub use query::handle_query; +pub use query::{handle_query, refuse_duplicate_key_condition}; pub use request_limits::check_request_item_counts; pub use scan::handle_scan; pub use search_vectors::handle_search_vectors; diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 5edf802b9..6417fe744 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -36,6 +36,7 @@ use crate::{DispatchMetrics, DispatchResult}; mod request_checks; use request_checks::CheckedRequest; +pub use request_checks::refuse_duplicate_key_condition; /// Handle a `Query` request. /// diff --git a/crates/engine/src/query/request_checks.rs b/crates/engine/src/query/request_checks.rs index 0669349f2..1e6a0dde9 100644 --- a/crates/engine/src/query/request_checks.rs +++ b/crates/engine/src/query/request_checks.rs @@ -1,12 +1,18 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! The checks `handle_query` makes on a request before it reads the table. +//! The checks `handle_query` makes on a request before it reads the table, +//! and the refusal authorization makes with them for a key condition with two +//! conditions on one key attribute. + +use std::collections::HashMap; use serde_json::Value; use extenddb_core::error::DynamoDbError; -use extenddb_core::expression::{Expr, ExpressionMaps, KeyCondition}; +use extenddb_core::expression::{ + Expr, ExpressionKind, ExpressionMaps, KeyCondition, has_duplicate_key_condition, tokenize_for, +}; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::QueryInput; @@ -107,3 +113,116 @@ pub(super) fn check_request( key_condition_expression, }) } + +/// Refuse a `Query` body whose `KeyConditionExpression` has more than one +/// condition on one key attribute, with the first fault [`check_request`] +/// finds in it. Any other body returns `Ok(())`. +/// +/// Authorization calls this before the IAM decision. The service refuses such +/// a request before it evaluates the caller's policy. Principals fenced by +/// `dynamodb:LeadingKeys` to a value in the key condition or away from every +/// value in it, a principal with no policy that allows `dynamodb:Query` and +/// one with a Deny on it get the answer the table's owner gets: the +/// one-condition-per-key message, or a fault the service reports ahead of it, +/// such as `Limit`, a `FilterExpression` fault or an undefined reference +/// (measured 2026-11-19 in us-east-1, two samples each). +/// +/// # Errors +/// +/// The `ValidationException` that [`check_request`] returns for the body. +pub fn refuse_duplicate_key_condition( + body: &Value, + limits: &LimitsConfig, +) -> Result<(), DynamoDbError> { + let Some(kce) = body.get("KeyConditionExpression").and_then(Value::as_str) else { + return Ok(()); + }; + let names: Option> = body + .get("ExpressionAttributeNames") + .and_then(|names| serde_json::from_value(names.clone()).ok()); + let maps = build_expression_maps(names.as_ref(), None); + let duplicate = tokenize_for( + kce, + limits.max_expression_tokens, + ExpressionKind::KeyCondition, + ) + .is_ok_and(|tokens| has_duplicate_key_condition(&tokens, &maps.names)); + if duplicate { + check_request(body.clone(), limits)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::refuse_duplicate_key_condition; + use extenddb_core::error::DynamoDbError; + use extenddb_core::limits::LimitsConfig; + use serde_json::{Value, json}; + + fn refuse(kce: &str, extra: Value) -> Result<(), DynamoDbError> { + let mut body = json!({ + "TableName": "t", + "KeyConditionExpression": kce, + "ExpressionAttributeValues": { + ":own": {"S": "alice"}, ":other": {"S": "bob"}, ":b": {"S": "x"}, ":c": {"S": "y"}, + }, + }); + if let (Some(body), Value::Object(extra)) = (body.as_object_mut(), extra) { + body.extend(extra); + } + refuse_duplicate_key_condition(&body, &LimitsConfig::default()) + } + + /// The service gave each answer below to the table's owner and to every + /// fenced, unallowed and denied principal (us-east-1, 2026-11-19). + #[test] + fn a_duplicate_gets_the_answer_of_the_table_owner() { + let one_per_key = "Invalid KeyConditionExpression: KeyConditionExpressions must only \ + contain one condition per key"; + let rows = [ + ("pk = :own AND sk = :b AND sk = :c", json!({}), one_per_key), + ("pk > :other AND pk = :own", json!({}), one_per_key), + ( + "#p = :own AND pk = :other", + json!({"ExpressionAttributeNames": {"#p": "pk"}}), + one_per_key, + ), + ( + "pk = :own AND pk = :other", + json!({"FilterExpression": "#q = :own"}), + "Invalid FilterExpression: An expression attribute name used in the document \ + path is not defined; attribute name: #q", + ), + ( + "pk = :other AND pk = :own AND #u = :c", + json!({}), + "Invalid KeyConditionExpression: An expression attribute name used in the \ + document path is not defined; attribute name: #u", + ), + ( + "pk = :other AND pk = :own", + json!({"Limit": 0}), + "1 validation error detected: Value at 'Limit' failed to satisfy constraint: \ + Member must have value greater than or equal to 1", + ), + ]; + for (kce, extra, want) in rows { + let label = format!("{kce} {extra}"); + let got = refuse(kce, extra); + assert!( + matches!(&got, Err(DynamoDbError::ValidationException(msg)) if msg == want), + "{label}: {got:?}" + ); + } + } + + /// The service authorizes these first: a principal fenced away from + /// `alice` gets AccessDeniedException for both (us-east-1, 2026-11-19). + #[test] + fn a_key_condition_without_a_duplicate_goes_on_to_authorization() { + for kce in ["pk = :own AND sk = :b", "pk > :own"] { + assert!(refuse(kce, json!({})).is_ok(), "{kce}"); + } + } +} diff --git a/crates/server/src/leading_keys/tests.rs b/crates/server/src/leading_keys/tests.rs index a59adf1ee..51de039d5 100644 --- a/crates/server/src/leading_keys/tests.rs +++ b/crates/server/src/leading_keys/tests.rs @@ -664,28 +664,6 @@ fn query_unreadable_partition_equality_binds_no_other_clause() { assert_ne!(r, Some(vec!["alice".to_owned()])); } -/// A second condition on one key attribute keeps the partition equality's -/// value, so a principal fenced to `own` reaches the engine, which refuses the -/// key condition, and one fenced away from it is denied. The engine refuses -/// every such key condition; which value the service binds for one is not -/// measured. -#[test] -fn query_duplicate_key_condition_binds_the_partition_equality() { - for kce in ["pk = :own AND sk = :b AND sk = :c", "pk = :own AND pk = :b"] { - let input = json!({ - "TableName": "t", - "KeyConditionExpression": kce, - "ExpressionAttributeValues": { - ":own": {"S": "own"}, - ":b": {"S": "bob"}, - ":c": {"S": "carol"}, - }, - }); - let r = single_table_leading_keys(&input, "Query", Some(&main_table()), MAX_TOKENS); - assert_eq!(r, Some(vec!["own".to_owned()]), "{kce}"); - } -} - /// Two non-equality clauses on the partition key: which operand the service /// binds is not measured, so neither is bound, in either clause order. #[test] diff --git a/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index 485ce725f..58254408f 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -466,6 +466,13 @@ pub(crate) async fn authorize_request( return Ok(authorized_key_info); } + // The service refuses a Query whose key condition has more than one + // condition on one key attribute before the IAM decision, with the answer + // the table's owner gets, for every principal. + if operation == "Query" { + extenddb_engine::refuse_duplicate_key_condition(input, &state.limits)?; + } + // Derive the targets the service authorizes this operation against. The // resource comes from the field the operation actually carries it in // (ResourceArn, StreamArn, BackupArn, TableArn, IndexName, or a table ARN diff --git a/tests/test_fgac_leading_keys.py b/tests/test_fgac_leading_keys.py index 2dcd94155..e06cbb2b5 100644 --- a/tests/test_fgac_leading_keys.py +++ b/tests/test_fgac_leading_keys.py @@ -380,12 +380,12 @@ def test_scan_denied_under_for_any_value(self, table): # -- A second clause on the partition key ------------------------------ def test_unreadable_partition_equality_does_not_bind_another_clause(self, table): - # An equality on the partition key decides dynamodb:LeadingKeys, and - # the fenced value in the second clause (`:v`) is never bound in its - # place. A principal allowed everything gets the one-condition-per-key - # error. A policy fenced to `:v`'s value denies the request, whether - # the equality's value can be read (`:u = {"S": "bob"}`, bound) or not - # (`:u = {"N": "bob"}`, absent, and refused either way). + # Two clauses on the partition key are refused before + # dynamodb:LeadingKeys is evaluated, so no clause is bound. A principal + # allowed everything and principals fenced to `:v`'s value get the + # same ValidationException (measured 2026-11-12 and 2026-11-19). When + # `:u = {"N": "bob"}`, the service reports that `bob` is not a number, + # which this server does not check in a Query yet (#544). kces = ("pk = :u AND pk > :v", "pk > :v AND pk = :u") readable = {":u": {"S": OTHER}, ":v": {"S": OWN}} unreadable = {":u": {"N": OTHER}, ":v": {"S": OWN}} @@ -412,30 +412,61 @@ def test_unreadable_partition_equality_does_not_bind_another_clause(self, table) with pytest.raises(ClientError) as e: c.query(TableName=table, KeyConditionExpression=kce, ExpressionAttributeValues=readable) - assert _denied(e), (form, kce) + err = e.value.response["Error"] + assert (err["Code"], err["Message"]) == ( + "ValidationException", ONE_PER_KEY), (form, kce) with pytest.raises(ClientError) as e: c.query(TableName=table, KeyConditionExpression=kce, ExpressionAttributeValues=unreadable) - assert e.value.response["Error"]["Code"] in ( - "AccessDeniedException", "ValidationException"), (form, kce) - - def test_duplicate_sort_key_condition_binds_the_partition_equality(self, table): - # A second condition on the sort key leaves dynamodb:LeadingKeys bound - # to the partition equality's value, so a principal fenced to that - # value reaches the engine and gets the one-condition-per-key error. - # With the key absent, the same principal would get - # AccessDeniedException. Which value the service binds for a key - # condition with two conditions on one key attribute is not measured. - c = self._user_client([("lk", self._leading_keys_policy( - "ForAnyValue", [OWN], table))]) - with pytest.raises(ClientError) as e: - c.query(TableName=table, - KeyConditionExpression="pk = :own AND sk = :b AND sk = :c", - ExpressionAttributeValues={":own": {"S": OWN}, ":b": {"S": "x"}, - ":c": {"S": "y"}}) - err = e.value.response["Error"] - assert err["Code"] == "ValidationException" - assert err["Message"] == ONE_PER_KEY + assert e.value.response["Error"]["Code"] == "ValidationException", (form, kce) + + def test_duplicate_key_condition_is_refused_before_leading_keys(self, table): + # A key condition with two conditions on one key attribute is refused + # before the IAM decision. Principals fenced to `own`, fenced away from + # every value in the request, allowed no Query or denied Query all get + # the one-condition-per-key error (measured 2026-11-12 and 2026-11-19, + # us-east-1). + values = {":own": {"S": OWN}, ":other": {"S": OTHER}, ":b": {"S": "x"}, + ":c": {"S": "y"}} + names = {"ExpressionAttributeNames": {"#p": "pk"}} + gsi = {"IndexName": "gsi1"} + shapes = [ + ("pk = :own AND sk = :b AND sk = :c", {}), + ("pk = :own AND pk = :other", {}), + ("pk = :other AND pk = :own", {}), + ("pk = :own AND pk > :other", {}), + ("pk > :other AND pk = :own", {}), + ("#p = :own AND pk = :other", names), + ("pk = :other AND #p = :own", names), + ("gpk = :own AND gpk = :other", gsi), + ("gpk = :own AND pk = :b AND pk = :c", gsi), + ] + guarded = self._leading_keys_policy("ForAllValues", [OWN], table) + guarded["Statement"][0]["Condition"]["Null"] = {"dynamodb:LeadingKeys": "false"} + arn = f"arn:aws:dynamodb:{self.region}:{self.account_id}:table/{table}" + resources = [arn, arn + "/index/*"] + policies = { + "ForAnyValue own": self._leading_keys_policy("ForAnyValue", [OWN], table), + "ForAnyValue other": self._leading_keys_policy("ForAnyValue", [OTHER], table), + "ForAllValues away": self._leading_keys_policy("ForAllValues", ["away"], table), + "ForAllValues own, Null guard": guarded, + "no Query": {"Version": "2012-10-17", "Statement": [{ + "Effect": "Allow", "Action": "dynamodb:DescribeTable", + "Resource": resources}]}, + "Query denied": {"Version": "2012-10-17", "Statement": [ + {"Effect": "Allow", "Action": "dynamodb:*", "Resource": resources}, + {"Effect": "Deny", "Action": "dynamodb:Query", "Resource": resources}]}, + } + for label, policy in policies.items(): + c = self._user_client([("lk", policy)]) + for kce, extra in shapes: + used = {k: values[k] for k in re.findall(r":\w+", kce)} + with pytest.raises(ClientError) as e: + c.query(TableName=table, KeyConditionExpression=kce, + ExpressionAttributeValues=used, **extra) + err = e.value.response["Error"] + assert (err["Code"], err["Message"]) == ( + "ValidationException", ONE_PER_KEY), (label, kce) def test_non_equality_partition_with_sort_clause_is_refused(self, table): # The fix binds the partition operand of these shapes; the engine still From 37462809655e60631db47f7353142275335420cb Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:02:41 +0000 Subject: [PATCH 20/29] refactor(query): reuse the server's names map for the duplicate check refuse_duplicate_key_condition read ExpressionAttributeNames from the body a second time. The server already builds that map, with # removed from each key, in leading_keys::names_map. The function now takes the map, and authorize_request passes names_map(input). The two reads give the same map when every names value is a string. For a value that is not a string, the old read dropped the whole map, and names_map skips only that entry. So a duplicate written through a #name beside such a value is now refused before the IAM decision, with the SerializationException that the table owner gets for the body. DynamoDB answers a SerializationException to every principal, with or without a duplicate. On us-east-1, on 19 Nov, the table owner and a role with no Allow for Query sent {"#k": 5} in three bodies, two samples each. The key conditions were pk = :a AND pk = :b, #p = :a AND pk = :b and pk = :a AND sk = :b. All 12 requests got this answer: SerializationException: NUMBER_VALUE cannot be converted to String This commit also shortens the doc comments of refuse_duplicate_key_condition and has_duplicate_key_condition. It removes the comment at the call, which repeated the doc of the function it calls. The unit test keeps one duplicate row without a fault beside its three fault rows. The wire tests send the two rows it drops. --- crates/core/src/expression/key_condition.rs | 7 ++-- crates/engine/src/query/request_checks.rs | 36 ++++++--------------- crates/server/src/leading_keys.rs | 2 +- crates/server/src/request_helpers.rs | 9 +++--- 4 files changed, 18 insertions(+), 36 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 0606a2dd9..db71bd1bb 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -627,11 +627,8 @@ pub fn parse_key_condition(tokens: &[Token]) -> Result, limits: &LimitsConfig, ) -> Result<(), DynamoDbError> { let Some(kce) = body.get("KeyConditionExpression").and_then(Value::as_str) else { return Ok(()); }; - let names: Option> = body - .get("ExpressionAttributeNames") - .and_then(|names| serde_json::from_value(names.clone()).ok()); - let maps = build_expression_maps(names.as_ref(), None); let duplicate = tokenize_for( kce, limits.max_expression_tokens, ExpressionKind::KeyCondition, ) - .is_ok_and(|tokens| has_duplicate_key_condition(&tokens, &maps.names)); + .is_ok_and(|tokens| has_duplicate_key_condition(&tokens, names)); if duplicate { check_request(body.clone(), limits)?; } @@ -155,7 +145,7 @@ pub fn refuse_duplicate_key_condition( #[cfg(test)] mod tests { - use super::refuse_duplicate_key_condition; + use super::{HashMap, refuse_duplicate_key_condition}; use extenddb_core::error::DynamoDbError; use extenddb_core::limits::LimitsConfig; use serde_json::{Value, json}; @@ -171,7 +161,7 @@ mod tests { if let (Some(body), Value::Object(extra)) = (body.as_object_mut(), extra) { body.extend(extra); } - refuse_duplicate_key_condition(&body, &LimitsConfig::default()) + refuse_duplicate_key_condition(&body, &HashMap::new(), &LimitsConfig::default()) } /// The service gave each answer below to the table's owner and to every @@ -182,12 +172,6 @@ mod tests { contain one condition per key"; let rows = [ ("pk = :own AND sk = :b AND sk = :c", json!({}), one_per_key), - ("pk > :other AND pk = :own", json!({}), one_per_key), - ( - "#p = :own AND pk = :other", - json!({"ExpressionAttributeNames": {"#p": "pk"}}), - one_per_key, - ), ( "pk = :own AND pk = :other", json!({"FilterExpression": "#q = :own"}), diff --git a/crates/server/src/leading_keys.rs b/crates/server/src/leading_keys.rs index f7f83b84b..6de728eb3 100644 --- a/crates/server/src/leading_keys.rs +++ b/crates/server/src/leading_keys.rs @@ -369,7 +369,7 @@ fn index_name(input: &Value) -> Option { /// `ExpressionAttributeNames` with the leading `#` stripped from each key, /// matching how the engine builds its name map. -fn names_map(input: &Value) -> HashMap { +pub(crate) fn names_map(input: &Value) -> HashMap { let mut out = HashMap::new(); if let Some(m) = input .get("ExpressionAttributeNames") diff --git a/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index 58254408f..d8b4cb577 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -466,11 +466,12 @@ pub(crate) async fn authorize_request( return Ok(authorized_key_info); } - // The service refuses a Query whose key condition has more than one - // condition on one key attribute before the IAM decision, with the answer - // the table's owner gets, for every principal. if operation == "Query" { - extenddb_engine::refuse_duplicate_key_condition(input, &state.limits)?; + extenddb_engine::refuse_duplicate_key_condition( + input, + &crate::leading_keys::names_map(input), + &state.limits, + )?; } // Derive the targets the service authorizes this operation against. The From 534fb77176cb87822cb93bcf00ee6917c2af13ec Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:14:26 +0000 Subject: [PATCH 21/29] refactor(core): drop the classifier's one-condition-per-key check resolve_multipart_with refused a second condition on one key attribute with its own copy of the check. No request reaches it with one. The engine refuses a duplicate in parse_key_condition_with_maps before any clause is classified. Authorization refuses one before the IAM decision (refuse_duplicate_key_condition), ahead of the map-less parse_key_condition it reads for dynamodb:LeadingKeys. The sorts that put the HASH and RANGE equalities in key-schema order stay, with a comment that says what they are for. The thirteen multi-attribute shapes of a_second_condition_on_one_key_attribute_is_refused move into the table of duplicate_condition_on_one_key_attribute_rejected, so they run through the parse that refuses them. The doc comments of resolve_multipart and resolve_multipart_with no longer list the check. --- crates/core/src/expression/key_condition.rs | 73 ++++++--------------- 1 file changed, 21 insertions(+), 52 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index db71bd1bb..059ca014c 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -128,8 +128,6 @@ impl KeyCondition { /// /// 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`. @@ -171,8 +169,8 @@ impl KeyCondition { /// [`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 + /// (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). @@ -241,20 +239,10 @@ impl KeyCondition { .as_deref() .and_then(|a| hash_attrs.iter().position(|h| *h == a)); - // One condition per key attribute. The engine parses a request's key - // condition with `parse_key_condition_with_maps`, which refuses a - // second condition on one key attribute before this runs. This guards - // the map-less `parse_key_condition`, which authorization reads for - // `dynamodb:LeadingKeys`. + // Key-schema order: the first HASH equality becomes `pk_path`, and the + // RANGE equalities keep this order below. 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(validation_err(ONE_CONDITION_PER_KEY_ERR)); - } // More conditions than key attributes (measured 2026-10-21: the count // is reported ahead of which attribute is missing). @@ -1848,41 +1836,6 @@ mod tests { 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 [ @@ -2188,7 +2141,7 @@ mod tests { /// sort key, written with plain names or through `#name` references and /// whatever the operators, answers the one-condition-per-key message; a /// nested path and redundant parentheses keep their own (measured - /// 2026-10-24, us-east-1). + /// 2026-10-24, us-east-1). The multi-attribute shapes are not measured. #[test] fn duplicate_condition_on_one_key_attribute_rejected() { const REDUNDANT_PARENS: &str = @@ -2227,6 +2180,22 @@ mod tests { ("#hh = :x AND h = :y AND a = :z", &[("hh", "h")], dup), ("#p = :a AND #q = :b", &[("p", "pk"), ("q", "pk")], dup), ("pk = :a AND #s = :b AND sk = :c", &[("s", "sk")], dup), + // The shapes of a multi-attribute key schema: `h` with the RANGE + // attributes `a, b, c, d`, and `h1, h2` with `r`. The check reads + // attribute names, so it needs no key schema. + ("h = :x AND h = :y", &[], dup), + ("h = :x AND h = :y AND a = :z", &[], dup), + ("h = :x AND a = :y AND a = :z", &[], dup), + ("h = :h AND a = :a AND a > :x", &[], dup), + ("h = :h AND a > :x AND a = :a", &[], dup), + ("h = :h AND a = :a AND b = :n AND b > :lo", &[], dup), + ("h = :h AND h > :x", &[], dup), + ("h = :h AND h = :y AND c = :c", &[], dup), + ("a = :a AND a = :y", &[], dup), + ("h1 = :x AND h1 = :y AND h2 = :z", &[], dup), + ("h1 = :x AND h1 = :y", &[], dup), + ("h1 = :x AND h2 = :n AND r = :r AND r > :y", &[], dup), + ("h1 = :x AND r = :r AND r = :y", &[], dup), ("pk = :a AND pk.foo = :b", &[], NESTED_KEY_ERR), ("((pk = :a)) AND (pk = :b)", &[], REDUNDANT_PARENS), ]; From 5d4ae9bb66fff5ba163aaa3d422f8ff24c8290ea Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:17:01 +0000 Subject: [PATCH 22/29] refactor(core): keep unsupported key condition clauses out of RawClause parse_clauses returned RawClause::Unsupported for a `<>` or `contains` clause, so that the duplicate check could read its attribute. classify_clauses refused such a clause before any clause reached raw_to_sk or key_condition_clause_operands. Both still had to match the variant, in arms no input reaches, and raw_to_sk returned a Result for that arm alone. The parser now returns a Clause: a RawClause that a key condition supports, or the path and message of a clause it does not. The reference, begins_with and duplicate checks read Clause. refuse_unsupported_clauses refuses the first unsupported clause and returns the RawClauses. raw_to_sk is main's infallible function again, and the two arms are gone. No answer changes. --- crates/core/src/expression/key_condition.rs | 97 +++++++++++---------- 1 file changed, 49 insertions(+), 48 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 059ca014c..5fd0ec5e5 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -493,11 +493,11 @@ fn check_references(tokens: &[Token], maps: &ExpressionMaps) -> Result<(), Dynam /// sk = :b` with `:n` a number answers this ahead of the one-condition-per-key /// message. fn check_begins_with_operands( - clauses: &[RawClause], + clauses: &[Clause], maps: &ExpressionMaps, ) -> Result<(), DynamoDbError> { for clause in clauses { - if let RawClause::BeginsWith(_, Expr::Placeholder(placeholder)) = clause + if let Clause::Supported(RawClause::BeginsWith(_, Expr::Placeholder(placeholder))) = clause && let Some(value) = maps.values.get(placeholder) && !matches!(value, AttributeValue::S(_) | AttributeValue::B(_)) { @@ -519,7 +519,7 @@ fn check_begins_with_operands( /// partition key and on the sort key alike, whatever the operators are /// (measured 2026-10-24, and 2026-11-11 for `<>` and `contains`). fn reject_duplicate_key_attrs( - clauses: &[RawClause], + clauses: &[Clause], names: &std::collections::HashMap, ) -> Result<(), DynamoDbError> { let mut seen: Vec<&str> = Vec::with_capacity(clauses.len()); @@ -655,8 +655,8 @@ pub fn parse_key_condition_with_maps( /// Read the parsed clauses as a partition key condition and sort key /// conditions, after refusing the first clause whose operator a key condition /// does not support. -fn classify_clauses(mut clauses: Vec) -> Result { - refuse_unsupported_clauses(&clauses)?; +fn classify_clauses(clauses: Vec) -> Result { + let mut clauses = refuse_unsupported_clauses(clauses)?; match clauses.len() { 1 => classify_single(clauses.remove(0)), 2 => classify_pair(clauses.remove(0), clauses.remove(0)), @@ -665,15 +665,15 @@ fn classify_clauses(mut clauses: Vec) -> Result Result<(), DynamoDbError> { - match clauses.iter().find_map(|clause| match clause { - RawClause::Unsupported(_, message) => Some(*message), - _ => None, - }) { - Some(message) => Err(validation_err(message)), - None => Ok(()), - } +/// with its message, or return the clauses. +fn refuse_unsupported_clauses(clauses: Vec) -> Result, DynamoDbError> { + clauses + .into_iter() + .map(|clause| match clause { + Clause::Supported(raw) => Ok(raw), + Clause::Unsupported(_, message) => Err(validation_err(message)), + }) + .collect() } /// The attribute path and single value operand of each clause of a @@ -696,9 +696,7 @@ fn refuse_unsupported_clauses(clauses: &[RawClause]) -> Result<(), DynamoDbError pub fn key_condition_clause_operands( tokens: &[Token], ) -> Result, DynamoDbError> { - let clauses = parse_clauses(tokens)?; - refuse_unsupported_clauses(&clauses)?; - Ok(clauses + Ok(refuse_unsupported_clauses(parse_clauses(tokens)?)? .into_iter() .filter_map(|clause| match clause { RawClause::Eq(path, value) => Some(KeyClauseOperand { @@ -713,7 +711,7 @@ pub fn key_condition_clause_operands( equality: false, }) } - RawClause::Between(..) | RawClause::Unsupported(..) => None, + RawClause::Between(..) => None, }) .collect()) } @@ -732,7 +730,7 @@ 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> { +fn parse_clauses(tokens: &[Token]) -> Result, DynamoDbError> { parser_common::check_redundant_parens(tokens) .map_err(|body| validation_err(&format!("Invalid KeyConditionExpression: {body}")))?; @@ -779,13 +777,15 @@ fn parse_clauses(tokens: &[Token]) -> Result, DynamoDbError> { } /// The attribute-side path of a raw clause. -fn raw_clause_path(clause: &RawClause) -> &[PathElement] { +fn raw_clause_path(clause: &Clause) -> &[PathElement] { match clause { - RawClause::Eq(path, _) - | RawClause::Compare(path, _, _) - | RawClause::Between(path, _, _) - | RawClause::BeginsWith(path, _) - | RawClause::Unsupported(path, _) => path, + Clause::Supported( + RawClause::Eq(path, _) + | RawClause::Compare(path, _, _) + | RawClause::Between(path, _, _) + | RawClause::BeginsWith(path, _), + ) + | Clause::Unsupported(path, _) => path, } } @@ -809,10 +809,14 @@ enum RawClause { Compare(Vec, CompareOp, Expr), Between(Vec, Expr, Expr), BeginsWith(Vec, Expr), - /// A clause whose operator a key condition does not support, with the - /// message it is refused with. It stays a clause until a second - /// condition on its attribute has been looked for, which the service - /// reports first. +} + +/// A parsed clause. A clause whose operator a key condition does not support +/// keeps its path and the message it is refused with until a second +/// condition on its attribute has been looked for, which the service reports +/// first. +enum Clause { + Supported(RawClause), Unsupported(Vec, &'static str), } @@ -847,7 +851,7 @@ fn classify_pair(a: RawClause, b: RawClause) -> Result) -> Result) -> Result Result { - Ok(match clause { +fn raw_to_sk(clause: RawClause) -> SortKeyCondition { + match clause { RawClause::Eq(path, value) => SortKeyCondition::Compare { path, op: CompareOp::Eq, @@ -925,11 +927,10 @@ fn raw_to_sk(clause: RawClause) -> Result { RawClause::Compare(path, op, value) => SortKeyCondition::Compare { path, op, value }, RawClause::Between(path, low, high) => SortKeyCondition::Between { path, low, high }, RawClause::BeginsWith(path, prefix) => SortKeyCondition::BeginsWith { path, prefix }, - RawClause::Unsupported(_, message) => return Err(validation_err(message)), - }) + } } -fn parse_key_clause(tokens: &[Token], pos: &mut usize) -> Result { +fn parse_key_clause(tokens: &[Token], pos: &mut usize) -> Result { if *pos >= tokens.len() { return Err(validation_err( "Invalid KeyConditionExpression: unexpected end of expression", @@ -952,7 +953,7 @@ fn parse_key_clause(tokens: &[Token], pos: &mut usize) -> Result Result { +fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result { if *pos >= tokens.len() { return Err(validation_err( "Invalid KeyConditionExpression: unexpected end of expression", @@ -971,7 +972,7 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result Result Result` clause is refused here, as before. if op == CompareOp::Ne { return match parse_key_operand_path(tokens, pos) { - Ok(path) if path.len() == 1 => Ok(RawClause::Unsupported(path, NE_UNSUPPORTED)), + Ok(path) if path.len() == 1 => Ok(Clause::Unsupported(path, NE_UNSUPPORTED)), _ => Err(validation_err(NE_UNSUPPORTED)), }; } @@ -1026,9 +1027,9 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result Result Result { *pos += 1; - Ok(RawClause::Unsupported(path, NE_UNSUPPORTED)) + Ok(Clause::Unsupported(path, NE_UNSUPPORTED)) } _ => Err(validation_err(NE_UNSUPPORTED)), }; @@ -1063,9 +1064,9 @@ fn parse_key_clause_inner(tokens: &[Token], pos: &mut usize) -> Result Date: Mon, 23 Nov 2026 20:23:30 +0000 Subject: [PATCH 23/29] fix(engine): read the key condition's shape after the table checks check_request parsed the whole KeyConditionExpression before handle_query read the table. So the shape refusals of classify_clauses answered ahead of the table, index, ConsistentRead and Select checks. Main and DynamoDB answer those checks first for these key conditions. On us-east-1, on 23 Nov, each of these went twice to a table that does not exist: pk > :a ResourceNotFoundException: Requested resource not found pk > :a AND sk > :b ResourceNotFoundException: Requested resource not found Before this commit the branch answered "partition key condition must use equality (=)" and "one condition must be an equality on the partition key". parse_key_condition_with_maps still refuses the faults that come after the grammar and before the table on the service. These are the references in written order, the begins_with operand type, the duplicate, and the <> and contains refusal. It now returns a fault of the shape inside Ok. handle_query returns that fault where main parsed the key condition: after the ConsistentRead and Select index checks, and before the vector index refusal. The wire tests add both requests as R10 and R11. A core test checks that the parse passes three shape faults and returns each refusal inside Ok. --- crates/core/src/expression/key_condition.rs | 47 +++++++++++++++---- crates/engine/src/expression_helpers.rs | 6 ++- crates/engine/src/query.rs | 6 ++- crates/engine/src/query/request_checks.rs | 18 +++---- tests/test_query_key_condition_one_per_key.py | 16 +++++-- 5 files changed, 66 insertions(+), 27 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 5fd0ec5e5..bfebd14cf 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -612,7 +612,7 @@ impl SortKeyCondition { /// /// Returns `ValidationException` for syntax errors or unsupported constructs. pub fn parse_key_condition(tokens: &[Token]) -> Result { - classify_clauses(parse_clauses(tokens)?) + classify_clauses(refuse_unsupported_clauses(parse_clauses(tokens)?)?) } /// Whether the key condition in `tokens` names one attribute twice, reading @@ -640,23 +640,22 @@ pub fn has_duplicate_key_condition( /// # Errors /// /// As [`parse_key_condition`], plus `ValidationException` for each of the -/// faults above. +/// faults above. A fault in the key condition's shape, such as no equality +/// on the partition key, is the `Err` inside `Ok`: the engine answers it +/// after the table checks, where the service does. pub fn parse_key_condition_with_maps( tokens: &[Token], maps: &ExpressionMaps, -) -> Result { +) -> Result, DynamoDbError> { let clauses = parse_clauses(tokens)?; check_references(tokens, maps)?; check_begins_with_operands(&clauses, maps)?; reject_duplicate_key_attrs(&clauses, &maps.names)?; - classify_clauses(clauses) + Ok(classify_clauses(refuse_unsupported_clauses(clauses)?)) } -/// Read the parsed clauses as a partition key condition and sort key -/// conditions, after refusing the first clause whose operator a key condition -/// does not support. -fn classify_clauses(clauses: Vec) -> Result { - let mut clauses = refuse_unsupported_clauses(clauses)?; +/// Read the clauses as a partition key condition and sort key conditions. +fn classify_clauses(mut clauses: Vec) -> Result { match clauses.len() { 1 => classify_single(clauses.remove(0)), 2 => classify_pair(clauses.remove(0), clauses.remove(0)), @@ -2110,7 +2109,7 @@ mod tests { values: &HashMap, ) -> Result { let tokens = tokenize(expr).unwrap(); - parse_key_condition_with_maps(&tokens, &ExpressionMaps::new(names.clone(), values.clone())) + parse_key_condition_with_maps(&tokens, &ExpressionMaps::new(names.clone(), values.clone()))? } /// [`parse_with`] with every placeholder of `expr` defined. @@ -2378,6 +2377,34 @@ mod tests { ); } + /// A key condition whose only fault is its shape passes the checks, and + /// its refusal comes inside `Ok`, for the engine to answer after the + /// table checks. + #[test] + fn the_shape_is_refused_after_the_checks() { + for (expr, want) in [ + ("pk > :a", "partition key condition must use equality (=)"), + ( + "pk > :a AND sk > :b", + "one condition must be an equality on the partition key", + ), + ( + "pk = :a AND sk > :b AND zz < :c", + "at most one non-equality condition is allowed", + ), + ] { + let tokens = tokenize(expr).unwrap(); + let maps = ExpressionMaps::new(HashMap::new(), values_of(expr)); + let shape = parse_key_condition_with_maps(&tokens, &maps) + .unwrap_or_else(|err| panic!("expr {expr} should pass the checks: {err:?}")); + assert_refused( + shape, + &format!("Invalid KeyConditionExpression: {want}"), + expr, + ); + } + } + #[test] fn distinct_key_attributes_accepted_after_duplicate_check() { // One condition per key attribute passes the check and resolves under diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 9b6f96d8f..03b393ebb 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -248,12 +248,14 @@ pub fn parse_projection_expr( /// # Errors /// /// Returns `DynamoDbError::ValidationException` for over-size, syntax, or -/// reserved-word errors, and for the faults above. +/// reserved-word errors, and for the faults above. A fault in the key +/// condition's shape is the `Err` inside `Ok`, as +/// [`parse_key_condition_with_maps`] returns it. pub fn parse_key_condition_expr( expr: &str, maps: &ExpressionMaps, limits: &LimitsConfig, -) -> Result { +) -> Result, DynamoDbError> { check_expression_size(expr, ExpressionKind::KeyCondition, limits)?; tokenize_for( expr, diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 6417fe744..923e85408 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -143,8 +143,10 @@ pub async fn handle_query( // Parse KeyConditionExpression or desugar legacy KeyConditions let (mut key_condition, legacy_kc_maps) = if let Some(parsed) = key_condition_expression { - // Parsed and checked above, after the FilterExpression. - (parsed, None) + // Parsed and checked above. A fault in its shape answers here, after + // the table checks (measured 2026-11-23: `pk > :a` on a table that does + // not exist answers ResourceNotFoundException). + (parsed?, None) } else if let Some(ref kc) = input.key_conditions { let key_schema_pairs: Vec<(String, bool)> = query_key_info .key_schema diff --git a/crates/engine/src/query/request_checks.rs b/crates/engine/src/query/request_checks.rs index d96bd7edc..f3c307c70 100644 --- a/crates/engine/src/query/request_checks.rs +++ b/crates/engine/src/query/request_checks.rs @@ -24,7 +24,9 @@ pub(super) struct CheckedRequest { pub(super) input: QueryInput, pub(super) maps: ExpressionMaps, pub(super) filter_expression: Option, - pub(super) key_condition_expression: Option, + /// The key condition, or the fault of its shape, which `handle_query` + /// answers after the table checks. + pub(super) key_condition_expression: Option>, } /// Read a `Query` body and refuse its faults that come before the table is @@ -47,9 +49,9 @@ pub(super) fn check_request( }], )?; // The service checks Select after Limit, the request's parameters, the - // FilterExpression and the KeyConditionExpression (measured 2026-11-11), - // so an invalid Select is left out of the typed input and its error waits - // for those checks below. + // FilterExpression and the KeyConditionExpression checks below (measured + // 2026-11-11), so an invalid Select is left out of the typed input and its + // error waits for those checks. let select_check = crate::validate_enum_fields( &body, &[crate::EnumField { @@ -94,10 +96,10 @@ pub(super) fn check_request( input.expression_attribute_values.as_ref(), ); - // The service checks a Query in this order (measured 2026-11-11 in - // us-east-1): Limit, then the request's parameters, then every - // FilterExpression fault, then every KeyConditionExpression fault, then - // Select, the table, the index and ConsistentRead. + // The service checks a Query in this order (measured 2026-11-11 and + // 2026-11-23 in us-east-1): Limit, then the request's parameters, then + // every FilterExpression fault, then every KeyConditionExpression fault + // except its shape, then Select, the table, the index and ConsistentRead. check_request_parameters(&input)?; let filter_expression = parse_filter_expression(&input, &maps, limits)?; let key_condition_expression = input diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index 5467421b7..7b7dc6259 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -64,6 +64,7 @@ GSI = "g-keys" HASH = "hash-table" # stands for the hash_table fixture in a row's TableName MISSING_TABLE = "extenddb-test-484-no-such-table" +NOT_FOUND = ("ResourceNotFoundException", "Requested resource not found") LEGACY_PK = {"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [A]}} @@ -103,15 +104,17 @@ def _q(kce: str | None = None, values=None, names: dict | None = None, **kwargs) return request -def _refused(client, table: str, request: dict, want: str) -> None: +def _refused(client, table: str, request: dict, want) -> None: """Send the Query against `table` and compare the ValidationException's - text with `want`, or its prefix when `want` is one. With KCE_PREFIX the - text must also not contain "operator".""" + text with `want`, or its prefix when `want` is one. A (code, text) pair + names another error. With KCE_PREFIX the text must also not contain + "operator".""" request = {"TableName": table, **request} + code, want = want if isinstance(want, tuple) else ("ValidationException", want) with pytest.raises(ClientError) as exc_info: client.query(**request) err = exc_info.value.response["Error"] - assert err["Code"] == "ValidationException", err + assert err["Code"] == code, err if want in (KCE_PREFIX, FILTER_PREFIX): assert err["Message"].startswith(want), err["Message"] if want == KCE_PREFIX: @@ -331,7 +334,8 @@ class TestQueryCheckOrder: 12:44Z): parameters, then the FilterExpression, then the KeyConditionExpression, then Select, the table, the index and ConsistentRead. F3 is an undefined filter value on a partition with no - items.""" + items. R10 and R11 (2026-11-23T16:58Z) have no equality on the partition + key: the service reads the key condition's shape after the table.""" Q = "#q = :a" CO = {"ConditionalOperator": "AND"} @@ -375,6 +379,8 @@ class TestQueryCheckOrder: _q("pk = :a", {":a": {"S": "p484-empty"}}, FilterExpression="foo = :zz"), _undefined(":zz", "FilterExpression"), ), + ("R10", _q("pk > :a", "a", TableName=MISSING_TABLE), NOT_FOUND), + ("R11", _q("pk > :a AND sk > :b", "a b", TableName=MISSING_TABLE), NOT_FOUND), ] @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) From 76e33b27c111db1b311825a3e4d27666c361e54e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:26:07 +0000 Subject: [PATCH 24/29] refactor(core): check the begins_with operand type in one place check_begins_with_operands wrote out the begins_with operand type check and message a second time, beside validate_begins_with_operands in resolver.rs. check_begins_with_operand in resolver.rs now refuses a :value that is not a string or a binary value, with a prefix the caller gives. Both checks call it: the key condition check with its Invalid KeyConditionExpression prefix, as before, and the filter and condition check with none, as before. No answer changes. --- crates/core/src/expression/key_condition.rs | 16 +++------- crates/core/src/expression/resolver.rs | 33 +++++++++++++-------- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index bfebd14cf..d6f6a7b27 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -15,12 +15,11 @@ use super::ast::{CompareOp, Expr, PathElement}; use super::parser_common; -use super::resolver::{ExpressionMaps, attribute_type_code}; +use super::resolver::{ExpressionMaps, check_begins_with_operand}; use super::tokenizer::Token; use crate::error::DynamoDbError; use crate::types::{ - AttributeValue, KeySchemaElement, KeyType, hash_key_elements, is_multipart_key_schema, - range_key_elements, + 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. @@ -497,15 +496,8 @@ fn check_begins_with_operands( maps: &ExpressionMaps, ) -> Result<(), DynamoDbError> { for clause in clauses { - if let Clause::Supported(RawClause::BeginsWith(_, Expr::Placeholder(placeholder))) = clause - && let Some(value) = maps.values.get(placeholder) - && !matches!(value, AttributeValue::S(_) | AttributeValue::B(_)) - { - return Err(validation_err(&format!( - "Invalid KeyConditionExpression: Incorrect operand type for operator or \ - function; operator or function: begins_with, operand type: {}", - attribute_type_code(value) - ))); + if let Clause::Supported(RawClause::BeginsWith(_, operand)) = clause { + check_begins_with_operand(operand, maps, "Invalid KeyConditionExpression: ")?; } } Ok(()) diff --git a/crates/core/src/expression/resolver.rs b/crates/core/src/expression/resolver.rs index 41637b9cd..0d6970bc0 100755 --- a/crates/core/src/expression/resolver.rs +++ b/crates/core/src/expression/resolver.rs @@ -506,18 +506,8 @@ pub fn validate_begins_with_operands( maps: &ExpressionMaps, ) -> 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(()) + Expr::Function { name, args } if name == "begins_with" && args.len() == 2 => { + check_begins_with_operand(&args[1], maps, "") } Expr::And(left, right) | Expr::Or(left, right) => { validate_begins_with_operands(left, maps)?; @@ -528,6 +518,25 @@ pub fn validate_begins_with_operands( } } +/// Refuse a `begins_with` operand that is a `:value` other than a string or a +/// binary value, with `prefix` ahead of the message. +pub(crate) fn check_begins_with_operand( + operand: &Expr, + maps: &ExpressionMaps, + prefix: &str, +) -> Result<(), DynamoDbError> { + if let Expr::Placeholder(placeholder) = operand + && 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!( + "{prefix}Incorrect operand type for operator or function; operator or function: begins_with, operand type: {type_code}" + ))); + } + Ok(()) +} + /// Return the DynamoDB type code for an AttributeValue (S, N, B, BOOL, NULL, /// L, M, SS, NS, BS). Used in operand-type validation messages. pub(crate) fn attribute_type_code(val: &AttributeValue) -> &'static str { From 06d7d2061b5a3984b0225903d77415ae43dc2b8a Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:37:35 +0000 Subject: [PATCH 25/29] refactor(engine): run the second filter operand check for QueryFilter only parse_filter_expression checks a FilterExpression's begins_with and ordering operand types against the request's values. Beside legacy KeyConditions, handle_query checked them a second time, against the request's values with the desugared KeyConditions values added. The desugar adds only _kc_ placeholders. So that pass repeated the first one. The second pass now runs only for a desugared QueryFilter, whose values the first pass does not see. One answer changes. A FilterExpression can name a _kc_ placeholder that the request also defines. The first pass checks the request's value, and the second pass checked the KeyConditions value that replaces it in the merged map. --- crates/engine/src/query.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index 923e85408..ae45b4fe8 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -379,11 +379,10 @@ pub async fn handle_query( ExpressionMaps::new(names, values) }; - // The filter's operand types against the values legacy KeyConditions or a - // QueryFilter add. A FilterExpression was checked against the request's own - // values when it was parsed. + // A desugared QueryFilter's operand types, against the values it adds. A + // FilterExpression was checked against the request's values when parsed. if let Some(f) = &filter - && (filter_maps.is_some() || legacy_kc_maps.is_some()) + && filter_maps.is_some() { check_filter_operand_types(f, &combined_maps)?; } From a3d77ee764223dd072eb08cc695e07a559c3c980 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:26:42 +0000 Subject: [PATCH 26/29] docs(server): say what the map-less key condition parse accepts The doc comment of Names::key_condition in request_attributes.rs said that it reads a key condition as parse_key_condition_expr reads it. The engine parse now reads the request's ExpressionAttributeNames and ExpressionAttributeValues and refuses more. The comment now says that this function reads the clause paths with the map-less parse_key_condition. That parse accepts key conditions that the engine refuses for an undefined reference, a begins_with operand type or a second condition on one key attribute. --- crates/server/src/request_attributes.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/server/src/request_attributes.rs b/crates/server/src/request_attributes.rs index 3404240e6..66717eef9 100644 --- a/crates/server/src/request_attributes.rs +++ b/crates/server/src/request_attributes.rs @@ -355,12 +355,12 @@ impl<'a> Names<'a> { } } - /// The paths in a `KeyConditionExpression`, read as the engine's key - /// condition parser reads it (`parse_key_condition_expr` in - /// `crates/engine/src/expression_helpers.rs`): under the size and token + /// The paths in a `KeyConditionExpression`, under the size and token /// limits, with the reserved-word check when `enforce_reserved_keywords` - /// is set, then `parse_key_condition`. A key condition the key condition - /// parser refuses gives none. + /// is set, then the map-less `parse_key_condition`, which accepts key + /// conditions the engine refuses for an undefined reference, a + /// `begins_with` operand type or a second condition on one key attribute. + /// A key condition `parse_key_condition` refuses gives none. fn key_condition(&mut self, value: Option<&Value>) { let Some(text) = self.text(value) else { return; From b83c3b8feebff453f1df051f9b4d0ca8c9b77d88 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:39:38 +0000 Subject: [PATCH 27/29] test(wire): drop the unreadable rows of the partition equality test test_unreadable_partition_equality_does_not_bind_another_clause also sent its two key conditions with :u = {"N": "bob"}, and it checked only the error code. Authorization refuses the duplicate before it reads any value, so those requests took the path of the readable ones. DynamoDB answers them with "The parameter cannot be converted to a numeric value: bob" (us-east-1, 23 Nov, two sends each). This server answers the one-condition-per-key text, and the check of those numbers is the subject of #544. The test keeps the readable rows, under the name test_partition_equality_does_not_bind_another_clause. The module docstring of test_query_key_condition_one_per_key.py drops its issue number. The TestOneConditionPerKey docstring no longer says that the class holds every measured duplicate shape. The reserved word row of 24 Oct is not in its table. --- tests/test_fgac_leading_keys.py | 17 +++++------------ tests/test_query_key_condition_one_per_key.py | 8 ++++---- 2 files changed, 9 insertions(+), 16 deletions(-) diff --git a/tests/test_fgac_leading_keys.py b/tests/test_fgac_leading_keys.py index e06cbb2b5..302eb07b4 100644 --- a/tests/test_fgac_leading_keys.py +++ b/tests/test_fgac_leading_keys.py @@ -379,16 +379,13 @@ def test_scan_denied_under_for_any_value(self, table): # -- A second clause on the partition key ------------------------------ - def test_unreadable_partition_equality_does_not_bind_another_clause(self, table): + def test_partition_equality_does_not_bind_another_clause(self, table): # Two clauses on the partition key are refused before # dynamodb:LeadingKeys is evaluated, so no clause is bound. A principal # allowed everything and principals fenced to `:v`'s value get the - # same ValidationException (measured 2026-11-12 and 2026-11-19). When - # `:u = {"N": "bob"}`, the service reports that `bob` is not a number, - # which this server does not check in a Query yet (#544). + # same ValidationException (measured 2026-11-12 and 2026-11-19). kces = ("pk = :u AND pk > :v", "pk > :v AND pk = :u") - readable = {":u": {"S": OTHER}, ":v": {"S": OWN}} - unreadable = {":u": {"N": OTHER}, ":v": {"S": OWN}} + values = {":u": {"S": OTHER}, ":v": {"S": OWN}} owner = self._user_client([("all", { "Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}], @@ -396,7 +393,7 @@ def test_unreadable_partition_equality_does_not_bind_another_clause(self, table) for kce in kces: with pytest.raises(ClientError) as e: owner.query(TableName=table, KeyConditionExpression=kce, - ExpressionAttributeValues=readable) + ExpressionAttributeValues=values) err = e.value.response["Error"] assert err["Code"] == "ValidationException", kce assert err["Message"] == ONE_PER_KEY, kce @@ -411,14 +408,10 @@ def test_unreadable_partition_equality_does_not_bind_another_clause(self, table) for kce in kces: with pytest.raises(ClientError) as e: c.query(TableName=table, KeyConditionExpression=kce, - ExpressionAttributeValues=readable) + ExpressionAttributeValues=values) err = e.value.response["Error"] assert (err["Code"], err["Message"]) == ( "ValidationException", ONE_PER_KEY), (form, kce) - with pytest.raises(ClientError) as e: - c.query(TableName=table, KeyConditionExpression=kce, - ExpressionAttributeValues=unreadable) - assert e.value.response["Error"]["Code"] == "ValidationException", (form, kce) def test_duplicate_key_condition_is_refused_before_leading_keys(self, table): # A key condition with two conditions on one key attribute is refused diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index 7b7dc6259..bef5bbec0 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -5,7 +5,7 @@ Amazon DynamoDB refuses a key condition that names the same key attribute twice, on the partition key and on the sort key alike, whatever the operators -are (issue #430): +are: ValidationException: Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key @@ -159,9 +159,9 @@ def hash_table(dynamodb_client): class TestOneConditionPerKey: - """Every measured duplicate shape (2026-10-24, and 2026-11-11 for J1 and - J2), the shapes that keep their own error, and the distinct conditions - that are served.""" + """The duplicate shapes of 2026-10-24 except the reserved word row, J1 and + J2 (2026-11-11), the shapes that keep their own error, and the distinct + conditions that are served.""" ROWS = [ ("pk = :a AND pk = :b", _q("pk = :a AND pk = :b", "a b"), ONE_PER_KEY), From 98d09b3a6f8441759104f3d229ff30056692f01f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:06:15 +0000 Subject: [PATCH 28/29] docs(upgrade): list the Query requests that this change refuses The upgrade manual had no entry for this change. A key condition with two conditions on one key attribute now gets the ValidationException for every principal, ahead of the IAM decision. Two FilterExpression shapes that 1.0.0 ran are refused too. The new v1.1.0 entry lists them. It also says that the 0.1.15 LeadingKeys entry does not hold for a key condition with two conditions on one key attribute. --- docs/manuals/07-upgrade-manual.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index ab3b307fe..b83fef0fd 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -388,6 +388,16 @@ 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: `Query` refuses a second condition on one key attribute + +**What changed** (#484). Some `Query` requests that 1.0.0 ran now get `ValidationException`, as DynamoDB answers them: + +- a `KeyConditionExpression` with two conditions on one key attribute, such as `pk = :a AND pk = :b`: `Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key` +- a `FilterExpression` that names a `:value` the request does not define, on a partition with no items +- a `FilterExpression` beside `KeyConditions` that names `:_kc_pk` when the request does not define it. ExtendDB uses that name for the `KeyConditions` partition value, and 1.0.0 compared the filter with that value. + +ExtendDB refuses a key condition with two conditions on one key attribute before the IAM decision. A principal whose policy does not allow such a request got `AccessDeniedException` from 1.0.0 and now gets the `ValidationException`. The 0.1.15 LeadingKeys entry below says that an equality on the partition key decides `dynamodb:LeadingKeys`. That no longer holds for a key condition with two conditions on one key attribute. No catalog migration is required. + ### 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 468b256c94884de20c2c55b360426963a7bab04c Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:34:35 +0000 Subject: [PATCH 29/29] fix(query): refuse an invalid Select before the IAM decision The merge of main moved the Select check behind the FilterExpression and KeyConditionExpression checks. The check that the server makes before the IAM decision then no longer covered Select. A principal the policy denies got AccessDeniedException for an invalid Select. Main gives that principal the Select text, because #544 checks Select before the IAM decision. refuse_duplicate_key_condition now runs check_request for an invalid Select too. Every principal gets the Select text, or a fault that check_request reports ahead of it. The measured rows still hold. An undefined filter name (H3) and a duplicate (B4) answer ahead of an invalid Select. No row measures the answer for a principal the policy denies. The new test an_invalid_select_is_refused_before_authorization sends pk = :own and pk > :own with Select BOGUS, and the shape of H3. It also deletes the three comment lines above the validate_query_request_body call in check_request, which repeated the list of checks in that function's doc. --- crates/engine/src/query/request_checks.rs | 63 +++++++++++++++++------ 1 file changed, 46 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/query/request_checks.rs b/crates/engine/src/query/request_checks.rs index 1039d0d56..bfa78489d 100644 --- a/crates/engine/src/query/request_checks.rs +++ b/crates/engine/src/query/request_checks.rs @@ -35,9 +35,6 @@ pub(super) fn check_request( mut body: Value, limits: &LimitsConfig, ) -> Result { - // The checks on the raw body, before typed deserialization: Limit, the - // ReturnConsumedCapacity enum, the parameter mix, the names map and the - // numbers, in the service's order. crate::query_key_values::validate_query_request_body(&body)?; // The service checks Select after Limit, the request's parameters, the // FilterExpression and the KeyConditionExpression checks below (measured @@ -87,10 +84,13 @@ pub(super) fn check_request( } /// Refuse a `Query` body whose `KeyConditionExpression` has two conditions on -/// one attribute, with the first fault [`check_request`] finds in it. `names` -/// is the body's `ExpressionAttributeNames` without the `#`. Authorization -/// calls this before the IAM decision, as the service refuses such a request -/// for every principal (measured 2026-11-19, us-east-1). +/// one attribute, or whose `Select` is invalid, with the first fault +/// [`check_request`] finds in it. `names` is the body's +/// `ExpressionAttributeNames` without the `#`. Authorization calls this before +/// the IAM decision. The service refuses a duplicate for every principal +/// (measured 2026-11-19, us-east-1). For an invalid `Select`, every principal +/// gets the `Select` text or a fault that `check_request` reports ahead of it. +/// That answer is not measured for a principal the policy denies. /// /// # Errors /// @@ -100,16 +100,18 @@ pub fn refuse_duplicate_key_condition( names: &HashMap, limits: &LimitsConfig, ) -> Result<(), DynamoDbError> { - let Some(kce) = body.get("KeyConditionExpression").and_then(Value::as_str) else { - return Ok(()); - }; - let duplicate = tokenize_for( - kce, - limits.max_expression_tokens, - ExpressionKind::KeyCondition, - ) - .is_ok_and(|tokens| has_duplicate_key_condition(&tokens, names)); - if duplicate { + let duplicate = body + .get("KeyConditionExpression") + .and_then(Value::as_str) + .is_some_and(|kce| { + tokenize_for( + kce, + limits.max_expression_tokens, + ExpressionKind::KeyCondition, + ) + .is_ok_and(|tokens| has_duplicate_key_condition(&tokens, names)) + }); + if duplicate || crate::query_key_values::validate_query_select(body).is_err() { check_request(body.clone(), limits)?; } Ok(()) @@ -181,4 +183,31 @@ mod tests { assert!(refuse(kce, json!({})).is_ok(), "{kce}"); } } + + /// An invalid `Select` is refused before authorization, after the filter + /// fault the service reports ahead of it (H3). + #[test] + fn an_invalid_select_is_refused_before_authorization() { + let select = "1 validation error detected: Value 'BOGUS' at 'select' failed to satisfy \ + constraint: Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, \ + COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]"; + let rows = [ + ("pk = :own", json!({"Select": "BOGUS"}), select), + ("pk > :own", json!({"Select": "BOGUS"}), select), + ( + "pk = :own", + json!({"Select": "BOGUS", "FilterExpression": "#q = :own"}), + "Invalid FilterExpression: An expression attribute name used in the document \ + path is not defined; attribute name: #q", + ), + ]; + for (kce, extra, want) in rows { + let label = format!("{kce} {extra}"); + let got = refuse(kce, extra); + assert!( + matches!(&got, Err(DynamoDbError::ValidationException(msg)) if msg == want), + "{label}: {got:?}" + ); + } + } }