Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions crates/core/src/backup_format/data_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
1 change: 1 addition & 0 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
96 changes: 96 additions & 0 deletions crates/core/src/map_order.rs
Original file line number Diff line number Diff line change
@@ -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<K: AsRef<str>, V>(members: impl IntoIterator<Item = (K, V)>) -> 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<Item = &'a str>) -> 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<String> = (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);
}
}
164 changes: 52 additions & 112 deletions crates/core/src/partiql/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand Down Expand Up @@ -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<String, Value>) -> impl Iterator<Item = (&str, &Value)> {
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.
Expand Down Expand Up @@ -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"));
}
Expand Down Expand Up @@ -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!(
Expand All @@ -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<String> = 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(&params),
Err(want.to_owned()),
Expand Down
Loading
Loading