diff --git a/crates/core/src/error/messages.rs b/crates/core/src/error/messages.rs index c99a20a64..907fd405c 100755 --- a/crates/core/src/error/messages.rs +++ b/crates/core/src/error/messages.rs @@ -43,6 +43,28 @@ pub fn validation_errors_detected(clauses: &[String]) -> String { /// authorization; the `GetShardIterator` handler checks the presence. pub const INVALID_STREAM_ARN: &str = "Invalid StreamArn"; +/// The service's answer to a `Query` key condition it cannot serve, such as +/// `pk > :x` on a key schema whose only HASH attribute is `pk`. +pub const QUERY_KEY_CONDITION_NOT_SUPPORTED: &str = "Query key condition not supported"; + +/// The service's answer to a `Query` key condition with no condition on +/// `attribute`, a key attribute the query needs. +#[must_use] +pub fn missed_key_schema_element(attribute: &str) -> String { + format!("Query condition missed key schema element: {attribute}") +} + +/// The service's answer to a `Query` key condition on a key schema with +/// several key attributes when the HASH attributes in `attributes` have no +/// equality condition. +#[must_use] +pub fn hash_attributes_without_equality(attributes: &[&str]) -> String { + format!( + "HASH key attributes {} must have equality conditions specified in the query", + attributes.join(", ") + ) +} + /// Keys for error message templates. Compile-time checked — no stringly-typed lookups. #[derive(Debug, Clone, Copy)] pub enum ErrorMessageKey { diff --git a/crates/core/src/error/mod.rs b/crates/core/src/error/mod.rs index 94b81c466..c72b3856e 100755 --- a/crates/core/src/error/mod.rs +++ b/crates/core/src/error/mod.rs @@ -3,8 +3,9 @@ mod messages; pub use messages::{ - ErrorMessageKey, INVALID_STREAM_ARN, error_message, validation_error, validation_errors, - validation_errors_detected, + ErrorMessageKey, INVALID_STREAM_ARN, QUERY_KEY_CONDITION_NOT_SUPPORTED, error_message, + hash_attributes_without_equality, missed_key_schema_element, validation_error, + validation_errors, validation_errors_detected, }; use crate::types::{CancellationReason, Item}; diff --git a/crates/core/src/expression/key_condition.rs b/crates/core/src/expression/key_condition.rs index 50fe9dad0..505547cab 100755 --- a/crates/core/src/expression/key_condition.rs +++ b/crates/core/src/expression/key_condition.rs @@ -22,6 +22,8 @@ use crate::types::{ KeySchemaElement, KeyType, hash_key_elements, is_multipart_key_schema, range_key_elements, }; +mod no_hash_equality; + /// Parsed key condition: partition key value expression(s) and optional sort key condition. /// /// For standard (single-attribute) keys, `pk_path`/`pk_value` hold the single PK condition @@ -31,7 +33,10 @@ use crate::types::{ /// `extra_pk_conditions` holds additional PK equality conditions. #[derive(Debug, Clone)] pub struct KeyCondition { - /// First partition key attribute path (resolved name). + /// First partition key attribute path (resolved name). Empty when the + /// expression held one or two clauses and none is an equality; they are + /// then `sk_condition` and `extra_sk_conditions`, and + /// [`KeyCondition::refuse_without_hash_equality`] refuses them. pub pk_path: Vec, /// First partition key value expression (placeholder or literal). pub pk_value: Expr, @@ -635,9 +640,10 @@ pub fn has_duplicate_key_condition( /// # Errors /// /// As [`parse_key_condition`], plus `ValidationException` for each of the -/// 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. +/// faults above. A fault in the key condition's shape, such as two +/// non-equality clauses beside an equality, is the `Err` inside `Ok`, for the +/// engine to answer after the table checks. A key condition with no equality +/// clause parses, and the engine refuses it once it knows the key schema. pub fn parse_key_condition_with_maps( tokens: &[Token], maps: &ExpressionMaps, @@ -828,9 +834,9 @@ fn classify_single(clause: RawClause) -> Result { sk_condition: None, extra_sk_conditions: Vec::new(), }), - _ => Err(validation_err( - "Invalid KeyConditionExpression: partition key condition must use equality (=)", - )), + // The wording of the refusal depends on the key schema, which is not + // known here. See `KeyCondition::refuse_without_hash_equality`. + other => Ok(KeyCondition::without_equality(raw_to_sk(other), None)), } } @@ -838,7 +844,7 @@ fn classify_pair(a: RawClause, b: RawClause) -> Result { Ok(KeyCondition { @@ -849,8 +855,11 @@ fn classify_pair(a: RawClause, b: RawClause) -> Result Err(validation_err( - "Invalid KeyConditionExpression: one condition must be an equality on the partition key", + // Neither clause is an equality. As for a single clause, the key + // schema decides the wording. See `KeyCondition::refuse_without_hash_equality`. + (a, b) => Ok(KeyCondition::without_equality( + raw_to_sk(a), + Some(raw_to_sk(b)), )), } } @@ -2377,27 +2386,16 @@ mod tests { /// 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, - ); - } + let expr = "pk = :a AND sk > :b AND zz < :c"; + 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, + "Invalid KeyConditionExpression: at most one non-equality condition is allowed", + expr, + ); } #[test] diff --git a/crates/core/src/expression/key_condition/no_hash_equality.rs b/crates/core/src/expression/key_condition/no_hash_equality.rs new file mode 100644 index 000000000..f840c8536 --- /dev/null +++ b/crates/core/src/expression/key_condition/no_hash_equality.rs @@ -0,0 +1,263 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! A `KeyConditionExpression` with no equality clause on the HASH attribute. +//! +//! Which message the service returns for `pk > :x` depends on the key schema +//! of the table or index being queried, and the parser does not know it. The +//! parser therefore accepts the clauses and records them in a +//! [`KeyCondition`] without a partition key condition (`pk_path` is empty). +//! The engine calls [`KeyCondition::refuse_without_hash_equality`] once the +//! key schema is known; that call is the only place the wording is chosen. +//! Every such condition is refused, so no storage backend receives one. +//! +//! Two shapes reach the refusal: +//! +//! - one or two clauses, none an equality (`pk > :x`, `sk > :x AND zz > :y`). +//! `sk_condition` is the first clause. The second is kept as its operands +//! in `extra_sk_conditions`, one `(path, operand)` entry per operand (two +//! for `BETWEEN`), so that the references of both clauses are counted as +//! used. +//! - an equality on another attribute plus a non-equality clause on the HASH +//! attribute of a single-HASH schema (`sk = :x AND pk > :y`). The parser +//! classifies the pair as it does any other, equality first, and +//! [`KeyCondition::lacks_hash_equality`] spots it once the schema is known. +//! +//! `tests/python/test_query_lone_non_equality.py` lists the service's +//! wording for each key schema and shape, with the dates it was measured. +//! +//! [`parse_key_condition_with_maps`](super::parse_key_condition_with_maps) +//! refuses an undefined `#name` or `:value` and two conditions on one +//! attribute before any clause is classified. The service reports an unused +//! value, an invalid `FilterExpression` or `ProjectionExpression` and an +//! invalid `Select` ahead of the wording, and an `ExclusiveStartKey` or a key +//! value size after it, so the engine calls the refusal between those. On a +//! schema with one HASH attribute the engine also type-checks the clause on +//! the HASH attribute before the wording; see [`KeyCondition::operands_naming`]. + +use std::collections::HashMap; + +use super::{CompareOp, Expr, KeyCondition, PathElement, SortKeyCondition}; +use crate::error::{ + DynamoDbError, QUERY_KEY_CONDITION_NOT_SUPPORTED, hash_attributes_without_equality, + missed_key_schema_element, +}; +use crate::types::{KeySchemaElement, hash_key_elements, is_multipart_key_schema}; + +#[cfg(test)] +mod tests; + +impl KeyCondition { + /// The condition for one or two clauses, none of them an equality. + /// + /// `pk_path` is empty because no partition key condition was given. + /// `pk_value` repeats the first clause's first operand so the field holds + /// a well-formed expression; it carries no meaning while `pk_path` is + /// empty. + /// + /// `sk_condition` keeps the first clause whole. The second clause is kept + /// as its operands in `extra_sk_conditions`. + pub(super) fn without_equality( + first: SortKeyCondition, + second: Option, + ) -> Self { + let pk_value = first_operand(&first).clone(); + let extra_sk_conditions = second.map_or_else(Vec::new, |clause| operands(&clause)); + Self { + pk_path: Vec::new(), + pk_value, + extra_pk_conditions: Vec::new(), + sk_condition: Some(first), + extra_sk_conditions, + } + } + + /// Whether the key schema has no equality clause on its HASH attribute + /// in this condition, in a shape [`Self::refuse_without_hash_equality`] + /// refuses. + /// + /// True for a condition with no equality clause at all. On a schema with + /// one HASH attribute it is also true for two clauses where the equality + /// names another attribute and the other clause names the HASH attribute + /// with a non-equality (`sk = :x AND pk > :y`). An equality on the HASH + /// attribute makes it false, so `pk = :x AND pk > :y` keeps its existing + /// handling. + #[must_use] + pub fn lacks_hash_equality( + &self, + key_schema: &[KeySchemaElement], + names: &HashMap, + ) -> bool { + if self.pk_path.is_empty() { + return self.sk_condition.is_some(); + } + if is_multipart_key_schema(key_schema) + || !self.extra_pk_conditions.is_empty() + || !self.extra_sk_conditions.is_empty() + { + return false; + } + let Some(hash_attr) = single_hash_attr(key_schema) else { + return false; + }; + let names_hash = |path: &[PathElement]| attr_of(path, names) == Some(hash_attr); + let Some(sk) = &self.sk_condition else { + return false; + }; + let sk_is_equality = matches!( + sk, + SortKeyCondition::Compare { + op: CompareOp::Eq, + .. + } + ); + // `pk_path` holds an equality whenever it is set. A second equality + // on the HASH attribute (`sk = :x AND pk = :y`) also satisfies it. + if names_hash(&self.pk_path) { + return false; + } + !sk_is_equality && names_hash(sk.path()) + } + + /// Refuse a key condition that has no equality clause on the HASH + /// attribute, choosing the message by the key schema being queried. + /// + /// Returns `Ok(())` for every other key condition. Call this after the + /// expression validations (unused names and values, `FilterExpression`, + /// `ProjectionExpression`, `Select`), and before the storage read. + /// + /// - A schema with several HASH or several RANGE attributes: the service + /// names every HASH attribute, because none has an equality condition. + /// Measured on 2026-10-23 on an index with HASH `h` and RANGE `a`, `b`, + /// `c`, `d` (`h > :x`, `a > :x`, `d > :x`, `z > :x`, `begins_with(a, :x)`, + /// `a BETWEEN :x AND :y`, and `h > :n` with an N value) and on an index + /// with HASH `h1`, `h2` and RANGE `r` (`h1`, `h2`, `r`, `z` and a + /// `#name` for `h1`). + /// - A schema with one HASH attribute and at most one RANGE attribute: if + /// a clause names the HASH attribute (`<`, `<=`, `>`, `>=`, + /// `begins_with`, `BETWEEN`), `Query key condition not supported`; + /// otherwise `Query condition missed key schema element: `. Measured on a table, a hash-only table, a GSI and an + /// LSI. + /// + /// # Errors + /// + /// Returns `ValidationException` for the conditions above, and + /// `InternalServerError` for a key schema with no HASH attribute. + pub fn refuse_without_hash_equality( + &self, + key_schema: &[KeySchemaElement], + names: &HashMap, + ) -> Result<(), DynamoDbError> { + if !self.lacks_hash_equality(key_schema, names) { + return Ok(()); + } + + if is_multipart_key_schema(key_schema) { + let hash_attrs: Vec<&str> = hash_key_elements(key_schema) + .iter() + .map(|ks| ks.attribute_name.as_str()) + .collect(); + return Err(DynamoDbError::ValidationException( + hash_attributes_without_equality(&hash_attrs), + )); + } + + let Some(pk_attr) = single_hash_attr(key_schema) else { + return Err(DynamoDbError::InternalServerError( + "key schema without a HASH attribute".to_owned(), + )); + }; + let message = if self.operands_naming(pk_attr, names).is_empty() { + missed_key_schema_element(pk_attr) + } else { + QUERY_KEY_CONDITION_NOT_SUPPORTED.to_owned() + }; + Err(DynamoDbError::ValidationException(message)) + } + + /// The value operands of every clause that names `attribute`, with + /// `#name` resolved through `names`: one for a comparison or + /// `begins_with`, two for `BETWEEN`. A clause whose `#name` is not + /// defined names no attribute. + /// + /// The engine type-checks the operands of the clause on the HASH + /// attribute with this, and no other operand (measured 2026-11-01: + /// `pk > :x AND sk > :n` with an N value on an S sort key answers `Query + /// key condition not supported`). + #[must_use] + pub fn operands_naming<'a>( + &'a self, + attribute: &str, + names: &HashMap, + ) -> Vec<(&'a [PathElement], &'a Expr)> { + let names_it = |path: &[PathElement]| attr_of(path, names) == Some(attribute); + let mut found: Vec<(&[PathElement], &Expr)> = Vec::new(); + if names_it(&self.pk_path) { + found.push((&self.pk_path, &self.pk_value)); + } + for (path, value) in self + .extra_pk_conditions + .iter() + .chain(&self.extra_sk_conditions) + { + if names_it(path) { + found.push((path, value)); + } + } + match &self.sk_condition { + Some(SortKeyCondition::Compare { path, value, .. }) if names_it(path) => { + found.push((path, value)); + } + Some(SortKeyCondition::Between { path, low, high }) if names_it(path) => { + found.push((path, low)); + found.push((path, high)); + } + Some(SortKeyCondition::BeginsWith { path, prefix }) if names_it(path) => { + found.push((path, prefix)); + } + _ => {} + } + found + } +} + +/// The only HASH attribute of a schema, or `None` for zero or several. +fn single_hash_attr(key_schema: &[KeySchemaElement]) -> Option<&str> { + match hash_key_elements(key_schema).as_slice() { + [only] => Some(only.attribute_name.as_str()), + _ => None, + } +} + +/// The top-level attribute a path names, with `#name` resolved; `None` when +/// the name is not defined or the path is not an attribute. +fn attr_of<'a>(path: &'a [PathElement], names: &'a HashMap) -> Option<&'a str> { + match path.first()? { + PathElement::Attribute(name) => match name.strip_prefix('#') { + Some(ref_name) => names.get(ref_name).map(String::as_str), + None => Some(name.as_str()), + }, + PathElement::Index(_) => None, + } +} + +/// The first value operand of a clause. +fn first_operand(clause: &SortKeyCondition) -> &Expr { + match clause { + SortKeyCondition::Compare { value, .. } => value, + SortKeyCondition::Between { low, .. } => low, + SortKeyCondition::BeginsWith { prefix, .. } => prefix, + } +} + +/// Every value operand of a clause as a `(path, operand)` entry. +fn operands(clause: &SortKeyCondition) -> Vec<(Vec, Expr)> { + match clause { + SortKeyCondition::Compare { path, value, .. } => vec![(path.clone(), value.clone())], + SortKeyCondition::Between { path, low, high } => { + vec![(path.clone(), low.clone()), (path.clone(), high.clone())] + } + SortKeyCondition::BeginsWith { path, prefix } => vec![(path.clone(), prefix.clone())], + } +} diff --git a/crates/core/src/expression/key_condition/no_hash_equality/tests.rs b/crates/core/src/expression/key_condition/no_hash_equality/tests.rs new file mode 100644 index 000000000..cd4919d22 --- /dev/null +++ b/crates/core/src/expression/key_condition/no_hash_equality/tests.rs @@ -0,0 +1,202 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Key conditions with no equality clause on the HASH attribute. Each +//! expected message is the service's answer to the same request, as +//! `tests/python/test_query_lone_non_equality.py` records it. + +use std::collections::HashMap; + +use super::*; +use crate::expression::{parse_key_condition, tokenize}; +use crate::types::KeyType::{Hash, Range}; + +type Schema = &'static [(&'static str, crate::types::KeyType)]; + +const TABLE: Schema = &[("pk", Hash), ("sk", Range)]; +const HASH_ONLY: Schema = &[("pk", Hash)]; +/// A local secondary index on `TABLE`. +const LSI: Schema = &[("pk", Hash), ("ls", Range)]; +const GSI: Schema = &[("g", Hash), ("s", Range)]; +const MULTI_RANGE: Schema = &[ + ("h", Hash), + ("a", Range), + ("b", Range), + ("c", Range), + ("d", Range), +]; +const TWO_HASH: Schema = &[("h1", Hash), ("h2", Hash), ("r", Range)]; + +fn key_schema(schema: Schema) -> Vec { + schema + .iter() + .map(|(name, key_type)| KeySchemaElement { + attribute_name: (*name).to_owned(), + key_type: *key_type, + }) + .collect() +} + +/// `#p`, `#s`, `#z` and `#a` stand for `pk`, `sk`, `zz` and `h1`. +fn names() -> HashMap { + [("p", "pk"), ("s", "sk"), ("z", "zz"), ("a", "h1")] + .into_iter() + .map(|(reference, attr)| (reference.to_owned(), attr.to_owned())) + .collect() +} + +fn parse(expr: &str) -> KeyCondition { + let tokens = tokenize(expr).unwrap(); + parse_key_condition(&tokens).unwrap_or_else(|e| panic!("{expr}: {e:?}")) +} + +fn refusal(expr: &str, schema: Schema) -> String { + match parse(expr).refuse_without_hash_equality(&key_schema(schema), &names()) { + Err(DynamoDbError::ValidationException(msg)) => msg, + other => panic!("{expr}: expected a refusal, got {other:?}"), + } +} + +#[test] +fn a_clause_on_the_only_hash_attribute_is_not_supported() { + for (expr, schema) in [ + ("pk > :x", TABLE), + ("begins_with(pk, :x)", TABLE), + ("pk BETWEEN :x AND :y", TABLE), + ("#p > :x", TABLE), + ("pk > :x AND sk > :y", TABLE), + ("zz > :x AND pk > :y", TABLE), + ("sk = :x AND pk > :y", TABLE), + ("zz = :x AND pk > :y", TABLE), + ("begins_with(pk, :x) AND sk = :y", TABLE), + ("pk BETWEEN :x AND :y AND sk = :x", TABLE), + ("begins_with(pk, :x)", HASH_ONLY), + ("pk > :x", LSI), + ("g > :x", GSI), + ("g > :x AND s = :y", GSI), + ] { + assert_eq!( + refusal(expr, schema), + "Query key condition not supported", + "{expr}" + ); + } +} + +#[test] +fn no_clause_on_the_only_hash_attribute_misses_it() { + for (expr, schema, hash) in [ + ("sk > :x", TABLE, "pk"), + ("z > :x", TABLE, "pk"), + ("#s > :x", TABLE, "pk"), + ("#z > :x", TABLE, "pk"), + ("begins_with(#s, :x)", TABLE, "pk"), + ("sk > :x AND zz > :y", TABLE, "pk"), + ("ls > :x", LSI, "pk"), + ("s > :x", GSI, "g"), + ("s > :x AND zz > :y", GSI, "g"), + ("pk > :x AND s > :y", GSI, "g"), + ] { + assert_eq!( + refusal(expr, schema), + format!("Query condition missed key schema element: {hash}"), + "{expr}" + ); + } +} + +#[test] +fn a_schema_with_several_key_attributes_names_every_hash_attribute() { + for (expr, schema, hash) in [ + ("h > :x", MULTI_RANGE, "h"), + ("a > :x", MULTI_RANGE, "h"), + ("z > :x", MULTI_RANGE, "h"), + ("begins_with(a, :x)", MULTI_RANGE, "h"), + ("a BETWEEN :x AND :y", MULTI_RANGE, "h"), + ("h1 > :x", TWO_HASH, "h1, h2"), + ("r > :x", TWO_HASH, "h1, h2"), + ("#a > :x", TWO_HASH, "h1, h2"), + ] { + assert_eq!( + refusal(expr, schema), + format!( + "HASH key attributes {hash} must have equality conditions specified in the query" + ), + "{expr}" + ); + } +} + +#[test] +fn lacks_hash_equality_decides_which_conditions_are_refused() { + for (expr, schema, lacks) in [ + ("pk > :x", TABLE, true), + ("sk = :x AND pk > :y", TABLE, true), + ("zz = :x AND #p > :y", TABLE, true), + ("pk = :p", TABLE, false), + ("pk = :p AND sk > :s", TABLE, false), + ("sk > :s AND pk = :p", TABLE, false), + ("sk = :s AND pk = :p", TABLE, false), + // An equality on another attribute is left to the engine's missed + // key schema element check. + ("sk = :x", TABLE, false), + ("zz = :x AND sk > :y", TABLE, false), + ("zz = :x AND yy = :y", TABLE, false), + ("a = :a AND b = :b AND pk > :x", TABLE, false), + ("pk = :x AND s > :y", GSI, false), + ("h = :h AND a > :x", MULTI_RANGE, false), + ] { + let kc = parse(expr); + let schema = key_schema(schema); + assert_eq!(kc.lacks_hash_equality(&schema, &names()), lacks, "{expr}"); + assert_eq!( + kc.refuse_without_hash_equality(&schema, &names()).is_err(), + lacks, + "{expr}" + ); + } +} + +#[test] +fn a_key_schema_with_no_hash_attribute_is_an_internal_error() { + match parse("pk > :x").refuse_without_hash_equality(&key_schema(&[("sk", Range)]), &names()) { + Err(DynamoDbError::InternalServerError(msg)) => { + assert_eq!(msg, "key schema without a HASH attribute"); + } + other => panic!("expected an internal error, got {other:?}"), + } +} + +/// The placeholder names of `operands_naming(attribute)` for `expr`. +fn operand_names(expr: &str, attribute: &str, names: &HashMap) -> Vec { + parse(expr) + .operands_naming(attribute, names) + .into_iter() + .map(|(_, value)| match value { + Expr::Placeholder(name) => name.clone(), + other => panic!("{expr}: {other:?}"), + }) + .collect() +} + +#[test] +fn operands_naming_finds_the_clause_on_an_attribute_wherever_it_is() { + let none = HashMap::new(); + for (expr, want) in [ + ("pk > :n", vec!["n"]), + ("pk > :n AND sk > :y", vec!["n"]), + ("sk > :y AND pk > :n", vec!["n"]), + ("sk = :x AND pk > :n", vec!["n"]), + ("pk BETWEEN :n AND :m", vec!["n", "m"]), + ("sk > :y AND pk BETWEEN :n AND :m", vec!["n", "m"]), + ("begins_with(pk, :n)", vec!["n"]), + ("pk = :n", vec!["n"]), + ("sk > :y", vec![]), + ("sk = :x AND zz > :y", vec![]), + ] { + assert_eq!(operand_names(expr, "pk", &none), want, "{expr}"); + } + assert_eq!(operand_names("sk > :y AND #p > :n", "pk", &names()), ["n"]); + // An undefined `#name` names no attribute. + assert!(operand_names("#q > :n", "pk", &names()).is_empty()); +} diff --git a/crates/engine/src/query.rs b/crates/engine/src/query.rs index a0ca9fb76..7f50077d2 100755 --- a/crates/engine/src/query.rs +++ b/crates/engine/src/query.rs @@ -115,9 +115,24 @@ pub async fn handle_query( )); } + // A key condition with no equality on the HASH attribute of the key schema + // queried skips the Select index check and the classification below, and + // `refuse_without_hash_equality` refuses it. Legacy KeyConditions always + // has that equality, or its desugar below refuses it. + let queried_key_schema = index_info + .as_ref() + .map_or(&key_info.key_schema, |idx| &idx.key_schema); + let lacks_hash_equality = matches!( + &key_condition_expression, + Some(Ok(kc)) if kc.lacks_hash_equality(queried_key_schema, &maps.names) + ); + // Select=ALL_ATTRIBUTES requires an ALL-projection GSI (shared with Scan). // With an ExclusiveStartKey this runs after the start key checks below. - if input.exclusive_start_key.is_none() { + // The service refuses a key condition with no HASH equality first + // (measured 2026-11-24: `g > :a` on a KEYS_ONLY index answers `Query key + // condition not supported`). + if input.exclusive_start_key.is_none() && !lacks_hash_equality { validate_query_select_index_support(input.select, index_info.as_ref())?; } @@ -144,8 +159,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. 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). + // the table checks. A key condition with no equality on the HASH + // attribute is refused below, also 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 @@ -232,30 +249,42 @@ pub async fn handle_query( &query_key_info.attribute_definitions }; let check_types_here = multipart || legacy_kc_maps.is_some(); - key_condition.resolve_key_schema_with( - &query_key_info.key_schema, - &effective_maps.names, - |path, value| { - if check_types_here { - check_key_value_type(path, value, type_definitions, effective_maps) - } else { - Ok(()) + // A key condition with no equality clause, and on a schema with one HASH + // attribute an equality on another attribute paired with a non-equality + // on the HASH attribute (`sk = :x AND pk > :y`), has no partition key + // clause to assign or check. It skips the classification and the value + // checks here and is refused after the expression validations below, + // where the key schema picks the wording (measured 2026-10-23: an unused + // value, an invalid FilterExpression or ProjectionExpression and an + // invalid Select are reported ahead of it, and an unused value and an + // invalid FilterExpression ahead of a wrong-typed value in its clause on + // the HASH attribute). See `refuse_without_hash_equality`. + if !lacks_hash_equality { + key_condition.resolve_key_schema_with( + &query_key_info.key_schema, + &effective_maps.names, + |path, value| { + if check_types_here { + check_key_value_type(path, value, type_definitions, effective_maps) + } else { + Ok(()) + } + }, + )?; + // The parse checked a KeyConditionExpression's begins_with value. + if legacy_kc_maps.is_some() { + refuse_begins_with_on_number(&key_condition, effective_maps)?; + } + // On a single-attribute key schema, validate that the partition key is + // referenced in the condition. The classifier has already required an + // equality on every HASH attribute of a multi-attribute one. + if !multipart { + let pk_resolved = resolve_path_attr_name(&key_condition.pk_path, &effective_maps.names); + if pk_resolved.as_deref() != Some(pk_attr.as_str()) { + return Err(DynamoDbError::ValidationException( + extenddb_core::error::missed_key_schema_element(pk_attr), + )); } - }, - )?; - // The parse checked a KeyConditionExpression's begins_with value. - if legacy_kc_maps.is_some() { - refuse_begins_with_on_number(&key_condition, effective_maps)?; - } - // On a single-attribute key schema, validate that the partition key is - // actually referenced in the condition. The classifier has already required - // an equality on every HASH attribute of a multi-attribute one. - if !multipart { - let pk_resolved = resolve_path_attr_name(&key_condition.pk_path, &effective_maps.names); - if pk_resolved.as_deref() != Some(pk_attr.as_str()) { - return Err(DynamoDbError::ValidationException(format!( - "Query condition missed key schema element: {pk_attr}" - ))); } } @@ -367,6 +396,20 @@ pub async fn handle_query( extenddb_core::validation::IS_QUERY, )?; + // A key condition that skipped the classification above is refused here, + // the key schema of the table or index queried picking the wording. An + // ExclusiveStartKey or a key value size is checked after it (measured + // 2026-10-23). Legacy KeyConditions is desugared above with an equality + // clause, or refused there, so it never lacks the HASH equality. + if lacks_hash_equality { + refuse_without_hash_equality( + &key_condition, + &query_key_info.key_schema, + &query_key_info.attribute_definitions, + effective_maps, + )?; + } + // When Select=ALL_PROJECTED_ATTRIBUTES, capture the index info for post-read filtering. let index_proj = if matches!(input.select, Some(Select::AllProjectedAttributes)) { index_info.as_ref() @@ -631,6 +674,33 @@ fn refuse_begins_with_on_number( }) } +/// Refuse a key condition with no equality on the HASH attribute, which +/// `handle_query` passes here after the expression validations, in the +/// service's two steps: +/// +/// 1. On a key schema with one HASH and at most one RANGE attribute, a value +/// in a clause on the HASH attribute whose type differs from the +/// attribute's definition. The parse refused a `begins_with` value that is +/// not a string or a binary value. +/// 2. The key schema's wording (`KeyCondition::refuse_without_hash_equality`). +/// +/// `tests/python/test_query_lone_non_equality.py` lists the measured rows. +fn refuse_without_hash_equality( + key_condition: &extenddb_core::expression::KeyCondition, + key_schema: &[extenddb_core::types::KeySchemaElement], + attribute_definitions: &[extenddb_core::types::AttributeDefinition], + maps: &ExpressionMaps, +) -> Result<(), DynamoDbError> { + if !extenddb_core::types::is_multipart_key_schema(key_schema) + && let Some(hash) = key_schema.iter().find(|ks| ks.key_type == KeyType::Hash) + { + for (path, value) in key_condition.operands_naming(&hash.attribute_name, &maps.names) { + check_key_value_type(path, value, attribute_definitions, maps)?; + } + } + key_condition.refuse_without_hash_equality(key_schema, &maps.names) +} + /// The checks of a request's parameters that follow the raw-body checks of /// `query_key_values::validate_query_request_body`, in this order: an empty /// `KeyConditionExpression`, `ExpressionAttributeNames` and @@ -808,6 +878,9 @@ mod empty_key_condition_tests { } } +#[cfg(test)] +mod no_hash_equality_tests; + #[cfg(test)] #[path = "query_begins_with_tests.rs"] mod begins_with_tests; diff --git a/crates/engine/src/query/no_hash_equality_tests.rs b/crates/engine/src/query/no_hash_equality_tests.rs new file mode 100644 index 000000000..4920bf2e1 --- /dev/null +++ b/crates/engine/src/query/no_hash_equality_tests.rs @@ -0,0 +1,163 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The order of the checks `refuse_without_hash_equality` runs on a key +//! condition that skipped the classification in `handle_query`. Every +//! expected refusal was measured on the service: `pk > :x` on 2026-10-21, +//! the value type rules on 2026-11-01, the rest on 2026-10-23. + +use std::collections::HashMap; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::expression::{ExpressionMaps, parse_key_condition, tokenize}; +use extenddb_core::types::{ + AttributeDefinition, AttributeValue, KeySchemaElement, KeyType, ScalarAttributeType, +}; + +use super::refuse_without_hash_equality; + +const TYPE_MISMATCH: &str = "One or more parameter values were invalid: Condition parameter \ + type does not match schema type"; +const NOT_SUPPORTED: &str = "Query key condition not supported"; +const MISSED_PK: &str = "Query condition missed key schema element: pk"; +const MISSED_G: &str = "Query condition missed key schema element: g"; +const HASH_H: &str = "HASH key attributes h must have equality conditions specified in the query"; + +fn key(name: &str, key_type: KeyType) -> KeySchemaElement { + KeySchemaElement { + attribute_name: name.to_owned(), + key_type, + } +} + +fn definition(name: &str, attribute_type: ScalarAttributeType) -> AttributeDefinition { + AttributeDefinition { + attribute_name: name.to_owned(), + attribute_type, + } +} + +/// Run the checks on `expr`, with `:x` and `:y` strings and `:n` and `:m` +/// numbers. +fn check( + expr: &str, + key_schema: &[KeySchemaElement], + definitions: &[AttributeDefinition], +) -> Result<(), String> { + let kc = parse_key_condition(&tokenize(expr).unwrap()).unwrap(); + let values = HashMap::from([ + ("x".to_owned(), AttributeValue::S("a".to_owned())), + ("y".to_owned(), AttributeValue::S("b".to_owned())), + ("n".to_owned(), AttributeValue::N("1".to_owned())), + ("m".to_owned(), AttributeValue::N("2".to_owned())), + ]); + let maps = ExpressionMaps::new(HashMap::new(), values); + refuse_without_hash_equality(&kc, key_schema, definitions, &maps).map_err(|e| match e { + DynamoDbError::ValidationException(msg) => msg, + other => panic!("{expr}: {other:?}"), + }) +} + +fn assert_refusals( + rows: &[(&str, &str)], + key_schema: &[KeySchemaElement], + definitions: &[AttributeDefinition], +) { + for (expr, want) in rows { + assert_eq!( + check(expr, key_schema, definitions).unwrap_err(), + *want, + "{expr}" + ); + } +} + +/// HASH `pk` and RANGE `sk`, both strings. +fn string_table() -> (Vec, Vec) { + ( + vec![key("pk", KeyType::Hash), key("sk", KeyType::Range)], + vec![ + definition("pk", ScalarAttributeType::S), + definition("sk", ScalarAttributeType::S), + ], + ) +} + +/// An index with HASH `g` and RANGE `s` on the table above, which defines +/// its own key attributes as well. All four are strings. +fn string_index() -> (Vec, Vec) { + ( + vec![key("g", KeyType::Hash), key("s", KeyType::Range)], + ["pk", "sk", "g", "s"] + .into_iter() + .map(|name| definition(name, ScalarAttributeType::S)) + .collect(), + ) +} + +#[test] +fn single_attribute_schema_reports_a_wrong_typed_value_before_the_wording() { + // Row M8c. + let (schema, definitions) = string_table(); + assert_refusals( + &[("pk > :n", TYPE_MISMATCH), ("pk > :x", NOT_SUPPORTED)], + &schema, + &definitions, + ); +} + +#[test] +fn a_number_value_on_a_number_key_gets_the_wording() { + // Row 6b. Row 6, `begins_with(pk, :n)`, is refused by the parse. + let schema = [key("pk", KeyType::Hash)]; + let definitions = [definition("pk", ScalarAttributeType::N)]; + assert_refusals(&[("pk > :n", NOT_SUPPORTED)], &schema, &definitions); +} + +#[test] +fn only_the_clause_on_the_hash_attribute_is_type_checked() { + let (schema, definitions) = string_table(); + assert_refusals( + &[ + ("pk > :n AND sk > :y", TYPE_MISMATCH), + ("sk = :x AND pk > :n", TYPE_MISMATCH), + ("pk BETWEEN :n AND :m", TYPE_MISMATCH), + // An N value on the S sort key is not checked. + ("pk > :x AND sk > :n", NOT_SUPPORTED), + ], + &schema, + &definitions, + ); +} + +#[test] +fn no_value_is_type_checked_without_a_clause_on_the_hash_attribute() { + let (schema, definitions) = string_table(); + assert_refusals( + &[("sk > :n", MISSED_PK), ("zz > :n", MISSED_PK)], + &schema, + &definitions, + ); + // Measured on an index with HASH `gsi1_pk` and RANGE `SK` of a table + // with HASH `PK`: `PK > :n` and `SK > :n` answer the missing key sentence + // for `gsi1_pk`. Here `pk` is the table's HASH attribute and `s` the + // index's RANGE attribute. + let (schema, definitions) = string_index(); + assert_refusals( + &[("pk > :n", MISSED_G), ("s > :n", MISSED_G)], + &schema, + &definitions, + ); +} + +#[test] +fn multi_attribute_schema_reports_the_hash_wording_before_a_wrong_typed_value() { + // Row 4. + let mut schema = vec![key("h", KeyType::Hash)]; + let mut definitions = vec![definition("h", ScalarAttributeType::S)]; + for range in ["a", "b", "c", "d"] { + schema.push(key(range, KeyType::Range)); + definitions.push(definition(range, ScalarAttributeType::S)); + } + assert_refusals(&[("h > :n", HASH_H)], &schema, &definitions); +} diff --git a/crates/server/src/leading_keys/tests.rs b/crates/server/src/leading_keys/tests.rs index 51de039d5..a6df89124 100644 --- a/crates/server/src/leading_keys/tests.rs +++ b/crates/server/src/leading_keys/tests.rs @@ -300,6 +300,34 @@ fn query_kce_sort_key_before_partition_key() { assert_eq!(r, Some(vec!["alice".to_owned()])); } +#[test] +fn query_kce_without_a_partition_key_equality_binds_only_a_partition_operand() { + // Clauses with no equality parse without a partition key condition, and + // an equality on another attribute with a non-equality on the partition + // key is no partition key equality either; the engine refuses these + // requests by the key schema. Authorization binds the operand of the one + // clause that names the partition key, as + // `query_non_equality_partition_key_binds_the_operand` does for `pk > :v`, + // and never the operand of a clause on another attribute: `sk = :v AND + // pk > :s` binds `:s`, not `:v`. + for (kce, want) in [ + ("pk > :v", Some("alice")), + ("begins_with(pk, :v)", Some("alice")), + ("sk > :v", None), + ("pk > :v AND sk > :s", Some("alice")), + ("sk > :v AND zz > :s", None), + ("sk = :v AND pk > :s", Some("x")), + ] { + let input = json!({ + "TableName": "t", + "KeyConditionExpression": kce, + "ExpressionAttributeValues": {":v": {"S": "alice"}, ":s": {"S": "x"}}, + }); + let r = single_table_leading_keys(&input, "Query", Some(&main_table()), MAX_TOKENS); + assert_eq!(r, want.map(|v| vec![v.to_owned()]), "{kce}"); + } +} + #[test] fn query_legacy_key_conditions() { let input = json!({ @@ -779,30 +807,34 @@ fn query_non_equality_on_a_gsi_partition_key_binds_the_index_operand() { assert_eq!(r, Some(vec!["galice".to_owned()])); } -/// The single-clause shapes of the fix are shapes the engine's own parser -/// rejects, so the engine never reads a partition value for them and cannot -/// disagree with the value authorization binds. The two-clause shapes the fix -/// also binds (`pk > :v AND sk = :s`, `pk > :v AND sk < :s`) parse or not -/// depending on the sort clause, and the engine refuses them when it resolves -/// the partition attribute; the wire test -/// `test_non_equality_partition_with_sort_clause_is_refused` covers that. The -/// equality shapes the engine accepts keep the value they had, which the -/// accepted-shape tests above cover. +/// The shapes of the fix have no equality on the partition key. The engine +/// refuses them by the key schema before it reads anything, so it never reads +/// a partition value for them and cannot disagree with the value authorization +/// binds. The wire test `test_non_equality_partition_with_sort_clause_is_refused` +/// covers the two-clause shapes. The equality shapes the engine accepts keep the +/// value they had, which the accepted-shape tests above cover. #[test] -fn the_parser_still_rejects_every_single_clause_shape_whose_operand_is_now_bound() { +fn the_engine_still_refuses_every_shape_whose_operand_is_now_bound() { + let key_schema = main_table().key_schema; for kce in [ "pk > :v", "pk < :v", "pk <= :v", "pk >= :v", "begins_with(pk, :v)", + "pk > :v AND sk = :s", + "pk > :v AND sk < :s", ] { let tokens = extenddb_core::expression::tokenize(kce).unwrap(); - let err = extenddb_core::expression::parse_key_condition(&tokens).unwrap_err(); + let kc = extenddb_core::expression::parse_key_condition(&tokens).unwrap(); + let err = kc + .refuse_without_hash_equality(&key_schema, &HashMap::new()) + .unwrap_err(); assert!( matches!( - err, - extenddb_core::error::DynamoDbError::ValidationException(_) + &err, + extenddb_core::error::DynamoDbError::ValidationException(msg) + if msg == "Query key condition not supported" ), "{kce}: {err:?}" ); diff --git a/crates/server/src/request_attributes.rs b/crates/server/src/request_attributes.rs index 66717eef9..3f889c382 100644 --- a/crates/server/src/request_attributes.rs +++ b/crates/server/src/request_attributes.rs @@ -360,7 +360,9 @@ impl<'a> Names<'a> { /// 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. + /// A key condition `parse_key_condition` refuses gives none. So does one + /// with no equality clause, which the parser accepts and the engine + /// refuses once it knows the key schema. fn key_condition(&mut self, value: Option<&Value>) { let Some(text) = self.text(value) else { return; @@ -377,7 +379,7 @@ impl<'a> Names<'a> { } parse_key_condition(&tokens) }); - let Ok(condition) = parsed else { + let Some(condition) = parsed.ok().filter(|kc| !kc.pk_path.is_empty()) else { return; }; self.path(&condition.pk_path); diff --git a/crates/server/src/request_attributes/tests.rs b/crates/server/src/request_attributes/tests.rs index 7a4ecb2dc..56e313321 100644 --- a/crates/server/src/request_attributes/tests.rs +++ b/crates/server/src/request_attributes/tests.rs @@ -357,11 +357,14 @@ fn a_query_of_a_table_that_does_not_exist_holds_its_key_condition_names() { "ExpressionAttributeNames": {"#s": "sort", "#p": "part"}, }); assert_eq!(single("Query", &prefix, None), names(&["part", "sort"])); - // A key condition the key condition parser refuses gives none. On this - // table, which does not exist, the engine answers - // ResourceNotFoundException before it reads the key condition. + // A key condition the key condition parser refuses, or one with no + // equality clause, gives none. On this table, which does not exist, the + // engine answers ResourceNotFoundException before it reads the key + // condition. let refused = json!({"TableName": "gone", "KeyConditionExpression": "pk > :v"}); assert_eq!(single("Query", &refused, None), None); + let refused = json!({"TableName": "gone", "KeyConditionExpression": "pk > :v AND sk > :s"}); + assert_eq!(single("Query", &refused, None), None); let refused = json!({"TableName": "gone", "KeyConditionExpression": "pk = :p OR sk = :s"}); assert_eq!(single("Query", &refused, None), None); } diff --git a/tests/python/test_query_lone_non_equality.py b/tests/python/test_query_lone_non_equality.py new file mode 100644 index 000000000..5c566cb85 --- /dev/null +++ b/tests/python/test_query_lone_non_equality.py @@ -0,0 +1,590 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Query whose key condition has no equality clause on the HASH attribute. + +Every row below is one measured on the service in us-east-1: the issue table +rows on 2026-10-21, the rows of ``TestValueTypes`` and the two-clause +``begins_with`` rows on 2026-11-01, the rest on 2026-10-23. Rows M8c, 5a +and 5b were measured again on 2026-10-31 with the same answers. The table has +HASH ``pk`` and RANGE ``sk``, an LSI ``lsi`` on RANGE ``ls``, an index +``single-idx`` with HASH ``g`` and RANGE ``s``, an index ``multi-idx`` with +HASH ``h`` and RANGE ``a``, ``b``, ``c``, ``d`` and an index ``two-hash`` with +HASH ``h1``, ``h2`` and RANGE ``r``. A second table has only HASH ``pk``, a +third only HASH ``pk`` (N) and a fourth HASH ``pk`` (N) and RANGE ``sk``. All +attributes are strings unless stated. + +The service answers with one of these, chosen by the key schema of the table +or index being queried and by the attributes the clauses name: + +- a non-equality clause names the single HASH attribute: ``Query key condition + not supported`` +- no clause names the single HASH attribute: ``Query condition missed key + schema element: `` +- the schema has several key attributes: ``HASH key attributes must + have equality conditions specified in the query`` +- two conditions on one attribute: ``Invalid KeyConditionExpression: + KeyConditionExpressions must only contain one condition per key`` +- a ``#name`` or ``:value`` the request does not define, ahead of all of the + above: ``Invalid KeyConditionExpression: An expression attribute ...`` + +An unused value, an invalid ``FilterExpression`` or ``ProjectionExpression`` +and an invalid ``Select`` are reported ahead of the key schema wording. An +``ExclusiveStartKey`` and a key value size are reported after it. + +On a schema with one HASH attribute, two conditions on one attribute are +reported ahead of a wrong-typed value (``TestValueTypes``). A wrong-typed +value in the clause on the HASH attribute is reported before the key schema +wording (row M8c and ``TestValueTypes``). It is reported after an unused value +and an invalid ``FilterExpression`` (rows 5a and 5b). No other value is +checked against its key attribute's type. A ``begins_with`` with a number +value on a number HASH attribute gets the operand type message instead of the +key schema wording. Row 6 and the two-clause ``begins_with`` rows show this +for either clause. On an index with several key attributes the HASH wording +comes first (row 4, ``h > :n``). +""" + +from __future__ import annotations + +import pytest +from botocore.exceptions import ClientError + +from helpers import unique_name, wait_for_active, wait_for_deleted + +NOT_SUPPORTED = "Query key condition not supported" +MISSED_PK = "Query condition missed key schema element: pk" +MISSED_G = "Query condition missed key schema element: g" +HASH_H = "HASH key attributes h must have equality conditions specified in the query" +HASH_H1_H2 = "HASH key attributes h1, h2 must have equality conditions specified in the query" +ONE_PER_KEY = ( + "Invalid KeyConditionExpression: KeyConditionExpressions must only contain one " + "condition per key" +) +NO_VALUE = ( + "Invalid KeyConditionExpression: An expression attribute value used in expression is " + "not defined; attribute value: :x" +) +TYPE_MISMATCH = ( + "One or more parameter values were invalid: Condition parameter type does not match " + "schema type" +) +BEGINS_WITH_ON_N = ( + "Invalid KeyConditionExpression: Incorrect operand type for operator or function; " + "operator or function: begins_with, operand type: N" +) + + +def _attr(name: str, kind: str = "S") -> dict: + return {"AttributeName": name, "AttributeType": kind} + + +def _key(name: str, key_type: str) -> dict: + return {"AttributeName": name, "KeyType": key_type} + + +def _index(name: str, schema: list[dict]) -> dict: + return {"IndexName": name, "KeySchema": schema, "Projection": {"ProjectionType": "ALL"}} + + +def _drop(client, name: str) -> None: + try: + client.delete_table(TableName=name) + except client.exceptions.ResourceNotFoundException: + return + wait_for_deleted(client, name) + + +@pytest.fixture(scope="module") +def table(dynamodb_client): + """HASH ``pk`` and RANGE ``sk``, the LSI and the three indexes above.""" + name = unique_name("qlne") + names = ("pk", "sk", "ls", "g", "s", "h", "a", "b", "c", "d", "h1", "h2", "r") + dynamodb_client.create_table( + TableName=name, + AttributeDefinitions=[_attr(n) for n in names], + KeySchema=[_key("pk", "HASH"), _key("sk", "RANGE")], + BillingMode="PAY_PER_REQUEST", + LocalSecondaryIndexes=[_index("lsi", [_key("pk", "HASH"), _key("ls", "RANGE")])], + GlobalSecondaryIndexes=[ + _index("single-idx", [_key("g", "HASH"), _key("s", "RANGE")]), + _index( + "multi-idx", + [_key("h", "HASH")] + [_key(n, "RANGE") for n in ("a", "b", "c", "d")], + ), + _index( + "two-hash", + [_key("h1", "HASH"), _key("h2", "HASH"), _key("r", "RANGE")], + ), + ], + ) + try: + wait_for_active(dynamodb_client, name) + yield name + finally: + _drop(dynamodb_client, name) + + +def _plain_table(client, prefix: str, attributes: list[dict], schema: list[dict]): + """Create a table with no index, yield its name, then drop it.""" + name = unique_name(prefix) + client.create_table( + TableName=name, + AttributeDefinitions=attributes, + KeySchema=schema, + BillingMode="PAY_PER_REQUEST", + ) + try: + wait_for_active(client, name) + yield name + finally: + _drop(client, name) + + +@pytest.fixture(scope="module") +def hash_only_table(dynamodb_client): + """A table with only HASH ``pk`` (S).""" + yield from _plain_table(dynamodb_client, "qlne-hash", [_attr("pk")], [_key("pk", "HASH")]) + + +@pytest.fixture(scope="module") +def number_table(dynamodb_client): + """A table with only HASH ``pk`` (N).""" + yield from _plain_table(dynamodb_client, "qlne-num", [_attr("pk", "N")], [_key("pk", "HASH")]) + + +@pytest.fixture(scope="module") +def number_range_table(dynamodb_client): + """A table with HASH ``pk`` (N) and RANGE ``sk`` (S).""" + pk_sk = [_key("pk", "HASH"), _key("sk", "RANGE")] + yield from _plain_table(dynamodb_client, "qlne-numr", [_attr("pk", "N"), _attr("sk")], pk_sk) + + +def _refused_request(client, message: str, **request) -> None: + """Run the Query and assert the refusal's code, status and exact text.""" + with pytest.raises(ClientError) as exc_info: + client.query(**request) + err = exc_info.value.response + assert err["Error"]["Code"] == "ValidationException", err["Error"]["Message"] + assert err["ResponseMetadata"]["HTTPStatusCode"] == 400 + assert err["Error"]["Message"] == message + + +def _refused_prefix(client, prefix: str, **request) -> None: + """Like ``_refused_request`` for a refusal whose text ExtendDB words differently.""" + with pytest.raises(ClientError) as exc_info: + client.query(**request) + err = exc_info.value.response + assert err["Error"]["Code"] == "ValidationException", err["Error"]["Message"] + assert err["Error"]["Message"].startswith(prefix), err["Error"]["Message"] + + +def _values(expression: str) -> dict: + """Those of ``:x``, ``:y`` (strings), ``:n`` and ``:m`` (numbers) the expression uses.""" + values = {":x": {"S": "a"}, ":y": {"S": "b"}, ":n": {"N": "1"}, ":m": {"N": "2"}} + return {name: value for name, value in values.items() if name in expression} + + +def _refused( + client, + table: str, + message: str, + expression: str, + index: str | None = None, + **extra, +) -> None: + """``_refused_request`` with the values ``_values`` gives.""" + request: dict = { + "TableName": table, + "KeyConditionExpression": expression, + "ExpressionAttributeValues": _values(expression), + } + if index is not None: + request["IndexName"] = index + request.update(extra) + _refused_request(client, message, **request) + + +class TestPartitionKeyClause: + """Rows 1 to 3 of the issue: the clause names the single HASH attribute.""" + + def test_table_partition_key_greater_than(self, dynamodb_client, table): + _refused(dynamodb_client, table, NOT_SUPPORTED, "pk > :x") + + def test_table_partition_key_begins_with(self, dynamodb_client, table): + _refused(dynamodb_client, table, NOT_SUPPORTED, "begins_with(pk, :x)") + + def test_index_partition_key_greater_than(self, dynamodb_client, table): + _refused(dynamodb_client, table, NOT_SUPPORTED, "g > :x", index="single-idx") + + +class TestSortKeyClause: + """Rows 4 and 5 of the issue: the clause names a sort key.""" + + def test_table_sort_key_greater_than(self, dynamodb_client, table): + _refused(dynamodb_client, table, MISSED_PK, "sk > :x") + + def test_index_sort_key_greater_than(self, dynamodb_client, table): + _refused(dynamodb_client, table, MISSED_G, "s > :x", index="single-idx") + + +class TestMultiAttributeIndex: + """Row 6 of the issue and the shapes measured around it.""" + + def test_hash_attribute_greater_than(self, dynamodb_client, table): + _refused(dynamodb_client, table, HASH_H, "h > :x", index="multi-idx") + + @pytest.mark.parametrize( + "expression", + ["a > :x", "d > :x", "z > :x", "begins_with(a, :x)", "a BETWEEN :x AND :y"], + ) + def test_other_attributes_name_the_hash_attribute(self, dynamodb_client, table, expression): + _refused(dynamodb_client, table, HASH_H, expression, index="multi-idx") + + def test_a_number_value_does_not_change_the_wording(self, dynamodb_client, table): + # `h` is a string: the service answers the HASH wording, not a type error. + _refused_request( + dynamodb_client, + HASH_H, + TableName=table, + IndexName="multi-idx", + KeyConditionExpression="h > :n", + ExpressionAttributeValues={":n": {"N": "1"}}, + ) + + @pytest.mark.parametrize("expression", ["h1 > :x", "h2 > :x", "r > :x", "z > :x"]) + def test_two_hash_index_names_both_hash_attributes(self, dynamodb_client, table, expression): + _refused(dynamodb_client, table, HASH_H1_H2, expression, index="two-hash") + + def test_two_hash_index_with_a_name_reference(self, dynamodb_client, table): + _refused( + dynamodb_client, + table, + HASH_H1_H2, + "#a > :x", + index="two-hash", + ExpressionAttributeNames={"#a": "h1"}, + ) + + +class TestMeasuredShapes: + """Rows M1 to M9, measured 2026-10-23: shapes the issue table did not cover.""" + + def test_table_partition_key_between(self, dynamodb_client, table): + _refused(dynamodb_client, table, NOT_SUPPORTED, "pk BETWEEN :x AND :y") + + def test_index_partition_key_between(self, dynamodb_client, table): + _refused(dynamodb_client, table, NOT_SUPPORTED, "g BETWEEN :x AND :y", index="single-idx") + + def test_hash_only_table_begins_with(self, dynamodb_client, hash_only_table): + _refused(dynamodb_client, hash_only_table, NOT_SUPPORTED, "begins_with(pk, :x)") + + @pytest.mark.parametrize( + "fixture,expression,message", + [ + ("number_table", "pk > :n", NOT_SUPPORTED), + ("number_table", "begins_with(pk, :n)", BEGINS_WITH_ON_N), + ("number_range_table", "begins_with(pk, :n) AND sk > :x", BEGINS_WITH_ON_N), + ("number_range_table", "sk > :x AND begins_with(pk, :n)", BEGINS_WITH_ON_N), + ], + ) + def test_number_keyed_tables(self, dynamodb_client, request, fixture, expression, message): + """Rows 6b and 6 (2026-10-23); ``begins_with`` with a clause on ``sk`` (2026-11-01).""" + _refused(dynamodb_client, request.getfixturevalue(fixture), message, expression) + + def test_number_value_on_a_string_key_reports_the_type(self, dynamodb_client, table): + # Row M8c: the type check comes before the key schema wording. + _refused_request( + dynamodb_client, + TYPE_MISMATCH, + TableName=table, + KeyConditionExpression="pk > :n", + ExpressionAttributeValues={":n": {"N": "1"}}, + ) + + def test_lsi_partition_key_greater_than(self, dynamodb_client, table): + _refused(dynamodb_client, table, NOT_SUPPORTED, "pk > :x", index="lsi") + + def test_lsi_lone_range_clause(self, dynamodb_client, table): + _refused(dynamodb_client, table, MISSED_PK, "ls > :x", index="lsi") + + def test_non_key_attribute(self, dynamodb_client, table): + _refused(dynamodb_client, table, MISSED_PK, "z > :x") + + def test_legacy_key_conditions_greater_than_on_partition_key(self, dynamodb_client, table): + _refused_request( + dynamodb_client, + NOT_SUPPORTED, + TableName=table, + KeyConditions={"pk": {"ComparisonOperator": "GT", "AttributeValueList": [{"S": "a"}]}}, + ) + + def test_legacy_key_conditions_sort_key_only(self, dynamodb_client, table): + _refused_request( + dynamodb_client, + MISSED_PK, + TableName=table, + KeyConditions={"sk": {"ComparisonOperator": "GT", "AttributeValueList": [{"S": "a"}]}}, + ) + + +class TestNameReferences: + """Rows 2a to 2d, measured 2026-10-23: a defined ``#name`` is resolved.""" + + @pytest.mark.parametrize( + "expression,reference,attribute,message", + [ + ("#p > :x", "#p", "pk", NOT_SUPPORTED), + ("#s > :x", "#s", "sk", MISSED_PK), + ("#z > :x", "#z", "zz", MISSED_PK), + ("begins_with(#s, :x)", "#s", "sk", MISSED_PK), + ], + ) + def test_defined_name_is_resolved( + self, dynamodb_client, table, expression, reference, attribute, message + ): + _refused( + dynamodb_client, + table, + message, + expression, + ExpressionAttributeNames={reference: attribute}, + ) + + +class TestUndefinedReferences: + """Undefined references win over the key schema wording, with the prefix.""" + + def test_undefined_name(self, dynamodb_client, table): + _refused( + dynamodb_client, + table, + "Invalid KeyConditionExpression: An expression attribute name used in the " + "document path is not defined; attribute name: #nope", + "#nope > :x", + ) + + def test_undefined_name_in_the_first_of_two_clauses(self, dynamodb_client, table): + _refused( + dynamodb_client, + table, + "Invalid KeyConditionExpression: An expression attribute name used in the " + "document path is not defined; attribute name: #n", + "#n > :x AND sk > :y", + ) + + @pytest.mark.parametrize("expression", ["pk > :x", "sk > :x", "pk = :x"]) + def test_undefined_value(self, dynamodb_client, table, expression): + _refused_request( + dynamodb_client, NO_VALUE, TableName=table, KeyConditionExpression=expression + ) + + def test_undefined_value_in_the_first_of_two_clauses(self, dynamodb_client, table): + _refused_request( + dynamodb_client, + NO_VALUE, + TableName=table, + KeyConditionExpression="pk > :x AND sk > :y", + ExpressionAttributeValues={":y": {"S": "b"}}, + ) + + +class TestTwoClauses: + """Measured 2026-10-23: one or two clauses, no HASH equality.""" + + @pytest.mark.parametrize( + "expression", + [ + "pk > :x AND sk > :y", + "sk > :x AND pk > :y", + "pk > :x AND zz > :y", + "zz > :x AND pk > :y", + "pk >= :x AND sk = :y", + "sk = :x AND pk > :y", + "pk > :x AND sk = :y", + "begins_with(pk, :x) AND sk = :y", + "pk BETWEEN :x AND :y AND sk = :x", + "zz = :x AND pk > :y", + ], + ) + def test_a_non_equality_names_the_partition_key(self, dynamodb_client, table, expression): + _refused(dynamodb_client, table, NOT_SUPPORTED, expression) + + @pytest.mark.parametrize("expression", ["sk > :x AND zz > :y", "zz > :x AND sk > :y"]) + def test_no_clause_names_the_partition_key(self, dynamodb_client, table, expression): + _refused(dynamodb_client, table, MISSED_PK, expression) + + @pytest.mark.parametrize( + "expression", + ["zz = :x AND sk > :y", "zz = :x AND yy = :y", "sk = :x AND zz = :y"], + ) + def test_equalities_on_other_attributes_miss_the_partition_key( + self, dynamodb_client, table, expression + ): + _refused(dynamodb_client, table, MISSED_PK, expression) + + @pytest.mark.parametrize("expression", ["g > :x AND s > :y", "g > :x AND s = :y"]) + def test_index_clause_names_the_index_partition_key(self, dynamodb_client, table, expression): + _refused(dynamodb_client, table, NOT_SUPPORTED, expression, index="single-idx") + + @pytest.mark.parametrize( + "expression", ["s > :x AND zz > :y", "pk > :x AND s > :y", "pk = :x AND s > :y"] + ) + def test_index_clauses_that_miss_the_index_partition_key( + self, dynamodb_client, table, expression + ): + _refused(dynamodb_client, table, MISSED_G, expression, index="single-idx") + + @pytest.mark.parametrize("expression", ["pk > :x AND pk < :y", "sk > :x AND sk < :y"]) + def test_two_conditions_on_one_key(self, dynamodb_client, table, expression): + _refused(dynamodb_client, table, ONE_PER_KEY, expression) + + +class TestOrderAmongOtherRefusals: + """Rows 5a, 5b, 8, 9, 10, 11 and P4, measured 2026-10-23. + + Reported ahead of the key schema wording: an unused value, an invalid + ``FilterExpression`` or ``ProjectionExpression`` and an invalid ``Select``. + Reported after it: an ``ExclusiveStartKey`` and a key value size. + """ + + def test_unused_value_is_reported_first(self, dynamodb_client, table): + _refused_request( + dynamodb_client, + "Value provided in ExpressionAttributeValues unused in expressions: keys: {:y}", + TableName=table, + KeyConditionExpression="pk > :x", + ExpressionAttributeValues={":x": {"S": "a"}, ":y": {"S": "b"}}, + ) + + def test_unused_value_is_reported_before_a_wrong_typed_value(self, dynamodb_client, table): + # Row 5a: `:n` is an N value on the S key. + _refused_request( + dynamodb_client, + "Value provided in ExpressionAttributeValues unused in expressions: keys: {:y}", + TableName=table, + KeyConditionExpression="pk > :n", + ExpressionAttributeValues={":n": {"N": "1"}, ":y": {"S": "b"}}, + ) + + def test_invalid_filter_expression_is_reported_before_a_wrong_typed_value( + self, dynamodb_client, table + ): + # Row 5b: `:n` is an N value on the S key. Only the label is asserted, + # as in the test below. + _refused_prefix( + dynamodb_client, + "Invalid FilterExpression: ", + TableName=table, + KeyConditionExpression="pk > :n", + FilterExpression="nope(", + ExpressionAttributeValues={":n": {"N": "1"}}, + ) + + def test_invalid_filter_expression_is_reported_first(self, dynamodb_client, table): + # The service's text is 'Invalid FilterExpression: Syntax error; token: + # "", near: "("'. ExtendDB words it differently, so only the label + # is asserted: the filter error comes before the key condition wording. + _refused_prefix( + dynamodb_client, + "Invalid FilterExpression: ", + TableName=table, + KeyConditionExpression="pk > :x", + FilterExpression="nope(", + ExpressionAttributeValues={":x": {"S": "a"}}, + ) + + def test_invalid_projection_expression_is_reported_first(self, dynamodb_client, table): + # The service's text is 'Invalid ProjectionExpression: Syntax error; token: + # ",", near: ",,b"'. + _refused_prefix( + dynamodb_client, + "Invalid ProjectionExpression: ", + TableName=table, + KeyConditionExpression="pk > :x", + ProjectionExpression="a,,b", + ExpressionAttributeValues={":x": {"S": "a"}}, + ) + + def test_count_with_a_projection_is_reported_first(self, dynamodb_client, table): + _refused_request( + dynamodb_client, + "1 validation error detected: Cannot specify the ProjectionExpression when " + "choosing to get only the Count", + TableName=table, + KeyConditionExpression="pk > :x", + Select="COUNT", + ProjectionExpression="a", + ExpressionAttributeValues={":x": {"S": "a"}}, + ) + + def test_all_projected_attributes_without_an_index_is_reported_first( + self, dynamodb_client, table + ): + _refused_request( + dynamodb_client, + "1 validation error detected: ALL_PROJECTED_ATTRIBUTES can be used only when " + "Querying using an IndexName", + TableName=table, + KeyConditionExpression="pk > :x", + Select="ALL_PROJECTED_ATTRIBUTES", + ExpressionAttributeValues={":x": {"S": "a"}}, + ) + + @pytest.mark.parametrize( + "start_key", + [ + {"pk": {"S": "other"}, "sk": {"S": "a"}}, + {"pk": {"S": "other"}}, + ], + ids=["other-partition", "missing-sort-key"], + ) + def test_exclusive_start_key_is_checked_after_the_wording( + self, dynamodb_client, table, start_key + ): + _refused(dynamodb_client, table, NOT_SUPPORTED, "pk > :x", ExclusiveStartKey=start_key) + + def test_partition_key_size_is_checked_after_the_wording(self, dynamodb_client, table): + _refused_request( + dynamodb_client, + NOT_SUPPORTED, + TableName=table, + KeyConditionExpression="pk > :x", + ExpressionAttributeValues={":x": {"S": "x" * 2049}}, + ) + + def test_sort_key_size_is_checked_after_the_wording(self, dynamodb_client, table): + _refused_request( + dynamodb_client, + MISSED_PK, + TableName=table, + KeyConditionExpression="sk > :x", + ExpressionAttributeValues={":x": {"S": "x" * 1025}}, + ) + + +class TestValueTypes: + """A wrong-typed value with no HASH equality, measured on 2026-11-01. + + Two conditions on one attribute are refused first. Only the clause on the + HASH attribute is type-checked, and with no such clause no value is. The + index was measured with HASH ``gsi1_pk`` and RANGE ``SK`` of a table with + HASH ``PK``; here ``pk`` is outside ``single-idx`` and ``s`` its RANGE. + """ + + @pytest.mark.parametrize( + "expression,index,message", + [ + ("pk > :x AND pk < :n", None, ONE_PER_KEY), + ("pk > :n AND pk < :m", None, ONE_PER_KEY), + ("pk > :n AND sk > :y", None, TYPE_MISMATCH), + ("sk = :x AND pk > :n", None, TYPE_MISMATCH), + ("pk BETWEEN :n AND :m", None, TYPE_MISMATCH), + ("pk > :x AND sk > :n", None, NOT_SUPPORTED), + ("sk > :n", None, MISSED_PK), + ("zz > :n", None, MISSED_PK), + ("pk > :n", "single-idx", MISSED_G), + ("s > :n", "single-idx", MISSED_G), + ], + ) + def test_value_type(self, dynamodb_client, table, expression, index, message): + _refused(dynamodb_client, table, message, expression, index=index) diff --git a/tests/test_query_key_condition_one_per_key.py b/tests/test_query_key_condition_one_per_key.py index bef5bbec0..2a7f0f5fb 100644 --- a/tests/test_query_key_condition_one_per_key.py +++ b/tests/test_query_key_condition_one_per_key.py @@ -335,7 +335,11 @@ class TestQueryCheckOrder: KeyConditionExpression, then Select, the table, the index and ConsistentRead. F3 is an undefined filter value on a partition with no 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.""" + key: the service reads the key condition's shape after the table. W5 + (2026-11-24T22:04Z) has no equality on the HASH attribute of the KEYS_ONLY + index: the service refuses it ahead of the Select index check. A3 + (2026-11-25T04:41Z) has no clause on that attribute, and the missed key + schema element also comes ahead of the Select index check.""" Q = "#q = :a" CO = {"ConditionalOperator": "AND"} @@ -381,6 +385,16 @@ class TestQueryCheckOrder: ), ("R10", _q("pk > :a", "a", TableName=MISSING_TABLE), NOT_FOUND), ("R11", _q("pk > :a AND sk > :b", "a b", TableName=MISSING_TABLE), NOT_FOUND), + ( + "W5", + _q("g > :a", "a", IndexName=GSI, Select="ALL_ATTRIBUTES"), + "Query key condition not supported", + ), + ( + "A3", + _q("sk > :a", "a", IndexName=GSI, Select="ALL_ATTRIBUTES"), + "Query condition missed key schema element: g", + ), ] @pytest.mark.parametrize("row", ROWS, ids=[r[0] for r in ROWS]) diff --git a/tests/test_vector_index_query_scan.py b/tests/test_vector_index_query_scan.py index af75a7834..0bb0b73dc 100644 --- a/tests/test_vector_index_query_scan.py +++ b/tests/test_vector_index_query_scan.py @@ -278,6 +278,26 @@ def test_query_key_condition_syntax_fires_before_vector_refusal( # the vector-index refusal. assert _error_message(resp).startswith("Invalid KeyConditionExpression:") + @pytest.mark.parametrize("expression", ["pk > :v", "zz > :v"]) + def test_query_vector_refusal_fires_before_the_hash_equality_check( + self, vector_table, expression + ): + # Measured 2026-11-25 on a table keyed on pk alone, as here, and on + # one keyed on pk and sk: with no equality on pk, the service answers + # the vector refusal ahead of the messages for a key condition with no + # HASH equality. + resp = _signed_post( + "Query", + { + "TableName": vector_table, + "IndexName": "vidx", + "KeyConditionExpression": expression, + "ExpressionAttributeValues": {":v": {"S": "a"}}, + }, + ) + assert resp.status_code == 400, resp.text + assert _error_message(resp) == QUERY_REFUSAL + class TestControlsUnaffected: """Base-table and GSI reads on the same table still succeed."""