diff --git a/Cargo.toml b/Cargo.toml index 138d50d1e..17e7d4149 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,9 @@ extenddb-app = { path = "crates/app", version = "=1.0.0" } # Serialization serde = { version = "1", features = ["derive"] } -serde_json = "1" +# 1.0.129 added `Value::sort_all_objects`, which the transaction token hash +# calls. +serde_json = "1.0.129" toml = "0.8" # Error handling diff --git a/crates/core/src/backup_format/data_file.rs b/crates/core/src/backup_format/data_file.rs index 70a226541..4a863b4bf 100644 --- a/crates/core/src/backup_format/data_file.rs +++ b/crates/core/src/backup_format/data_file.rs @@ -795,9 +795,9 @@ where /// the item being built, whatever the nesting depth. Peak heap growth while /// decoding one line, per line byte (requested bytes counted by a global /// allocator, release build, `serde_json` 1.0.150 without `preserve_order`, -/// which is the default `extenddb` binary and `cargo test -p extenddb-core`; -/// a build that includes the MongoDB backend enables `preserve_order` -/// through `bson`, replaces `serde_json`'s `BTreeMap` with `indexmap`, and +/// which is `cargo test -p extenddb-core`; every build that includes the +/// server enables `preserve_order` (the server crate turns it on, and so +/// does `bson`), replaces `serde_json`'s `BTreeMap` with `indexmap`, and /// measures about two thirds of each figure, 51 for the flat list, so the /// table is the larger of the two; the `VmHWM` growth on Linux x86-64 with /// glibc malloc is within 4% of it): diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 35fd2d055..a1692bfdb 100755 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -12,6 +12,7 @@ pub mod backup_format; pub mod error; pub mod expression; pub mod limits; +pub mod map_order; pub mod metrics; #[cfg(feature = "partiql")] pub mod partiql; diff --git a/crates/core/src/map_order.rs b/crates/core/src/map_order.rs new file mode 100644 index 000000000..b3ef215df --- /dev/null +++ b/crates/core/src/map_order.rs @@ -0,0 +1,96 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The order in which the service visits the members of one request map. + +/// The members of a map in the order the service visits them, given in the +/// order the request sends them: the iteration order of a Java `HashMap` +/// filled from the request's map. The service prints the maps of a statement +/// list's echo in this order (measured 2026-11-02 on maps of 2, 3, 4, 6, 12, +/// 13, 24 and 48 members). It checks the members of one +/// `ExpressionAttributeValues` map and of one PartiQL parameter map in this +/// order too (measured 2026-11-12 and 2026-11-19 on maps of 2, 3 and 4 +/// members). +/// +/// The table has the smallest power of two of buckets at or above +/// `size / 0.75` rounded up. A key sits in the bucket its Java +/// `String.hashCode` picks once the hash's high 16 bits are folded into its +/// low 16 by exclusive or. The buckets come in ascending order, and the keys +/// of one bucket in the order the request sends them. +/// +/// The keys of one bucket keep the order `members` yields them in. For a +/// parsed request that is the request's order in every build that includes +/// the server: its crate turns on serde_json's `preserve_order` feature. +pub fn hash_map_order, V>(members: impl IntoIterator) -> Vec<(K, V)> { + let mut members: Vec<(K, V)> = members.into_iter().collect(); + // `size / 0.75` rounded up, in whole numbers. + let buckets = (members.len() * 4).div_ceil(3).next_power_of_two(); + // The sort is stable, so the keys of one bucket keep their order. + members.sort_by_cached_key(|(key, _)| bucket(key.as_ref(), buckets)); + members +} + +/// The bucket of `key` in a Java `HashMap` table of `buckets` buckets. +fn bucket(key: &str, buckets: usize) -> usize { + // Java's `String.hashCode`: 31 times the hash plus each UTF-16 unit, + // wrapping at 32 bits. + let hash = key.encode_utf16().fold(0_u32, |hash, unit| { + hash.wrapping_mul(31).wrapping_add(u32::from(unit)) + }); + (hash ^ (hash >> 16)) as usize & (buckets - 1) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The keys of `members`, given in this order, in the order the service + /// visits them. + fn visited<'a>(members: impl IntoIterator) -> Vec<&'a str> { + hash_map_order(members.into_iter().map(|key| (key, ()))) + .into_iter() + .map(|(key, ())| key) + .collect() + } + + #[test] + fn map_members_come_in_the_measured_order() { + assert_eq!(visited(["c", "a", "p"]), ["p", "a", "c"]); + assert_eq!( + visited(["zeta", "alpha", "mid", "beta"]), + ["zeta", "mid", "beta", "alpha"] + ); + let keys: Vec = (0..=12).rev().map(|i| format!("k{i}")).collect(); + assert_eq!( + visited(keys.iter().map(String::as_str)), + [ + "k0", "k1", "k2", "k3", "k4", "k11", "k5", "k10", "k6", "k7", "k12", "k8", "k9" + ] + ); + } + + #[test] + fn the_table_holds_size_over_three_quarters_rounded_up() { + // 3 members take 4 buckets and 6 take 8, not 8 and 16. + assert_eq!(visited(["m0", "m1", "m2"]), ["m1", "m2", "m0"]); + assert_eq!( + visited(["k0", "k1", "k2", "k3", "k4", "k5"]), + ["k3", "k4", "k5", "k0", "k1", "k2"] + ); + } + + #[test] + fn keys_that_share_a_bucket_keep_the_order_they_come_in() { + // q and a share bucket 1 of 4. + assert_eq!(bucket("q", 4), bucket("a", 4)); + assert_eq!(visited(["q", "a"]), ["q", "a"]); + assert_eq!(visited(["a", "q"]), ["a", "q"]); + } + + #[test] + fn a_key_hashes_over_its_utf16_units() { + // 0xD83D * 31 + 0xDE00 = 1772899, whose folded low five bits are 24. + assert_eq!(bucket("\u{1F600}", 32), 24); + assert_eq!(bucket("a", 1), 0); + } +} diff --git a/crates/core/src/partiql/params.rs b/crates/core/src/partiql/params.rs index 751127e58..4768c7609 100644 --- a/crates/core/src/partiql/params.rs +++ b/crates/core/src/partiql/params.rs @@ -20,7 +20,7 @@ //! and `{"S": "a", "X": "1"}` is the string `a`. //! - It then converts each statement's parameters before it looks at the //! statement, and reports the first problem it reaches walking the values -//! in document order (see [`check_parameter_values`]): a map or list nested +//! in the order below (see [`check_parameter_values`]): a map or list nested //! past the item limit, an `N` (or `NS` member) that cannot be converted or //! breaks a number rule, an attribute value with no type or with two, a //! null member of a set, map or list, an empty set, a set that holds a @@ -36,23 +36,25 @@ //! 2026-11-06). Such a problem is the statement's own: in a //! `BatchExecuteStatement` the other statements run. //! -//! The walks here run over the parsed request body: parameters and list -//! elements in request order, the members of a map in the order the parsed -//! JSON object holds them. That is the request's order when the build -//! includes the MongoDB storage crate, whose JSON dependency makes every JSON -//! map keep it (any build of the whole workspace), and name order otherwise. -//! In name order, when two members of one map both have a problem, the one -//! reported can differ from the service's, which walks the request's order -//! (measured 2026-11-02). +//! Both walks run over the parsed request body, with parameters and list +//! elements in request order. The first pass visits the members of a map in +//! the order the parsed JSON object holds them. That is the request's order +//! in every build that includes the server, whose crate turns on +//! serde_json's `preserve_order` feature, and name order in a build without +//! it, such as this crate's own tests. The second pass visits them in the +//! order the service checks them, the order a Java `HashMap` of the map +//! yields them, and the members of one bucket in the order of the first pass +//! (see [`crate::map_order::hash_map_order`]; measured 2026-11-12 and +//! 2026-11-19). use std::collections::HashSet; -use base64::Engine; -use base64::engine::general_purpose::STANDARD as BASE64; use serde::Deserialize; use serde_json::{Map, Value}; use super::number::{check_number, parameter_message}; +pub use crate::serde_helpers::check_parameter_types; +use crate::serde_helpers::typed_members; use crate::types::AttributeValue; use crate::validation::MAX_ITEM_NESTING_DEPTH; use crate::validation::number::validate_and_normalize_number; @@ -86,99 +88,6 @@ const NULL_BINARY_SET_MEMBER: &str = "One or more parameter values were invalid: Binary sets may not contain null or empty values"; const NULL_MEMBER: &str = "The supplied Item contains a null AttributeValue"; -/// The members an attribute value may hold. Any other member is ignored. -const TYPES: [&str; 10] = ["S", "N", "B", "SS", "NS", "BS", "M", "L", "NULL", "BOOL"]; - -/// Check the JSON types of a statement's parameters (wire attribute values), -/// the first of the two passes (see the module documentation). The caller -/// checks every statement of the request this way before it checks -/// anything else of the request. -/// -/// The walk visits every map and list. The request body's JSON nesting -/// limit bounds its depth, at most one level for each two JSON levels. -/// -/// # Errors -/// -/// Returns a description of the first value whose JSON the attribute value -/// model cannot read: a value that is not a JSON object, or a member with a -/// payload of the wrong JSON type. -pub fn check_parameter_types(parameters: &[Value]) -> Result<(), String> { - parameters.iter().try_for_each(check_types) -} - -fn check_types(value: &Value) -> Result<(), String> { - let Value::Object(members) = value else { - return Err(AttributeValue::deserialize(value).err().map_or_else( - || "an attribute value must be a JSON object".to_owned(), - |e| e.to_string(), - )); - }; - for (tag, payload) in typed_members(members) { - match (tag, payload) { - ("S" | "N", Value::String(_)) | ("NULL" | "BOOL", Value::Bool(_)) => {} - ("B", Value::String(text)) => check_base64(text)?, - ("SS" | "NS", Value::Array(items)) => { - if items - .iter() - .any(|item| !item.is_string() && !item.is_null()) - { - return Err(format!("{tag} member must be a string")); - } - } - ("BS", Value::Array(items)) => { - for item in items { - match item { - Value::String(text) => check_base64(text)?, - Value::Null => {} - _ => return Err("BS member must be a base64 string".to_owned()), - } - } - } - ("M", Value::Object(entries)) => { - for member in entries.values().filter(|member| !member.is_null()) { - check_types(member)?; - } - } - ("L", Value::Array(items)) => { - for item in items.iter().filter(|item| !item.is_null()) { - check_types(item)?; - } - } - (tag, _) => return Err(wrong_payload(tag)), - } - } - Ok(()) -} - -/// The description of a payload of the wrong JSON type, in the attribute -/// value deserializer's words. -fn wrong_payload(tag: &str) -> String { - let expected = match tag { - "S" | "N" => "a string", - "B" => "a base64 string", - "NULL" | "BOOL" => "a boolean", - "M" => "an object", - _ => "an array", - }; - format!("{tag} value must be {expected}") -} - -fn check_base64(text: &str) -> Result<(), String> { - BASE64 - .decode(text) - .map(drop) - .map_err(|e| format!("invalid base64: {e}")) -} - -/// The members of an attribute value the model reads: those it names whose -/// value is not null, in the order the value holds them. -fn typed_members(members: &Map) -> impl Iterator { - members - .iter() - .filter(|(tag, payload)| !payload.is_null() && TYPES.contains(&tag.as_str())) - .map(|(tag, payload)| (tag.as_str(), payload)) -} - /// `value` as the attribute value model reads it: without the members it /// ignores, at every level. Its parameters passed [`check_parameter_types`] /// and [`check_parameter_values`], so the result deserializes. @@ -235,7 +144,7 @@ fn check_value(value: &Value, depth: usize) -> Result<(), String> { match (tag, payload) { ("M", Value::Object(entries)) => { let next = enter(depth)?; - for (name, member) in entries { + for (name, member) in crate::map_order::hash_map_order(entries) { if member.is_null() { return Err(format!("{NULL_MEMBER}: {name} is null")); } @@ -341,7 +250,7 @@ mod tests { const ABC: &str = "The parameter cannot be converted to a numeric value: abc"; #[test] - fn parameters_are_walked_in_request_order_and_map_members_as_the_map_holds_them() { + fn parameters_are_walked_in_request_order_and_map_members_in_hash_map_order() { let d = deep(40, "{\"S\":\"leaf\"}"); let bad = "{\"N\":\"abc\"}"; assert_eq!( @@ -352,16 +261,47 @@ mod tests { check_parameter_values(&doc(&format!("[{bad},{d}]"))), Err(ABC.to_owned()) ); - // Within one map the member the parsed map holds first is reached - // first: the one whose name sorts first, or the one the request wrote - // first in a build whose JSON maps keep the request's order. + // Within one map the members are reached in the order a Java + // `HashMap` of the map yields them, in either order written + // (measured 2026-11-12 and 2026-11-19). In 4 buckets `bad` and `x` + // are in bucket 0, `a` and `e` in 1 and `n` in 2. In the 8 buckets of + // a map of four members, `a` is in bucket 1 and `bad` in 4. + let x = "{\"S\":\"1\"}"; + for (members, want) in [ + (vec![("e", d.as_str()), ("bad", bad)], ABC), + (vec![("n", d.as_str()), ("bad", bad)], ABC), + (vec![("bad", bad), ("a", d.as_str())], ABC), + (vec![("bad", bad), ("a", d.as_str()), ("x", x)], ABC), + ( + vec![("bad", bad), ("a", d.as_str()), ("x", x), ("y", x)], + NESTING_MESSAGE, + ), + ] { + let reversed = members.iter().rev().copied().collect(); + for order in [members, reversed] { + let written: Vec = order + .iter() + .map(|(name, value)| format!("\"{name}\":{value}")) + .collect(); + let written = written.join(","); + assert_eq!( + check_parameter_values(&doc(&format!("[{{\"M\":{{{written}}}}}]"))), + Err(want.to_owned()), + "{written}" + ); + } + } + // `d` and `bad` share bucket 0 of 4, so the member the parsed map + // holds first is reached first: the one the request wrote first in a + // build whose JSON maps keep the request's order, as the service + // does (measured 2026-11-12). for members in [ - format!("\"a\":{d},\"b\":{bad}"), - format!("\"b\":{bad},\"a\":{d}"), + format!("\"d\":{d},\"bad\":{bad}"), + format!("\"bad\":{bad},\"d\":{d}"), ] { let params = doc(&format!("[{{\"M\":{{{members}}}}}]")); let first = params[0]["M"].as_object().unwrap().keys().next().unwrap(); - let want = if first == "a" { NESTING_MESSAGE } else { ABC }; + let want = if first == "d" { NESTING_MESSAGE } else { ABC }; assert_eq!( check_parameter_values(¶ms), Err(want.to_owned()), diff --git a/crates/core/src/serde_helpers.rs b/crates/core/src/serde_helpers.rs index 3a4ffb3cd..6929d0fc3 100644 --- a/crates/core/src/serde_helpers.rs +++ b/crates/core/src/serde_helpers.rs @@ -5,13 +5,18 @@ //! //! Validate `ExpressionAttributeNames` / `ExpressionAttributeValues` map entries //! at deserialization time, before expression parsing, matching Amazon -//! `DynamoDB`'s order: non-empty map, well-formed placeholder keys -//! (`[A-Za-z0-9_]+`, <=255 bytes incl. prefix), non-empty mapped value. +//! `DynamoDB`'s order for each map (see `deserialize_placeholder_map`): a +//! non-empty map and the JSON type of each value come first. Then +//! `ExpressionAttributeValues` checks its keys (`[A-Za-z0-9_]+`, <=255 +//! bytes incl. prefix) ahead of its values, and `ExpressionAttributeNames` its +//! names ahead of its keys. use std::collections::HashMap; +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64; use serde::de::{self, Deserialize, Deserializer}; -use serde_json::Value; +use serde_json::{Map, Value}; use crate::types::AttributeValue; @@ -54,14 +59,25 @@ fn validate_placeholder_key( } /// Deserialize a placeholder map, sharing the structure check (non-empty map, -/// well-formed keys). The caller supplies the per-type value check and +/// well-formed keys). The caller supplies the per-type value checks and the /// conversion. Values arrive as raw `serde_json::Value` so a value error can /// name its key (serde errors do not carry the failing key). +/// +/// The checks come in Amazon `DynamoDB`'s order (measured 2026-11-19). A +/// value of the wrong JSON type is refused first, the first one written, +/// because the service refuses it while it reads the request's JSON. +/// `wrong_type` finds such a value and `convert` gives its refusal. Then come +/// the keys and the values, the values first when `values_before_keys`. Both +/// are visited in the order a Java `HashMap` of the map yields them (see +/// [`crate::map_order::hash_map_order`]). +#[allow(clippy::too_many_arguments)] fn deserialize_placeholder_map<'de, D, T>( deserializer: D, prefix: char, field_name: &str, include_size_in_too_long: bool, + wrong_type: impl Fn(&Value) -> bool, + values_before_keys: bool, check_value: impl Fn(&str, &Value) -> Result<(), String>, convert: impl Fn(Value) -> Result, ) -> Result>, D::Error> @@ -74,11 +90,24 @@ where if raw.is_empty() { return Err(de::Error::custom(format!("{field_name} must not be empty"))); } - let mut out = HashMap::with_capacity(raw.len()); - for (key, value) in raw { - validate_placeholder_key(&key, prefix, field_name, include_size_in_too_long) + for value in raw.values().filter(|value| wrong_type(value)) { + convert(value.clone()).map_err(de::Error::custom)?; + } + let members = crate::map_order::hash_map_order(raw); + if values_before_keys { + for (key, value) in &members { + check_value(key, value).map_err(de::Error::custom)?; + } + } + for (key, _) in &members { + validate_placeholder_key(key, prefix, field_name, include_size_in_too_long) .map_err(de::Error::custom)?; - check_value(&key, &value).map_err(de::Error::custom)?; + } + let mut out = HashMap::with_capacity(members.len()); + for (key, value) in members { + if !values_before_keys { + check_value(&key, &value).map_err(de::Error::custom)?; + } let converted = convert(value).map_err(de::Error::custom)?; out.insert(key, converted); } @@ -102,6 +131,11 @@ where '#', "ExpressionAttributeNames", true, + // A name that is not a string is refused first, and an empty name + // ahead of a malformed key. A JSON null is neither: an empty name + // beside it is refused (measured 2026-11-19). + |value| !value.is_string() && !value.is_null(), + true, |key, value| { // Only a genuine empty *string* is rejected. A non-string falls // through to `convert` -> type error -> SerializationException, @@ -135,6 +169,12 @@ where ':', "ExpressionAttributeValues", false, + // A value the attribute value model cannot read is refused first, + // and a malformed key ahead of an empty value. A JSON null is not + // such a value: an empty value beside it is refused (measured + // 2026-11-19). + |value| !value.is_null() && check_types(value).is_err(), + false, |key, value| { // Empty AttributeValue (no datatype). Caught here so the error names // its key. Mirrors the empty-object check in `types::attribute_value`; @@ -152,6 +192,100 @@ where ) } +/// The members an attribute value may hold. Any other member is ignored. +const TYPES: [&str; 10] = ["S", "N", "B", "SS", "NS", "BS", "M", "L", "NULL", "BOOL"]; + +/// Check the JSON types of a statement's parameters (wire attribute +/// values), the first of the two passes of the PartiQL parameter checks. +/// The caller checks every statement of the request this way before it +/// checks anything else of the request. [`deserialize_expression_values`] +/// checks its values the same way before it checks their keys. +/// +/// The walk visits every map and list. The request body's JSON nesting +/// limit bounds its depth, at most one level for each two JSON levels. +/// +/// # Errors +/// +/// Returns a description of the first value whose JSON the attribute value +/// model cannot read: a value that is not a JSON object, or a member with a +/// payload of the wrong JSON type. +pub fn check_parameter_types(parameters: &[Value]) -> Result<(), String> { + parameters.iter().try_for_each(check_types) +} + +fn check_types(value: &Value) -> Result<(), String> { + let Value::Object(members) = value else { + return Err(AttributeValue::deserialize(value).err().map_or_else( + || "an attribute value must be a JSON object".to_owned(), + |e| e.to_string(), + )); + }; + for (tag, payload) in typed_members(members) { + match (tag, payload) { + ("S" | "N", Value::String(_)) | ("NULL" | "BOOL", Value::Bool(_)) => {} + ("B", Value::String(text)) => check_base64(text)?, + ("SS" | "NS", Value::Array(items)) => { + if items + .iter() + .any(|item| !item.is_string() && !item.is_null()) + { + return Err(format!("{tag} member must be a string")); + } + } + ("BS", Value::Array(items)) => { + for item in items { + match item { + Value::String(text) => check_base64(text)?, + Value::Null => {} + _ => return Err("BS member must be a base64 string".to_owned()), + } + } + } + ("M", Value::Object(entries)) => { + for member in entries.values().filter(|member| !member.is_null()) { + check_types(member)?; + } + } + ("L", Value::Array(items)) => { + for item in items.iter().filter(|item| !item.is_null()) { + check_types(item)?; + } + } + (tag, _) => return Err(wrong_payload(tag)), + } + } + Ok(()) +} + +/// The description of a payload of the wrong JSON type, in the attribute +/// value deserializer's words. +fn wrong_payload(tag: &str) -> String { + let expected = match tag { + "S" | "N" => "a string", + "B" => "a base64 string", + "NULL" | "BOOL" => "a boolean", + "M" => "an object", + _ => "an array", + }; + format!("{tag} value must be {expected}") +} + +fn check_base64(text: &str) -> Result<(), String> { + BASE64 + .decode(text) + .map(drop) + .map_err(|e| format!("invalid base64: {e}")) +} + +/// The members of an attribute value the model reads: those it names whose +/// value is not null, in the order the value holds them. +pub(crate) fn typed_members(members: &Map) -> impl Iterator { + members + .iter() + .filter(|(tag, payload)| !payload.is_null() && TYPES.contains(&tag.as_str())) + .map(|(tag, payload)| (tag.as_str(), payload)) +} + #[cfg(test)] mod tests { use super::*; @@ -317,4 +451,78 @@ mod tests { "{msg}" ); } + + /// Two faults in one map, the members of `first` written ahead of those + /// of `second` and after them, and the refusal the service gave in both + /// orders (measured 2026-11-12 and 2026-11-19). The map's own order is + /// name order in this crate's tests, and the order written in a build + /// with serde_json's `preserve_order` feature. + #[test] + fn two_faults_in_one_map_are_refused_as_the_service_refuses_them() { + let empty_value = |key: &str| { + format!( + "ExpressionAttributeValues contains invalid value: Supplied AttributeValue \ + is empty, must contain exactly one of the supported datatypes for key {key}" + ) + }; + let empty_name = |key: &str| { + format!( + "ExpressionAttributeNames contains invalid value: Empty attribute name for key {key}" + ) + }; + let values_key = + r#"ExpressionAttributeValues contains invalid key: Syntax error; key: "b""#; + let s_number = "S value must be a string".to_owned(); + let name_number = "invalid type: integer `5`, expected a string".to_owned(); + let rows = [ + // Two empty values: the one in the lower bucket (see + // `crate::map_order`). In 4 buckets `:b` is in 0, `:c` in 1 and + // `:a` in 3. In 8, `:c` is in 1, `:f` in 4, `:p` in 6 and `:a` + // and `:q` in 7. + ("values", r#"":c":{}"#, r#"":b":{}"#, empty_value(":b")), + ("values", r#"":a":{}"#, r#"":c":{}"#, empty_value(":c")), + ( + "values", + r#"":a":{}"#, + r#"":f":{},":p":{"S":"p"},":q":{"S":"q"}"#, + empty_value(":f"), + ), + // A value of the wrong JSON type, wherever it stands. + ("values", r#"":b":{}"#, r#"":a":{"S":5}"#, s_number.clone()), + ("values", r#""b":{"S":"p"}"#, r#"":c":{"S":5}"#, s_number), + ("names", r##""#c":"""##, r##""#b":5"##, name_number.clone()), + ("names", r#""b":"x""#, r##""#c":5"##, name_number), + // A malformed key ahead of an empty value, but an empty name + // ahead of a malformed key. + ("values", r#""b":{}"#, r#"":c":{}"#, values_key.to_owned()), + ( + "values", + r#""b":{"S":"p"}"#, + r#"":c":{}"#, + values_key.to_owned(), + ), + ("names", r#""b":"x""#, r##""#c":"""##, empty_name("#c")), + // A value refused for its content is met in its bucket. + ( + "values", + r#"":b":{"NULL":false}"#, + r#"":a":{}"#, + "Null attribute value types must have the value of true".to_owned(), + ), + // A JSON null is not a value of the wrong type. + ("values", r#"":b":{}"#, r#"":a":null"#, empty_value(":b")), + ("names", r##""#c":"""##, r##""#b":null"##, empty_name("#c")), + ]; + for (map, first, second, refusal) in rows { + for members in [format!("{first},{second}"), format!("{second},{first}")] { + let json = format!("{{\"{map}\":{{{members}}}}}"); + let msg = if map == "names" { + names_err(&json) + } else { + values_err(&json) + }; + assert!(msg.contains(&refusal), "{json}: {msg}"); + } + } + } } diff --git a/crates/core/tests/data_file_nested_decode_memory.rs b/crates/core/tests/data_file_nested_decode_memory.rs index f843c908c..75e2256e3 100644 --- a/crates/core/tests/data_file_nested_decode_memory.rs +++ b/crates/core/tests/data_file_nested_decode_memory.rs @@ -67,9 +67,9 @@ const LEAVES: usize = 409_458; /// Peak heap growth allowed while decoding, per line byte. Measured at 76 /// for this item with `serde_json`'s default `BTreeMap` (`cargo test -p -/// extenddb-core`, the default binary) and 51 when `preserve_order` is on -/// (CI's `cargo test --workspace`, where the MongoDB backend's `bson` -/// enables it and `indexmap` replaces the map), and about 1,200 when either +/// extenddb-core`) and 51 when `preserve_order` is on (every build that +/// includes the server, whose crate enables it, and CI's `cargo test +/// --workspace`; `indexmap` replaces the map), and about 1,200 when either /// the `L` or the `M` arm copies its subtree again. The bound leaves about /// 1.5x headroom over the larger figure for allocator-visible changes in /// `serde_json` or in std's `BTreeMap` node layout, which is the dominant diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a27d59eb3..8b51f6a05 100755 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -50,6 +50,9 @@ tokio = { workspace = true, features = ["test-util"] } extenddb-storage-sqlite = { path = "../storage-sqlite" } # Scratch directories that are removed when a test panics. tempfile = "3" +# A parsed request keeps its members in the order the client wrote them, so +# the transaction token tests can hold members out of name order. +serde_json = { workspace = true, features = ["preserve_order"] } # `tests/private_modes.rs` sets umask 0. [target.'cfg(unix)'.dev-dependencies] diff --git a/crates/engine/src/partiql/common.rs b/crates/engine/src/partiql/common.rs index 4e73cee80..8dc0dc072 100644 --- a/crates/engine/src/partiql/common.rs +++ b/crates/engine/src/partiql/common.rs @@ -423,10 +423,10 @@ pub(super) fn condition_key_refusal( /// statements share an identity when they address the same item. pub(super) fn canonical_identity(table: &str, key: &Map) -> String { // A JSON map holds its members in the order the build gives it: the order - // they were inserted in when the build includes the MongoDB storage crate - // (any build of the whole workspace), name order otherwise. The key is - // always built pk before sk, so in either order equal (table, key) pairs - // serialise identically. + // they were inserted in when the build includes the server, whose crate + // turns on serde_json's `preserve_order` feature, name order otherwise. + // The key is always built pk before sk, so in either order equal + // (table, key) pairs serialise identically. serde_json::json!({ "t": table, "k": key }).to_string() } diff --git a/crates/engine/src/partiql/mod.rs b/crates/engine/src/partiql/mod.rs index b461f28dc..505c400ca 100644 --- a/crates/engine/src/partiql/mod.rs +++ b/crates/engine/src/partiql/mod.rs @@ -325,13 +325,11 @@ pub(crate) fn member_parameters(list: Option<&Value>) -> impl Iterator, write: impl Fn(&mut Echo, } /// A map as `{name=value, ...}`, its members in the order the service prints -/// them (see [`print_order`]). Writing stops at the first member past +/// them (see [`hash_map_order`]). Writing stops at the first member past /// [`MAX_ECHO_BYTES`]. fn write_map(echo: &mut Echo, value: Option<&Value>) { let Some(Value::Object(members)) = value else { @@ -166,7 +167,7 @@ fn write_map(echo: &mut Echo, value: Option<&Value>) { return; }; echo.push("{"); - for (index, (name, member)) in print_order(members).into_iter().enumerate() { + for (index, (name, member)) in hash_map_order(members).into_iter().enumerate() { if echo.full() { return; } @@ -180,43 +181,5 @@ fn write_map(echo: &mut Echo, value: Option<&Value>) { echo.push("}"); } -/// The members of a map in the order the service prints them (measured -/// 2026-11-02 on maps of 2, 3, 4, 6, 12, 13, 24 and 48 members): the -/// iteration order of a Java `HashMap` filled from the request's map. Its -/// table has the smallest power of two of buckets at or above `size / 0.75` -/// rounded up. A key -/// sits in the bucket its Java `String.hashCode` picks once the hash's high -/// 16 bits are folded into its low 16 by exclusive or. The buckets print in -/// ascending order, and the keys of one bucket in the order the request sends -/// them. -/// -/// Here the keys of one bucket come in the order the parsed request holds -/// them: the request's when the build includes the MongoDB storage crate, -/// whose JSON dependency makes every JSON map keep it (any build of the whole -/// workspace), and name order otherwise. In name order, two keys that share -/// a bucket print sorted by name, which differs from the service when the -/// request sends them in another order. -fn print_order(members: &Map) -> Vec<(&String, &Value)> { - // `size / 0.75` rounded up, in whole numbers. - let buckets = (members.len() * 4).div_ceil(3).next_power_of_two(); - let mut ordered: Vec<(usize, (&String, &Value))> = members - .iter() - .map(|member| (bucket(member.0, buckets), member)) - .collect(); - // The sort is stable, so the keys of one bucket keep their order. - ordered.sort_by_key(|(bucket, _)| *bucket); - ordered.into_iter().map(|(_, member)| member).collect() -} - -/// The bucket of `key` in a Java `HashMap` table of `buckets` buckets. -fn bucket(key: &str, buckets: usize) -> usize { - // Java's `String.hashCode`: 31 times the hash plus each UTF-16 unit, - // wrapping at 32 bits. - let hash = key.encode_utf16().fold(0_u32, |hash, unit| { - hash.wrapping_mul(31).wrapping_add(u32::from(unit)) - }); - (hash ^ (hash >> 16)) as usize & (buckets - 1) -} - #[cfg(test)] mod tests; diff --git a/crates/engine/src/partiql/request_checks/echo/tests.rs b/crates/engine/src/partiql/request_checks/echo/tests.rs index c05e25c45..9b1c7d07a 100644 --- a/crates/engine/src/partiql/request_checks/echo/tests.rs +++ b/crates/engine/src/partiql/request_checks/echo/tests.rs @@ -3,7 +3,7 @@ //! Unit tests for the echo of a statement list. -use serde_json::json; +use serde_json::{Map, json}; use super::*; @@ -169,64 +169,6 @@ fn an_echo_is_cut_at_a_character_boundary() { assert_eq!(echo.0.len(), MAX_ECHO_BYTES); } -fn printed(map: &Value) -> Vec<&str> { - print_order(map.as_object().unwrap()) - .into_iter() - .map(|(name, _)| name.as_str()) - .collect() -} - -#[test] -fn map_members_print_in_the_measured_order() { - let map = json!({ "c": {"S": "1"}, "a": {"S": "2"}, "p": {"S": "3"} }); - assert_eq!(printed(&map), ["p", "a", "c"]); - let map = json!({ "zeta": {}, "alpha": {}, "mid": {}, "beta": {} }); - assert_eq!(printed(&map), ["zeta", "mid", "beta", "alpha"]); - let members: Map = (0..=12) - .rev() - .map(|i| (format!("k{i}"), json!({ "N": i.to_string() }))) - .collect(); - assert_eq!( - printed(&Value::Object(members)), - [ - "k0", "k1", "k2", "k3", "k4", "k11", "k5", "k10", "k6", "k7", "k12", "k8", "k9" - ] - ); -} - -#[test] -fn the_table_holds_size_over_three_quarters_rounded_up() { - // 3 members take 4 buckets and 6 take 8, not 8 and 16. - let map = json!({ "m0": {}, "m1": {}, "m2": {} }); - assert_eq!(printed(&map), ["m1", "m2", "m0"]); - let members: Map = (0..6).map(|i| (format!("k{i}"), json!({}))).collect(); - assert_eq!( - printed(&Value::Object(members)), - ["k3", "k4", "k5", "k0", "k1", "k2"] - ); -} - -#[test] -fn keys_that_share_a_bucket_keep_the_order_the_map_holds_them_in() { - // q and a share bucket 1 of 4. - assert_eq!(bucket("q", 4), bucket("a", 4)); - let map = json!({ "q": {"S": "1"}, "a": {"S": "2"} }); - let held: Vec<&str> = map - .as_object() - .unwrap() - .keys() - .map(String::as_str) - .collect(); - assert_eq!(printed(&map), held); -} - -#[test] -fn a_key_hashes_over_its_utf16_units() { - // 0xD83D * 31 + 0xDE00 = 1772899, whose folded low five bits are 24. - assert_eq!(bucket("\u{1F600}", 32), 24); - assert_eq!(bucket("a", 1), 0); -} - #[test] fn a_nested_map_is_echoed_in_the_same_order() { let value = json!({ "L": [{ "M": { "c": {"S": "1"}, "a": {"S": "2"}, "p": {"S": "3"} } }] }); diff --git a/crates/engine/src/transact_write_helpers.rs b/crates/engine/src/transact_write_helpers.rs index 2a09d062a..065c18a3a 100755 --- a/crates/engine/src/transact_write_helpers.rs +++ b/crates/engine/src/transact_write_helpers.rs @@ -306,9 +306,20 @@ pub(crate) fn compute_fingerprint( return_item_collection_metrics: ReturnItemCollectionMetrics, ) -> String { let items = body.get("TransactItems").unwrap_or(&Value::Null); + // The service replays a retry that writes the members of an object in + // another order (measured 2026-11-10 for an item's attributes and + // 2026-11-16 for a Put's members), so the hash covers a copy with the + // members of every object sorted by name. Those are the bytes that a + // build without serde_json's `preserve_order` feature hashed before every + // build kept the client's order, so its stored tokens still match. A + // build with the feature (MongoDB, or the whole workspace) hashed the + // client's order: its token for a request whose members were not in name + // order no longer matches. + let mut sorted = items.clone(); + sorted.sort_all_objects(); // serde_json::to_string on a Value is infallible — all Value variants // are representable as JSON. Using unwrap_or_default as a defensive fallback. - let json = serde_json::to_string(items).unwrap_or_default(); + let json = serde_json::to_string(&sorted).unwrap_or_default(); // HMAC-SHA256 accepts any key length — new_from_slice cannot fail. // `InvalidLength` is impossible for HMAC per RFC 2104 (oversized keys are hashed). #[allow(clippy::expect_used)] @@ -367,6 +378,36 @@ pub(crate) fn validate_no_key_updates( mod tests { use super::*; + /// Each row's fingerprint under token "tok-1" is the one a build without + /// serde_json's `preserve_order` feature stored before every build kept + /// the client's member order: it hashed the items with the members of + /// every object sorted by name. A retry that writes the members in another + /// order, at either level, gets the same fingerprint. + #[test] + fn fingerprint_hashes_the_members_sorted_by_name() { + for (body, stored) in [ + ( + r#"{"TransactItems":[{"Put":{"Item":{"pk":{"S":"a"}},"TableName":"t"}}]}"#, + "ef18f4e7c37d6b12", + ), + ( + r#"{"TransactItems":[{"Put":{"TableName":"t","Item":{"pk":{"S":"a"}}}}]}"#, + "ef18f4e7c37d6b12", + ), + ( + r#"{"TransactItems":[{"Put":{"Item":{"a":{"N":"1"},"pk":{"S":"k"}},"TableName":"t"}}]}"#, + "89c79e090f17b7af", + ), + ( + r#"{"TransactItems":[{"Put":{"TableName":"t","Item":{"pk":{"S":"k"},"a":{"N":"1"}}}}]}"#, + "89c79e090f17b7af", + ), + ] { + let body: Value = serde_json::from_str(body).unwrap(); + assert_eq!(fp(&body, "tok-1"), stored, "{body}"); + } + } + #[test] fn validate_token_valid() { assert!(validate_client_request_token("abc-123").is_ok()); diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index d0d7a7410..184374115 100755 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -39,7 +39,13 @@ hyper = { workspace = true } hyper-util = { workspace = true } tokio = { workspace = true } serde = { workspace = true } -serde_json = { workspace = true } +# A parsed request keeps its members in the order the client wrote them, in +# every build that includes the server. The typed input deserializers stop at +# the first member that fails, and the service answers a body with two type +# faults with the fault of the member written first. Without this feature a +# parsed object is sorted by name, except in a build that also compiles +# `bson`, which turns the feature on. +serde_json = { workspace = true, features = ["preserve_order"] } tracing = { workspace = true } crc32fast = { workspace = true } uuid = { workspace = true } diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 6033494d6..dbeb01c80 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -431,3 +431,7 @@ pub(crate) async fn handle_request( response } + +#[cfg(test)] +#[path = "handler_member_order_tests.rs"] +mod member_order_tests; diff --git a/crates/server/src/handler_member_order_tests.rs b/crates/server/src/handler_member_order_tests.rs new file mode 100644 index 000000000..80248d038 --- /dev/null +++ b/crates/server/src/handler_member_order_tests.rs @@ -0,0 +1,79 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The member order a parsed request keeps in this crate's build. + +use std::sync::Arc; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::limits::LimitsConfig; +use extenddb_engine::{AuthorizedKeyInfo, BackupRuntime, OperationContext}; +use extenddb_storage_sqlite::SqliteEngine; +use serde_json::Value; + +/// This crate turns on serde_json's `preserve_order` feature, so a body parsed +/// in its build keeps the members in the order the client wrote them, and the +/// typed input of `dispatch` stops at the first member that fails. So a body +/// with two type faults answers the fault of the member written first, as the +/// service does (measured 2026-11-12). The texts are serde_json's. The test +/// parses the body itself and so checks the feature and `dispatch`, not +/// `handle_request`: `tests/test_request_member_order.py` sends the bodies +/// through the handler. In a build of the whole workspace `bson` and the +/// engine's dev-dependency on serde_json turn the feature on too, so there the +/// test checks `dispatch` alone. A build of this crate alone, `cargo test -p +/// extenddb-server`, checks the feature too. The Python file checks it on a +/// server built without them, such as `-p extenddb --no-default-features +/// --features sqlite`. +#[tokio::test] +async fn two_type_faults_answer_the_member_written_first() { + let storage = SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) + .await + .expect("an in-memory database opens"); + let ctx = OperationContext { + storage: Arc::new(storage), + backup: Arc::new(BackupRuntime::new(1)), + limits: Arc::new(LimitsConfig::default()), + region: Arc::from("us-east-1"), + account_id: Arc::from("000000000000"), + import_paths: Arc::from(Vec::new()), + export_paths: Arc::from(Vec::new()), + authorized_key_info: AuthorizedKeyInfo::new(), + auth_cache: extenddb_auth::AuthCacheRegistry::default(), + table_key_info_lookup: None, + item_authorizer: None, + }; + let query = r#""TableName":"t","KeyConditionExpression":"pk = :p""#; + for (operation, body, fault) in [ + ( + "Query", + format!(r#"{{{query},"Limit":"0","ConsistentRead":"x"}}"#), + r#"string "0", expected i64"#, + ), + ( + "Query", + format!(r#"{{{query},"ConsistentRead":"x","Limit":"0"}}"#), + r#"string "x", expected a boolean"#, + ), + ( + "TransactWriteItems", + r#"{"TransactItems":[{"Put":{"TableName":5,"Item":"x"}}]}"#.to_owned(), + "integer `5`, expected a string", + ), + ( + "TransactWriteItems", + r#"{"TransactItems":[{"Put":{"Item":"x","TableName":5}}]}"#.to_owned(), + r#"string "x", expected a map"#, + ), + ] { + let input: Value = serde_json::from_slice(body.as_bytes()).expect("the body is JSON"); + let want = + format!("Start of structure or map found where not expected: invalid type: {fault}"); + match extenddb_engine::dispatch(operation, input, &ctx, "").await { + Err(DynamoDbError::SerializationException(message)) => { + assert_eq!(message, want, "{body}"); + } + Err(other) => panic!("{body}: {other:?}"), + Ok(_) => panic!("{body}: accepted"), + } + } +} diff --git a/crates/server/src/table_name_gate.rs b/crates/server/src/table_name_gate.rs index 1268878ed..87bb944fa 100644 --- a/crates/server/src/table_name_gate.rs +++ b/crates/server/src/table_name_gate.rs @@ -44,10 +44,9 @@ //! - A `RequestItems` key outside the pattern: `at 'requestItems'` with the //! map-key constraint list. The service renders its own dump of the whole //! map inside `Value '...'`; the first offending key the parsed map yields -//! is rendered alone here. That is request order only when `serde_json`'s -//! `preserve_order` feature is in the build (the MongoDB driver turns it -//! on), and key order otherwise. A key that is an ARN takes the ARN -//! constraint list (`arn_gate::MAP_KEYS_ARN`). +//! is rendered alone here, which is the first in request order: this crate +//! turns on `serde_json`'s `preserve_order` feature. A key that is an ARN +//! takes the ARN constraint list (`arn_gate::MAP_KEYS_ARN`). //! - ARN-shaped values: see `arn_gate`. //! //! The service reads `SourceTableName`, `TargetTableName` (both restores), diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index 267e1e9e2..c6652090f 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -53,15 +53,13 @@ SIGTERM directly. Alternatively start it with ```bash curl --cacert ~/.extenddb/tls/cert.pem https://127.0.0.1:18443/health -# {"components":{},"status":"healthy"} -# (the order of the keys depends on the build: the default PostgreSQL build -# writes "status" first, the SQLite build "components" first; read the keys) +# {"status":"healthy","components":{}} # with a backup store configured: -# {"components":{"backup_store":{"kind":"filesystem","status":"healthy"}},"status":"healthy"} +# {"status":"healthy","components":{"backup_store":{"status":"healthy","kind":"filesystem"}}} # while it cannot be reached: -# {"components":{"backup_store":{"kind":"s3","reason":"unreachable","status":"unhealthy"}},"status":"degraded"} +# {"status":"degraded","components":{"backup_store":{"status":"unhealthy","kind":"s3","reason":"unreachable"}}} # right after startup, before an S3 store's first check has returned: -# {"components":{"backup_store":{"kind":"s3","status":"checking"}},"status":"healthy"} +# {"status":"healthy","components":{"backup_store":{"status":"checking","kind":"s3"}}} ``` `status` is `healthy`, or `degraded` when a component is unhealthy; the HTTP @@ -1191,8 +1189,7 @@ JSON metrics endpoint with DynamoDB CloudWatch-style metric names and dimensions ```bash curl --cacert ~/.extenddb/tls/cert.pem https://127.0.0.1:18443/health # {"status":"healthy","components":{}} -# (the key order depends on the build; the earlier Health Check section -# shows the components a backup store adds) +# (the earlier Health Check section shows the components a backup store adds) ``` The `components` object carries the `backup_store` component when a backup diff --git a/docs/manuals/14-backup-and-restore.md b/docs/manuals/14-backup-and-restore.md index 4dc36cd8b..9c235492e 100644 --- a/docs/manuals/14-backup-and-restore.md +++ b/docs/manuals/14-backup-and-restore.md @@ -292,8 +292,8 @@ copied under the new root and `extenddb backup sync --move-store ` re- store to a new root](#moving-a-store-to-a-new-root)). `/health` reports the store as the `backup_store` component, for example -`{"components":{"backup_store":{"kind":"filesystem","status":"healthy"}},"status":"healthy"}` (on MongoDB -`status` comes first). An unhealthy store (unreachable, or failing its identity check) is `status` `degraded` +`{"status":"healthy","components":{"backup_store":{"status":"healthy","kind":"filesystem"}}}`. +An unhealthy store (unreachable, or failing its identity check) is `status` `degraded` with HTTP 200 kept, so a store outage never takes the data plane out of rotation; `CreateBackup`, and the restore and delete of a backup in that store, are refused with a `ValidationException` until the next check passes. @@ -635,13 +635,13 @@ With the sections back, the store's `extenddb-store.json` still names the old ca starts with the store unhealthy: ``` -{"components":{"backup_store":{"kind":"filesystem","reason":"owned by another catalog","status":"unhealthy"}},"status":"degraded"} +{"status":"degraded","components":{"backup_store":{"status":"unhealthy","kind":"filesystem","reason":"owned by another catalog"}}} ``` On file-backed SQLite with the default root (no `[backup.store]` section) the server instead logs a warning, "the default root ... failed its check (extenddb-store.json names catalog ; this catalog is ); the catalog has no backup rows for it, so the store is unconfigured and CreateBackup writes in-catalog -backups", and `/health` shows no `backup_store` component (`{"components":{},"status":"healthy"}`). Until +backups", and `/health` shows no `backup_store` component (`{"status":"healthy","components":{}}`). Until the adoption below, `CreateBackup` answers `AVAILABLE` at once and writes an in-catalog backup into the database file, the failure domain this manual's first paragraph warns about; such a backup stays in-catalog after the adoption until `extenddb backup migrate-legacy` copies it into the store ([Legacy diff --git a/tests/raw_signed_request.py b/tests/raw_signed_request.py index 2fe02dfc5..a82fb087f 100644 --- a/tests/raw_signed_request.py +++ b/tests/raw_signed_request.py @@ -6,7 +6,8 @@ boto3 validates and reshapes the parameters before it signs, so it cannot send a tag written as ``["k", "v"]``. ``signed_post`` signs the bytes it is given with botocore's signer and posts them unchanged, with the credentials of the caller -rather than the ones in the environment. +rather than the ones in the environment. ``answer`` reads the status, the error +type and the message of the response. """ from __future__ import annotations @@ -46,3 +47,18 @@ def signed_post( verify=not endpoint.startswith("https://"), timeout=30, ) + + +def answer(resp: requests.Response) -> tuple[int, str, str]: + """The HTTP status, the error type after the ``#`` and the message of a + JSON answer, or the status, an empty type and the text of an answer that + is not JSON.""" + try: + doc = resp.json() + except ValueError: + return resp.status_code, "", resp.text + return ( + resp.status_code, + doc.get("__type", "").rsplit("#", 1)[-1], + doc.get("message", doc.get("Message", "")), + ) diff --git a/tests/test_partiql_numbers.py b/tests/test_partiql_numbers.py index 0ab6e7035..5c343b87e 100644 --- a/tests/test_partiql_numbers.py +++ b/tests/test_partiql_numbers.py @@ -18,7 +18,6 @@ from __future__ import annotations -import os import uuid import pytest @@ -26,21 +25,6 @@ from conftest import wait_for_active -# ExtendDB walks the members of a parameter map in the order the parsed request -# holds them. That is the order the request sent, as the service walks them -# (measured 2026-11-02), when the server is built together with the MongoDB -# backend crate, whose JSON dependency keeps map order: any build of the whole -# workspace, as CI's are. A build of the server package alone with another -# backend sorts map members by name, and answers differently when a map's first -# member in request order is not its first by name. Not strict, because which -# order a server has depends on how it was built. -MAP_MEMBERS_IN_NAME_ORDER = pytest.mark.xfail( - bool(os.environ.get("EXTENDDB_TEST_ENDPOINT", "").strip()), - reason="a server built without the MongoDB crate checks parameter map members in name order", - raises=AssertionError, - strict=False, -) - NOT_WELL_FORMED = "Statement wasn't well formed, can't be processed: " UNCONVERTIBLE = "The parameter cannot be converted to a numeric value" OVERFLOW = ( @@ -367,7 +351,6 @@ def test_the_first_problem_in_parameter_order_is_reported(self, dynamodb_client, == f"{UNCONVERTIBLE}: abc" ) - @MAP_MEMBERS_IN_NAME_ORDER def test_the_first_problem_in_map_member_order_is_reported(self, dynamodb_client, tables): deep_first = {"M": {"d": deep(40), "bad": {"N": "abc"}}} assert message(dynamodb_client, self.single(tables), [deep_first]) == NESTED diff --git a/tests/test_request_member_order.py b/tests/test_request_member_order.py new file mode 100644 index 000000000..701bb8a0f --- /dev/null +++ b/tests/test_request_member_order.py @@ -0,0 +1,445 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""The answer to a request body with two faults, in both member orders. + +Amazon DynamoDB answers a body with two type faults (members it cannot +convert to their type) with the fault of the member written first, and a +type fault beside a validation fault with the type fault in either order. +For a Limit of 0.0 beside an empty value it gives the Limit fault in both +orders. Inside one map the other checks visit the members in the order a +Java HashMap of the map yields them. There the order written decides only +between two members that share a bucket, such as `:a` and `:e`. For two +malformed keys in ExpressionAttributeValues and for two empty names, the +service named either member from one send to the next, so no row pins them. +Measured in us-east-1 on 2026-11-12 (Query, Scan, TransactWriteItems, +ExecuteStatement), 2026-11-16 (GetItem, PutItem, UpdateItem) and 2026-11-19 +(UpdateItem and ExecuteStatement). Each row pins the service's status, error +type and message for one body in one member order. + +ExtendDB words a type fault with serde_json's text or with its own (#1012), +so on ExtendDB a type-fault row checks that text instead. For two type faults +the text names the member written first, so a server that reads the members +in another order fails the row. + +The bodies are posted with their members in the order written, signed as the +client's caller, because botocore refuses these values before it sends them. + +Dual-target against Amazon DynamoDB and ExtendDB. +""" + +from __future__ import annotations + +from typing import Any + +import boto3 +import pytest + +from conftest import _is_real_dynamodb, scoped_table +from raw_signed_request import answer, signed_post +from test_partiql_numbers import NESTED, UNCONVERTIBLE, deep + +ON_EXTENDDB = not _is_real_dynamodb() + + +def _differs(reason: str): + """ExtendDB answers the row otherwise, in every build.""" + return pytest.mark.xfail(ON_EXTENDDB, reason=reason, raises=AssertionError, strict=True) + + +# 720: a fractional Limit is a SerializationException on ExtendDB. +FRACTIONAL_LIMIT = _differs("#720: a fractional Limit answers SerializationException") +# 778: a Limit fault after an ExpressionAttributeValues fault answers the value fault. +LIMIT_AFTER_VALUE = _differs("#778: the value fault written first is answered") + +SERDE = "Start of structure or map found where not expected: " + +P = {"S": "p0"} +KEY = {"pk": {"S": "k0"}} +EAV_P = {"ExpressionAttributeValues": {":p": P}} +EAV_EMPTY = {"ExpressionAttributeValues": {":p": P, ":a": {}}} + +STRING_TO_INTEGER = (400, "SerializationException", "STRING_VALUE cannot be converted to Integer") +NUMBER_TO_STRING = (400, "SerializationException", "NUMBER_VALUE cannot be converted to String") +UNEXPECTED_TOKEN = (400, "SerializationException", "Unexpected token received from parser") +UNEXPECTED_FIELD_TYPE = (400, "SerializationException", "Unexpected field type") +LIMIT_BELOW_ONE = ( + 400, + "ValidationException", + "1 validation error detected: Value '0' at 'limit' failed to satisfy constraint: " + "Member must have value greater than or equal to 1", +) + + +def _empty(key: str) -> tuple[int, str, str]: + return ( + 400, + "ValidationException", + "ExpressionAttributeValues contains invalid value: Supplied AttributeValue is empty, " + f"must contain exactly one of the supported datatypes for key {key}", + ) + + +EMPTY_B = _empty(":b") +EMPTY_NAME_C = ( + 400, + "ValidationException", + "ExpressionAttributeNames contains invalid value: Empty attribute name for key #c", +) +BAD_VALUES_KEY_B = ( + 400, + "ValidationException", + 'ExpressionAttributeValues contains invalid key: Syntax error; key: "b"', +) +NOT_A_NUMBER = (400, "ValidationException", f"{UNCONVERTIBLE}: abc") +NESTING = (400, "ValidationException", NESTED) + +# serde_json's description of each faulty member, or ExtendDB's own, as +# ExtendDB reports it. +LIMIT = 'invalid type: string "0", expected i64' +CONSISTENT_READ = 'invalid type: string "x", expected a boolean' +NUMBER_FOR_STRING = "invalid type: integer `{}`, expected a string" +STRING_FOR_MAP = 'invalid type: string "x", expected a map' +NUMBER_IN_S = "S value must be a string" +STRING_IN_BOOL = "BOOL value must be a boolean" + + +def _query(table: str, *members: dict[str, Any]) -> dict[str, Any]: + body: dict[str, Any] = {"TableName": table, "KeyConditionExpression": "pk = :p"} + for member in members: + body.update(member) + return body + + +def _scan(table: str, values: dict[str, Any]) -> dict[str, Any]: + return { + "TableName": table, + "FilterExpression": "pk IN (:p, :a, :b)", + "ExpressionAttributeValues": {":p": P, **values}, + } + + +def _put(put: dict[str, Any]) -> dict[str, Any]: + return {"TransactItems": [{"Put": put}]} + + +def _update(table: str, expression: str, values: dict[str, Any], names=None) -> dict[str, Any]: + body: dict[str, Any] = {"TableName": table, "Key": KEY, "UpdateExpression": expression} + if names is not None: + body["ExpressionAttributeNames"] = names + body["ExpressionAttributeValues"] = values + return body + + +def _select(table: str, members: dict[str, Any]) -> dict[str, Any]: + return { + "Statement": f"SELECT * FROM \"{table}\" WHERE pk = 'p' AND x = ?", + "Parameters": [{"M": members}], + } + + +def _one_map(name, operation, build, first, second, answers, extenddb_texts=None): + """The rows of one map with two faults: the members of ``first`` written + ahead of those of ``second``, then after them. ``build`` takes the table + and the map. ``answers`` is the service's answer to both orders, or a list + of its answer to each, and ``extenddb_texts`` the same for ExtendDB's + text.""" + if not isinstance(answers, list): + answers = [answers, answers] + if not isinstance(extenddb_texts, list): + extenddb_texts = [extenddb_texts, extenddb_texts] + orders = [(first, second, "then"), (second, first, "after")] + return [ + pytest.param( + operation, + lambda t, a=a, b=b: build(t, {**dict(a), **dict(b)}), + answer, + extenddb_text, + id=f"{name}_{word}", + ) + for (a, b, word), answer, extenddb_text in zip(orders, answers, extenddb_texts) + ] + + +# (operation, body, service answer, ExtendDB's serde_json text or None) +ROWS = [ + # Two type faults: the member written first. + pytest.param( + "Query", + lambda t: _query(t, EAV_P, {"Limit": "0"}, {"ConsistentRead": "x"}), + STRING_TO_INTEGER, + LIMIT, + id="query_limit_then_consistent_read", + ), + pytest.param( + "Query", + lambda t: _query(t, EAV_P, {"ConsistentRead": "x"}, {"Limit": "0"}), + UNEXPECTED_TOKEN, + CONSISTENT_READ, + id="query_consistent_read_then_limit", + ), + pytest.param( + "Query", + lambda t: _query(t, EAV_P, {"Select": 7}, {"Limit": "0"}), + NUMBER_TO_STRING, + NUMBER_FOR_STRING.format(7), + id="query_select_then_limit", + ), + pytest.param( + "Query", + lambda t: _query(t, EAV_P, {"Limit": "0"}, {"Select": 7}), + STRING_TO_INTEGER, + LIMIT, + id="query_limit_then_select", + ), + pytest.param( + "TransactWriteItems", + lambda t: _put({"TableName": 5, "Item": "x"}), + NUMBER_TO_STRING, + NUMBER_FOR_STRING.format(5), + id="transact_put_table_name_then_item", + ), + pytest.param( + "TransactWriteItems", + lambda t: _put({"Item": "x", "TableName": 5}), + UNEXPECTED_FIELD_TYPE, + STRING_FOR_MAP, + id="transact_put_item_then_table_name", + ), + pytest.param( + "GetItem", + lambda t: {"TableName": t, "Key": KEY, "ConsistentRead": "x", "ProjectionExpression": 5}, + UNEXPECTED_TOKEN, + CONSISTENT_READ, + id="get_consistent_read_then_projection", + ), + pytest.param( + "GetItem", + lambda t: {"TableName": t, "Key": KEY, "ProjectionExpression": 5, "ConsistentRead": "x"}, + NUMBER_TO_STRING, + NUMBER_FOR_STRING.format(5), + id="get_projection_then_consistent_read", + ), + pytest.param( + "PutItem", + lambda t: {"TableName": t, "Item": KEY, "ReturnValues": 5, "Expected": "x"}, + NUMBER_TO_STRING, + NUMBER_FOR_STRING.format(5), + id="put_return_values_then_expected", + ), + pytest.param( + "PutItem", + lambda t: {"TableName": t, "Item": KEY, "Expected": "x", "ReturnValues": 5}, + UNEXPECTED_FIELD_TYPE, + STRING_FOR_MAP, + id="put_expected_then_return_values", + ), + pytest.param( + "UpdateItem", + lambda t: {"TableName": t, "Key": KEY, "ReturnValues": 5, "ExpressionAttributeNames": "x"}, + NUMBER_TO_STRING, + NUMBER_FOR_STRING.format(5), + id="update_return_values_then_names", + ), + pytest.param( + "UpdateItem", + lambda t: {"TableName": t, "Key": KEY, "ExpressionAttributeNames": "x", "ReturnValues": 5}, + UNEXPECTED_FIELD_TYPE, + STRING_FOR_MAP, + id="update_names_then_return_values", + ), + # A type fault beside a validation fault: the type fault in both orders. + pytest.param( + "Query", + lambda t: _query(t, {"Limit": "0"}, EAV_EMPTY), + STRING_TO_INTEGER, + LIMIT, + id="query_string_limit_then_empty_value", + ), + pytest.param( + "Query", + lambda t: _query(t, EAV_EMPTY, {"Limit": "0"}), + STRING_TO_INTEGER, + None, + id="query_empty_value_then_string_limit", + marks=LIMIT_AFTER_VALUE, + ), + # Two validation faults in two members: one answer in both orders. The + # service reads a Limit of 0.0 as 0. ExtendDB answers it as a type fault + # (#720). + pytest.param( + "Query", + lambda t: _query(t, {"Limit": 0.0}, EAV_EMPTY), + LIMIT_BELOW_ONE, + None, + id="query_float_limit_then_empty_value", + marks=FRACTIONAL_LIMIT, + ), + pytest.param( + "Query", + lambda t: _query(t, EAV_EMPTY, {"Limit": 0.0}), + LIMIT_BELOW_ONE, + None, + id="query_empty_value_then_float_limit", + marks=LIMIT_AFTER_VALUE, + ), + # Two faults in one map. A value of the wrong JSON type is answered + # first. Then come the keys in ExpressionAttributeValues, and the empty + # names ahead of the keys in ExpressionAttributeNames. The other checks + # visit the members in the order a Java HashMap of the map yields them. + # In 4 buckets :b is in bucket 0, :c in 1, and :a and :e in 3. Also in + # 4, bad and x are in 0, and a and e in 1. In the 8 buckets of a map of + # four members, a is in 1 and bad in 4. + *_one_map( + "update_empty_c_b", + "UpdateItem", + lambda t, v: _update(t, "SET x = :b, y = :c", v), + [(":c", {})], + [(":b", {})], + EMPTY_B, + ), + *_one_map( + "update_empty_a_c", + "UpdateItem", + lambda t, v: _update(t, "SET x = :a, y = :c", v), + [(":a", {})], + [(":c", {})], + _empty(":c"), + ), + *_one_map( + "update_empty_a_e", + "UpdateItem", + lambda t, v: _update(t, "SET x = :a, y = :e", v), + [(":a", {})], + [(":e", {})], + [_empty(":a"), _empty(":e")], + ), + # Three members take 4 buckets. In 8, :e would come ahead of :a. + *_one_map( + "update_empty_a_e_p", + "UpdateItem", + lambda t, v: _update(t, "SET x = :a, y = :e, z = :p", v), + [(":a", {})], + [(":e", {}), (":p", P)], + [_empty(":a"), _empty(":e")], + ), + # The service answers {"X": "1"} with the text for an empty value. + # ExtendDB answers it as a type fault (#629), but it checks :b first. + *_one_map( + "scan_empty_b_unknown_a", + "Scan", + _scan, + [(":b", {})], + [(":a", {"X": "1"})], + EMPTY_B, + ), + *_one_map( + "update_empty_b_number_in_a", + "UpdateItem", + lambda t, v: _update(t, "SET x = :a, y = :b", v), + [(":b", {})], + [(":a", {"S": 5})], + NUMBER_TO_STRING, + NUMBER_IN_S, + ), + # Two type faults in one map: the member written first, though :b is in + # a lower bucket than :c. + *_one_map( + "update_number_in_c_string_in_b", + "UpdateItem", + lambda t, v: _update(t, "SET x = :b, y = :c", v), + [(":c", {"S": 5})], + [(":b", {"BOOL": "x"})], + [NUMBER_TO_STRING, UNEXPECTED_TOKEN], + [NUMBER_IN_S, STRING_IN_BOOL], + ), + *_one_map( + "update_key_b_empty_c", + "UpdateItem", + lambda t, v: _update(t, "SET x = :c", v), + [("b", P)], + [(":c", {})], + BAD_VALUES_KEY_B, + ), + *_one_map( + "update_empty_name_c_number_name_b", + "UpdateItem", + lambda t, n: _update(t, "SET #b = :p, #c = :p", {":p": P}, n), + [("#c", "")], + [("#b", 5)], + NUMBER_TO_STRING, + NUMBER_FOR_STRING.format(5), + ), + *_one_map( + "update_empty_name_c_null_name_b", + "UpdateItem", + lambda t, n: _update(t, "SET #b = :p, #c = :p", {":p": P}, n), + [("#c", "")], + [("#b", None)], + EMPTY_NAME_C, + ), + *_one_map( + "select_deep_e_bad", + "ExecuteStatement", + _select, + [("e", deep(40))], + [("bad", {"N": "abc"})], + NOT_A_NUMBER, + ), + *_one_map( + "select_bad_deep_a", + "ExecuteStatement", + _select, + [("bad", {"N": "abc"})], + [("a", deep(40))], + NOT_A_NUMBER, + ), + *_one_map( + "select_bad_deep_a_x", + "ExecuteStatement", + _select, + [("bad", {"N": "abc"})], + [("a", deep(40)), ("x", {"S": "1"})], + NOT_A_NUMBER, + ), + *_one_map( + "select_bad_deep_a_x_y", + "ExecuteStatement", + _select, + [("bad", {"N": "abc"})], + [("a", deep(40)), ("x", {"S": "1"}), ("y", {"S": "1"})], + NESTING, + ), +] + + +@pytest.fixture(scope="module") +def hash_table(dynamodb_client): + """Hash-only table for the module, deleted on teardown.""" + with scoped_table(dynamodb_client) as name: + yield name + + +def _answer(client, endpoint_url: str | None, operation: str, body: dict[str, Any]): + """The status, the error type and the message of ``body``'s answer.""" + creds = boto3.Session().get_credentials().get_frozen_credentials() + return answer( + signed_post( + endpoint_url or client.meta.endpoint_url, + creds.access_key, + creds.secret_key, + client.meta.region_name, + operation, + body, + session_token=creds.token, + ) + ) + + +@pytest.mark.parametrize("operation, body, expected, extenddb_text", ROWS) +def test_two_fault_body_gets_the_service_answer( + dynamodb_client, endpoint_url, hash_table, operation, body, expected, extenddb_text +): + if endpoint_url and extenddb_text: + expected = (400, "SerializationException", SERDE + extenddb_text) + assert _answer(dynamodb_client, endpoint_url, operation, body(hash_table)) == expected