From 260bd5bda6b2dee66efdcd98cc55430df42b5bb4 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 16 Nov 2026 22:05:45 -0800 Subject: [PATCH 001/101] feat(storage): let a vector search carry an item filter A SearchVectors condition beyond equality (a range, OR, NOT, IN, an existence function) cannot be lowered to the equality pairs a vector search takes today, and the service applies the condition before the TopK cut, so the backend has to evaluate it. VectorSearch gains item_filter, an optional VectorItemFilter that a backend calls on each candidate before ranking it. SQLite calls it in its candidate loop. PostgreSQL runs its statement with LIMIT NULL when a filter is present, reads the rows in score order with the same tie break, and keeps the first top_k that match. Every existing caller passes None, and with None both backends run the statement and the loop they ran before. The trait lives in the storage crate so a backend evaluates a condition without depending on the grammar that produced it. --- crates/engine/src/search_vectors.rs | 1 + crates/storage-postgres/src/lib.rs | 1 + crates/storage-postgres/src/vector_search.rs | 22 ++++++- .../src/vector_search_filtered.rs | 64 +++++++++++++++++++ .../tests/catalog_nul_index_writes.rs | 1 + crates/storage-sqlite/src/vector_bench.rs | 1 + crates/storage-sqlite/src/vector_search.rs | 6 ++ crates/storage/src/lib.rs | 7 ++ crates/storage/src/vector_filter.rs | 30 +++++++++ 9 files changed, 130 insertions(+), 3 deletions(-) create mode 100644 crates/storage-postgres/src/vector_search_filtered.rs create mode 100644 crates/storage/src/vector_filter.rs diff --git a/crates/engine/src/search_vectors.rs b/crates/engine/src/search_vectors.rs index 731c011ce..bbde25a08 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -199,6 +199,7 @@ pub async fn handle_search_vectors( top_k: input.top_k, hash_key, filters: &filters, + item_filter: None, }) .await .map_err(storage_err_to_dynamo)?; diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index 885a8f925..735c7f90e 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -44,6 +44,7 @@ mod ttl_worker; mod update_table; mod vector; mod vector_search; +mod vector_search_filtered; mod warm_throughput; mod worker_store; mod workers; diff --git a/crates/storage-postgres/src/vector_search.rs b/crates/storage-postgres/src/vector_search.rs index 7f846f947..9925a4f81 100644 --- a/crates/storage-postgres/src/vector_search.rs +++ b/crates/storage-postgres/src/vector_search.rs @@ -177,6 +177,7 @@ impl VectorSearchEngine for PostgresEngine { .iter() .map(|(name, value)| ((*name).to_owned(), (*value).clone())) .collect(); + let item_filter = req.item_filter.clone(); Box::pin(async move { let partition = partition?; @@ -275,7 +276,9 @@ impl VectorSearchEngine for PostgresEngine { // Bytes, matching the BYTEA column: the unscoped sentinel contains // a NUL, so a text comparison would not even be storable. .bind(partition.into_bytes()) - .bind(top_k) + // NULL is no limit: with a condition the stream below stops at + // the top_k-th matching row instead. + .bind(item_filter.is_none().then_some(top_k)) .bind(query_norm); for (name, value) in &filters { let value_json = serde_json::to_string(value) @@ -283,7 +286,7 @@ impl VectorSearchEngine for PostgresEngine { query = query.bind(name).bind(value_json); } - let rows = query.fetch_all(&self.data_pool).await.map_err(|e| { + let map_sql = |e: sqlx::Error| { let mapped = crate::vector::map_vector_sql_error(e); // The data table is gone, which happens when the index is deleted // between the catalog read above and this statement. That is a @@ -294,7 +297,20 @@ impl VectorSearchEngine for PostgresEngine { } else { mapped } - })?; + }; + let rows = match &item_filter { + None => query.fetch_all(&self.data_pool).await.map_err(map_sql)?, + Some(condition) => { + crate::vector_search_filtered::fetch_matching( + query, + &self.data_pool, + condition.as_ref(), + top_k, + map_sql, + ) + .await? + } + }; let mut hits = Vec::with_capacity(rows.len()); for (ordered, embedding, item_json) in rows { diff --git a/crates/storage-postgres/src/vector_search_filtered.rs b/crates/storage-postgres/src/vector_search_filtered.rs new file mode 100644 index 000000000..fcbce4ccd --- /dev/null +++ b/crates/storage-postgres/src/vector_search_filtered.rs @@ -0,0 +1,64 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Vector search with a [`VectorItemFilter`]. +//! +//! The filter is evaluated in this process, on the decoded item, with the +//! condition semantics that FilterExpression uses. Translating it to SQL would +//! give a second implementation of those semantics, and the two would drift +//! on a missing attribute, a number comparison or a type mismatch. +//! +//! The statement is the unfiltered one with `LIMIT NULL`, which PostgreSQL +//! reads as no limit. Rows arrive in score order with the same tie break, and +//! the stream stops at the `top_k`-th matching row. So the cut applies to +//! matching rows only, as it does for the equality filters in SQL. + +use futures::TryStreamExt; +use pgvector::Vector; +use sqlx::PgPool; +use sqlx::postgres::{PgArguments, Postgres}; +use sqlx::query::QueryAs; + +use extenddb_core::types::Item; +use extenddb_storage::VectorItemFilter; +use extenddb_storage::error::StorageError; + +/// One row of the search statement: the ordered score, the stored vector and +/// the stored item. +pub(crate) type SearchRow = (f64, Vector, serde_json::Value); + +/// Run `query` and return the first `top_k` rows whose item satisfies +/// `filter`, in the order the statement returns them. +/// +/// `map_sql` turns a statement failure into the error the unfiltered path +/// reports for it. +/// +/// # Errors +/// +/// Returns the mapped statement error, [`StorageError::Internal`] for a stored +/// item that does not decode, or the error of [`VectorItemFilter::matches`]. +pub(crate) async fn fetch_matching<'q>( + query: QueryAs<'q, Postgres, SearchRow, PgArguments>, + pool: &PgPool, + filter: &dyn VectorItemFilter, + top_k: i64, + map_sql: impl Fn(sqlx::Error) -> StorageError, +) -> Result, StorageError> { + let wanted = usize::try_from(top_k.max(0)).unwrap_or(0); + let mut kept = Vec::with_capacity(wanted.min(128)); + if wanted == 0 { + return Ok(kept); + } + let mut rows = query.fetch(pool); + while let Some(row) = rows.try_next().await.map_err(&map_sql)? { + let item: Item = serde_json::from_value(row.2.clone()) + .map_err(|e| StorageError::Internal(format!("stored item: {e}")))?; + if filter.matches(&item)? { + kept.push(row); + if kept.len() == wanted { + break; + } + } + } + Ok(kept) +} diff --git a/crates/storage-postgres/tests/catalog_nul_index_writes.rs b/crates/storage-postgres/tests/catalog_nul_index_writes.rs index beafcd2e8..f704605d3 100644 --- a/crates/storage-postgres/tests/catalog_nul_index_writes.rs +++ b/crates/storage-postgres/tests/catalog_nul_index_writes.rs @@ -365,6 +365,7 @@ async fn a_vector_index_keeps_its_attribute_names() { top_k: 5, hash_key: Some((hash, &tenant)), filters: &[], + item_filter: None, }) .await .expect("SearchVectors"); diff --git a/crates/storage-sqlite/src/vector_bench.rs b/crates/storage-sqlite/src/vector_bench.rs index f6f80dadc..6b2c4ae45 100644 --- a/crates/storage-sqlite/src/vector_bench.rs +++ b/crates/storage-sqlite/src/vector_bench.rs @@ -169,6 +169,7 @@ mod tests { top_k: i64::try_from(top_k).expect("top_k fits"), hash_key: None, filters: &[], + item_filter: None, }; let vector_engine = engine.as_vector_search().expect("vector capable"); diff --git a/crates/storage-sqlite/src/vector_search.rs b/crates/storage-sqlite/src/vector_search.rs index ee98c7a4c..b2f69b213 100644 --- a/crates/storage-sqlite/src/vector_search.rs +++ b/crates/storage-sqlite/src/vector_search.rs @@ -198,6 +198,7 @@ impl VectorSearchEngine for SqliteEngine { .iter() .map(|(name, value)| ((*name).to_owned(), (*value).clone())) .collect(); + let item_filter = req.item_filter.clone(); Box::pin(async move { let partition = partition?; @@ -282,6 +283,11 @@ impl VectorSearchEngine for SqliteEngine { { continue; } + if let Some(condition) = &item_filter + && !condition.matches(&item)? + { + continue; + } let candidate_score = score(function, &query_vector, &candidate); top.offer(candidate_score, item, candidate); diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 7580c0bc1..c3a18bdef 100755 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -52,6 +52,7 @@ pub mod stream_lineage; pub mod test_pause; pub mod transact; pub mod vector_catalog; +pub mod vector_filter; pub mod vector_lifecycle; pub use backend::{Backend, BackendAlreadySet, backend_name, set_backend, try_backend}; @@ -65,6 +66,7 @@ pub use restore_engine::{BulkLoadFile, Finished, RestoreEngine}; pub use snapshot::{SnapshotEngine, SnapshotInfo, TableSnapshot}; pub use transact::{IdempotencyKey, TransactGetOp, TransactWriteOp}; +pub use vector_filter::VectorItemFilter; pub use server_components::{ BackendError, KeySource, ServerComponents, ServerComponentsFactory, create_server_components, @@ -194,6 +196,10 @@ pub struct VectorSearch<'a> { /// range or function conditions are rejected before reaching a backend. If /// the service ever admits range conditions this type must widen. pub filters: &'a [(&'a str, &'a AttributeValue)], + /// A condition each candidate must satisfy before it is ranked, for a + /// search condition that `filters` cannot express. `None` means no + /// condition beyond `hash_key` and `filters`. See [`VectorItemFilter`]. + pub item_filter: Option>, } /// TTL table info: `(account_id, table_name, ttl_attribute)`. pub type TtlTableInfo = (String, String, String); @@ -983,6 +989,7 @@ mod vector_opt_out_tests { top_k: 10, hash_key: None, filters: &[], + item_filter: None, }) .await .expect("a participating backend answers a search"); diff --git a/crates/storage/src/vector_filter.rs b/crates/storage/src/vector_filter.rs new file mode 100644 index 000000000..cdeaa66e6 --- /dev/null +++ b/crates/storage/src/vector_filter.rs @@ -0,0 +1,30 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! A predicate that a vector search applies to each candidate item. +//! +//! The engine parses and validates a search condition, and a backend only +//! evaluates it. A backend that serves vector search calls +//! [`VectorItemFilter::matches`] on each candidate before ranking it, so the +//! `top_k` cut applies to matching items only. +//! +//! The engine sets [`crate::VectorSearch::item_filter`] only for a condition +//! that the equality pairs of [`crate::VectorSearch::filters`] cannot express. +//! Otherwise the field is `None`, and a backend behaves exactly as it does +//! without it. + +use extenddb_core::types::Item; + +use crate::error::StorageError; + +/// A condition on the attributes of one item. +pub trait VectorItemFilter: Send + Sync { + /// Whether `item` satisfies the condition. + /// + /// # Errors + /// + /// Returns [`StorageError::Internal`] when the condition cannot be + /// evaluated. The engine validates the condition before the search, so an + /// error here is a defect, not a caller mistake. + fn matches(&self, item: &Item) -> Result; +} From fb474543837583b75dd35b4b40f61c8f683be988 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 16 Nov 2026 22:05:54 -0800 Subject: [PATCH 002/101] feat(core): parse the extended SearchConditionExpression grammar For accounts the service enables, a SearchVectors condition takes the comparators <>, <, <=, > and >=, BETWEEN, IN, OR, NOT, parentheses, attribute_exists and attribute_not_exists, and more than one condition on an attribute. The service parses it with the condition grammar it shares with ConditionExpression, then applies its search rules: each comparison, BETWEEN, IN and function is one condition, at most 50; IN lists and BETWEEN bounds hold values only; nested paths and other functions are refused. Once the index is known, it requires one must-match = on the HASH attribute, allows ordering operators only on Number attributes, and checks each value's type, in that order. ExtendDB accepted only an AND of equalities. The new search_filter module, behind the search-inequality-filters feature, implements that grammar with its own lexer and parser, so a syntax error can quote the offending token and its neighbours. Checks run in the order the service applies them: size, syntax, redundant parentheses, names and values, operand types, BETWEEN bounds, IN list length, the 300 operator limit, the combined size, the search rules in written order, and unused values. The parsed tree lowers to the existing condition AST, so evaluation uses the FilterExpression semantics. The module also parses the search_inequality_filters setting: off, all, or a list of account IDs. Unit tests cover the grammar, the rules, the schema checks and evaluation. Their expected messages and results are predictions, not yet measured against the live service. --- crates/core/Cargo.toml | 6 + crates/core/src/expression/mod.rs | 2 + .../core/src/expression/search_filter/gate.rs | 98 ++++ .../src/expression/search_filter/grammar.rs | 284 ++++++++++++ .../src/expression/search_filter/lexer.rs | 188 ++++++++ .../core/src/expression/search_filter/mod.rs | 207 +++++++++ .../src/expression/search_filter/rules.rs | 303 ++++++++++++ .../src/expression/search_filter/schema.rs | 130 ++++++ .../expression/search_filter/tests_eval.rs | 252 ++++++++++ .../expression/search_filter/tests_grammar.rs | 337 ++++++++++++++ .../expression/search_filter/tests_rules.rs | 230 ++++++++++ .../expression/search_filter/tests_schema.rs | 431 ++++++++++++++++++ .../expression/search_filter/tests_support.rs | 126 +++++ .../core/src/expression/search_filter/walk.rs | 416 +++++++++++++++++ crates/core/src/settings_keys.rs | 7 + 15 files changed, 3017 insertions(+) create mode 100644 crates/core/src/expression/search_filter/gate.rs create mode 100644 crates/core/src/expression/search_filter/grammar.rs create mode 100644 crates/core/src/expression/search_filter/lexer.rs create mode 100644 crates/core/src/expression/search_filter/mod.rs create mode 100644 crates/core/src/expression/search_filter/rules.rs create mode 100644 crates/core/src/expression/search_filter/schema.rs create mode 100644 crates/core/src/expression/search_filter/tests_eval.rs create mode 100644 crates/core/src/expression/search_filter/tests_grammar.rs create mode 100644 crates/core/src/expression/search_filter/tests_rules.rs create mode 100644 crates/core/src/expression/search_filter/tests_schema.rs create mode 100644 crates/core/src/expression/search_filter/tests_support.rs create mode 100644 crates/core/src/expression/search_filter/walk.rs diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 9b8e71939..8bc0451ed 100755 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -27,3 +27,9 @@ default = ["partiql"] # PartiQL grammar, AST and query planning. Removable: with this off, the # `partiql` module is not compiled and nothing else in core references it. partiql = [] +# SearchVectors inequality filters: the extended SearchConditionExpression +# grammar (comparators, BETWEEN, IN, OR, NOT, attribute_exists and +# attribute_not_exists) for the accounts the `search_inequality_filters` +# runtime setting names. Off by default. Removable: with this off, the +# grammar module is not compiled and SearchVectors behaves as before. +search-inequality-filters = [] diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 629a03617..70d8caca8 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -20,6 +20,8 @@ mod projection; mod reserved_words; mod resolver; mod search_condition; +#[cfg(feature = "search-inequality-filters")] +pub mod search_filter; #[cfg(test)] mod test_timeout; mod tokenizer; diff --git a/crates/core/src/expression/search_filter/gate.rs b/crates/core/src/expression/search_filter/gate.rs new file mode 100644 index 000000000..65c0b71e4 --- /dev/null +++ b/crates/core/src/expression/search_filter/gate.rs @@ -0,0 +1,98 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Which accounts get the extended grammar. +//! +//! The service enables the grammar for a request when the caller or the +//! table owner is enabled. The setting names them: `off`, `all`, or a +//! comma-separated list of 12-digit account IDs. + +use std::collections::BTreeSet; + +/// The parsed value of the setting. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum EnabledAccounts { + /// No account. The default, and the value when the setting is absent. + #[default] + Off, + /// Every account. + All, + /// The listed accounts. + Listed(BTreeSet), +} + +impl EnabledAccounts { + /// Parse a setting value. + /// + /// # Errors + /// + /// Returns the reason the value is refused, for the settings validator. + pub fn parse(value: &str) -> Result { + match value.trim() { + "off" => return Ok(Self::Off), + "all" => return Ok(Self::All), + _ => {} + } + let mut accounts = BTreeSet::new(); + for entry in value.split(',') { + let account = entry.trim(); + if account.len() != 12 || !account.bytes().all(|b| b.is_ascii_digit()) { + return Err( + "must be 'off', 'all', or a comma-separated list of 12-digit account IDs", + ); + } + accounts.insert(account.to_owned()); + } + Ok(Self::Listed(accounts)) + } + + /// Whether a request by `caller` on a table owned by `owner` gets the + /// grammar. `owner` is `None` when the caller owns the table. + #[must_use] + pub fn enabled_for(&self, caller: &str, owner: Option<&str>) -> bool { + match self { + Self::Off => false, + Self::All => true, + Self::Listed(accounts) => std::iter::once(caller) + .chain(owner) + .any(|account| accounts.contains(account)), + } + } +} + +#[cfg(test)] +mod tests { + use super::EnabledAccounts; + + #[test] + fn off_and_all_parse() { + assert_eq!(EnabledAccounts::parse("off"), Ok(EnabledAccounts::Off)); + assert_eq!(EnabledAccounts::parse("all"), Ok(EnabledAccounts::All)); + assert!(!EnabledAccounts::Off.enabled_for("123456789012", None)); + assert!(EnabledAccounts::All.enabled_for("123456789012", None)); + } + + #[test] + fn a_list_enables_the_caller_or_the_owner() { + let listed = EnabledAccounts::parse("111111111111, 222222222222").unwrap(); + assert!(listed.enabled_for("111111111111", None)); + assert!(listed.enabled_for("333333333333", Some("222222222222"))); + assert!(!listed.enabled_for("333333333333", None)); + assert!(!listed.enabled_for("333333333333", Some("444444444444"))); + } + + #[test] + fn a_malformed_value_is_refused() { + for bad in [ + "", + "on", + "true", + "12345", + "111111111111,", + "11111111111a", + "ALL", + ] { + assert!(EnabledAccounts::parse(bad).is_err(), "{bad:?}"); + } + } +} diff --git a/crates/core/src/expression/search_filter/grammar.rs b/crates/core/src/expression/search_filter/grammar.rs new file mode 100644 index 000000000..20a8af866 --- /dev/null +++ b/crates/core/src/expression/search_filter/grammar.rs @@ -0,0 +1,284 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The condition grammar a search condition shares with ConditionExpression, +//! parsed into a tree that keeps the operands as written. +//! +//! ```text +//! condition := and ( OR and )* +//! and := not ( AND not )* +//! not := NOT not | primary +//! primary := '(' condition ')' +//! | call -- a function as a condition +//! | operand comparator operand +//! | operand BETWEEN operand AND operand +//! | operand IN '(' operand ( ',' operand )* ')' +//! operand := path | :value | call +//! call := name '(' operand ( ',' operand )* ')' +//! path := ( name | #name ) ( '.' ( name | #name ) | '[' digits ']' )* +//! ``` +//! +//! Keywords are case-insensitive. A number is a token, but no rule takes +//! one outside a list index, so `a = 10` is a syntax error at `10`. + +use super::lexer::{Kind, Tok, syntax_error}; +use crate::expression::CompareOp; + +/// One element of a document path, as written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum Element { + /// A bare name or a `#name` reference, with its `#`. + Name(String), + /// A list index, as its digits. + Index(String), +} + +/// An operand as written. +#[derive(Debug, Clone, PartialEq)] +pub(super) enum Operand { + Path(Vec), + /// A `:value` reference, with its colon. + Value(String), + Call(Call), +} + +/// A function call. +#[derive(Debug, Clone, PartialEq)] +pub(super) struct Call { + pub(super) name: String, + pub(super) args: Vec, +} + +/// A condition node. +#[derive(Debug, Clone, PartialEq)] +pub(super) enum Node { + Or(Box, Box), + And(Box, Box), + Not(Box), + Compare { + left: Operand, + op: CompareOp, + right: Operand, + }, + Between { + subject: Operand, + low: Operand, + high: Operand, + }, + In { + subject: Operand, + list: Vec, + }, + Function(Call), +} + +/// Parse the whole expression. +/// +/// # Errors +/// +/// Returns the syntax error body (see [`syntax_error`]) or the redundant +/// parentheses body, without the expression prefix. +pub(super) fn parse(src: &str, toks: &[Tok]) -> Result { + if let Some(at) = toks.iter().position(|t| t.kind == Kind::Unknown) { + return Err(syntax_error(src, toks, at)); + } + check_redundant_parens(toks)?; + let mut p = Parser { src, toks, pos: 0 }; + let node = p.condition()?; + if p.kind() != &Kind::Eof { + return Err(p.error()); + } + Ok(node) +} + +/// A parenthesised group whose whole content is another parenthesised group, +/// such as `((a = :v))`. The same rule as the other expression parsers. +fn check_redundant_parens(toks: &[Tok]) -> Result<(), String> { + let mut stack: Vec = Vec::new(); + for (i, tok) in toks.iter().enumerate() { + match tok.kind { + Kind::LParen => stack.push(i > 0 && toks[i - 1].kind == Kind::LParen), + Kind::RParen => { + let doubled = stack.pop() == Some(true); + if doubled && toks.get(i + 1).map(|t| &t.kind) == Some(&Kind::RParen) { + return Err("The expression has redundant parentheses;".to_owned()); + } + } + _ => {} + } + } + Ok(()) +} + +struct Parser<'a> { + src: &'a str, + toks: &'a [Tok], + pos: usize, +} + +impl Parser<'_> { + fn kind(&self) -> &Kind { + &self.toks[self.pos].kind + } + + fn peek_kind(&self, ahead: usize) -> &Kind { + self.toks + .get(self.pos + ahead) + .map_or(&Kind::Eof, |t| &t.kind) + } + + fn text(&self) -> &str { + let t = &self.toks[self.pos]; + &self.src[t.start..t.end] + } + + fn error(&self) -> String { + syntax_error(self.src, self.toks, self.pos) + } + + fn bump(&mut self) { + if self.pos + 1 < self.toks.len() { + self.pos += 1; + } + } + + fn expect(&mut self, kind: &Kind) -> Result<(), String> { + if self.kind() == kind { + self.bump(); + Ok(()) + } else { + Err(self.error()) + } + } + + fn condition(&mut self) -> Result { + let mut left = self.and()?; + while self.kind() == &Kind::Or { + self.bump(); + let right = self.and()?; + left = Node::Or(Box::new(left), Box::new(right)); + } + Ok(left) + } + + fn and(&mut self) -> Result { + let mut left = self.not()?; + while self.kind() == &Kind::And { + self.bump(); + let right = self.not()?; + left = Node::And(Box::new(left), Box::new(right)); + } + Ok(left) + } + + fn not(&mut self) -> Result { + if self.kind() == &Kind::Not { + self.bump(); + return Ok(Node::Not(Box::new(self.not()?))); + } + self.primary() + } + + fn primary(&mut self) -> Result { + if self.kind() == &Kind::LParen { + self.bump(); + let inner = self.condition()?; + self.expect(&Kind::RParen)?; + return Ok(inner); + } + let subject = self.operand()?; + let op = match self.kind() { + Kind::Eq => CompareOp::Eq, + Kind::Ne => CompareOp::Ne, + Kind::Lt => CompareOp::Lt, + Kind::Le => CompareOp::Le, + Kind::Gt => CompareOp::Gt, + Kind::Ge => CompareOp::Ge, + Kind::Between => { + self.bump(); + let low = self.operand()?; + self.expect(&Kind::And)?; + let high = self.operand()?; + return Ok(Node::Between { subject, low, high }); + } + Kind::In => { + self.bump(); + self.expect(&Kind::LParen)?; + let mut list = vec![self.operand()?]; + while self.kind() == &Kind::Comma { + self.bump(); + list.push(self.operand()?); + } + self.expect(&Kind::RParen)?; + return Ok(Node::In { subject, list }); + } + // A function on its own is a condition: attribute_exists(a). + _ => { + return match subject { + Operand::Call(call) => Ok(Node::Function(call)), + Operand::Path(_) | Operand::Value(_) => Err(self.error()), + }; + } + }; + self.bump(); + let right = self.operand()?; + Ok(Node::Compare { + left: subject, + op, + right, + }) + } + + fn operand(&mut self) -> Result { + match self.kind() { + Kind::ValueRef => { + let value = self.text().to_owned(); + self.bump(); + Ok(Operand::Value(value)) + } + Kind::Name if self.peek_kind(1) == &Kind::LParen => { + let name = self.text().to_owned(); + self.bump(); + self.bump(); + let mut args = vec![self.operand()?]; + while self.kind() == &Kind::Comma { + self.bump(); + args.push(self.operand()?); + } + self.expect(&Kind::RParen)?; + Ok(Operand::Call(Call { name, args })) + } + Kind::Name | Kind::NameRef => self.path(), + _ => Err(self.error()), + } + } + + fn path(&mut self) -> Result { + let mut elements = vec![Element::Name(self.text().to_owned())]; + self.bump(); + loop { + match self.kind() { + Kind::Dot => { + self.bump(); + match self.kind() { + Kind::Name | Kind::NameRef => { + elements.push(Element::Name(self.text().to_owned())); + self.bump(); + } + _ => return Err(self.error()), + } + } + Kind::LBracket => { + self.bump(); + if self.kind() != &Kind::Number { + return Err(self.error()); + } + elements.push(Element::Index(self.text().to_owned())); + self.bump(); + self.expect(&Kind::RBracket)?; + } + _ => return Ok(Operand::Path(elements)), + } + } + } +} diff --git a/crates/core/src/expression/search_filter/lexer.rs b/crates/core/src/expression/search_filter/lexer.rs new file mode 100644 index 000000000..579e866a3 --- /dev/null +++ b/crates/core/src/expression/search_filter/lexer.rs @@ -0,0 +1,188 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Tokens of a search condition, with their byte spans. +//! +//! The spans exist for the syntax error message. The service names the +//! offending token and the text near it: the token before, the whitespace +//! touching the offending token, the offending token, and the token after. +//! `a == :s` gives `Syntax error; token: "=", near: "== :s"`. + +/// The kind of a token. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum Kind { + /// A bare attribute or function name. + Name, + /// `#name`. + NameRef, + /// `:value`. + ValueRef, + /// A run of digits. + Number, + And, + Or, + Not, + Between, + In, + Eq, + Ne, + Lt, + Le, + Gt, + Ge, + LParen, + RParen, + LBracket, + RBracket, + Comma, + Dot, + Plus, + Minus, + /// A character no token starts with, a leading byte-order mark included. + Unknown, + /// The end of the expression. + Eof, +} + +/// A token and the bytes of the expression it covers. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Tok { + pub(super) kind: Kind, + pub(super) start: usize, + pub(super) end: usize, +} + +fn is_word_byte(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' +} + +fn keyword(word: &str) -> Option { + match word.to_ascii_uppercase().as_str() { + "AND" => Some(Kind::And), + "OR" => Some(Kind::Or), + "NOT" => Some(Kind::Not), + "BETWEEN" => Some(Kind::Between), + "IN" => Some(Kind::In), + _ => None, + } +} + +/// Split `src` into tokens, ending with one [`Kind::Eof`]. +/// +/// Never fails: a character that starts no token becomes [`Kind::Unknown`], +/// which the parser reports as a syntax error at that character. +pub(super) fn lex(src: &str) -> Vec { + let bytes = src.as_bytes(); + let mut toks = Vec::new(); + let mut i = 0; + while i < bytes.len() { + let start = i; + let b = bytes[i]; + let single = |kind| Some((kind, 1)); + let fixed = match b { + b' ' | b'\t' | b'\r' | b'\n' => { + i += 1; + continue; + } + b'(' => single(Kind::LParen), + b')' => single(Kind::RParen), + b'[' => single(Kind::LBracket), + b']' => single(Kind::RBracket), + b',' => single(Kind::Comma), + b'.' => single(Kind::Dot), + b'+' => single(Kind::Plus), + b'-' => single(Kind::Minus), + b'=' => single(Kind::Eq), + b'<' => match bytes.get(i + 1) { + Some(b'>') => Some((Kind::Ne, 2)), + Some(b'=') => Some((Kind::Le, 2)), + _ => single(Kind::Lt), + }, + b'>' => match bytes.get(i + 1) { + Some(b'=') => Some((Kind::Ge, 2)), + _ => single(Kind::Gt), + }, + _ => None, + }; + if let Some((kind, len)) = fixed { + i += len; + toks.push(Tok { + kind, + start, + end: i, + }); + continue; + } + let kind = match b { + b'#' | b':' if bytes.get(i + 1).copied().is_some_and(is_word_byte) => { + i += 1; + while i < bytes.len() && is_word_byte(bytes[i]) { + i += 1; + } + if b == b'#' { + Kind::NameRef + } else { + Kind::ValueRef + } + } + b if b.is_ascii_digit() => { + while i < bytes.len() && bytes[i].is_ascii_digit() { + i += 1; + } + Kind::Number + } + b if b.is_ascii_alphabetic() || b == b'_' => { + while i < bytes.len() && is_word_byte(bytes[i]) { + i += 1; + } + keyword(&src[start..i]).unwrap_or(Kind::Name) + } + _ => { + // One whole character, which may take several bytes. + let len = src[i..].chars().next().map_or(1, char::len_utf8); + i += len; + Kind::Unknown + } + }; + toks.push(Tok { + kind, + start, + end: i, + }); + } + toks.push(Tok { + kind: Kind::Eof, + start: src.len(), + end: src.len(), + }); + toks +} + +/// The syntax error body for the token at `at`, without the expression +/// prefix: `Syntax error; token: "", near: ""`. +/// +/// `near` runs from the start of the token before (or from the start of the +/// expression when there is none) to the end of the offending token, then on +/// to the end of the token after, which takes in the whitespace between them. +/// The end of the expression reads as `` in `token` and as nothing in +/// `near`. NUL characters are dropped from the message, as the service drops +/// them. +pub(super) fn syntax_error(src: &str, toks: &[Tok], at: usize) -> String { + let cur = &toks[at]; + let near_start = at + .checked_sub(1) + .and_then(|prev| toks.get(prev)) + .map_or(0, |prev| prev.start); + let near_end = if cur.kind == Kind::Eof { + cur.end + } else { + toks.get(at + 1).map_or(cur.end, |next| next.end) + }; + let token = if cur.kind == Kind::Eof { + "" + } else { + &src[cur.start..cur.end] + }; + let near = &src[near_start..near_end]; + format!("Syntax error; token: \"{token}\", near: \"{near}\"").replace('\0', "") +} diff --git a/crates/core/src/expression/search_filter/mod.rs b/crates/core/src/expression/search_filter/mod.rs new file mode 100644 index 000000000..6f2039159 --- /dev/null +++ b/crates/core/src/expression/search_filter/mod.rs @@ -0,0 +1,207 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The extended `SearchConditionExpression` grammar of `SearchVectors`. +//! +//! With the grammar enabled for a request, a search condition takes the +//! comparators `=`, `<>`, `<`, `<=`, `>` and `>=`, BETWEEN, IN, AND, OR, NOT, +//! parentheses, `attribute_exists` and `attribute_not_exists`, and more than +//! one condition on one attribute. The checks run in this order, and the +//! first failure is the answer: +//! +//! 1. the expression is not empty and is at most 4096 bytes; +//! 2. the syntax, then redundant parentheses; +//! 3. the checks of the condition grammar, post-order (see [`walk`]); +//! 4. at most 300 operators, then the combined size; +//! 5. the search rules, in written order (see [`rules`]): attribute operands, +//! nested paths, unsupported functions, and the condition limit; +//! 6. every `ExpressionAttributeValues` key is used. +//! +//! Every failure in 1 to 5 carries the prefix +//! `Invalid SearchConditionExpression: `; the failure in 6 does not. The schema +//! check ([`SearchFilter::validate_against_schema`]) runs once the index is +//! known, and its messages carry no prefix either. +//! +//! Evaluation uses the condition evaluator that FilterExpression uses, so a +//! missing attribute, a number comparison and a type mismatch behave as they +//! do in a Query or Scan filter. +//! +//! Pure synchronous Rust: no async, no I/O. + +mod gate; +mod grammar; +mod lexer; +mod rules; +mod schema; +mod walk; + +use std::collections::{BTreeSet, HashMap}; + +pub use gate::EnabledAccounts; +pub use rules::{Condition, Operator}; + +use crate::error::DynamoDbError; +use crate::expression::{Expr, ExpressionMaps}; +use crate::types::{AttributeDefinition, AttributeValue, Item, SearchSchemaElement}; + +/// The condition limit the service applies by default. +pub const DEFAULT_MAX_CONDITIONS: usize = 50; + +/// The most bytes an expression takes, counted before substitution. +const MAX_EXPRESSION_BYTES: usize = 4096; + +const PREFIX: &str = "Invalid SearchConditionExpression: "; + +fn invalid(body: &str) -> DynamoDbError { + DynamoDbError::ValidationException(format!("{PREFIX}{body}")) +} + +/// A search condition that passed every check that needs no index metadata. +#[derive(Debug, Clone)] +pub struct SearchFilter { + expr: Expr, + maps: ExpressionMaps, + conditions: Vec, +} + +/// Parse and check a search condition with the extended grammar. +/// +/// # Errors +/// +/// Returns `ValidationException` with the message of the first failed check, +/// in the order the module documentation gives. +pub fn parse_search_filter( + expr: &str, + names: Option<&HashMap>, + values: Option<&HashMap>, + max_conditions: usize, +) -> Result { + if expr.is_empty() { + return Err(invalid("The expression can not be empty;")); + } + if expr.len() > MAX_EXPRESSION_BYTES { + return Err(invalid( + "Expression size has exceeded the maximum allowed size;", + )); + } + let toks = lexer::lex(expr); + let tree = grammar::parse(expr, &toks).map_err(|body| invalid(&body))?; + let maps = walk::Maps { names, values }; + walk::check(&tree, &maps).map_err(|body| invalid(&body))?; + let operators = walk::operators(&tree); + if operators > walk::MAX_OPERATORS { + return Err(invalid(&format!( + "The expression contains too many operators; operator count: {operators}" + ))); + } + if walk::combined_bytes(expr, &tree, &maps) > walk::MAX_COMBINED_BYTES { + return Err(invalid( + "Expression size has exceeded the maximum allowed size;", + )); + } + let conditions = rules::collect(&tree, &maps, max_conditions).map_err(|body| invalid(&body))?; + unused_values(&toks, expr, values)?; + + Ok(SearchFilter { + expr: rules::lower(&tree), + maps: evaluation_maps(names, values), + conditions, + }) +} + +/// Every supplied value must be used. The keys are listed in sorted order. +fn unused_values( + toks: &[lexer::Tok], + src: &str, + values: Option<&HashMap>, +) -> Result<(), DynamoDbError> { + let Some(values) = values else { + return Ok(()); + }; + let used: BTreeSet<&str> = toks + .iter() + .filter(|t| t.kind == lexer::Kind::ValueRef) + .map(|t| &src[t.start..t.end]) + .collect(); + let unused: BTreeSet<&str> = values + .keys() + .map(String::as_str) + .filter(|k| !used.contains(k)) + .collect(); + if unused.is_empty() { + return Ok(()); + } + Err(DynamoDbError::ValidationException(format!( + "Value provided in ExpressionAttributeValues unused in expressions: keys: {{{}}}", + unused.into_iter().collect::>().join(", ") + ))) +} + +/// The maps the evaluator reads: names keyed without `#`, values without `:`. +fn evaluation_maps( + names: Option<&HashMap>, + values: Option<&HashMap>, +) -> ExpressionMaps { + let names = names + .into_iter() + .flatten() + .filter_map(|(k, v)| Some((k.strip_prefix('#')?.to_owned(), v.clone()))) + .collect(); + let values = values + .into_iter() + .flatten() + .filter_map(|(k, v)| Some((k.strip_prefix(':')?.to_owned(), v.clone()))) + .collect(); + ExpressionMaps::new(names, values) +} + +impl SearchFilter { + /// The conditions in written order. + #[must_use] + pub fn conditions(&self) -> &[Condition] { + &self.conditions + } + + /// Check the conditions against the index search schema, and return the + /// HASH attribute and the value that selects its partition when the + /// schema declares a HASH element. + /// + /// # Errors + /// + /// Returns `ValidationException` with the message of the first failed + /// check, without the expression prefix. + pub fn validate_against_schema( + &self, + schema: Option<&[SearchSchemaElement]>, + definitions: &[AttributeDefinition], + ) -> Result, DynamoDbError> { + schema::validate(&self.conditions, schema.unwrap_or_default(), definitions) + .map_err(DynamoDbError::ValidationException) + } + + /// Whether `item` satisfies the condition. + /// + /// # Errors + /// + /// Returns the evaluator's error. The checks above refuse every + /// condition the evaluator would refuse, so this does not happen for a + /// parsed filter. + pub fn matches(&self, item: &Item) -> Result { + crate::expression::evaluate_condition(&self.expr, item, &self.maps) + } +} + +#[cfg(test)] +mod tests_support; + +#[cfg(test)] +mod tests_grammar; + +#[cfg(test)] +mod tests_rules; + +#[cfg(test)] +mod tests_schema; + +#[cfg(test)] +mod tests_eval; diff --git a/crates/core/src/expression/search_filter/rules.rs b/crates/core/src/expression/search_filter/rules.rs new file mode 100644 index 000000000..7f71350cb --- /dev/null +++ b/crates/core/src/expression/search_filter/rules.rs @@ -0,0 +1,303 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The search rules, applied once the tree is built: one condition for each +//! comparison, BETWEEN, IN and function, in written order, and the condition +//! limit. + +use super::grammar::{Call, Element, Node, Operand}; +use super::walk::Maps; +use crate::expression::{CompareOp, Expr, PathElement}; +use crate::types::AttributeValue; + +/// The operator of one condition, as written. `:v < a` is [`Operator::Lt`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Operator { + Eq, + Ne, + Lt, + Le, + Gt, + Ge, + Between, + In, + Exists, + NotExists, +} + +impl Operator { + /// `<`, `<=`, `>`, `>=` and BETWEEN compare by order, which only a Number + /// attribute has in a search. + #[must_use] + pub fn is_ordering(self) -> bool { + matches!( + self, + Self::Lt | Self::Le | Self::Gt | Self::Ge | Self::Between + ) + } + + /// The operator as the schema messages name it. + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Eq => "=", + Self::Ne => "<>", + Self::Lt => "<", + Self::Le => "<=", + Self::Gt => ">", + Self::Ge => ">=", + Self::Between => "BETWEEN", + Self::In => "IN", + Self::Exists => "attribute_exists", + Self::NotExists => "attribute_not_exists", + } + } + + fn of(op: CompareOp) -> Self { + match op { + CompareOp::Eq => Self::Eq, + CompareOp::Ne => Self::Ne, + CompareOp::Lt => Self::Lt, + CompareOp::Le => Self::Le, + CompareOp::Gt => Self::Gt, + CompareOp::Ge => Self::Ge, + } + } +} + +/// One condition on one attribute. +#[derive(Debug, Clone, PartialEq)] +pub struct Condition { + /// The attribute, with a `#name` resolved. + pub attribute: String, + pub operator: Operator, + /// The values in written order: one for a comparison, the bounds for + /// BETWEEN, the list for IN, none for a function. + pub values: Vec, + /// True when every operator above the condition is AND, so every item the + /// search returns satisfies it. + pub must_match: bool, +} + +/// Collect the conditions of `root` in written order. +/// +/// # Errors +/// +/// Returns the first failure's message body, without the expression prefix. +pub(super) fn collect( + root: &Node, + maps: &Maps<'_>, + max_conditions: usize, +) -> Result, String> { + let mut out = Vec::new(); + walk(root, true, maps, max_conditions, root, &mut out)?; + Ok(out) +} + +fn walk( + node: &Node, + must_match: bool, + maps: &Maps<'_>, + max: usize, + root: &Node, + out: &mut Vec, +) -> Result<(), String> { + let condition = match node { + Node::And(l, r) => { + walk(l, must_match, maps, max, root, out)?; + return walk(r, must_match, maps, max, root, out); + } + // Either side of an OR is enough, and NOT inverts, so a condition + // below them need not hold for every returned item. + Node::Or(l, r) => { + walk(l, false, maps, max, root, out)?; + return walk(r, false, maps, max, root, out); + } + Node::Not(inner) => return walk(inner, false, maps, max, root, out), + Node::Compare { left, op, right } => { + let (path, value) = match (left, right) { + (Operand::Path(p), Operand::Value(v)) | (Operand::Value(v), Operand::Path(p)) => { + (p, v) + } + (Operand::Path(_), Operand::Path(_)) => { + return Err("Invalid condition in SearchConditionExpression: Multiple \ + attribute names used in one condition" + .to_owned()); + } + (Operand::Value(_), Operand::Value(_)) => return Err(no_attribute_names()), + (Operand::Call(call), _) | (_, Operand::Call(call)) => { + return Err(unsupported(call)); + } + }; + let values = vec![value_of(value, maps)?]; + condition(path, Operator::of(*op), values, must_match, maps)? + } + Node::In { subject, list } => { + let values = bound_values(list, maps, IN_LIST_ATTRIBUTE)?; + let path = subject_path(subject)?; + condition(path, Operator::In, values, must_match, maps)? + } + Node::Between { subject, low, high } => { + let bounds = [low.clone(), high.clone()]; + let values = bound_values(&bounds, maps, BETWEEN_BOUND_ATTRIBUTE)?; + let path = subject_path(subject)?; + condition(path, Operator::Between, values, must_match, maps)? + } + Node::Function(call) => { + let operator = match call.name.as_str() { + "attribute_exists" => Operator::Exists, + "attribute_not_exists" => Operator::NotExists, + _ => return Err(unsupported(call)), + }; + let Some(Operand::Path(path)) = call.args.first() else { + return Err(format!( + "Operator or function requires a document path; operator or function: {}", + call.name + )); + }; + condition(path, operator, Vec::new(), must_match, maps)? + } + }; + // The condition is checked first, so a malformed condition past the limit + // gets its own message. The count covers the whole expression. + if out.len() >= max { + return Err(format!( + "The expression contains too many conditions; number of conditions: {}, \ + maximum: {max}", + count(root) + )); + } + out.push(condition); + Ok(()) +} + +const IN_LIST_ATTRIBUTE: &str = "The IN operator list must contain only expression attribute \ + values (:value), not attribute names"; +const BETWEEN_BOUND_ATTRIBUTE: &str = "The BETWEEN operator bounds must be expression \ + attribute values (:value), not attribute names"; + +fn no_attribute_names() -> String { + "Invalid condition in SearchConditionExpression: No attribute names used in a condition" + .to_owned() +} + +fn unsupported(call: &Call) -> String { + format!( + "The function is not allowed in a search condition; function: {}", + call.name + ) +} + +/// The values of an IN list or of BETWEEN bounds, checked before the attribute. +fn bound_values( + operands: &[Operand], + maps: &Maps<'_>, + path_message: &str, +) -> Result, String> { + operands + .iter() + .map(|o| match o { + Operand::Value(v) => value_of(v, maps), + Operand::Path(_) => Err(path_message.to_owned()), + Operand::Call(call) => Err(unsupported(call)), + }) + .collect() +} + +fn subject_path(subject: &Operand) -> Result<&[Element], String> { + match subject { + Operand::Path(p) => Ok(p), + Operand::Value(_) => Err(no_attribute_names()), + Operand::Call(call) => Err(unsupported(call)), + } +} + +fn value_of(reference: &str, maps: &Maps<'_>) -> Result { + // The tree-building checks already refused an undefined value. + maps.value(reference).cloned().ok_or_else(|| { + format!( + "An expression attribute value used in expression is not defined; attribute value: \ + {reference}" + ) + }) +} + +fn condition( + path: &[Element], + operator: Operator, + values: Vec, + must_match: bool, + maps: &Maps<'_>, +) -> Result { + let [Element::Name(first)] = path else { + return Err( + "SearchConditionExpression cannot have conditions on nested attributes".to_owned(), + ); + }; + Ok(Condition { + attribute: maps.name(first).unwrap_or(first).to_owned(), + operator, + values, + must_match, + }) +} + +/// A comparison, BETWEEN, IN and function count one; AND, OR and NOT none. +fn count(node: &Node) -> usize { + match node { + Node::And(l, r) | Node::Or(l, r) => count(l) + count(r), + Node::Not(inner) => count(inner), + Node::Compare { .. } | Node::Between { .. } | Node::In { .. } | Node::Function(_) => 1, + } +} + +/// The tree as the condition evaluator reads it. `#name` and `:value` +/// references stay as written; the evaluator resolves them through +/// [`crate::expression::ExpressionMaps`]. +pub(super) fn lower(node: &Node) -> Expr { + match node { + Node::Or(l, r) => Expr::Or(Box::new(lower(l)), Box::new(lower(r))), + Node::And(l, r) => Expr::And(Box::new(lower(l)), Box::new(lower(r))), + Node::Not(inner) => Expr::Not(Box::new(lower(inner))), + Node::Compare { left, op, right } => Expr::Compare { + left: Box::new(lower_operand(left)), + op: *op, + right: Box::new(lower_operand(right)), + }, + Node::Between { subject, low, high } => Expr::Between { + operand: Box::new(lower_operand(subject)), + low: Box::new(lower_operand(low)), + high: Box::new(lower_operand(high)), + }, + Node::In { subject, list } => Expr::In { + operand: Box::new(lower_operand(subject)), + list: list.iter().map(lower_operand).collect(), + }, + Node::Function(call) => lower_call(call), + } +} + +fn lower_call(call: &Call) -> Expr { + Expr::Function { + name: call.name.clone(), + args: call.args.iter().map(lower_operand).collect(), + } +} + +fn lower_operand(o: &Operand) -> Expr { + match o { + Operand::Path(elements) => Expr::Path( + elements + .iter() + .map(|e| match e { + Element::Name(n) => PathElement::Attribute(n.clone()), + Element::Index(d) => PathElement::Index(d.parse().unwrap_or(usize::MAX)), + }) + .collect(), + ), + Operand::Value(reference) => { + Expr::Placeholder(reference.trim_start_matches(':').to_owned()) + } + Operand::Call(call) => lower_call(call), + } +} diff --git a/crates/core/src/expression/search_filter/schema.rs b/crates/core/src/expression/search_filter/schema.rs new file mode 100644 index 000000000..a7320a872 --- /dev/null +++ b/crates/core/src/expression/search_filter/schema.rs @@ -0,0 +1,130 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The search condition against the index search schema. +//! +//! The HASH checks run first. Then each condition in written order is checked +//! for schema membership, then an ordering operator against the attribute +//! type, then the type of each value. The first failure is the answer. These +//! messages carry no expression prefix. + +use super::rules::{Condition, Operator}; +use crate::types::{ + AttributeDefinition, AttributeValue, ScalarAttributeType, SearchSchemaElement, + SearchSchemaElementType, +}; + +const HASH_MISSING: &str = + "SearchConditionExpression must have all HASH attributes in configured SearchSchema"; +const HASH_MORE_THAN_ONCE: &str = "SearchConditionExpression must contain only one condition \ + on the HASH attribute; to search more than one HASH value, \ + make one SearchVectors call for each value"; + +/// How the conditions use one HASH attribute. +enum HashUse<'a> { + Missing, + /// Exactly one condition on it, a must-match `=`: the condition. + Selects(&'a Condition), + /// A condition on it that is not a must-match `=`. + NotMustMatchEquals, + /// More than one condition on it, each a must-match `=`. + MoreThanOnce, +} + +fn hash_use<'a>(conditions: &'a [Condition], attribute: &str) -> HashUse<'a> { + let on = || conditions.iter().filter(move |c| c.attribute == attribute); + if on().any(|c| !(c.operator == Operator::Eq && c.must_match)) { + return HashUse::NotMustMatchEquals; + } + let mut equals = on().filter(|c| !c.values.is_empty()); + match (equals.next(), equals.next()) { + (None, _) => HashUse::Missing, + (Some(condition), None) => HashUse::Selects(condition), + (Some(_), Some(_)) => HashUse::MoreThanOnce, + } +} + +/// Validate `conditions` against the index search schema and return the +/// HASH attribute and the value that selects its partition, if the schema has +/// a HASH element. +/// +/// # Errors +/// +/// Returns the message of the first failed check. +pub(super) fn validate<'a>( + conditions: &'a [Condition], + schema: &[SearchSchemaElement], + definitions: &[AttributeDefinition], +) -> Result, String> { + let mut selected = None; + for element in schema + .iter() + .filter(|e| e.element_type == SearchSchemaElementType::Hash) + { + match hash_use(conditions, &element.attribute_name) { + HashUse::Selects(condition) => { + if let Some(value) = condition.values.first() { + selected.get_or_insert((condition.attribute.as_str(), value)); + } + } + HashUse::Missing => return Err(HASH_MISSING.to_owned()), + HashUse::NotMustMatchEquals => { + return Err(format!( + "SearchConditionExpression must use = on the HASH attribute, not inside OR \ + or NOT; HASH attribute: {}", + element.attribute_name + )); + } + HashUse::MoreThanOnce => return Err(HASH_MORE_THAN_ONCE.to_owned()), + } + } + + for condition in conditions { + let Some(element) = schema + .iter() + .find(|e| e.attribute_name == condition.attribute) + else { + return Err(format!( + "SearchConditionExpression must not contain any attributes that is not in \ + SearchSchema. Invalid attribute: {}", + condition.attribute + )); + }; + let Some(declared) = definitions + .iter() + .find(|d| d.attribute_name == element.attribute_name) + .map(|d| d.attribute_type) + else { + continue; + }; + if condition.operator.is_ordering() && declared != ScalarAttributeType::N { + return Err(format!( + "SearchConditionExpression allows this operator only on Number (N) attributes; \ + operator: {}, attribute: {}, attribute type: {}", + condition.operator.as_str(), + element.attribute_name, + type_code(declared) + )); + } + for value in &condition.values { + let given = crate::expression::resolver::attribute_type_code(value); + if given != type_code(declared) { + return Err(format!( + "Type of '{}' attribute in SearchConditionExpression ({given}) does not \ + match type in search schema ({})", + condition.attribute, + type_code(declared) + )); + } + } + } + Ok(selected) +} + +fn type_code(t: ScalarAttributeType) -> &'static str { + match t { + ScalarAttributeType::S => "S", + ScalarAttributeType::N => "N", + ScalarAttributeType::B => "B", + } +} diff --git a/crates/core/src/expression/search_filter/tests_eval.rs b/crates/core/src/expression/search_filter/tests_eval.rs new file mode 100644 index 000000000..6a5facb6b --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_eval.rs @@ -0,0 +1,252 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Which items a search condition matches. +//! +//! Evaluation uses the FilterExpression semantics: a comparison with a +//! missing attribute is false except `<>`, which is true; numbers compare as +//! decimals, so `1E2` equals `100` and 38-digit values keep their order; a +//! value of another type than the attribute's compares unequal. Not yet +//! measured against the live service for SearchVectors. + +use std::collections::{BTreeMap, HashMap}; + +use super::parse_search_filter; +use super::tests_support::{n, s, used_values}; +use crate::types::{AttributeValue, Item}; + +/// `(id, Country, Category, Price, Tag)`; `None` is an absent attribute. +type Row = ( + &'static str, + &'static str, + Option<&'static str>, + Option, + Option, +); + +fn items() -> Vec { + let rows: Vec = vec![ + ("i1", "US", Some("a"), Some(n("5")), Some(1)), + ("i2", "US", Some("b"), Some(n("10")), Some(2)), + ("i3", "US", Some("c"), Some(n("15")), None), + ("i4", "US", Some("a"), None, None), + ("i5", "US", None, Some(n("-2.5")), None), + ("i6", "US", Some("a"), Some(n("100")), None), + ("i7", "US", Some("b"), Some(n("1E2")), None), + ("i8", "CA", Some("a"), Some(n("5")), None), + ( + "i9", + "US", + Some("c"), + Some(n("99999999999999999999999999999999999999")), + None, + ), + ("i10", "US", Some("b"), Some(n("0.1")), None), + // a Price of another type than the schema declares + ("i11", "US", Some("c"), Some(s("ten")), None), + ]; + rows.into_iter() + .map(|(id, country, category, price, tag)| { + let mut item: Item = BTreeMap::new(); + item.insert("id".to_owned(), s(id)); + item.insert("Country".to_owned(), s(country)); + if let Some(c) = category { + item.insert("Category".to_owned(), s(c)); + } + if let Some(p) = price { + item.insert("Price".to_owned(), p); + } + if let Some(t) = tag { + item.insert("Tag".to_owned(), AttributeValue::B(vec![t])); + } + item + }) + .collect() +} + +fn values() -> HashMap { + [ + (":us", s("US")), + (":ca", s("CA")), + (":a", s("a")), + (":b", s("b")), + (":p0", n("0")), + (":p5", n("5")), + (":p10", n("10")), + (":p15", n("15")), + (":p100", n("100")), + (":big", n("99999999999999999999999999999999999998")), + (":t1", AttributeValue::B(vec![1])), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect() +} + +/// The ids of the items `expr` matches, in item order. +fn matching(expr: &str) -> Vec { + let used = used_values(expr, &values()); + let filter = parse_search_filter(expr, None, Some(&used), 50) + .unwrap_or_else(|e| panic!("{expr}: {e:?}")); + items() + .iter() + .filter(|item| { + filter + .matches(item) + .unwrap_or_else(|e| panic!("{expr}: {e:?}")) + }) + .map(|item| match item.get("id") { + Some(AttributeValue::S(id)) => id.clone(), + _ => unreachable!(), + }) + .collect() +} + +fn assert_matches(cases: &[(&str, &[&str])]) { + let mismatches: Vec = cases + .iter() + .filter_map(|(expr, expected)| { + let actual = matching(expr); + (actual != *expected) + .then(|| format!("{expr:?}: expected {expected:?}, got {actual:?}")) + }) + .collect(); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +const H: &str = "Country = :us AND"; + +fn h(rest: &str) -> String { + format!("{H} {rest}") +} + +#[test] +fn each_comparator_on_a_number() { + let cases = [ + (h("Price = :p10"), vec!["i2"]), + (h("Price < :p10"), vec!["i1", "i5", "i10"]), + (h("Price <= :p10"), vec!["i1", "i2", "i5", "i10"]), + (h("Price > :p10"), vec!["i3", "i6", "i7", "i9"]), + (h("Price >= :p10"), vec!["i2", "i3", "i6", "i7", "i9"]), + // the value on the left reads the comparison the other way + (h(":p10 > Price"), vec!["i1", "i5", "i10"]), + (h("Price > :p5 AND Price < :p15"), vec!["i2"]), + (h("Price >= :p5 AND Price = :p5"), vec!["i1"]), + (h("Price = :p5 AND Price = :p10"), vec![]), + (h("Price > :p15 AND Price < :p5"), vec![]), + (h("Price > :p0 AND Price < :p5"), vec!["i10"]), + (h("Price < :p0"), vec!["i5"]), + (h("Price BETWEEN :p5 AND :p10"), vec!["i1", "i2"]), + (h("Price BETWEEN :p5 AND :p5"), vec!["i1"]), + ( + h("(Price BETWEEN :p5 AND :p10 OR Price > :p100)"), + vec!["i1", "i2", "i9"], + ), + ( + h("NOT Price BETWEEN :p5 AND :p10"), + vec!["i3", "i4", "i5", "i6", "i7", "i9", "i10", "i11"], + ), + (h("Price IN (:p5, :p10)"), vec!["i1", "i2"]), + ]; + let refs: Vec<(&str, &[&str])> = cases + .iter() + .map(|(e, x)| (e.as_str(), x.as_slice())) + .collect(); + assert_matches(&refs); +} + +/// Unmeasured, needs live confirmation: a missing attribute under `<>` and +/// under NOT. FilterExpression reads `<>` with a missing attribute as true, +/// and NOT of a false comparison as true. +#[test] +fn a_missing_attribute_under_not_equal_and_not() { + let cases = [ + ( + h("Price <> :p10"), + vec!["i1", "i3", "i4", "i5", "i6", "i7", "i9", "i10", "i11"], + ), + ( + h("NOT (Price = :p10)"), + vec!["i1", "i3", "i4", "i5", "i6", "i7", "i9", "i10", "i11"], + ), + ( + h("Category <> :a"), + vec!["i2", "i3", "i5", "i7", "i9", "i10", "i11"], + ), + ( + h("Price > :p0"), + vec!["i1", "i2", "i3", "i6", "i7", "i9", "i10"], + ), + (h("attribute_not_exists(Price)"), vec!["i4"]), + ( + h("attribute_exists(Price)"), + vec!["i1", "i2", "i3", "i5", "i6", "i7", "i9", "i10", "i11"], + ), + ]; + let refs: Vec<(&str, &[&str])> = cases + .iter() + .map(|(e, x)| (e.as_str(), x.as_slice())) + .collect(); + assert_matches(&refs); +} + +/// Unmeasured, needs live confirmation: `1E2` against `100`, and 38-digit +/// values. +#[test] +fn numbers_compare_as_decimals() { + let cases = [ + (h("Price = :p100"), vec!["i6", "i7"]), + (h("Price > :big"), vec!["i9"]), + ]; + let refs: Vec<(&str, &[&str])> = cases + .iter() + .map(|(e, x)| (e.as_str(), x.as_slice())) + .collect(); + assert_matches(&refs); +} + +/// Unmeasured, needs live confirmation: an item whose attribute has another +/// type than the schema declares matches no ordering and no equality, and +/// does match `<>`. +#[test] +fn a_stored_value_of_another_type() { + assert!(!matching(&h("Price >= :p0")).contains(&"i11".to_owned())); + assert!(!matching(&h("Price = :p0")).contains(&"i11".to_owned())); + assert!(matching(&h("Price <> :p0")).contains(&"i11".to_owned())); +} + +#[test] +fn strings_binaries_and_logic() { + let cases = [ + (h("Category = :a"), vec!["i1", "i4", "i6"]), + (h("Tag = :t1"), vec!["i1"]), + ( + h("Tag <> :t1"), + vec!["i2", "i3", "i4", "i5", "i6", "i7", "i9", "i10", "i11"], + ), + ( + h("Category IN (:a, :b)"), + vec!["i1", "i2", "i4", "i6", "i7", "i10"], + ), + (h("(Price = :p5 OR Price = :p10)"), vec!["i1", "i2"]), + ( + h("NOT (Category = :a)"), + vec!["i2", "i3", "i5", "i7", "i9", "i10", "i11"], + ), + ( + h("(Category = :a OR (Price > :p5 AND NOT Price = :p15))"), + vec!["i1", "i2", "i4", "i6", "i7", "i9"], + ), + (h("NOT NOT Price = :p5"), vec!["i1"]), + ( + "Country = :us and (Price = :p5 or not Price = :p10)".to_owned(), + vec!["i1", "i3", "i4", "i5", "i6", "i7", "i9", "i10", "i11"], + ), + ("Country = :ca AND Price = :p5".to_owned(), vec!["i8"]), + ]; + let refs: Vec<(&str, &[&str])> = cases + .iter() + .map(|(e, x)| (e.as_str(), x.as_slice())) + .collect(); + assert_matches(&refs); +} diff --git a/crates/core/src/expression/search_filter/tests_grammar.rs b/crates/core/src/expression/search_filter/tests_grammar.rs new file mode 100644 index 000000000..1fa3d921e --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_grammar.rs @@ -0,0 +1,337 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The grammar and the tree-building checks, before any search schema. +//! +//! Not yet measured against the live service: every expected message here is +//! a prediction, and a live run confirms or corrects it. + +use super::tests_support::{OK, and_chain, assert_outcomes, in_list, outcome, p}; + +const IN_LIST_ATTRIBUTE: &str = "The IN operator list must contain only expression attribute \ + values (:value), not attribute names"; +const BETWEEN_BOUND_ATTRIBUTE: &str = "The BETWEEN operator bounds must be expression \ + attribute values (:value), not attribute names"; +const NESTED: &str = "SearchConditionExpression cannot have conditions on nested attributes"; +const MULTIPLE_NAMES: &str = "Invalid condition in SearchConditionExpression: Multiple \ + attribute names used in one condition"; +const NO_NAMES: &str = + "Invalid condition in SearchConditionExpression: No attribute names used in a condition"; + +fn ordering(operator: &str, operand_type: &str) -> String { + p(&format!( + "Incorrect operand type for operator or function; operator or function: {operator}, \ + operand type: {operand_type}" + )) +} + +fn unsupported(function: &str) -> String { + p(&format!( + "The function is not allowed in a search condition; function: {function}" + )) +} + +#[test] +fn the_extended_grammar_accepts_every_documented_form() { + let accepted = [ + "a = :s", + ":s = a", + "#x = :s", + "#y = :s", + "a = :s AND b = :n", + "a = :s AND b = :n AND c = :b AND d = :t", + "(a = :s) AND (b = :n)", + "a = :s AND (b = :n AND c = :b)", + // more than one condition on an attribute, a contradiction included + "a > :n AND a < :n2", + "a >= :n AND a <= :n2", + "a = :s AND a = :s2", + "a = :s AND a = :s", + "a = :s AND a > :n", + // the attribute type is unknown here: the schema check refuses these + "a > :s", + "a > :b", + "a <> :t", + "a = :s OR b > :n", + "a = :s AND (b > :n OR c = :b)", + "(a = :s AND b > :n) OR (a = :s2 AND b < :n2)", + "NOT (a > :n)", + "NOT a = :s", + "NOT NOT (a = :s)", + "a = :s AND NOT (b = :n OR c = :b)", + "a IN (:s, :s2)", + "a IN (:s)", + "a IN (:s, :s)", + "a IN (:s, :n)", + "NOT a IN (:s, :s2)", + "attribute_exists(a)", + "attribute_not_exists(a)", + "attribute_exists(a) AND NOT attribute_not_exists(b)", + "a BETWEEN :n AND :n2", + "a BETWEEN :n AND :n", + "a = :s AND b BETWEEN :n AND :n2", + "a > :n OR b BETWEEN :n AND :n2", + "NOT a BETWEEN :n AND :n2", + "a BETWEEN :s2 AND :s", + // keywords in any case + "a = :s and (b = :n or not c = :b)", + "a = :s AnD b bEtWeEn :n aNd :n2", + ]; + assert_outcomes(50, accepted.iter().map(|e| (*e, OK))); +} + +#[test] +fn operands_of_a_condition_are_checked_in_written_order() { + assert_outcomes( + 50, + [ + ("a IN (b, :s)", p(IN_LIST_ATTRIBUTE)), + ("a IN (:s, b)", p(IN_LIST_ATTRIBUTE)), + // the list is checked before the attribute + (":s IN (a)", p(IN_LIST_ATTRIBUTE)), + (":s IN (:s2)", p(NO_NAMES)), + ("a.b IN (:s)", p(NESTED)), + ("attribute_exists(a.b)", p(NESTED)), + ("a BETWEEN b AND :n", p(BETWEEN_BOUND_ATTRIBUTE)), + ("a BETWEEN :n AND b", p(BETWEEN_BOUND_ATTRIBUTE)), + (":n BETWEEN a AND :n2", p(BETWEEN_BOUND_ATTRIBUTE)), + (":n BETWEEN :n AND :n2", p(NO_NAMES)), + ("a.b BETWEEN :n AND :n2", p(NESTED)), + // two rules broken: the first condition as written decides + ("a BETWEEN b AND :n OR c IN (d)", p(BETWEEN_BOUND_ATTRIBUTE)), + ("c IN (d) OR a BETWEEN b AND :n", p(IN_LIST_ATTRIBUTE)), + ("a > b", p(MULTIPLE_NAMES)), + ("a = b", p(MULTIPLE_NAMES)), + (":n > :n2", p(NO_NAMES)), + (":s = :s2", p(NO_NAMES)), + ("a.b > :n", p(NESTED)), + ("a.b = :s", p(NESTED)), + ("a[0] < :n", p(NESTED)), + ("a[0] = :s", p(NESTED)), + ], + ); +} + +#[test] +fn between_bounds_are_checked_while_the_tree_is_built() { + assert_outcomes( + 50, + [ + ( + "a BETWEEN :n2 AND :n", + p( + "The BETWEEN operator requires upper bound to be greater than or equal to \ + lower bound; lower bound operand: AttributeValue: {N:10}, upper bound \ + operand: AttributeValue: {N:5}", + ), + ), + ( + "a BETWEEN :n AND :s", + p( + "The BETWEEN operator requires same data type for lower and upper bounds; \ + lower bound operand: AttributeValue: {N:5}, upper bound operand: \ + AttributeValue: {S:US}", + ), + ), + ("a BETWEEN :t AND :t", ordering("BETWEEN", "BOOL")), + ( + "a BETWEEN a AND :n", + p( + "The first operand must be distinct from the remaining operands for this \ + operator or function; operator: BETWEEN, first operand: [a]", + ), + ), + ], + ); +} + +#[test] +fn ordering_takes_only_string_number_and_binary_values() { + assert_outcomes( + 50, + [ + ("a > :t", ordering(">", "BOOL")), + ("a > :null", ordering(">", "NULL")), + ("a <= :t", ordering("<=", "BOOL")), + (":t < a", ordering("<", "BOOL")), + // checked while the tree is built, before the rules + ("a > :t OR b = :s", ordering(">", "BOOL")), + ], + ); +} + +#[test] +fn names_and_values_resolve_before_any_rule() { + assert_outcomes( + 50, + [ + ( + "a = :missing", + p( + "An expression attribute value used in expression is not defined; attribute \ + value: :missing", + ), + ), + ( + "a = #missing", + p( + "An expression attribute name used in the document path is not defined; \ + attribute name: #missing", + ), + ), + ( + "year = :s", + p("Attribute name is a reserved keyword; reserved keyword: year"), + ), + ( + "YEAR = :s", + p("Attribute name is a reserved keyword; reserved keyword: YEAR"), + ), + // the left operand is checked before the comparison + ( + "year > :t", + p("Attribute name is a reserved keyword; reserved keyword: year"), + ), + ], + ); +} + +#[test] +fn syntax_errors_name_the_token_and_the_text_near_it() { + assert_outcomes( + 50, + [ + ("", p("The expression can not be empty;")), + ("a = ", p("Syntax error; token: \"\", near: \"= \"")), + ("a == :s", p("Syntax error; token: \"=\", near: \"== :s\"")), + ("a = 10", p("Syntax error; token: \"10\", near: \"= 10\"")), + ("((a = :s))", p("The expression has redundant parentheses;")), + ( + "\u{feff}attribute_exists(a)", + p("Syntax error; token: \"\u{feff}\", near: \"\u{feff}attribute_exists\""), + ), + ( + "\u{feff}a = :s", + p("Syntax error; token: \"\u{feff}\", near: \"\u{feff}a\""), + ), + ], + ); +} + +#[test] +fn only_the_two_existence_functions_are_conditions() { + assert_outcomes( + 50, + [ + ("begins_with(a, :s)", unsupported("begins_with")), + ("contains(a, :s)", unsupported("contains")), + ("attribute_type(a, :ty)", unsupported("attribute_type")), + ("size(a) = :n", unsupported("size")), + ("a = :s OR begins_with(b, :s)", unsupported("begins_with")), + ("size(a) > :n", unsupported("size")), + (":n < size(a)", unsupported("size")), + ("size(a) IN (:n)", unsupported("size")), + ("a IN (:n, size(b))", unsupported("size")), + ("size(a) BETWEEN :n AND :n2", unsupported("size")), + ("a BETWEEN :n AND size(b)", unsupported("size")), + // the type name is checked while the tree is built + ( + "attribute_type(a, :s)", + p("Invalid attribute type name found; type: US, valid types: \ + {S,SS,N,NS,B,BS,BOOL,NULL,L,M}"), + ), + ], + ); +} + +#[test] +fn the_shared_grammar_limits_apply() { + assert_eq!(outcome(&in_list(100)), OK); + assert_eq!( + outcome(&in_list(101)), + p("The IN operator is provided with too many operands; number of operands: 101") + ); + // 151 comparisons and 150 ANDs: the operator limit answers before the + // condition limit + assert_eq!( + outcome(&and_chain(151)), + p("The expression contains too many operators; operator count: 301") + ); + let sized = |len: usize| format!("{} = :s", "a".repeat(len - " = :s".len())); + assert_eq!(outcome(&sized(4096)), OK); + assert_eq!( + outcome(&sized(4097)), + p("Expression size has exceeded the maximum allowed size;") + ); + let not_chain = format!("{}a = :s", "NOT ".repeat(1020)); + assert!(not_chain.len() <= 4096); + assert_eq!( + outcome(¬_chain), + p("The expression contains too many operators; operator count: 1021") + ); +} + +#[test] +fn not_counts_as_an_operator_and_not_as_a_condition() { + let with_operators = |count: usize, operators: usize| { + format!( + "{}{}", + "NOT ".repeat(operators - (2 * count - 1)), + and_chain(count) + ) + }; + assert_eq!(outcome(&with_operators(50, 300)), OK); + assert_eq!( + outcome(&with_operators(50, 301)), + p("The expression contains too many operators; operator count: 301") + ); + let not_chain = |count: usize| format!("{}a = :s", "NOT ".repeat(count)); + assert_eq!(outcome(¬_chain(299)), OK); + assert_eq!( + outcome(¬_chain(300)), + p("The expression contains too many operators; operator count: 301") + ); +} + +#[test] +fn the_combined_size_counts_each_substituted_name() { + use std::collections::HashMap; + let refs: Vec = (0..17).map(|i| format!("#x{i}")).collect(); + let long: HashMap = refs + .iter() + .map(|r| (r.clone(), format!("{r}{}", "x".repeat(65530)))) + .collect(); + let expr = refs + .iter() + .map(|r| format!("{r} = :s")) + .collect::>() + .join(" AND "); + let values: HashMap<_, _> = [(":s".to_owned(), super::tests_support::s("US"))].into(); + let err = super::parse_search_filter(&expr, Some(&long), Some(&values), 50).unwrap_err(); + assert_eq!( + super::tests_support::message(err), + p("Expression size has exceeded the maximum allowed size;") + ); +} + +#[test] +fn an_unused_value_is_named_without_the_prefix() { + use std::collections::HashMap; + let values: HashMap = [ + (":s".to_owned(), super::tests_support::s("US")), + (":x".to_owned(), super::tests_support::s("unused")), + (":w".to_owned(), super::tests_support::s("unused")), + ] + .into(); + let err = super::parse_search_filter("a > :s", None, Some(&values), 50).unwrap_err(); + assert_eq!( + super::tests_support::message(err), + "Value provided in ExpressionAttributeValues unused in expressions: keys: {:w, :x}" + ); + // a parse failure answers before the unused value + let err = super::parse_search_filter("a > :s OR", None, Some(&values), 50).unwrap_err(); + assert_eq!( + super::tests_support::message(err), + p("Syntax error; token: \"\", near: \"OR\"") + ); +} diff --git a/crates/core/src/expression/search_filter/tests_rules.rs b/crates/core/src/expression/search_filter/tests_rules.rs new file mode 100644 index 000000000..0b6914a03 --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_rules.rs @@ -0,0 +1,230 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The conditions a search condition records, and the condition limit. +//! +//! Not yet measured against the live service: every expected value here is +//! a prediction, and a live run confirms or corrects it. + +use super::rules::{Condition, Operator}; +use super::tests_support::{ + OK, and_chain, assert_outcomes, in_list, n, outcome_with, p, parse_with, s, +}; +use crate::types::AttributeValue; + +fn cond( + attribute: &str, + operator: Operator, + values: impl IntoIterator, + must_match: bool, +) -> Condition { + Condition { + attribute: attribute.to_owned(), + operator, + values: values.into_iter().collect(), + must_match, + } +} + +fn too_many(count: usize, max: usize) -> String { + p(&format!( + "The expression contains too many conditions; number of conditions: {count}, \ + maximum: {max}" + )) +} + +#[test] +fn each_comparator_is_recorded_as_written_on_either_side() { + use Operator::{Eq, Ge, Gt, Le, Lt, Ne}; + for (symbol, operator) in [ + ("=", Eq), + ("<>", Ne), + ("<", Lt), + ("<=", Le), + (">", Gt), + (">=", Ge), + ] { + for expr in [format!("a {symbol} :n"), format!(":n {symbol} a")] { + let filter = parse_with(&expr, 50).unwrap(); + assert_eq!( + filter.conditions(), + [cond("a", operator, [n("5")], true)], + "{expr}" + ); + } + } +} + +#[test] +fn each_condition_is_recorded_with_its_position() { + use Operator::{Between, Eq, Exists, Gt, In, NotExists}; + let (us, ca, five, ten) = (s("US"), s("CA"), n("5"), n("10")); + let cases: Vec<(&str, Vec)> = vec![ + ( + "a = :s AND (b > :n OR c IN (:s, :s2))", + vec![ + cond("a", Eq, [us.clone()], true), + cond("b", Gt, [five.clone()], false), + cond("c", In, [us.clone(), ca.clone()], false), + ], + ), + ( + "a = :s AND b = :n AND c = :s", + vec![ + cond("a", Eq, [us.clone()], true), + cond("b", Eq, [five.clone()], true), + cond("c", Eq, [us.clone()], true), + ], + ), + // AND binds tighter than OR, so nothing here must match + ( + "a = :s AND b = :n OR c = :s", + vec![ + cond("a", Eq, [us.clone()], false), + cond("b", Eq, [five.clone()], false), + cond("c", Eq, [us.clone()], false), + ], + ), + ("NOT a = :s", vec![cond("a", Eq, [us.clone()], false)]), + ("NOT NOT (a = :s)", vec![cond("a", Eq, [us.clone()], false)]), + ("a IN (:s)", vec![cond("a", In, [us.clone()], true)]), + ( + "a BETWEEN :n AND :n2", + vec![cond("a", Between, [five.clone(), ten.clone()], true)], + ), + ( + "a = :s AND NOT b BETWEEN :n AND :n2", + vec![ + cond("a", Eq, [us.clone()], true), + cond("b", Between, [five.clone(), ten.clone()], false), + ], + ), + ( + "attribute_exists(a) AND NOT attribute_not_exists(b)", + vec![ + cond("a", Exists, Vec::new(), true), + cond("b", NotExists, Vec::new(), false), + ], + ), + // a #name is recorded as the attribute it names + ( + ":s = #x AND b = :n", + vec![ + cond("a", Eq, [us.clone()], true), + cond("b", Eq, [five.clone()], true), + ], + ), + ]; + for (expr, expected) in cases { + assert_eq!( + parse_with(expr, 50).unwrap().conditions(), + expected, + "{expr}" + ); + } +} + +#[test] +fn the_condition_limit_counts_the_whole_expression() { + assert_eq!(outcome_with(&and_chain(50), 50), OK); + assert_eq!(outcome_with(&and_chain(51), 50), too_many(51, 50)); + assert_eq!(outcome_with(&and_chain(52), 50), too_many(52, 50)); + assert_eq!(outcome_with(&and_chain(60), 50), too_many(60, 50)); +} + +#[test] +fn comparisons_between_in_and_functions_count_one_each() { + // conditions on one attribute count too + assert_outcomes( + 3, + [ + ("a > :n AND a < :n2 AND b = :s", OK.to_owned()), + ("a > :n AND a < :n2 AND a <> :n AND b = :s", too_many(4, 3)), + ("a BETWEEN :n AND :n2 AND b = :s AND c = :s", OK.to_owned()), + ( + "a BETWEEN :n AND :n2 AND b = :s AND c = :s AND d = :s", + too_many(4, 3), + ), + ( + "a IN (:s, :s2, :s) AND (attribute_exists(b) OR NOT c = :s)", + OK.to_owned(), + ), + ( + "a IN (:s, :s2, :s) AND (attribute_exists(b) OR NOT c = :s) AND d = :s", + too_many(4, 3), + ), + // conditions past the limit are counted, a BETWEEN among them + ( + "a IN (:s, :s2, :s) AND (attribute_exists(b) OR NOT c = :s) AND d = :s AND \ + (e IN (:s) OR NOT f BETWEEN :n AND :n2)", + too_many(6, 3), + ), + // the condition that crosses the limit is checked first + ( + "a > :n AND a < :n2 AND b = :s AND c = d", + p( + "Invalid condition in SearchConditionExpression: Multiple attribute names \ + used in one condition", + ), + ), + ], + ); + // a full IN list still counts one + assert_eq!(outcome_with(&in_list(100), 1), OK); +} + +/// 50 conditions, with a HASH condition first, in the shapes of a search over +/// 18 Number inline filters. +fn conditions_with(count: usize, at: usize, shape: &str) -> String { + let mut parts = vec!["h = :s".to_owned()]; + for i in 1..count { + let f = format!("f{:02}", i % 18); + parts.push(if i + 1 == at { + shape.replace("{f}", &f) + } else { + format!("{f} > :n") + }); + } + parts.join(" AND ") +} + +#[test] +fn the_limit_with_a_hash_condition_and_mixed_shapes() { + assert_eq!(outcome_with(&conditions_with(50, 0, ""), 50), OK); + assert_eq!( + outcome_with(&conditions_with(51, 0, ""), 50), + too_many(51, 50) + ); + // an OR group of 50 after the HASH condition is 51 + let ors = (0..50) + .map(|i| format!("f{:02} > :n", i % 18)) + .collect::>() + .join(" OR "); + assert_eq!( + outcome_with(&format!("h = :s AND ({ors})"), 50), + too_many(51, 50) + ); + // one IN of 100 values among 50 conditions + let with_in = conditions_with(50, 2, &format!("{{f}} IN ({})", vec![":n"; 100].join(", "))); + assert_eq!(outcome_with(&with_in, 50), OK); + // NOT adds no condition + let nots = (1..50) + .map(|_| "NOT f00 = :n".to_owned()) + .collect::>() + .join(" AND "); + assert_eq!(outcome_with(&format!("h = :s AND {nots}"), 50), OK); + // a BETWEEN counts one, at the 10th, the 50th or past the limit + let between = "{f} BETWEEN :n AND :n2"; + assert_eq!(outcome_with(&conditions_with(50, 10, between), 50), OK); + assert_eq!(outcome_with(&conditions_with(50, 50, between), 50), OK); + assert_eq!( + outcome_with(&conditions_with(51, 51, between), 50), + too_many(51, 50) + ); + // an unsupported function before the limit gets its own message + let early = conditions_with(51, 2, "begins_with({f}, :s)"); + assert_eq!( + outcome_with(&early, 50), + p("The function is not allowed in a search condition; function: begins_with") + ); +} diff --git a/crates/core/src/expression/search_filter/tests_schema.rs b/crates/core/src/expression/search_filter/tests_schema.rs new file mode 100644 index 000000000..7b2c561a3 --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_schema.rs @@ -0,0 +1,431 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The search condition against the index search schema. +//! +//! Not yet measured against the live service: every expected message here is +//! a prediction, and a live run confirms or corrects it. + +use std::collections::HashMap; + +use super::parse_search_filter; +use super::tests_support::{OK, message, n, p, s, used_values}; +use crate::types::{ + AttributeDefinition, AttributeValue, ScalarAttributeType, SearchSchemaElement, + SearchSchemaElementType, +}; + +const NOT_MUST_MATCH: &str = "SearchConditionExpression must use = on the HASH attribute, not \ + inside OR or NOT; HASH attribute: Category"; +const MORE_THAN_ONCE: &str = "SearchConditionExpression must contain only one condition on \ + the HASH attribute; to search more than one HASH value, make one \ + SearchVectors call for each value"; +const HASH_MISSING: &str = + "SearchConditionExpression must have all HASH attributes in configured SearchSchema"; + +fn not_in_schema(attribute: &str) -> String { + format!( + "SearchConditionExpression must not contain any attributes that is not in SearchSchema. \ + Invalid attribute: {attribute}" + ) +} + +fn number_only(operator: &str, attribute: &str, attribute_type: &str) -> String { + format!( + "SearchConditionExpression allows this operator only on Number (N) attributes; \ + operator: {operator}, attribute: {attribute}, attribute type: {attribute_type}" + ) +} + +fn wrong_type(attribute: &str, given: &str, declared: &str) -> String { + format!( + "Type of '{attribute}' attribute in SearchConditionExpression ({given}) does not match \ + type in search schema ({declared})" + ) +} + +struct Index { + schema: Vec, + definitions: Vec, +} + +/// `(name, type, is_hash)` for each search schema element. +fn index(elements: &[(&str, ScalarAttributeType, bool)]) -> Index { + Index { + schema: elements + .iter() + .map(|(name, _, hash)| SearchSchemaElement { + attribute_name: (*name).to_owned(), + element_type: if *hash { + SearchSchemaElementType::Hash + } else { + SearchSchemaElementType::InlineFilter + }, + }) + .collect(), + definitions: elements + .iter() + .map(|(name, t, _)| AttributeDefinition { + attribute_name: (*name).to_owned(), + attribute_type: *t, + }) + .collect(), + } +} + +use ScalarAttributeType::{B, N, S}; + +/// HASH `Category` (S); `Country` (S), `ProductCount` (N), `Thumbnail` (B). +fn with_hash() -> Index { + index(&[ + ("Category", S, true), + ("Country", S, false), + ("ProductCount", N, false), + ("Thumbnail", B, false), + ]) +} + +/// `Country` (S) and `ProductCount` (N), no HASH. +fn without_hash() -> Index { + index(&[("Country", S, false), ("ProductCount", N, false)]) +} + +fn values() -> HashMap { + [ + (":s", s("Electronics")), + (":other", s("Books")), + (":n", n("5")), + (":hi", n("10")), + (":b", AttributeValue::B(b"hi".to_vec())), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect() +} + +fn outcome(index: &Index, expr: &str, all: &HashMap) -> String { + let names: HashMap = [ + ("#country", "Country"), + ("#category", "Category"), + ("#c", "Category"), + ("#u", "Color"), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + let used = used_values(expr, all); + match parse_search_filter(expr, Some(&names), Some(&used), 50).and_then(|filter| { + filter + .validate_against_schema(Some(&index.schema), &index.definitions) + .map(|_| ()) + }) { + Ok(()) => OK.to_owned(), + Err(e) => message(e), + } +} + +fn assert_all(index: &Index, all: &HashMap, cases: &[(&str, &str)]) { + let mismatches: Vec = cases + .iter() + .filter_map(|(expr, expected)| { + let actual = outcome(index, expr, all); + (actual != *expected) + .then(|| format!("{expr:?}: expected {expected:?}, got {actual:?}")) + }) + .collect(); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +#[test] +fn the_hash_must_be_one_must_match_equals() { + assert_all( + &with_hash(), + &values(), + &[ + ("Category <> :s", NOT_MUST_MATCH), + ("Category > :s", NOT_MUST_MATCH), + (":s <= Category", NOT_MUST_MATCH), + ("Category BETWEEN :other AND :s", NOT_MUST_MATCH), + ("Category = :s AND Category > :other", NOT_MUST_MATCH), + ("Category > :other AND Category = :s", NOT_MUST_MATCH), + ("Category = :s AND Category IN (:s, :other)", NOT_MUST_MATCH), + ( + "Category = :s AND attribute_exists(Category)", + NOT_MUST_MATCH, + ), + ( + "Category = :s AND Category BETWEEN :other AND :s", + NOT_MUST_MATCH, + ), + ("Category = :s AND Category = :other", MORE_THAN_ONCE), + ("Category = :s AND Category = :s", MORE_THAN_ONCE), + ("ProductCount > :n", HASH_MISSING), + ("Country = :s AND ProductCount > :n", HASH_MISSING), + // the HASH checks run before the per-condition checks + ("Color = :s AND Category > :s", NOT_MUST_MATCH), + ( + "Color = :s AND Category = :s AND Category = :other", + MORE_THAN_ONCE, + ), + ("Color > :n", HASH_MISSING), + ("Category = :s OR Country = :s", NOT_MUST_MATCH), + ("ProductCount > :n OR Category = :s", NOT_MUST_MATCH), + ("NOT (Category = :s)", NOT_MUST_MATCH), + ("NOT NOT (Category = :s)", NOT_MUST_MATCH), + ("Category IN (:s, :other)", NOT_MUST_MATCH), + ("Category IN (:s)", NOT_MUST_MATCH), + ("NOT Category IN (:s, :other)", NOT_MUST_MATCH), + ("attribute_exists(Category)", NOT_MUST_MATCH), + ("attribute_not_exists(Category)", NOT_MUST_MATCH), + ( + "(Category = :s AND ProductCount > :n) OR (Category = :other AND ProductCount < :hi)", + NOT_MUST_MATCH, + ), + ( + "(Category = :s AND Country = :s) OR (Category = :s AND ProductCount > :n)", + NOT_MUST_MATCH, + ), + ( + "Category = :s AND Country = :s OR ProductCount > :n", + NOT_MUST_MATCH, + ), + ( + "Category = :s AND (Category = :s OR ProductCount > :n)", + NOT_MUST_MATCH, + ), + // a #name reports the attribute it names + ("#c <> :s", NOT_MUST_MATCH), + ], + ); +} + +#[test] +fn ordering_needs_a_number_attribute() { + let mut cases: Vec<(String, String)> = Vec::new(); + for op in ["<", "<=", ">", ">="] { + cases.push(( + format!("Category = :s AND Country {op} :other"), + number_only(op, "Country", "S"), + )); + cases.push(( + format!("Category = :s AND :other {op} Country"), + number_only(op, "Country", "S"), + )); + cases.push(( + format!("Category = :s AND Thumbnail {op} :b"), + number_only(op, "Thumbnail", "B"), + )); + } + for (expr, expected) in [ + ( + "Category = :s AND Country BETWEEN :other AND :s", + number_only("BETWEEN", "Country", "S"), + ), + ( + "Category = :s AND Thumbnail BETWEEN :b AND :b", + number_only("BETWEEN", "Thumbnail", "B"), + ), + // the operator is checked before the value type + ( + "Category = :s AND Country > :n", + number_only(">", "Country", "S"), + ), + ( + "Category = :s AND Country BETWEEN :n AND :hi", + number_only("BETWEEN", "Country", "S"), + ), + ("Category = :s AND Color > :n", not_in_schema("Color")), + ( + "Category = :s AND ProductCount > :s", + wrong_type("ProductCount", "S", "N"), + ), + ( + "Category = :s AND ProductCount BETWEEN :other AND :s", + wrong_type("ProductCount", "S", "N"), + ), + // written order decides between two conditions + ( + "Category = :s AND Country > :s AND Color = :s", + number_only(">", "Country", "S"), + ), + ( + "Category = :s AND Color = :s AND Country > :s", + not_in_schema("Color"), + ), + ( + "Category = :s AND (ProductCount > :n OR Country > :other)", + number_only(">", "Country", "S"), + ), + ( + "Category = :s AND NOT (Thumbnail > :b)", + number_only(">", "Thumbnail", "B"), + ), + // <> is not an ordering operator + ("Category = :s AND Country <> :other", OK.to_owned()), + ("Category = :s AND Thumbnail <> :b", OK.to_owned()), + ] { + cases.push((expr.to_owned(), expected)); + } + let refs: Vec<(&str, &str)> = cases + .iter() + .map(|(e, x)| (e.as_str(), x.as_str())) + .collect(); + assert_all(&with_hash(), &values(), &refs); +} + +#[test] +fn in_lists_and_functions_are_checked_against_the_schema() { + let country_n = wrong_type("Country", "N", "S"); + let count_s = wrong_type("ProductCount", "S", "N"); + let color = not_in_schema("Color"); + assert_all( + &with_hash(), + &values(), + &[ + ("Category = :s AND attribute_exists(Color)", &color), + ("Category = :s AND Color IN (:s)", &color), + ("Category = :s AND Country IN (:other, :n)", &country_n), + ("Category = :s AND NOT ProductCount IN (:n, :s)", &count_s), + ("Category = :s AND attribute_exists(ProductCount)", OK), + ("Category = :s AND attribute_not_exists(Thumbnail)", OK), + ], + ); +} + +#[test] +fn the_first_failure_in_written_order_answers() { + assert_all( + &with_hash(), + &values(), + &[ + ( + "Category = :s AND Color = :s AND ProductCount = :s", + ¬_in_schema("Color"), + ), + ( + "Category = :s AND ProductCount = :s AND Color = :s", + &wrong_type("ProductCount", "S", "N"), + ), + ("Color = :s AND ProductCount = :n", HASH_MISSING), + ( + "Category = :n AND Color = :s", + &wrong_type("Category", "N", "S"), + ), + ("Color = :s AND Category = :n", ¬_in_schema("Color")), + ], + ); +} + +#[test] +fn accepted_shapes_select_the_hash_partition() { + let index = with_hash(); + for expr in [ + "Category = :s", + "Category = :s AND ProductCount > :n", + "Category = :s AND ProductCount > :n AND ProductCount < :hi", + "ProductCount >= :n AND :hi >= ProductCount AND Category = :s", + "Category = :s AND :n <= ProductCount", + "Category = :s AND Country <> :other", + "Category = :s AND Thumbnail <> :b", + "Category = :s AND Country = :s AND Country = :other", + "Category = :s AND (Country = :s OR ProductCount > :n)", + ":s = Category AND NOT (Country = :other)", + "Category = :s AND attribute_exists(Country)", + "Category = :s AND attribute_not_exists(Thumbnail)", + "Category = :s AND Country IN (:s, :other)", + "Category = :s AND NOT Country IN (:s, :other)", + "Category = :s AND ProductCount BETWEEN :n AND :hi", + "Category = :s AND ((Country = :s AND ProductCount > :n) OR (Country = :other AND ProductCount < :hi))", + ] { + let used = used_values(expr, &values()); + let filter = parse_search_filter(expr, None, Some(&used), 50).unwrap(); + let selected = filter + .validate_against_schema(Some(&index.schema), &index.definitions) + .unwrap_or_else(|e| panic!("{expr}: {e:?}")); + assert_eq!(selected, Some(("Category", &s("Electronics"))), "{expr}"); + } +} + +#[test] +fn an_index_without_hash_searches_the_whole_index() { + let index = without_hash(); + for expr in [ + "ProductCount > :n", + "ProductCount > :n AND ProductCount < :hi", + "ProductCount BETWEEN :n AND :hi", + "Country = :s AND Country = :other", + "Country <> :s AND :n < ProductCount", + "Country = :s OR Country = :other", + "NOT Country IN (:s, :other) AND attribute_exists(ProductCount)", + ] { + let used = used_values(expr, &values()); + let filter = parse_search_filter(expr, None, Some(&used), 50).unwrap(); + let selected = filter + .validate_against_schema(Some(&index.schema), &index.definitions) + .unwrap_or_else(|e| panic!("{expr}: {e:?}")); + assert_eq!(selected, None, "{expr}"); + } +} + +/// HASH `Country` (S); `Category` and `Brand` (S); every value is `S` "USA". +#[test] +fn rules_with_a_string_only_schema() { + let index = index(&[ + ("Country", S, true), + ("Category", S, false), + ("Brand", S, false), + ]); + let all: HashMap = [":a", ":b", ":c"] + .into_iter() + .map(|k| (k.to_owned(), s("USA"))) + .collect(); + let country = "SearchConditionExpression must use = on the HASH attribute, not inside OR \ + or NOT; HASH attribute: Country"; + assert_all( + &index, + &all, + &[ + ("#country <> :c AND #category = :a", country), + ( + "#country = :a AND #country = :b AND #category = :c", + MORE_THAN_ONCE, + ), + ( + "#country = :c AND #category > :a AND #category < :b", + &number_only(">", "Category", "S"), + ), + ( + "#country = :c AND #category BETWEEN :a AND :b", + &number_only("BETWEEN", "Category", "S"), + ), + ("#country BETWEEN :a AND :b AND #category = :c", country), + ("#country = :c OR #category = :a OR #category = :b", country), + ("NOT (#country = :c) AND #category IN (:a, :b)", country), + ("#country IN (:c, :a) AND #category = :b", country), + ( + "attribute_exists(#country) AND #category IN (:c, :a, :b)", + country, + ), + ( + "#country = :c AND #category IN (:a, :b, #country)", + &p( + "The IN operator list must contain only expression attribute values (:value), \ + not attribute names", + ), + ), + ( + "#country = :c AND #category BETWEEN :a AND #country", + &p( + "The BETWEEN operator bounds must be expression attribute values (:value), \ + not attribute names", + ), + ), + ( + "#country = :c AND begins_with(#category, :a) AND #category = :b", + &p("The function is not allowed in a search condition; function: begins_with"), + ), + // a #name is reported as the attribute it names + ("#country = :c AND #u = :a", ¬_in_schema("Color")), + ], + ); +} diff --git a/crates/core/src/expression/search_filter/tests_support.rs b/crates/core/src/expression/search_filter/tests_support.rs new file mode 100644 index 000000000..80cb24abe --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_support.rs @@ -0,0 +1,126 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Fixtures shared by the search filter tests. +//! +//! None of the expected messages in these tests has been measured against the +//! live service yet. Each one is a prediction of the service's answer, and a +//! live run confirms or corrects it. + +use std::collections::HashMap; + +use super::lexer::{Kind, lex}; +use super::{SearchFilter, parse_search_filter}; +use crate::error::DynamoDbError; +use crate::types::AttributeValue; + +pub(super) const OK: &str = "Ok"; +pub(super) const PREFIX: &str = "Invalid SearchConditionExpression: "; + +pub(super) fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_owned()) +} + +pub(super) fn n(v: &str) -> AttributeValue { + AttributeValue::N(v.to_owned()) +} + +/// The values every grammar test draws from. +pub(super) fn all_values() -> HashMap { + [ + (":s", s("US")), + (":s2", s("CA")), + (":n", n("5")), + (":n2", n("10")), + (":t", AttributeValue::Bool(true)), + (":null", AttributeValue::Null), + (":ty", s("S")), + (":b", AttributeValue::B(b"hi".to_vec())), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect() +} + +pub(super) fn names() -> HashMap { + [("#x", "a"), ("#y", "year")] + .into_iter() + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect() +} + +/// The values of `all` that `expr` references, so no test trips the unused +/// value check by accident. +pub(super) fn used_values( + expr: &str, + all: &HashMap, +) -> HashMap { + lex(expr) + .iter() + .filter(|t| t.kind == Kind::ValueRef) + .filter_map(|t| { + let key = &expr[t.start..t.end]; + all.get(key).map(|v| (key.to_owned(), v.clone())) + }) + .collect() +} + +pub(super) fn parse_with(expr: &str, max: usize) -> Result { + let values = used_values(expr, &all_values()); + parse_search_filter(expr, Some(&names()), Some(&values), max) +} + +/// `Ok`, or the message of the error. +pub(super) fn outcome_with(expr: &str, max: usize) -> String { + match parse_with(expr, max) { + Ok(_) => OK.to_owned(), + Err(DynamoDbError::ValidationException(m)) => m, + Err(other) => format!("{other:?}"), + } +} + +pub(super) fn outcome(expr: &str) -> String { + outcome_with(expr, super::DEFAULT_MAX_CONDITIONS) +} + +/// Assert every `(expression, expected)` pair, reporting all mismatches. +pub(super) fn assert_outcomes, X: AsRef>( + max: usize, + cases: impl IntoIterator, +) { + let mismatches: Vec = cases + .into_iter() + .filter_map(|(expr, expected)| { + let (expr, expected) = (expr.as_ref(), expected.as_ref()); + let actual = outcome_with(expr, max); + (actual != expected).then(|| format!("{expr:?}: expected {expected:?}, got {actual:?}")) + }) + .collect(); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +/// The message with the expression prefix. +pub(super) fn p(body: &str) -> String { + format!("{PREFIX}{body}") +} + +/// `a0 = :n AND a1 = :n AND ...` with `count` comparisons. +pub(super) fn and_chain(count: usize) -> String { + (0..count) + .map(|i| format!("a{i} = :n")) + .collect::>() + .join(" AND ") +} + +/// `a IN (:s, :s, ...)` with `count` values. +pub(super) fn in_list(count: usize) -> String { + format!("a IN ({})", vec![":s"; count].join(", ")) +} + +/// The message of a `ValidationException`. +pub(super) fn message(err: DynamoDbError) -> String { + match err { + DynamoDbError::ValidationException(m) => m, + other => format!("{other:?}"), + } +} diff --git a/crates/core/src/expression/search_filter/walk.rs b/crates/core/src/expression/search_filter/walk.rs new file mode 100644 index 000000000..c29b99cbc --- /dev/null +++ b/crates/core/src/expression/search_filter/walk.rs @@ -0,0 +1,416 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The checks the condition grammar applies while it builds the tree, before +//! any search rule. +//! +//! The walk is post-order and left to right: the operands of a node are +//! checked before the node. The first failure is the answer. So in +//! `year > :t` the reserved word in the left operand is reported, not the +//! ordering of a BOOL value. + +use std::collections::HashMap; + +use super::grammar::{Call, Element, Node, Operand}; +use crate::expression::CompareOp; +use crate::expression::resolver::{attribute_type_code, number_value}; +use crate::types::AttributeValue; + +/// The most values an IN list takes. +pub(super) const MAX_IN_OPERANDS: usize = 100; +/// The most operators an expression takes. +pub(super) const MAX_OPERATORS: usize = 300; +/// The combined size limit: the expression plus every substitution it makes. +pub(super) const MAX_COMBINED_BYTES: usize = 1_048_576; + +/// The request's substitution maps, keyed as the request keys them. +pub(super) struct Maps<'a> { + pub(super) names: Option<&'a HashMap>, + pub(super) values: Option<&'a HashMap>, +} + +impl<'a> Maps<'a> { + pub(super) fn name(&self, reference: &str) -> Option<&'a str> { + self.names + .and_then(|m| m.get(reference)) + .map(String::as_str) + } + + pub(super) fn value(&self, reference: &str) -> Option<&'a AttributeValue> { + self.values.and_then(|m| m.get(reference)) + } +} + +/// Run the tree-building checks over `node`. +/// +/// # Errors +/// +/// Returns the first failure's message body, without the expression prefix. +pub(super) fn check(node: &Node, maps: &Maps<'_>) -> Result<(), String> { + match node { + Node::Or(l, r) | Node::And(l, r) => { + check(l, maps)?; + check(r, maps) + } + Node::Not(inner) => check(inner, maps), + Node::Compare { left, op, right } => { + operand(left, maps)?; + operand(right, maps)?; + if let Some(symbol) = ordering_symbol(*op) { + for side in [left, right] { + unordered_value(side, maps, symbol)?; + } + } + distinct_first_operand(compare_symbol(*op), left, [right], maps) + } + Node::Between { subject, low, high } => { + for o in [subject, low, high] { + operand(o, maps)?; + } + for o in [subject, low, high] { + unordered_value(o, maps, "BETWEEN")?; + } + distinct_first_operand("BETWEEN", subject, [low, high], maps)?; + between_bounds(low, high, maps) + } + Node::In { subject, list } => { + operand(subject, maps)?; + for o in list { + operand(o, maps)?; + } + if list.len() > MAX_IN_OPERANDS { + return Err(format!( + "The IN operator is provided with too many operands; number of operands: {}", + list.len() + )); + } + distinct_first_operand("IN", subject, list.iter(), maps) + } + Node::Function(call) => function(call, true, maps), + } +} + +fn operand(o: &Operand, maps: &Maps<'_>) -> Result<(), String> { + match o { + Operand::Path(elements) => path(elements, maps), + Operand::Value(reference) => match maps.value(reference) { + Some(_) => Ok(()), + None => Err(format!( + "An expression attribute value used in expression is not defined; \ + attribute value: {reference}" + )), + }, + Operand::Call(call) => function(call, false, maps), + } +} + +fn path(elements: &[Element], maps: &Maps<'_>) -> Result<(), String> { + for element in elements { + let Element::Name(name) = element else { + continue; + }; + if name.starts_with('#') { + if maps.name(name).is_none() { + return Err(format!( + "An expression attribute name used in the document path is not defined; \ + attribute name: {name}" + )); + } + } else if crate::expression::reserved_words::is_reserved(name) { + return Err(format!( + "Attribute name is a reserved keyword; reserved keyword: {name}" + )); + } + } + Ok(()) +} + +/// The condition functions and the number of operands each takes. +fn arity(name: &str) -> Option { + match name { + "attribute_exists" | "attribute_not_exists" | "size" => Some(1), + "attribute_type" | "begins_with" | "contains" => Some(2), + _ => None, + } +} + +/// The types `attribute_type` accepts as its second operand, in the order the +/// service lists them. +const TYPE_NAMES: [&str; 10] = ["S", "SS", "N", "NS", "B", "BS", "BOOL", "NULL", "L", "M"]; + +/// `condition` is true when the call stands as a condition and false when it +/// is an operand. +fn function(call: &Call, condition: bool, maps: &Maps<'_>) -> Result<(), String> { + for arg in &call.args { + operand(arg, maps)?; + } + let name = call.name.as_str(); + let Some(expected) = arity(name) else { + return Err(if matches!(name, "if_not_exists" | "list_append") { + format!("The function is not allowed in a condition expression; function: {name}") + } else { + format!("Invalid function name; function: {name}") + }); + }; + if call.args.len() != expected { + return Err(format!( + "Incorrect number of operands for operator or function; operator or function: \ + {name}, number of operands: {}", + call.args.len() + )); + } + // Only size returns a value; every other function is a condition. + if condition == (name == "size") { + return Err(format!( + "The function is not allowed to be used this way in an expression; function: {name}" + )); + } + for arg in &call.args { + if let Operand::Call(inner) = arg + && inner.name != "size" + { + return Err(format!( + "The function is not allowed to be used this way in an expression; \ + function: {}", + inner.name + )); + } + } + if !matches!(call.args[0], Operand::Path(_)) { + return Err(format!( + "Operator or function requires a document path; operator or function: {name}" + )); + } + match name { + "begins_with" => { + if let Some(value) = literal(&call.args[1], maps) + && !matches!(value, AttributeValue::S(_) | AttributeValue::B(_)) + { + return Err(operand_type(name, value)); + } + } + "attribute_type" => match literal(&call.args[1], maps) { + Some(AttributeValue::S(type_name)) if TYPE_NAMES.contains(&type_name.as_str()) => {} + Some(AttributeValue::S(type_name)) => { + return Err(format!( + "Invalid attribute type name found; type: {type_name}, valid types: {{{}}}", + TYPE_NAMES.join(",") + )); + } + Some(other) => return Err(operand_type(name, other)), + None => {} + }, + _ => {} + } + if expected == 2 { + distinct_first_operand(name, &call.args[0], [&call.args[1]], maps)?; + } + Ok(()) +} + +fn literal<'a>(o: &Operand, maps: &Maps<'a>) -> Option<&'a AttributeValue> { + match o { + Operand::Value(reference) => maps.value(reference), + Operand::Path(_) | Operand::Call(_) => None, + } +} + +fn operand_type(operator: &str, value: &AttributeValue) -> String { + format!( + "Incorrect operand type for operator or function; operator or function: {operator}, \ + operand type: {}", + attribute_type_code(value) + ) +} + +fn ordering_symbol(op: CompareOp) -> Option<&'static str> { + match op { + CompareOp::Lt => Some("<"), + CompareOp::Le => Some("<="), + CompareOp::Gt => Some(">"), + CompareOp::Ge => Some(">="), + CompareOp::Eq | CompareOp::Ne => None, + } +} + +pub(super) fn compare_symbol(op: CompareOp) -> &'static str { + match op { + CompareOp::Eq => "=", + CompareOp::Ne => "<>", + other => ordering_symbol(other).unwrap_or_default(), + } +} + +/// An ordering operator takes only S, N and B values. +fn unordered_value(o: &Operand, maps: &Maps<'_>, operator: &str) -> Result<(), String> { + match literal(o, maps) { + Some(value) + if !matches!( + value, + AttributeValue::S(_) | AttributeValue::N(_) | AttributeValue::B(_) + ) => + { + Err(operand_type(operator, value)) + } + _ => Ok(()), + } +} + +/// The attribute must not be repeated among the other operands: +/// `a BETWEEN a AND :n`. +fn distinct_first_operand<'o>( + operator: &str, + first: &Operand, + rest: impl IntoIterator, + maps: &Maps<'_>, +) -> Result<(), String> { + let Operand::Path(first_path) = first else { + return Ok(()); + }; + let resolved = resolved_path(first_path, maps); + for other in rest { + if let Operand::Path(p) = other + && resolved_path(p, maps) == resolved + { + return Err(format!( + "The first operand must be distinct from the remaining operands for this \ + operator or function; operator: {operator}, first operand: [{resolved}]" + )); + } + } + Ok(()) +} + +/// A path with each `#name` resolved, elements joined with `.` and indexes +/// written `[n]`. +pub(super) fn resolved_path(elements: &[Element], maps: &Maps<'_>) -> String { + let mut out = String::new(); + for element in elements { + match element { + Element::Name(name) => { + if !out.is_empty() { + out.push('.'); + } + out.push_str(maps.name(name).unwrap_or(name)); + } + Element::Index(digits) => { + out.push('['); + out.push_str(digits); + out.push(']'); + } + } + } + out +} + +/// When both bounds are values: the same type, then the lower bound not +/// above the upper bound. +fn between_bounds(low: &Operand, high: &Operand, maps: &Maps<'_>) -> Result<(), String> { + let (Some(lo), Some(hi)) = (literal(low, maps), literal(high, maps)) else { + return Ok(()); + }; + let bounds = || { + format!( + "lower bound operand: AttributeValue: {{{}}}, upper bound operand: \ + AttributeValue: {{{}}}", + shown(lo), + shown(hi) + ) + }; + let above = match (lo, hi) { + (AttributeValue::S(l), AttributeValue::S(h)) => l > h, + (AttributeValue::B(l), AttributeValue::B(h)) => l > h, + (AttributeValue::N(l), AttributeValue::N(h)) => match (number_value(l), number_value(h)) { + (Some(l), Some(h)) => l > h, + _ => false, + }, + _ => { + return Err(format!( + "The BETWEEN operator requires same data type for lower and upper bounds; {}", + bounds() + )); + } + }; + if above { + return Err(format!( + "The BETWEEN operator requires upper bound to be greater than or equal to lower \ + bound; {}", + bounds() + )); + } + Ok(()) +} + +/// A bound as the BETWEEN messages show it: `N:5`, `S:US`, or `B:` and the +/// base64 of the bytes. +fn shown(value: &AttributeValue) -> String { + use base64::Engine as _; + match value { + AttributeValue::S(s) => format!("S:{s}"), + AttributeValue::N(n) => format!("N:{n}"), + AttributeValue::B(b) => { + format!("B:{}", base64::engine::general_purpose::STANDARD.encode(b)) + } + other => attribute_type_code(other).to_owned(), + } +} + +/// The number of operators in `node`: each AND, OR, NOT, comparison, BETWEEN, +/// IN and function is one, a function used as an operand included. +/// Parentheses are none. +pub(super) fn operators(node: &Node) -> usize { + fn in_operand(o: &Operand) -> usize { + match o { + Operand::Call(call) => 1 + call.args.iter().map(in_operand).sum::(), + Operand::Path(_) | Operand::Value(_) => 0, + } + } + match node { + Node::Or(l, r) | Node::And(l, r) => 1 + operators(l) + operators(r), + Node::Not(inner) => 1 + operators(inner), + Node::Compare { left, right, .. } => 1 + in_operand(left) + in_operand(right), + Node::Between { subject, low, high } => { + 1 + in_operand(subject) + in_operand(low) + in_operand(high) + } + Node::In { subject, list } => { + 1 + in_operand(subject) + list.iter().map(in_operand).sum::() + } + Node::Function(call) => 1 + call.args.iter().map(in_operand).sum::(), + } +} + +/// The expression's bytes plus the bytes each substitution adds, counted at +/// every use. +pub(super) fn combined_bytes(src: &str, node: &Node, maps: &Maps<'_>) -> usize { + fn in_operand(o: &Operand, maps: &Maps<'_>) -> usize { + match o { + Operand::Path(elements) => elements + .iter() + .map(|e| match e { + Element::Name(n) if n.starts_with('#') => maps.name(n).map_or(0, str::len), + Element::Name(_) | Element::Index(_) => 0, + }) + .sum(), + Operand::Value(reference) => maps + .value(reference) + .map_or(0, crate::types::attribute_value_size), + Operand::Call(call) => call.args.iter().map(|a| in_operand(a, maps)).sum(), + } + } + fn in_node(node: &Node, maps: &Maps<'_>) -> usize { + match node { + Node::Or(l, r) | Node::And(l, r) => in_node(l, maps) + in_node(r, maps), + Node::Not(inner) => in_node(inner, maps), + Node::Compare { left, right, .. } => in_operand(left, maps) + in_operand(right, maps), + Node::Between { subject, low, high } => [subject, low, high] + .into_iter() + .map(|o| in_operand(o, maps)) + .sum(), + Node::In { subject, list } => { + in_operand(subject, maps) + list.iter().map(|o| in_operand(o, maps)).sum::() + } + Node::Function(call) => call.args.iter().map(|a| in_operand(a, maps)).sum(), + } + } + src.len() + in_node(node, maps) +} diff --git a/crates/core/src/settings_keys.rs b/crates/core/src/settings_keys.rs index 27ab58054..485568cd1 100644 --- a/crates/core/src/settings_keys.rs +++ b/crates/core/src/settings_keys.rs @@ -100,6 +100,13 @@ pub const VECTOR_INDEX_MIN_CREATING_MS: &str = "vector_index_min_creating_ms"; /// Unset, nothing waits and no branch is taken. pub const VECTOR_ALLOCATION_PHASE_DELAY_MS: &str = "vector_allocation_phase_delay_ms"; +/// The accounts whose SearchVectors requests accept the extended +/// `SearchConditionExpression` grammar: `off` (the default when the row is +/// absent), `all`, or a comma-separated list of 12-digit account IDs. Read on +/// every SearchVectors request, so a change applies without a restart. +#[cfg(feature = "search-inequality-filters")] +pub const SEARCH_INEQUALITY_FILTERS: &str = "search_inequality_filters"; + /// Resolve a caller-supplied settings key to its canonical name. /// /// Accepting the old name keeps `extenddb settings set gsi_propagation_delay_ms 0` From 6506ece5b125f5945bfe36bfe7aa3e87137afec6 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 16 Nov 2026 22:05:54 -0800 Subject: [PATCH 003/101] feat(engine): serve the extended search grammar to enabled accounts The service parses a SearchVectors condition with the extended grammar: comparators other than `=`, BETWEEN, IN, OR, NOT, parentheses and functions. SearchVectors parses the condition with the extended grammar when the search_inequality_filters setting enables the caller, and otherwise runs the equality-only validator as before. The setting is read on every request from the settings store the server installs at startup, so a change takes effect without a restart; an absent, unreadable or malformed value enables no account. The HASH condition selects the partition and the whole condition becomes the backend's item filter. The parser takes the backend's vector search engine, which exists only after the vector gate passed, so a backend without vector search refuses the request before the grammar runs. The search-inequality-filters feature is declared in the engine, server, app and binary crates and is off by default. With it off, the module is an uninhabited stub, the setting is not a known key, and SearchVectors runs exactly as before. Engine tests cover the setting's values, a failing store, and the filter handed to the backend. --- crates/app/Cargo.toml | 6 + crates/bin/Cargo.toml | 4 + crates/engine/Cargo.toml | 6 + crates/engine/src/lib.rs | 3 + crates/engine/src/search_vectors.rs | 35 +++- crates/engine/src/search_vectors_extended.rs | 175 +++++++++++++++++ .../src/search_vectors_extended_tests.rs | 178 ++++++++++++++++++ crates/server/Cargo.toml | 6 + crates/server/src/management/ops_settings.rs | 10 + crates/server/src/serve.rs | 5 + 10 files changed, 422 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/search_vectors_extended.rs create mode 100644 crates/engine/src/search_vectors_extended_tests.rs diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index e9d2cf1d9..cd8cd0b63 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -18,6 +18,12 @@ homepage.workspace = true dev-mode = ["extenddb-config/dev-mode"] mongodb-test-hooks = ["extenddb-server/mongodb-test-hooks"] backup-test-hooks = ["extenddb-server/backup-test-hooks"] +# SearchVectors inequality filters: the extended SearchConditionExpression +# grammar (comparators, BETWEEN, IN, OR, NOT, attribute_exists and +# attribute_not_exists) for the accounts the `search_inequality_filters` +# runtime setting names. Off by default. Removable: with this off, the +# grammar module is not compiled and SearchVectors behaves as before. +search-inequality-filters = ["extenddb-server/search-inequality-filters"] [dependencies] extenddb-auth = { workspace = true } diff --git a/crates/bin/Cargo.toml b/crates/bin/Cargo.toml index 23a47320e..1a242aaae 100755 --- a/crates/bin/Cargo.toml +++ b/crates/bin/Cargo.toml @@ -38,6 +38,10 @@ mongodb-test-hooks = [ # fails (`main.rs` checks this at compile time). A production `sqlite` build # leaves it off. dev-mode = ["extenddb-app/dev-mode"] +# SearchVectors inequality filters: the extended SearchConditionExpression +# grammar for the accounts the `search_inequality_filters` runtime setting +# names. Off by default; with it off SearchVectors behaves as before. +search-inequality-filters = ["extenddb-app/search-inequality-filters"] [dependencies] extenddb-app = { workspace = true } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a27d59eb3..35a443ac9 100755 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -20,6 +20,12 @@ backup-test-hooks = [] # off, the three operations are not known and the server answers them with # UnknownOperationException exactly as before. partiql = ["extenddb-core/partiql"] +# SearchVectors inequality filters: the extended SearchConditionExpression +# grammar (comparators, BETWEEN, IN, OR, NOT, attribute_exists and +# attribute_not_exists) for the accounts the `search_inequality_filters` +# runtime setting names. Off by default. Removable: with this off, the +# grammar module is not compiled and SearchVectors behaves as before. +search-inequality-filters = ["extenddb-core/search-inequality-filters"] [dependencies] extenddb-auth = { workspace = true } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 061f68cbd..de3042f53 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,6 +45,7 @@ mod read_helpers; mod request_limits; mod scan; mod search_vectors; +mod search_vectors_extended; mod start_key; pub mod stream_capture; mod streams; @@ -79,6 +80,8 @@ pub use query::handle_query; pub use request_limits::check_request_item_counts; pub use scan::handle_scan; pub use search_vectors::handle_search_vectors; +#[cfg(feature = "search-inequality-filters")] +pub use search_vectors_extended::install_search_filter_settings; pub use streams::{SHARD_ITERATOR_EXPIRED_MESSAGE, ShardIteratorClass, classify_shard_iterator}; pub use streams::{ShardIterator, decode_shard_iterator, encode_shard_iterator}; pub use streams::{ diff --git a/crates/engine/src/search_vectors.rs b/crates/engine/src/search_vectors.rs index bbde25a08..cdf51cdf3 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -124,7 +124,17 @@ pub async fn handle_search_vectors( } // Structural validation of the filter expression (schema-independent). + // An account the extended grammar is enabled for gets that parser instead. + let extended = crate::search_vectors_extended::parse_request( + vector_search, + &ctx.account_id, + input.search_condition_expression.as_deref(), + input.expression_attribute_names.as_ref(), + input.expression_attribute_values.as_ref(), + ) + .await?; let conditions = match input.search_condition_expression.as_deref() { + Some(_) if extended.is_some() => Vec::new(), Some(expr) => validate_search_condition_expression( expr, input.expression_attribute_names.as_ref(), @@ -185,11 +195,24 @@ pub async fn handle_search_vectors( ))); } - let (hash_key, filters) = resolve_search_scope( - &conditions, - vector_index.search_schema.as_deref(), - &table.attribute_definitions, - )?; + let (hash_key, filters, item_filter) = match &extended { + Some(extended) => { + let (hash_key, item_filter) = crate::search_vectors_extended::resolve_scope( + extended, + vector_index.search_schema.as_deref(), + &table.attribute_definitions, + )?; + (hash_key, Vec::new(), Some(item_filter)) + } + None => { + let (hash_key, filters) = resolve_search_scope( + &conditions, + vector_index.search_schema.as_deref(), + &table.attribute_definitions, + )?; + (hash_key, filters, None) + } + }; let search_output = vector_search .search_vectors(extenddb_storage::VectorSearch { @@ -199,7 +222,7 @@ pub async fn handle_search_vectors( top_k: input.top_k, hash_key, filters: &filters, - item_filter: None, + item_filter, }) .await .map_err(storage_err_to_dynamo)?; diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs new file mode 100644 index 000000000..7ac5e8ae4 --- /dev/null +++ b/crates/engine/src/search_vectors_extended.rs @@ -0,0 +1,175 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `SearchVectors` with the extended `SearchConditionExpression` grammar. +//! +//! The handler calls [`parse_request`] and, when it returns a filter, +//! [`resolve_scope`] in place of the equality-only validator. With the +//! `search-inequality-filters` feature off, [`parse_request`] always returns +//! `None` and the handler runs exactly as it does without this module. +//! +//! With the feature on, the `search_inequality_filters` runtime setting says +//! which accounts get the grammar. It is read on every request through the +//! settings store the server installs with +//! [`install_search_filter_settings`], so a change applies without a restart. +//! Until a store is installed, no account gets the grammar. + +pub(crate) use imp::{parse_request, resolve_scope}; + +#[cfg(feature = "search-inequality-filters")] +pub use imp::install_search_filter_settings; + +#[cfg(feature = "search-inequality-filters")] +mod imp { + use std::collections::HashMap; + use std::sync::{Arc, RwLock}; + + use extenddb_core::error::DynamoDbError; + use extenddb_core::expression::search_filter::{ + DEFAULT_MAX_CONDITIONS, EnabledAccounts, SearchFilter, parse_search_filter, + }; + use extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS; + use extenddb_core::types::{AttributeDefinition, AttributeValue, Item, SearchSchemaElement}; + use extenddb_storage::error::StorageError; + use extenddb_storage::management_store::SettingsStore; + use extenddb_storage::{VectorItemFilter, VectorSearchEngine}; + + static SETTINGS: RwLock>> = RwLock::new(None); + + /// The HASH attribute and the value that selects its partition, and the + /// filter the backend applies to each candidate. + pub(crate) type Scope<'a> = ( + Option<(&'a str, &'a AttributeValue)>, + Arc, + ); + + /// Read the `search_inequality_filters` setting from `store` on every + /// SearchVectors request. The server calls this once at startup. + pub fn install_search_filter_settings(store: Arc) { + if let Ok(mut slot) = SETTINGS.write() { + *slot = Some(store); + } + } + + /// The accounts the setting enables. An absent, unreadable or malformed + /// value enables none, so a fault never widens the grammar. + async fn enabled_accounts() -> EnabledAccounts { + let store = SETTINGS.read().ok().and_then(|slot| slot.clone()); + let Some(store) = store else { + return EnabledAccounts::Off; + }; + match store.get_setting(SEARCH_INEQUALITY_FILTERS).await { + Ok(Some(value)) => EnabledAccounts::parse(&value).unwrap_or_else(|reason| { + tracing::warn!("{SEARCH_INEQUALITY_FILTERS} = {value:?} ignored: {reason}"); + EnabledAccounts::Off + }), + Ok(None) => EnabledAccounts::Off, + Err(e) => { + tracing::warn!("{SEARCH_INEQUALITY_FILTERS} could not be read: {e:?}"); + EnabledAccounts::Off + } + } + } + + /// A search condition parsed with the extended grammar. + pub(crate) struct Extended(Arc); + + /// Parse the request's search condition with the extended grammar when + /// the setting enables it for the caller. `None` when it does not, or when + /// the request has no search condition; the handler then runs its + /// equality-only validator. + /// + /// Taking the backend's vector search engine means the grammar is only + /// parsed once the backend has been found to serve vector search: a + /// backend without it refuses the request before this runs. + /// + /// # Errors + /// + /// Returns the `ValidationException` of the first failed check. + pub(crate) async fn parse_request( + _served_by: &dyn VectorSearchEngine, + account_id: &str, + expr: Option<&str>, + names: Option<&HashMap>, + values: Option<&HashMap>, + ) -> Result, DynamoDbError> { + let Some(expr) = expr else { + return Ok(None); + }; + // Cross-account access is refused before dispatch, so the caller is + // the table owner. + if !enabled_accounts().await.enabled_for(account_id, None) { + return Ok(None); + } + parse_search_filter(expr, names, values, DEFAULT_MAX_CONDITIONS) + .map(|filter| Some(Extended(Arc::new(filter)))) + } + + /// The partition the HASH condition selects and the filter the backend + /// applies to each candidate. + /// + /// # Errors + /// + /// Returns the `ValidationException` of the first failed schema check. + pub(crate) fn resolve_scope<'a>( + extended: &'a Extended, + schema: Option<&[SearchSchemaElement]>, + definitions: &[AttributeDefinition], + ) -> Result, DynamoDbError> { + let hash_key = extended.0.validate_against_schema(schema, definitions)?; + Ok((hash_key, Arc::new(Matcher(Arc::clone(&extended.0))))) + } + + struct Matcher(Arc); + + impl VectorItemFilter for Matcher { + fn matches(&self, item: &Item) -> Result { + self.0 + .matches(item) + .map_err(|e| StorageError::Internal(format!("search condition: {e}"))) + } + } +} + +#[cfg(all(test, feature = "search-inequality-filters"))] +#[path = "search_vectors_extended_tests.rs"] +mod tests; + +#[cfg(not(feature = "search-inequality-filters"))] +mod imp { + use std::collections::HashMap; + use std::sync::Arc; + + use extenddb_core::error::DynamoDbError; + use extenddb_core::types::{AttributeDefinition, AttributeValue, SearchSchemaElement}; + use extenddb_storage::{VectorItemFilter, VectorSearchEngine}; + + /// The HASH attribute and the value that selects its partition, and the + /// filter the backend applies to each candidate. + pub(crate) type Scope<'a> = ( + Option<(&'a str, &'a AttributeValue)>, + Arc, + ); + + /// No value exists: without the feature no request is parsed this way. + pub(crate) enum Extended {} + + #[allow(clippy::unused_async)] + pub(crate) async fn parse_request( + _served_by: &dyn VectorSearchEngine, + _account_id: &str, + _expr: Option<&str>, + _names: Option<&HashMap>, + _values: Option<&HashMap>, + ) -> Result, DynamoDbError> { + Ok(None) + } + + pub(crate) fn resolve_scope<'a>( + extended: &'a Extended, + _schema: Option<&[SearchSchemaElement]>, + _definitions: &[AttributeDefinition], + ) -> Result, DynamoDbError> { + match *extended {} + } +} diff --git a/crates/engine/src/search_vectors_extended_tests.rs b/crates/engine/src/search_vectors_extended_tests.rs new file mode 100644 index 000000000..d0779e7ad --- /dev/null +++ b/crates/engine/src/search_vectors_extended_tests.rs @@ -0,0 +1,178 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Which requests the extended grammar parses, and the filter it hands the +//! backend. +//! +//! The settings store is process-wide, so the tests that install one hold +//! `SERIAL` for their whole run. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::types::{ + AttributeDefinition, AttributeValue, Item, ScalarAttributeType, SearchSchemaElement, + SearchSchemaElementType, +}; +use extenddb_storage::management_store::{OpError, OpResult, SettingsStore}; +use extenddb_storage::{ + BoxedFuture, VectorSearch, VectorSearchEngine, VectorSearchOutput, VectorSearchResult, +}; +use futures::future::BoxFuture; + +use super::imp::{install_search_filter_settings, parse_request, resolve_scope}; + +static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +const CALLER: &str = "111111111111"; + +/// A settings store holding one optional value for every key, or failing +/// every read. +struct Store(Mutex, ()>>); + +impl SettingsStore for Store { + fn get_setting(&self, _key: &str) -> BoxFuture<'_, OpResult>> { + let answer = self.0.lock().unwrap().clone(); + Box::pin(async move { answer.map_err(|()| OpError::Internal("unreachable".to_owned())) }) + } + + fn set_setting(&self, _key: &str, _value: &str) -> BoxFuture<'_, OpResult<()>> { + Box::pin(async { Ok(()) }) + } + + fn list_settings(&self) -> BoxFuture<'_, OpResult>> { + Box::pin(async { Ok(Vec::new()) }) + } +} + +fn install(value: Result, ()>) { + let value = value.map(|v| v.map(str::to_owned)); + install_search_filter_settings(Arc::new(Store(Mutex::new(value)))); +} + +struct Served; + +impl VectorSearchEngine for Served { + fn search_vectors(&self, _req: VectorSearch<'_>) -> BoxedFuture<'_, VectorSearchResult> { + Box::pin(async { + Ok(VectorSearchOutput { + hits: Vec::new(), + distance_function: extenddb_core::types::DistanceFunction::Cosine, + }) + }) + } +} + +fn values() -> HashMap { + [ + (":c".to_owned(), AttributeValue::S("US".to_owned())), + (":p".to_owned(), AttributeValue::N("10".to_owned())), + ] + .into() +} + +const INEQUALITY: &str = "Country = :c AND Price > :p"; + +async fn parsed(expr: Option<&str>) -> Result { + let values = values(); + parse_request(&Served, CALLER, expr, None, Some(&values)) + .await + .map(|parsed| parsed.is_some()) +} + +#[tokio::test] +async fn the_setting_selects_the_accounts() { + let _serial = SERIAL.lock().await; + for (value, expected) in [ + (Ok(None), false), + (Ok(Some("off")), false), + (Ok(Some("all")), true), + (Ok(Some("111111111111")), true), + (Ok(Some("222222222222,111111111111")), true), + (Ok(Some("222222222222")), false), + // a value that does not parse, and a store that fails, read as off + (Ok(Some("on")), false), + (Err(()), false), + ] { + install(value); + assert_eq!( + parsed(Some(INEQUALITY)).await.unwrap(), + expected, + "{value:?}" + ); + } +} + +#[tokio::test] +async fn no_expression_is_left_to_the_equality_path() { + let _serial = SERIAL.lock().await; + install(Ok(Some("all"))); + assert!(!parsed(None).await.unwrap()); +} + +#[tokio::test] +async fn an_enabled_account_gets_the_extended_messages() { + let _serial = SERIAL.lock().await; + install(Ok(Some("all"))); + let err = parsed(Some( + "Country = :c AND Price > :p AND begins_with(Category, :c)", + )) + .await + .unwrap_err(); + let DynamoDbError::ValidationException(message) = err else { + panic!("expected ValidationException, got {err:?}"); + }; + assert_eq!( + message, + "Invalid SearchConditionExpression: The function is not allowed in a search \ + condition; function: begins_with" + ); +} + +fn item(country: &str, price: &str) -> Item { + [ + ("Country".to_owned(), AttributeValue::S(country.to_owned())), + ("Price".to_owned(), AttributeValue::N(price.to_owned())), + ] + .into() +} + +#[tokio::test] +async fn the_scope_selects_the_hash_partition_and_filters_items() { + let _serial = SERIAL.lock().await; + install(Ok(Some("all"))); + let values = values(); + let extended = parse_request(&Served, CALLER, Some(INEQUALITY), None, Some(&values)) + .await + .unwrap() + .expect("parsed with the extended grammar"); + let schema = [ + SearchSchemaElement { + attribute_name: "Country".to_owned(), + element_type: SearchSchemaElementType::Hash, + }, + SearchSchemaElement { + attribute_name: "Price".to_owned(), + element_type: SearchSchemaElementType::InlineFilter, + }, + ]; + let definitions = [ + AttributeDefinition { + attribute_name: "Country".to_owned(), + attribute_type: ScalarAttributeType::S, + }, + AttributeDefinition { + attribute_name: "Price".to_owned(), + attribute_type: ScalarAttributeType::N, + }, + ]; + let (hash_key, filter) = resolve_scope(&extended, Some(&schema), &definitions).unwrap(); + assert_eq!( + hash_key, + Some(("Country", &AttributeValue::S("US".to_owned()))) + ); + assert!(filter.matches(&item("US", "11")).unwrap()); + assert!(!filter.matches(&item("US", "10")).unwrap()); + assert!(!filter.matches(&item("CA", "11")).unwrap()); +} diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index d0d7a7410..1d23b6222 100755 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -21,6 +21,12 @@ mongodb-test-hooks = [] # `extenddb-storage/test-hooks` arms them in whichever backend the build # selects without naming a backend crate here (the server depends on none). backup-test-hooks = ["extenddb-engine/backup-test-hooks", "extenddb-storage/test-hooks"] +# SearchVectors inequality filters: the extended SearchConditionExpression +# grammar (comparators, BETWEEN, IN, OR, NOT, attribute_exists and +# attribute_not_exists) for the accounts the `search_inequality_filters` +# runtime setting names. Off by default. Removable: with this off, the +# grammar module is not compiled and SearchVectors behaves as before. +search-inequality-filters = ["extenddb-core/search-inequality-filters", "extenddb-engine/search-inequality-filters"] [dependencies] extenddb-cache = { workspace = true } diff --git a/crates/server/src/management/ops_settings.rs b/crates/server/src/management/ops_settings.rs index 82cd8962b..407593f7e 100755 --- a/crates/server/src/management/ops_settings.rs +++ b/crates/server/src/management/ops_settings.rs @@ -46,8 +46,18 @@ pub const KNOWN_KEYS: &[(&str, Validator)] = &[ extenddb_core::settings_keys::VECTOR_ALLOCATION_PHASE_DELAY_MS, validate_backfill_batch_delay_ms, ), + #[cfg(feature = "search-inequality-filters")] + ( + extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS, + validate_search_inequality_filters, + ), ]; +#[cfg(feature = "search-inequality-filters")] +fn validate_search_inequality_filters(value: &str) -> Result<(), &'static str> { + extenddb_core::expression::search_filter::EnabledAccounts::parse(value).map(|_| ()) +} + /// Read-only keys that cannot be changed via the settings API. pub const READONLY_KEYS: &[&str] = &[ "catalog_version", diff --git a/crates/server/src/serve.rs b/crates/server/src/serve.rs index 788593630..48832a263 100644 --- a/crates/server/src/serve.rs +++ b/crates/server/src/serve.rs @@ -734,6 +734,11 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { .flatten() .map_or(config_throttling, |v| v == "true"); + // SearchVectors reads the `search_inequality_filters` setting from this + // store on every request, so a change applies without a restart. + #[cfg(feature = "search-inequality-filters")] + extenddb_engine::install_search_filter_settings(catalog_store.clone()); + let throttle = Arc::new(extenddb_core::throttle::ThrottleManager::new( limits.per_account_max_rcu, limits.per_account_max_wcu, From a3402e221d8d4285aa245d3eaf08ab5a0e7ef4f1 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 16 Nov 2026 22:05:54 -0800 Subject: [PATCH 004/101] test(storage): run the extended search grammar on SQLite and PostgreSQL A vector search with a condition must rank only the items that satisfy it, so the TopK cut applies after the filter. Both backends gain a test-only search-inequality-filters feature. The SQLite test and the PostgreSQL integration test parse conditions with the extended grammar and search a table whose index has a HASH and a Number inline filter: a range with TopK 2 returns the two nearest matching items, not the two nearest, and the HASH value scopes the search. The cases for a missing attribute under <> and NOT, and for 1E2 against 100, follow the FilterExpression semantics and are not yet measured against the live service. The PostgreSQL test uses one database pair, created on first use and kept, and deletes its table when it passes. --- crates/storage-postgres/Cargo.toml | 4 + .../tests/vector_search_filter.rs | 339 ++++++++++++++++++ crates/storage-sqlite/Cargo.toml | 4 + crates/storage-sqlite/src/lib.rs | 2 + .../storage-sqlite/src/vector_filter_tests.rs | 233 ++++++++++++ 5 files changed, 582 insertions(+) create mode 100644 crates/storage-postgres/tests/vector_search_filter.rs create mode 100644 crates/storage-sqlite/src/vector_filter_tests.rs diff --git a/crates/storage-postgres/Cargo.toml b/crates/storage-postgres/Cargo.toml index fda1a04b6..5544ee9e8 100755 --- a/crates/storage-postgres/Cargo.toml +++ b/crates/storage-postgres/Cargo.toml @@ -18,6 +18,10 @@ test-hooks = ["extenddb-storage/test-hooks"] # and the registration with another keepalive interval, the serving # session's settings, and the post-check's definitions. test-util = ["extenddb-storage/test-util"] +# The SearchVectors inequality filter tests, which evaluate the extended +# grammar on this backend. Production builds do not need it: the backend +# applies whatever filter the engine hands it. +search-inequality-filters = ["extenddb-core/search-inequality-filters"] [dev-dependencies] # The storage-level vector control-plane tests drive the engine directly against diff --git a/crates/storage-postgres/tests/vector_search_filter.rs b/crates/storage-postgres/tests/vector_search_filter.rs new file mode 100644 index 000000000..3b0c4fd8e --- /dev/null +++ b/crates/storage-postgres/tests/vector_search_filter.rs @@ -0,0 +1,339 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! A vector search with a search condition parsed by the extended grammar, +//! on PostgreSQL. +//! +//! The backend streams the rows in score order and keeps the first `top_k` +//! that satisfy the condition, so `top_k` counts matching items only. The +//! match semantics are the FilterExpression ones; the cases that turn on a +//! missing attribute or a number written two ways are not yet measured +//! against the live service. +//! +//! Needs `EXTENDDB_TEST_PG_CONNECTION_STRING`, a base URL with no database, +//! for a role that may create databases and the pgvector extension. Without +//! it the tests report a skip and pass. The tests use one database pair, +//! `ineq_vf_catalog` and `ineq_vf_data`, created on first use and kept, and a +//! table of their own that they delete when they pass. + +#![cfg(feature = "search-inequality-filters")] + +use std::collections::HashMap; +use std::sync::Arc; + +use extenddb_core::expression::ExpressionMaps; +use extenddb_core::expression::search_filter::{SearchFilter, parse_search_filter}; +use extenddb_core::types::{AttributeValue, Item, TableKeyInfo}; +use extenddb_storage::error::StorageError; +use extenddb_storage::migrations::Runner; +use extenddb_storage::{ + DataEngine, TableEngine, VectorItemFilter, VectorSearch, VectorSearchEngine, +}; +use extenddb_storage_postgres::migrations::{ + PostgresMigrations, PostgresTarget, try_create_vector_extension, +}; +use extenddb_storage_postgres::{PostgresConfig, PostgresEngine}; +use serde_json::json; +use sqlx::postgres::PgPoolOptions; + +const ACCOUNT: &str = "123456789012"; +const CATALOG: &str = "ineq_vf_catalog"; +const DATA: &str = "ineq_vf_data"; + +static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +struct Matcher(SearchFilter); + +impl VectorItemFilter for Matcher { + fn matches(&self, item: &Item) -> Result { + self.0 + .matches(item) + .map_err(|e| StorageError::Internal(format!("{e:?}"))) + } +} + +fn base() -> Option { + let conn = std::env::var("EXTENDDB_TEST_PG_CONNECTION_STRING").unwrap_or_default(); + if conn.trim().is_empty() { + eprintln!("SKIP: EXTENDDB_TEST_PG_CONNECTION_STRING is not set"); + return None; + } + Some(conn.trim_end_matches('/').to_owned()) +} + +/// The engine on the database pair, migrated, with a fresh table `name` +/// whose index has HASH `Country` (S) and inline filter `Price` (N). +async fn fixture(base: &str, name: &str) -> Option<(PostgresEngine, TableKeyInfo)> { + let admin = PgPoolOptions::new() + .max_connections(1) + .connect(&format!("{base}/postgres")) + .await + .expect("connect to the server"); + for db in [CATALOG, DATA] { + let exists: bool = + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pg_database WHERE datname = $1)") + .bind(db) + .fetch_one(&admin) + .await + .expect("look up the database"); + if !exists { + sqlx::query(&format!("CREATE DATABASE \"{db}\"")) + .execute(&admin) + .await + .expect("create the database"); + } + } + admin.close().await; + let (catalog_url, data_url) = (format!("{base}/{CATALOG}"), format!("{base}/{DATA}")); + let line = try_create_vector_extension(&data_url.parse().expect("a URL"), None).await; + if !line.starts_with("pgvector available") { + eprintln!("SKIP: {line}"); + return None; + } + let target = PostgresTarget::new(catalog_url.parse().expect("a URL"), DATA) + .with_data_connection_row(&data_url); + let runner = PostgresMigrations::open_unlocked(&target) + .await + .expect("open the migration runner"); + let report = Runner::new(&runner, "test").migrate().await; + runner.close().await; + report.expect("migrate"); + let catalog = PgPoolOptions::new() + .max_connections(1) + .connect(&catalog_url) + .await + .expect("connect to the catalog"); + for key in ["control_plane_delay_seconds", "index_propagation_delay_ms"] { + sqlx::query( + "INSERT INTO settings (key, value) VALUES ($1, '0') \ + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value", + ) + .bind(key) + .execute(&catalog) + .await + .expect("write a setting"); + } + sqlx::query( + "INSERT INTO accounts (account_id, account_name) VALUES ($1, 'ineq') \ + ON CONFLICT DO NOTHING", + ) + .bind(ACCOUNT) + .execute(&catalog) + .await + .expect("seed the account"); + catalog.close().await; + let engine = PostgresEngine::new( + &PostgresConfig { + connection_string: catalog_url, + pool_size: 4, + max_item_size_bytes: 400_000, + }, + "us-east-1", + ) + .await + .expect("open the engine"); + let input = serde_json::from_value(json!({ + "TableName": name, + "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], + "AttributeDefinitions": [ + {"AttributeName": "id", "AttributeType": "S"}, + {"AttributeName": "Country", "AttributeType": "S"}, + {"AttributeName": "Price", "AttributeType": "N"} + ], + "BillingMode": "PAY_PER_REQUEST", + "VectorIndexes": [{ + "IndexName": "vix", + "Dimensions": 2, + "DistanceFunction": "COSINE", + "VectorAttribute": {"AttributeName": "emb"}, + "SearchSchema": [ + {"AttributeName": "Country", "SearchSchemaElementType": "HASH"}, + {"AttributeName": "Price", "SearchSchemaElementType": "INLINE_FILTER"} + ], + "Projection": {"ProjectionType": "ALL"} + }] + })) + .expect("input"); + engine + .create_table(ACCOUNT, input) + .await + .expect("create the table"); + let key_info = wait_active(&engine, name).await; + for (id, country, slope, price) in [ + ("n1", "US", "0", Some("5")), + ("n2", "US", "0.1", Some("10")), + ("n3", "US", "0.2", None), + ("n4", "US", "0.3", Some("1E2")), + ("n5", "US", "0.4", Some("15")), + ("c1", "CA", "0.05", Some("50")), + ] { + let mut item = Item::new(); + item.insert("id".to_owned(), AttributeValue::S(id.to_owned())); + item.insert("Country".to_owned(), AttributeValue::S(country.to_owned())); + item.insert( + "emb".to_owned(), + AttributeValue::L(vec![ + AttributeValue::N("1".to_owned()), + AttributeValue::N(slope.to_owned()), + ]), + ); + if let Some(p) = price { + item.insert("Price".to_owned(), AttributeValue::N(p.to_owned())); + } + engine + .put_item( + &key_info, + item, + false, + None, + &ExpressionMaps::default(), + None, + ) + .await + .expect("put item"); + } + Some((engine, key_info)) +} + +async fn wait_active(engine: &PostgresEngine, name: &str) -> TableKeyInfo { + for _ in 0..100 { + if let Ok(key_info) = engine.table_key_info(ACCOUNT, name).await + && key_info.vector_indexes.len() == 1 + { + let desc = engine + .describe_table( + ACCOUNT, + extenddb_core::types::DescribeTableInput { + table_name: name.to_owned(), + }, + ) + .await + .expect("describe"); + let ready = desc + .vector_indexes + .as_deref() + .unwrap_or_default() + .iter() + .all(|vi| vi.index_status.is_active()); + if ready { + return key_info; + } + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + panic!("the vector index of {name} did not become ACTIVE in 10 s"); +} + +fn values() -> HashMap { + [ + (":us", AttributeValue::S("US".to_owned())), + (":p5", AttributeValue::N("5".to_owned())), + (":p10", AttributeValue::N("10".to_owned())), + (":p100", AttributeValue::N("100".to_owned())), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect() +} + +async fn search( + engine: &PostgresEngine, + key_info: &TableKeyInfo, + expr: &str, + top_k: i64, +) -> Vec { + let used: HashMap = values() + .into_iter() + .filter(|(k, _)| { + expr.match_indices(k.as_str()).any(|(at, _)| { + !expr[at + k.len()..] + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphanumeric()) + }) + }) + .collect(); + let filter = parse_search_filter(expr, None, Some(&used), 50).expect("parse"); + let hash = filter + .validate_against_schema( + Some(key_info.vector_indexes[0].search_schema.as_slice()), + &key_info.attribute_definitions, + ) + .expect("schema") + .map(|(n, v)| (n.to_owned(), v.clone())); + let item_filter: Arc = Arc::new(Matcher(filter)); + let out = engine + .search_vectors(VectorSearch { + key_info, + index_name: "vix", + query_vector: &[1.0, 0.0], + top_k, + hash_key: hash.as_ref().map(|(n, v)| (n.as_str(), v)), + filters: &[], + item_filter: Some(item_filter), + }) + .await + .expect("search"); + out.hits + .iter() + .map(|hit| match hit.item.get("id") { + Some(AttributeValue::S(id)) => id.clone(), + other => panic!("id: {other:?}"), + }) + .collect() +} + +#[tokio::test] +async fn conditions_are_evaluated_before_the_top_k_cut() { + let Some(base) = base() else { + return; + }; + let _serial = SERIAL.lock().await; + let name = format!("vf_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]); + let Some((engine, key_info)) = fixture(&base, &name).await else { + return; + }; + // unfiltered, the two nearest would be n1 and n2 + assert_eq!( + search(&engine, &key_info, "Country = :us AND Price > :p5", 2).await, + ["n2", "n4"] + ); + assert_eq!( + search(&engine, &key_info, "Country = :us AND Price >= :p5", 10).await, + ["n1", "n2", "n4", "n5"] + ); + // not yet measured: a missing Price under <>, and 1E2 equal to 100 + assert_eq!( + search(&engine, &key_info, "Country = :us AND Price <> :p10", 10).await, + ["n1", "n3", "n4", "n5"] + ); + assert_eq!( + search( + &engine, + &key_info, + "Country = :us AND (attribute_not_exists(Price) OR Price = :p100)", + 10 + ) + .await, + ["n3", "n4"] + ); + assert_eq!( + search( + &engine, + &key_info, + "Country = :us AND NOT Price BETWEEN :p5 AND :p10", + 10 + ) + .await, + ["n3", "n4", "n5"] + ); + engine + .delete_table( + ACCOUNT, + extenddb_core::types::DeleteTableInput { + table_name: name.clone(), + }, + ) + .await + .expect("delete the table"); +} diff --git a/crates/storage-sqlite/Cargo.toml b/crates/storage-sqlite/Cargo.toml index e9a6ec2b8..d558f719d 100644 --- a/crates/storage-sqlite/Cargo.toml +++ b/crates/storage-sqlite/Cargo.toml @@ -19,6 +19,10 @@ memory = [] # Compiles the snapshot page-size setter the consistency test uses and the # shared conformance check. Production builds do not compile them. test-hooks = ["extenddb-storage/test-hooks"] +# The SearchVectors inequality filter tests, which evaluate the extended +# grammar on this backend. Production builds do not need it: the backend +# applies whatever filter the engine hands it. +search-inequality-filters = ["extenddb-core/search-inequality-filters"] [dependencies] extenddb-core = { workspace = true } diff --git a/crates/storage-sqlite/src/lib.rs b/crates/storage-sqlite/src/lib.rs index 58b08f951..c8dc360e0 100644 --- a/crates/storage-sqlite/src/lib.rs +++ b/crates/storage-sqlite/src/lib.rs @@ -55,6 +55,8 @@ mod table_engine; mod table_helpers; mod update_table; mod vector_bench; +#[cfg(all(test, feature = "search-inequality-filters"))] +mod vector_filter_tests; mod vector_search; mod warm_throughput; mod worker; diff --git a/crates/storage-sqlite/src/vector_filter_tests.rs b/crates/storage-sqlite/src/vector_filter_tests.rs new file mode 100644 index 000000000..59d660f5b --- /dev/null +++ b/crates/storage-sqlite/src/vector_filter_tests.rs @@ -0,0 +1,233 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! A vector search with a search condition parsed by the extended grammar. +//! +//! The backend applies the condition to each candidate before ranking, so +//! `top_k` counts matching items only. The match semantics are the +//! FilterExpression ones; the cases that turn on a missing attribute or a +//! number written two ways are not yet measured against the live service. + +use std::collections::HashMap; +use std::sync::Arc; + +use extenddb_core::expression::ExpressionMaps; +use extenddb_core::expression::search_filter::{SearchFilter, parse_search_filter}; +use extenddb_core::types::{AttributeValue, Item, TableKeyInfo}; +use extenddb_storage::error::StorageError; +use extenddb_storage::{VectorItemFilter, VectorSearch, VectorSearchEngine}; +use serde_json::json; + +use crate::SqliteEngine; + +const ACCOUNT: &str = "000000000000"; + +struct Matcher(SearchFilter); + +impl VectorItemFilter for Matcher { + fn matches(&self, item: &Item) -> Result { + self.0 + .matches(item) + .map_err(|e| StorageError::Internal(format!("{e:?}"))) + } +} + +/// A table whose index has HASH `Country` (S) and inline filter `Price` (N), +/// holding items at increasing distance from the query `[1, 0]`. +async fn fixture() -> (SqliteEngine, TableKeyInfo) { + let engine = SqliteEngine::new(":memory:", 1, "us-east-1", 4_096_000) + .await + .expect("engine"); + crate::migrations::apply_for_tests(&engine.pool).await; + sqlx::query("INSERT INTO accounts (account_id, account_name) VALUES (?, 'default')") + .bind(ACCOUNT) + .execute(&engine.pool) + .await + .expect("account"); + sqlx::query( + "INSERT INTO settings (key, value) VALUES ('index_propagation_delay_ms', '0') + ON CONFLICT(key) DO UPDATE SET value = '0'", + ) + .execute(&engine.pool) + .await + .expect("delay 0"); + let input = serde_json::from_value(json!({ + "TableName": "t", + "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], + "AttributeDefinitions": [ + {"AttributeName": "id", "AttributeType": "S"}, + {"AttributeName": "Country", "AttributeType": "S"}, + {"AttributeName": "Price", "AttributeType": "N"} + ], + "BillingMode": "PAY_PER_REQUEST", + "VectorIndexes": [{ + "IndexName": "vix", + "Dimensions": 2, + "DistanceFunction": "COSINE", + "VectorAttribute": {"AttributeName": "emb"}, + "SearchSchema": [ + {"AttributeName": "Country", "SearchSchemaElementType": "HASH"}, + {"AttributeName": "Price", "SearchSchemaElementType": "INLINE_FILTER"} + ], + "Projection": {"ProjectionType": "ALL"} + }] + })) + .expect("input"); + engine + .create_table_impl(ACCOUNT, input, false) + .await + .expect("create table"); + sqlx::query("UPDATE tables SET table_status = 'ACTIVE' WHERE account_id = ?") + .bind(ACCOUNT) + .execute(&engine.pool) + .await + .expect("activate"); + let key_info = engine + .fetch_table_key_info(ACCOUNT, "t") + .await + .expect("key info"); + for (id, country, slope, price) in [ + ("n1", "US", "0", Some("5")), + ("n2", "US", "0.1", Some("10")), + ("n3", "US", "0.2", None), + ("n4", "US", "0.3", Some("1E2")), + ("n5", "US", "0.4", Some("15")), + ("c1", "CA", "0.05", Some("50")), + ] { + let mut item = Item::new(); + item.insert("id".to_owned(), AttributeValue::S(id.to_owned())); + item.insert("Country".to_owned(), AttributeValue::S(country.to_owned())); + item.insert( + "emb".to_owned(), + AttributeValue::L(vec![ + AttributeValue::N("1".to_owned()), + AttributeValue::N(slope.to_owned()), + ]), + ); + if let Some(p) = price { + item.insert("Price".to_owned(), AttributeValue::N(p.to_owned())); + } + engine + .put_item_impl( + &key_info, + item, + false, + None, + &ExpressionMaps::default(), + None, + ) + .await + .expect("put item"); + } + (engine, key_info) +} + +fn values() -> HashMap { + [ + (":us", AttributeValue::S("US".to_owned())), + (":p5", AttributeValue::N("5".to_owned())), + (":p10", AttributeValue::N("10".to_owned())), + (":p100", AttributeValue::N("100".to_owned())), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect() +} + +/// The ids `expr` returns with `top_k`, nearest first. +async fn search( + engine: &SqliteEngine, + key_info: &TableKeyInfo, + expr: &str, + top_k: i64, +) -> Vec { + let all = values(); + let used: HashMap = all + .iter() + .filter(|(k, _)| { + expr.match_indices(k.as_str()).any(|(at, _)| { + !expr[at + k.len()..] + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphanumeric()) + }) + }) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + let filter = parse_search_filter(expr, None, Some(&used), 50).expect("parse"); + let schema = &key_info.vector_indexes[0].search_schema; + let definitions = &key_info.attribute_definitions; + let hash = filter + .validate_against_schema(Some(schema.as_slice()), definitions) + .expect("schema") + .map(|(name, value)| (name.to_owned(), value.clone())); + let item_filter: Arc = Arc::new(Matcher(filter)); + let out = engine + .search_vectors(VectorSearch { + key_info, + index_name: "vix", + query_vector: &[1.0, 0.0], + top_k, + hash_key: hash.as_ref().map(|(n, v)| (n.as_str(), v)), + filters: &[], + item_filter: Some(item_filter), + }) + .await + .expect("search"); + out.hits + .iter() + .map(|hit| match hit.item.get("id") { + Some(AttributeValue::S(id)) => id.clone(), + other => panic!("id: {other:?}"), + }) + .collect() +} + +#[tokio::test] +async fn top_k_counts_matching_items_only() { + let (engine, key_info) = fixture().await; + // unfiltered, the two nearest would be n1 and n2 + assert_eq!( + search(&engine, &key_info, "Country = :us AND Price > :p5", 2).await, + ["n2", "n4"] + ); +} + +#[tokio::test] +async fn the_hash_value_scopes_the_search() { + let (engine, key_info) = fixture().await; + assert_eq!( + search(&engine, &key_info, "Country = :us AND Price >= :p5", 10).await, + ["n1", "n2", "n4", "n5"] + ); +} + +/// Not yet measured: a missing Price under `<>`, and `1E2` equal to `100`. +#[tokio::test] +async fn a_missing_attribute_and_a_number_written_two_ways() { + let (engine, key_info) = fixture().await; + assert_eq!( + search(&engine, &key_info, "Country = :us AND Price <> :p10", 10).await, + ["n1", "n3", "n4", "n5"] + ); + assert_eq!( + search( + &engine, + &key_info, + "Country = :us AND (attribute_not_exists(Price) OR Price = :p100)", + 10 + ) + .await, + ["n3", "n4"] + ); + assert_eq!( + search( + &engine, + &key_info, + "Country = :us AND NOT Price BETWEEN :p5 AND :p10", + 10 + ) + .await, + ["n3", "n4", "n5"] + ); +} From e1b10cfbe3c5681fb3e0531ca337bdd940e50af7 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 16 Nov 2026 22:05:54 -0800 Subject: [PATCH 005/101] test: cover SearchVectors inequality filters over the wire The integration test turns the extended grammar on through the settings API, restores the previous value afterwards, and skips when the target answers an inequality search with the equality-only message. It covers each comparator, ordering refused on String and Binary attributes, a missing attribute, numbers compared as decimals, the HASH scope, the filter applied before TopK, OR, NOT, IN and BETWEEN, the HASH rules, the grammar rules, the schema checks in written order, and the 50 condition limit. On a backend without vector search it checks that the backend's refusal answers before the grammar runs. It passed against local servers on SQLite and on PostgreSQL. The expected responses are not yet measured against the live service. --- .../test_search_vectors_inequality_filters.py | 462 ++++++++++++++++++ 1 file changed, 462 insertions(+) create mode 100644 tests/test_search_vectors_inequality_filters.py diff --git a/tests/test_search_vectors_inequality_filters.py b/tests/test_search_vectors_inequality_filters.py new file mode 100644 index 000000000..0dbc67f8f --- /dev/null +++ b/tests/test_search_vectors_inequality_filters.py @@ -0,0 +1,462 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""SearchVectors with the extended SearchConditionExpression grammar. + +For an account the grammar is enabled for, a search condition takes ``<>``, +``<``, ``<=``, ``>``, ``>=``, BETWEEN, IN, OR, NOT, parentheses, +``attribute_exists`` and ``attribute_not_exists``, and more than one +condition on an attribute, up to 50 conditions. + +None of the expected responses here has been measured against the live +service yet. Each one is a prediction of the service's answer, and a live run +on an enabled account confirms or corrects it before these tests are relied +on. + +Against ExtendDB the module turns the grammar on for every account through the +management API, as the admin in ``EXTENDDB_ADMIN_USER`` and +``EXTENDDB_ADMIN_PASSWORD``, and restores the previous value afterwards. A +build without the feature refuses the setting. The module then probes one +inequality search, and skips when the target answers it with the +equality-only message, which is the answer of a build without the feature and +of an account the service has not enabled. + +On a backend without vector search, every SearchVectors request is refused by +the backend, the extended grammar included; ``TestBackendWithoutVectors`` +pins that. + +Tests post raw SigV4-signed JSON. Against the service, SearchVectors is sent to +the ``search-dynamodb`` host the SDKs use for it. +""" + +from __future__ import annotations + +import json +import os +import re +import time +import uuid + +import boto3 +import pytest +import requests +from botocore.auth import SigV4Auth +from botocore.awsrequest import AWSRequest + +_ENDPOINT_VAR = os.environ.get("EXTENDDB_TEST_ENDPOINT", "").strip() +_REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") +ENDPOINT = _ENDPOINT_VAR or f"https://dynamodb.{_REGION}.amazonaws.com/" +SEARCH_ENDPOINT = _ENDPOINT_VAR or f"https://search-dynamodb.{_REGION}.amazonaws.com/" +SETTING = "search_inequality_filters" + +P = "Invalid SearchConditionExpression: " +EQUALITY_ONLY = P + "Invalid comparator used in SearchConditionExpression" +NOT_SUPPORTED = "SearchVectors is not supported by this storage backend" +HASH_NOT_EQUALS = ( + "SearchConditionExpression must use = on the HASH attribute, not inside OR or " + "NOT; HASH attribute: Country" +) +HASH_TWICE = ( + "SearchConditionExpression must contain only one condition on the HASH " + "attribute; to search more than one HASH value, make one SearchVectors call " + "for each value" +) +HASH_MISSING = ( + "SearchConditionExpression must have all HASH attributes in configured SearchSchema" +) + + +def _number_only(operator: str, attribute: str, attribute_type: str) -> str: + return ( + "SearchConditionExpression allows this operator only on Number (N) " + f"attributes; operator: {operator}, attribute: {attribute}, attribute type: " + f"{attribute_type}" + ) + + +def _not_in_schema(attribute: str) -> str: + return ( + "SearchConditionExpression must not contain any attributes that is not in " + f"SearchSchema. Invalid attribute: {attribute}" + ) + + +def _wrong_type(attribute: str, given: str, declared: str) -> str: + return ( + f"Type of '{attribute}' attribute in SearchConditionExpression ({given}) does " + f"not match type in search schema ({declared})" + ) + + +def _signed_post(operation: str, body: dict) -> requests.Response: + """POST ``body`` under the DynamoDB JSON-1.0 protocol, SigV4-signed.""" + url = SEARCH_ENDPOINT if operation == "SearchVectors" else ENDPOINT + body_bytes = json.dumps(body).encode("utf-8") + headers = { + "X-Amz-Target": f"DynamoDB_20120810.{operation}", + "Content-Type": "application/x-amz-json-1.0", + } + creds = boto3.Session().get_credentials() + if creds is not None: + aws_req = AWSRequest(method="POST", url=url, data=body_bytes, headers=headers) + SigV4Auth(creds.get_frozen_credentials(), "dynamodb", _REGION).add_auth(aws_req) + headers = dict(aws_req.headers) + verify = True if not _ENDPOINT_VAR else not url.startswith("https://") + return requests.post(url, data=body_bytes, headers=headers, verify=verify, timeout=30) + + +def _message(resp: requests.Response) -> str: + payload = resp.json() + return payload.get("message", payload.get("Message", "")) + + +def _settings_api(): + """The settings URL and admin credentials, or ``None`` against the service.""" + password = os.environ.get("EXTENDDB_ADMIN_PASSWORD", "").strip() + if not _ENDPOINT_VAR or not password: + return None + user = os.environ.get("EXTENDDB_ADMIN_USER", "").strip() or "admin" + return f"{_ENDPOINT_VAR.rstrip('/')}/management/settings/{SETTING}", (user, password) + + +def _set_setting(value: str | None) -> bool: + """Write the setting; ``False`` when the target cannot take it.""" + api = _settings_api() + if api is None: + return False + url, auth = api + if value is None: + value = "off" + resp = requests.put(url, auth=auth, json={"value": value}, timeout=30, verify=False) + return resp.status_code == 200 + + +def _previous_setting() -> str | None: + api = _settings_api() + if api is None: + return None + url, auth = api + resp = requests.get(url, auth=auth, timeout=30, verify=False) + return resp.json().get("value") if resp.status_code == 200 else None + + +# id: (Country, Category, Price, Tag); None is an absent attribute. +ITEMS = { + "i1": ("US", "a", "5", "AQ=="), + "i2": ("US", "b", "10", "Ag=="), + "i3": ("US", "c", "15", None), + "i4": ("US", "a", None, None), + "i5": ("US", None, "-2.5", None), + "i6": ("US", "a", "100", None), + "i7": ("US", "b", "1E2", None), + "i8": ("CA", "a", "5", None), + "i9": ("US", "c", "99999999999999999999999999999999999999", None), + "i10": ("US", "b", "0.1", None), +} + +VALUES = { + ":us": {"S": "US"}, + ":ca": {"S": "CA"}, + ":a": {"S": "a"}, + ":b": {"S": "b"}, + ":p0": {"N": "0"}, + ":p5": {"N": "5"}, + ":p10": {"N": "10"}, + ":p15": {"N": "15"}, + ":p100": {"N": "100"}, + ":big": {"N": "99999999999999999999999999999999999998"}, + ":t1": {"B": "AQ=="}, + ":yes": {"BOOL": True}, +} + +H = "Country = :us AND " +US = {k for k, v in ITEMS.items() if v[0] == "US"} + + +def _wait_active(name: str) -> None: + deadline = time.monotonic() + (180.0 if _ENDPOINT_VAR else 1800.0) + while time.monotonic() < deadline: + resp = _signed_post("DescribeTable", {"TableName": name}) + if resp.status_code == 200: + table = resp.json()["Table"] + if table["TableStatus"] == "ACTIVE" and all( + vi.get("IndexStatus") == "ACTIVE" for vi in table.get("VectorIndexes", []) + ): + return + time.sleep(0.05 if _ENDPOINT_VAR else 10.0) + raise TimeoutError(f"table {name} did not become ACTIVE") + + +def _search(table: str, expr: str, top_k: int = 100, names=None) -> requests.Response: + used = set(re.findall(r":[A-Za-z0-9_]+", expr)) + body = { + "TableName": table, + "IndexName": "vix", + "SearchVector": [{"N": "1"}, {"N": "0"}, {"N": "0"}, {"N": "0"}], + "TopK": top_k, + "SearchConditionExpression": expr, + "ExpressionAttributeValues": {k: v for k, v in VALUES.items() if k in used}, + } + if names: + body["ExpressionAttributeNames"] = names + return _signed_post("SearchVectors", body) + + +def _ids(resp: requests.Response) -> set[str]: + assert resp.status_code == 200, resp.text + return {r["Item"]["id"]["S"] for r in resp.json()["SearchResults"]} + + +def _refused(resp: requests.Response, message: str) -> None: + assert resp.status_code == 400, resp.text + assert resp.json()["__type"].endswith("ValidationException"), resp.text + assert _message(resp) == message + + +@pytest.fixture(scope="module") +def grammar_table(): + """Table with HASH Country (S), inline filters Category (S), Price (N), Tag (B).""" + previous = _previous_setting() + managed = _set_setting("all") + name = f"extenddb-test-{uuid.uuid4().hex[:12]}" + created = False + try: + resp = _signed_post( + "CreateTable", + { + "TableName": name, + "AttributeDefinitions": [ + {"AttributeName": "id", "AttributeType": "S"}, + {"AttributeName": "Country", "AttributeType": "S"}, + {"AttributeName": "Category", "AttributeType": "S"}, + {"AttributeName": "Price", "AttributeType": "N"}, + {"AttributeName": "Tag", "AttributeType": "B"}, + ], + "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], + "BillingMode": "PAY_PER_REQUEST", + "VectorIndexes": [ + { + "IndexName": "vix", + "Dimensions": 4, + "DistanceFunction": "COSINE", + "VectorAttribute": {"AttributeName": "emb"}, + "SearchSchema": [ + {"AttributeName": "Country", "SearchSchemaElementType": "HASH"}, + {"AttributeName": "Category", "SearchSchemaElementType": "INLINE_FILTER"}, + {"AttributeName": "Price", "SearchSchemaElementType": "INLINE_FILTER"}, + {"AttributeName": "Tag", "SearchSchemaElementType": "INLINE_FILTER"}, + ], + "Projection": {"ProjectionType": "ALL"}, + } + ], + }, + ) + if resp.status_code == 400 and "not supported" in _message(resp): + pytest.skip("target backend does not support vector indexes") + assert resp.status_code == 200, resp.text + created = True + _wait_active(name) + for rank, (item_id, (country, category, price, tag)) in enumerate(ITEMS.items()): + item = { + "id": {"S": item_id}, + "Country": {"S": country}, + # distinct distances from the query, nearest first in id order + "emb": {"L": [{"N": "1"}, {"N": str(rank / 10)}, {"N": "0"}, {"N": "0"}]}, + } + if category is not None: + item["Category"] = {"S": category} + if price is not None: + item["Price"] = {"N": price} + if tag is not None: + item["Tag"] = {"B": tag} + put = _signed_post("PutItem", {"TableName": name, "Item": item}) + assert put.status_code == 200, put.text + probe = _search(name, H + "Price > :p5") + if probe.status_code == 400 and _message(probe) == EQUALITY_ONLY: + pytest.skip("the extended grammar is off for this account") + # Vector index maintenance may lag the write by the propagation delay. + deadline = time.monotonic() + 30 + while _ids(_search(name, H + "Price <> :p0")) != US: + if time.monotonic() > deadline: + raise TimeoutError("items did not reach the vector index") + time.sleep(0.1) + yield name + finally: + if created: + _signed_post("DeleteTable", {"TableName": name}) + if managed: + _set_setting(previous) + + + + +class TestOperators: + def test_each_comparator_on_a_number(self, grammar_table): + assert _ids(_search(grammar_table, H + "Price = :p10")) == {"i2"} + assert _ids(_search(grammar_table, H + "Price < :p10")) == {"i1", "i5", "i10"} + assert _ids(_search(grammar_table, H + "Price <= :p10")) == {"i1", "i2", "i5", "i10"} + assert _ids(_search(grammar_table, H + "Price > :p10")) == {"i3", "i6", "i7", "i9"} + assert _ids(_search(grammar_table, H + "Price >= :p10")) == {"i2", "i3", "i6", "i7", "i9"} + assert _ids(_search(grammar_table, H + ":p10 > Price")) == {"i1", "i5", "i10"} + + def test_ordering_on_a_string_or_binary_is_refused(self, grammar_table): + for op in ("<", "<=", ">", ">="): + _refused( + _search(grammar_table, H + f"Category {op} :a"), + _number_only(op, "Category", "S"), + ) + _refused(_search(grammar_table, H + "Tag < :t1"), _number_only("<", "Tag", "B")) + + def test_not_equal_and_equal_on_strings_and_binaries(self, grammar_table): + assert _ids(_search(grammar_table, H + "Category = :a")) == {"i1", "i4", "i6"} + assert _ids(_search(grammar_table, H + "Tag = :t1")) == {"i1"} + assert "i1" not in _ids(_search(grammar_table, H + "Tag <> :t1")) + + def test_a_range_on_one_attribute(self, grammar_table): + assert _ids(_search(grammar_table, H + "Price > :p5 AND Price < :p15")) == {"i2"} + assert _ids(_search(grammar_table, H + "Price >= :p5 AND Price = :p5")) == {"i1"} + assert _ids(_search(grammar_table, H + "Price = :p5 AND Price = :p10")) == set() + + +class TestEvaluation: + """Not yet measured: a missing attribute, ``1E2`` against ``100``, 38 digits.""" + + def test_a_missing_attribute_under_not_equal_and_not(self, grammar_table): + assert "i4" in _ids(_search(grammar_table, H + "Price <> :p10")) + assert "i4" in _ids(_search(grammar_table, H + "NOT (Price = :p10)")) + assert "i5" in _ids(_search(grammar_table, H + "Category <> :a")) + assert "i4" not in _ids(_search(grammar_table, H + "Price > :p0")) + + def test_existence_functions(self, grammar_table): + assert _ids(_search(grammar_table, H + "attribute_not_exists(Price)")) == {"i4"} + assert _ids(_search(grammar_table, H + "attribute_exists(Price)")) == US - {"i4"} + + def test_numbers_compare_as_decimals(self, grammar_table): + assert _ids(_search(grammar_table, H + "Price = :p100")) == {"i6", "i7"} + assert _ids(_search(grammar_table, H + "Price > :big")) == {"i9"} + assert _ids(_search(grammar_table, H + "Price < :p0")) == {"i5"} + assert _ids(_search(grammar_table, H + "Price > :p0 AND Price < :p5")) == {"i10"} + + def test_the_hash_value_scopes_the_search(self, grammar_table): + assert _ids(_search(grammar_table, "Country = :ca AND Price = :p5")) == {"i8"} + + def test_the_filter_applies_before_top_k(self, grammar_table): + resp = _search(grammar_table, H + "Price > :p5", top_k=2) + assert [r["Item"]["id"]["S"] for r in resp.json()["SearchResults"]] == ["i2", "i3"] + + +class TestLogic: + def test_or_not_and_parentheses(self, grammar_table): + assert _ids(_search(grammar_table, H + "(Price = :p5 OR Price = :p10)")) == {"i1", "i2"} + assert _ids(_search(grammar_table, H + "NOT NOT Price = :p5")) == {"i1"} + assert _ids( + _search(grammar_table, H + "(Category = :a OR (Price > :p5 AND NOT Price = :p15))") + ) == {"i1", "i2", "i4", "i6", "i7", "i9"} + + def test_keywords_in_lower_case(self, grammar_table): + assert "i1" in _ids( + _search(grammar_table, "Country = :us and (Price = :p5 or not Price = :p10)") + ) + + def test_in_and_between(self, grammar_table): + assert _ids(_search(grammar_table, H + "Price IN (:p5, :p10)")) == {"i1", "i2"} + assert _ids(_search(grammar_table, H + "Category IN (:a, :b)")) == { + "i1", "i2", "i4", "i6", "i7", "i10" + } + assert _ids(_search(grammar_table, H + "Price BETWEEN :p5 AND :p10")) == {"i1", "i2"} + assert _ids(_search(grammar_table, H + "Price BETWEEN :p5 AND :p5")) == {"i1"} + assert "i1" not in _ids(_search(grammar_table, H + "NOT Price BETWEEN :p5 AND :p10")) + + +class TestRefusals: + def test_hash_rules(self, grammar_table): + _refused(_search(grammar_table, "Category = :a"), HASH_MISSING) + _refused(_search(grammar_table, "Country <> :us"), HASH_NOT_EQUALS) + _refused(_search(grammar_table, "Country = :us AND Country > :ca"), HASH_NOT_EQUALS) + _refused(_search(grammar_table, "Country = :us AND Country = :ca"), HASH_TWICE) + _refused(_search(grammar_table, "Country IN (:us)"), HASH_NOT_EQUALS) + _refused(_search(grammar_table, "Country = :us OR Price = :p5"), HASH_NOT_EQUALS) + _refused(_search(grammar_table, "Country > :ca"), HASH_NOT_EQUALS) + _refused( + _search( + grammar_table, + "(Country = :us AND Price = :p5) OR (Country = :us AND Price = :p10)", + ), + HASH_NOT_EQUALS, + ) + _refused(_search(grammar_table, "Country = :p5"), _wrong_type("Country", "N", "S")) + + def test_grammar_rules(self, grammar_table): + _refused( + _search(grammar_table, H + "Category IN (:a, Price)"), + P + "The IN operator list must contain only expression attribute values " + "(:value), not attribute names", + ) + _refused( + _search(grammar_table, H + "begins_with(Category, :a)"), + P + "The function is not allowed in a search condition; function: begins_with", + ) + _refused( + _search(grammar_table, H + "attribute_exists(Info.Price)"), + P + "SearchConditionExpression cannot have conditions on nested attributes", + ) + _refused( + _search(grammar_table, H + "Price > :yes"), + P + "Incorrect operand type for operator or function; operator or " + "function: >, operand type: BOOL", + ) + _refused( + _search(grammar_table, H + "Price BETWEEN :p10 AND :p5"), + P + "The BETWEEN operator requires upper bound to be greater than or equal " + "to lower bound; lower bound operand: AttributeValue: {N:10}, upper bound " + "operand: AttributeValue: {N:5}", + ) + _refused( + _search(grammar_table, H + "Price = "), + P + 'Syntax error; token: "", near: "= "', + ) + + def test_schema_checks_in_written_order(self, grammar_table): + _refused(_search(grammar_table, H + "Color = :a AND Category > :a"), _not_in_schema("Color")) + _refused( + _search(grammar_table, H + "Category > :a AND Color = :a"), + _number_only(">", "Category", "S"), + ) + _refused( + _search(grammar_table, H + "Category > :p5"), _number_only(">", "Category", "S") + ) + _refused(_search(grammar_table, H + "Price = :a"), _wrong_type("Price", "S", "N")) + _refused( + _search(grammar_table, H + "Category IN (:a, :p5)"), + _wrong_type("Category", "N", "S"), + ) + _refused( + _search(grammar_table, H + "#c > :a", names={"#c": "Category"}), + _number_only(">", "Category", "S"), + ) + + def test_the_condition_limit(self, grammar_table): + conditions = [f"Price > :p{i % 2 * 5}" for i in range(49)] + assert _search(grammar_table, H + " AND ".join(conditions)).status_code == 200 + _refused( + _search(grammar_table, H + " AND ".join([*conditions, "Price > :p0"])), + P + "The expression contains too many conditions; number of conditions: " + "51, maximum: 50", + ) + + +class TestBackendWithoutVectors: + def test_the_backend_refuses_before_the_grammar_runs(self): + """On a backend without vector search the refusal is the backend's.""" + if not _ENDPOINT_VAR: + pytest.skip("requires EXTENDDB_TEST_ENDPOINT") + previous = _previous_setting() + managed = _set_setting("all") + try: + resp = _search(f"extenddb-test-{uuid.uuid4().hex[:12]}", H + "Price > :p5") + if resp.status_code == 400 and _message(resp) == NOT_SUPPORTED: + return + pytest.skip("target backend supports vector search") + finally: + if managed: + _set_setting(previous) From 3e2616946355ede8e2b04ddc9ee7e6d36ec3b29e Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Sat, 21 Nov 2026 17:05:08 +0000 Subject: [PATCH 006/101] fix(engine): check the SearchVectors expression maps as the service does The service checks ExpressionAttributeNames and ExpressionAttributeValues once TopK and SearchVector are valid, before it reads the projection or the search condition. An empty map is refused with "... must not be empty", names first. Each name is checked for an empty attribute name, then for a name of 65536 bytes or more, then each key for being empty, longer than 255 bytes, or not a placeholder; a too-long key reports its size in both maps. Names with neither a search condition nor a projection, and values without a search condition, are refused with "... can only be specified when using expressions". The projection is read before the search condition. Once the condition parses, a name that neither expression uses is refused with "Value provided in ExpressionAttributeNames unused in expressions", ahead of unused values and the index schema checks. ExtendDB accepted an empty map and answered the next check, or 200. It did not check the keys or the name values, accepted values and names sent without an expression, never refused an unused name, and read the projection after the search. The checks now run in that order for both search condition grammars, in a module of their own. The key messages differ from those of the other operations, so the other operations keep the shared deserializers and their messages. Verified against live DynamoDB in eu-north-1, each request twice with the same answer both times: 41 requests on check order (TopK, IndexName, SearchVector and ReturnConsumedCapacity before an empty map; the empty map before a dimension mismatch and a missing table; names before values; the projection before the condition; unused names after a condition syntax error and before unused values and the HASH check), and the 22 map and expression rows of the SearchVectors parity catalog, 14 of them measured again with no empty map in the request. Unit tests pin each message and order. --- crates/core/src/expression/mod.rs | 1 + crates/core/src/expression/search_params.rs | 206 ++++++++++++++++ .../src/expression/search_params_tests.rs | 231 ++++++++++++++++++ crates/core/src/serde_helpers.rs | 2 +- crates/engine/src/lib.rs | 1 + crates/engine/src/search_vectors.rs | 13 +- crates/engine/src/search_vectors_extended.rs | 14 +- .../src/search_vectors_extended_tests.rs | 4 +- crates/engine/src/search_vectors_params.rs | 71 ++++++ 9 files changed, 535 insertions(+), 8 deletions(-) mode change 100755 => 100644 crates/core/src/expression/mod.rs create mode 100644 crates/core/src/expression/search_params.rs create mode 100644 crates/core/src/expression/search_params_tests.rs create mode 100644 crates/engine/src/search_vectors_params.rs diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs old mode 100755 new mode 100644 index 70d8caca8..993a3ac4e --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -20,6 +20,7 @@ mod projection; mod reserved_words; mod resolver; mod search_condition; +pub mod search_params; #[cfg(feature = "search-inequality-filters")] pub mod search_filter; #[cfg(test)] diff --git a/crates/core/src/expression/search_params.rs b/crates/core/src/expression/search_params.rs new file mode 100644 index 000000000..5bb3ec056 --- /dev/null +++ b/crates/core/src/expression/search_params.rs @@ -0,0 +1,206 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The `ExpressionAttributeNames` and `ExpressionAttributeValues` checks of a +//! `SearchVectors` request. +//! +//! The service checks both maps once `TopK` and `SearchVector` are valid and +//! before it reads the projection or the search condition, so a fault here +//! answers ahead of a dimension mismatch, a missing table and any expression +//! error. In order: +//! +//! 1. the names: an empty attribute name anywhere in the map, then a name of +//! 65536 bytes or more, then an empty map, then each key (empty, longer than +//! 255 bytes, not `#` followed by letters, digits or `_`); +//! 2. the values: an empty map, then each key, as for the names with `:`; +//! 3. names with neither a search condition nor a projection, then values +//! without a search condition. +//! +//! After the expressions parse, every name must be used by the search +//! condition or the projection. That check answers ahead of the unused-values +//! check and ahead of the index schema checks. +//! +//! The key messages of this endpoint differ from those of the other +//! operations, which `serde_helpers` produces: an empty key has its own +//! message, and a key that is too long reports its size in both maps. +//! +//! Pure synchronous Rust: no async, no I/O. + +use std::collections::{BTreeSet, HashMap}; + +use crate::error::DynamoDbError; +use crate::serde_helpers::is_placeholder_ident; +use crate::types::AttributeValue; + +/// The longest key either map takes, in bytes, prefix included. +const MAX_KEY_BYTES: usize = 255; + +/// An attribute name must be shorter than this many bytes. +const NAME_LIMIT_BYTES: usize = 65536; + +const NAMES: &str = "ExpressionAttributeNames"; +const VALUES: &str = "ExpressionAttributeValues"; + +/// The start of the unused-values message of both search condition grammars. +const UNUSED_VALUES: &str = "Value provided in ExpressionAttributeValues unused in expressions"; + +fn invalid(msg: String) -> DynamoDbError { + DynamoDbError::ValidationException(msg) +} + +/// Check one map's size and keys, in the order the service checks them. +fn check_keys<'a>( + field: &str, + prefix: char, + mut keys: impl ExactSizeIterator, +) -> Result<(), DynamoDbError> { + if keys.len() == 0 { + return Err(invalid(format!("{field} must not be empty"))); + } + keys.try_for_each(|key| { + if key.is_empty() { + return Err(invalid(format!( + "{field} contains invalid key: The expression attribute map contains an empty key;" + ))); + } + if key.len() > MAX_KEY_BYTES { + return Err(invalid(format!( + "{field} contains invalid key: The expression attribute map contains a key that is \ + too long; size of key: {}", + key.len() + ))); + } + if !key.strip_prefix(prefix).is_some_and(is_placeholder_ident) { + return Err(invalid(format!( + "{field} contains invalid key: Syntax error; key: \"{key}\"" + ))); + } + Ok(()) + }) +} + +fn check_names(names: &HashMap) -> Result<(), DynamoDbError> { + if let Some((key, _)) = names.iter().find(|(_, name)| name.is_empty()) { + return Err(invalid(format!( + "{NAMES} contains invalid value: Empty attribute name for key {key}" + ))); + } + if let Some((key, _)) = names + .iter() + .find(|(_, name)| name.len() >= NAME_LIMIT_BYTES) + { + return Err(invalid(format!( + "Attribute name is too large, must be less than {NAME_LIMIT_BYTES} bytes for key {key}" + ))); + } + check_keys(NAMES, '#', names.keys()) +} + +/// Check the two maps of a `SearchVectors` request before either expression +/// is read. +/// +/// # Errors +/// +/// Returns the `ValidationException` of the first failed check, in the order +/// the module documentation gives. +pub fn check_search_maps( + names: Option<&HashMap>, + values: Option<&HashMap>, + has_condition: bool, + has_projection: bool, +) -> Result<(), DynamoDbError> { + if let Some(names) = names { + check_names(names)?; + } + if let Some(values) = values { + check_keys(VALUES, ':', values.keys())?; + } + if names.is_some() && !has_condition && !has_projection { + return Err(invalid(format!( + "{NAMES} can only be specified when using expressions" + ))); + } + if values.is_some() && !has_condition { + return Err(invalid(format!( + "{VALUES} can only be specified when using expressions" + ))); + } + Ok(()) +} + +/// Every `#name` written in `exprs`. +fn written_names<'a>(exprs: &[&'a str]) -> BTreeSet<&'a str> { + let mut found = BTreeSet::new(); + for expr in exprs { + let bytes = expr.as_bytes(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'#' { + let end = bytes[i + 1..] + .iter() + .position(|b| !(b.is_ascii_alphanumeric() || *b == b'_')) + .map_or(bytes.len(), |n| i + 1 + n); + found.insert(&expr[i..end]); + i = end.max(i + 1); + } else { + i += 1; + } + } + } + found +} + +/// Every name in `names` must be written in one of `exprs` (the search +/// condition and the projection). The unused keys are listed in sorted order. +/// +/// # Errors +/// +/// Returns the unused-names `ValidationException`. +pub fn check_unused_names( + names: Option<&HashMap>, + exprs: &[&str], +) -> Result<(), DynamoDbError> { + let Some(names) = names else { + return Ok(()); + }; + let written = written_names(exprs); + let unused: BTreeSet<&str> = names + .keys() + .map(String::as_str) + .filter(|k| !written.contains(k)) + .collect(); + if unused.is_empty() { + return Ok(()); + } + Err(invalid(format!( + "Value provided in {NAMES} unused in expressions: keys: {{{}}}", + unused.into_iter().collect::>().join(", ") + ))) +} + +/// Apply the unused-names check to the result of parsing a search condition. +/// +/// A parse failure answers first, except the unused-values failure, which +/// both grammars report last and the service reports after the unused names. +/// +/// # Errors +/// +/// Returns the parse error, or the unused-names error, as above. +pub fn with_unused_names( + parsed: Result, + names: Option<&HashMap>, + exprs: &[&str], +) -> Result { + match parsed { + Ok(parsed) => check_unused_names(names, exprs).map(|()| parsed), + Err(DynamoDbError::ValidationException(msg)) if msg.starts_with(UNUSED_VALUES) => { + check_unused_names(names, exprs)?; + Err(DynamoDbError::ValidationException(msg)) + } + Err(other) => Err(other), + } +} + +#[cfg(test)] +#[path = "search_params_tests.rs"] +mod tests; diff --git a/crates/core/src/expression/search_params_tests.rs b/crates/core/src/expression/search_params_tests.rs new file mode 100644 index 000000000..241b34875 --- /dev/null +++ b/crates/core/src/expression/search_params_tests.rs @@ -0,0 +1,231 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Each expectation is a live SearchVectors answer, measured twice in +//! eu-north-1 on 2026-11-21. + +use std::collections::HashMap; + +use super::{check_search_maps, check_unused_names, with_unused_names}; +use crate::error::DynamoDbError; +use crate::types::AttributeValue; + +fn names(pairs: &[(&str, &str)]) -> HashMap { + pairs + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect() +} + +fn values(keys: &[&str]) -> HashMap { + keys.iter() + .map(|k| ((*k).to_owned(), AttributeValue::S("x".to_owned()))) + .collect() +} + +/// Names, values, and the expected message. +type Case<'a> = ( + Option>, + HashMap, + &'a str, +); + +fn refused(result: Result<(), DynamoDbError>) -> String { + match result { + Err(DynamoDbError::ValidationException(m)) => m, + other => format!("not a ValidationException: {other:?}"), + } +} + +fn maps( + n: Option<&HashMap>, + v: Option<&HashMap>, +) -> String { + refused(check_search_maps(n, v, true, false)) +} + +#[test] +fn an_empty_map_is_refused_names_first() { + let empty_n = names(&[]); + let empty_v = values(&[]); + assert_eq!( + maps(None, Some(&empty_v)), + "ExpressionAttributeValues must not be empty" + ); + assert_eq!( + maps(Some(&empty_n), Some(&empty_v)), + "ExpressionAttributeNames must not be empty" + ); + assert_eq!( + refused(check_search_maps(None, Some(&empty_v), false, false)), + "ExpressionAttributeValues must not be empty" + ); +} + +#[test] +fn an_empty_attribute_name_answers_before_the_keys_and_the_values() { + let empty_v = values(&[]); + assert_eq!( + maps(Some(&names(&[("#c", "")])), Some(&empty_v)), + "ExpressionAttributeNames contains invalid value: Empty attribute name for key #c" + ); + assert_eq!( + maps(Some(&names(&[("#a-b", "")])), Some(&values(&[":us"]))), + "ExpressionAttributeNames contains invalid value: Empty attribute name for key #a-b" + ); +} + +#[test] +fn a_bad_name_key_answers_before_a_bad_value_key() { + assert_eq!( + maps( + Some(&names(&[("#a-b", "x")])), + Some(&values(&[":us", ":b-k"])) + ), + "ExpressionAttributeNames contains invalid key: Syntax error; key: \"#a-b\"" + ); +} + +#[test] +fn each_key_fault_has_its_own_message() { + let long_v = format!(":{}", "k".repeat(300)); + let long_n = format!("#{}", "k".repeat(300)); + let cases: Vec> = vec![ + ( + None, + values(&[":s", ":b-k"]), + "ExpressionAttributeValues contains invalid key: Syntax error; key: \":b-k\"", + ), + ( + None, + values(&[":s", ":"]), + "ExpressionAttributeValues contains invalid key: Syntax error; key: \":\"", + ), + ( + None, + values(&[":s", &long_v]), + "ExpressionAttributeValues contains invalid key: The expression attribute map \ + contains a key that is too long; size of key: 301", + ), + ( + None, + values(&[":s", ""]), + "ExpressionAttributeValues contains invalid key: The expression attribute map \ + contains an empty key;", + ), + ( + Some(names(&[("#", "x")])), + values(&[":us"]), + "ExpressionAttributeNames contains invalid key: Syntax error; key: \"#\"", + ), + ( + Some(names(&[(&long_n, "x")])), + values(&[":us"]), + "ExpressionAttributeNames contains invalid key: The expression attribute map \ + contains a key that is too long; size of key: 301", + ), + ( + Some(names(&[("", "x")])), + values(&[":us"]), + "ExpressionAttributeNames contains invalid key: The expression attribute map \ + contains an empty key;", + ), + ]; + for (n, v, expected) in cases { + assert_eq!(maps(n.as_ref(), Some(&v)), expected); + } +} + +#[test] +fn an_attribute_name_must_be_shorter_than_65536_bytes() { + let at_limit = "C".repeat(65536); + assert_eq!( + maps(Some(&names(&[("#c", &at_limit)])), Some(&values(&[":us"]))), + "Attribute name is too large, must be less than 65536 bytes for key #c" + ); + let below = "C".repeat(65535); + assert!(check_search_maps(Some(&names(&[("#c", &below)])), None, true, false).is_ok()); +} + +#[test] +fn a_map_needs_the_expression_that_reads_it() { + let n = names(&[("#p", "Price")]); + let v = values(&[":us"]); + let without = |n, v, cond, proj| refused(check_search_maps(n, v, cond, proj)); + assert_eq!( + without(Some(&n), None, false, false), + "ExpressionAttributeNames can only be specified when using expressions" + ); + assert_eq!( + without(Some(&n), Some(&v), false, false), + "ExpressionAttributeNames can only be specified when using expressions" + ); + assert_eq!( + without(None, Some(&v), false, false), + "ExpressionAttributeValues can only be specified when using expressions" + ); + assert_eq!( + without(Some(&n), Some(&v), false, true), + "ExpressionAttributeValues can only be specified when using expressions" + ); + assert!(check_search_maps(Some(&n), None, false, true).is_ok()); + assert!(check_search_maps(Some(&n), Some(&v), true, false).is_ok()); +} + +#[test] +fn a_name_is_used_by_the_condition_or_the_projection() { + let n = names(&[("#p", "Price"), ("#c", "Country")]); + assert!(check_unused_names(Some(&n), &["#c = :us", "#p"]).is_ok()); + assert!(check_unused_names(None, &["a = :s"]).is_ok()); + assert_eq!( + refused(check_unused_names(Some(&n), &["Country = :us", "Price"])), + "Value provided in ExpressionAttributeNames unused in expressions: keys: {#c, #p}" + ); + assert_eq!( + refused(check_unused_names(Some(&n), &["#c = :us", ""])), + "Value provided in ExpressionAttributeNames unused in expressions: keys: {#p}" + ); +} + +#[test] +fn unused_names_answer_after_a_parse_error_and_before_unused_values() { + let n = names(&[("#u", "x")]); + let syntax = || -> Result<(), DynamoDbError> { + Err(DynamoDbError::ValidationException( + "Invalid SearchConditionExpression: Syntax error".to_owned(), + )) + }; + let unused_values = |m: &str| -> Result<(), DynamoDbError> { + Err(DynamoDbError::ValidationException(m.to_owned())) + }; + let names_msg = "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}"; + assert_eq!( + refused(with_unused_names(syntax(), Some(&n), &["Country = = :us"])), + "Invalid SearchConditionExpression: Syntax error" + ); + assert_eq!( + refused(with_unused_names(Ok(()), Some(&n), &["Country = :us"])), + names_msg + ); + for values_msg in [ + "Value provided in ExpressionAttributeValues unused in expressions: keys: {:w}", + "Value provided in ExpressionAttributeValues unused in expressions", + ] { + assert_eq!( + refused(with_unused_names( + unused_values(values_msg), + Some(&n), + &["Country = :us"] + )), + names_msg + ); + assert_eq!( + refused(with_unused_names( + unused_values(values_msg), + None, + &["Country = :us"] + )), + values_msg + ); + } +} diff --git a/crates/core/src/serde_helpers.rs b/crates/core/src/serde_helpers.rs index 3a4ffb3cd..3f3dae411 100644 --- a/crates/core/src/serde_helpers.rs +++ b/crates/core/src/serde_helpers.rs @@ -20,7 +20,7 @@ const MAX_PLACEHOLDER_KEY_BYTES: usize = 255; /// A placeholder identifier (the text after the `#` / `:`) is one or more of /// `[A-Za-z0-9_]`. -fn is_placeholder_ident(rest: &str) -> bool { +pub(crate) fn is_placeholder_ident(rest: &str) -> bool { !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index de3042f53..d7df9944a 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -46,6 +46,7 @@ mod request_limits; mod scan; mod search_vectors; mod search_vectors_extended; +mod search_vectors_params; mod start_key; pub mod stream_capture; mod streams; diff --git a/crates/engine/src/search_vectors.rs b/crates/engine/src/search_vectors.rs index cdf51cdf3..8362f623c 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -16,7 +16,6 @@ use serde_json::Value; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ ExpressionMaps, Projection, validate_conditions_against_search_schema, - validate_search_condition_expression, }; use extenddb_core::types::{ AttributeValue, DescribeTableInput, Item, ReturnConsumedCapacity, SearchSchemaElementType, @@ -123,6 +122,14 @@ pub async fn handle_search_vectors( ))); } + crate::search_vectors_params::check( + input.expression_attribute_names.as_ref(), + input.expression_attribute_values.as_ref(), + input.search_condition_expression.as_deref(), + input.projection_expression.as_deref(), + &ctx.limits, + )?; + // Structural validation of the filter expression (schema-independent). // An account the extended grammar is enabled for gets that parser instead. let extended = crate::search_vectors_extended::parse_request( @@ -131,14 +138,16 @@ pub async fn handle_search_vectors( input.search_condition_expression.as_deref(), input.expression_attribute_names.as_ref(), input.expression_attribute_values.as_ref(), + input.projection_expression.as_deref(), ) .await?; let conditions = match input.search_condition_expression.as_deref() { Some(_) if extended.is_some() => Vec::new(), - Some(expr) => validate_search_condition_expression( + Some(expr) => crate::search_vectors_params::equality_conditions( expr, input.expression_attribute_names.as_ref(), input.expression_attribute_values.as_ref(), + input.projection_expression.as_deref(), )?, None => Vec::new(), }; diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs index 7ac5e8ae4..64023fbcf 100644 --- a/crates/engine/src/search_vectors_extended.rs +++ b/crates/engine/src/search_vectors_extended.rs @@ -28,6 +28,7 @@ mod imp { use extenddb_core::expression::search_filter::{ DEFAULT_MAX_CONDITIONS, EnabledAccounts, SearchFilter, parse_search_filter, }; + use extenddb_core::expression::search_params::with_unused_names; use extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS; use extenddb_core::types::{AttributeDefinition, AttributeValue, Item, SearchSchemaElement}; use extenddb_storage::error::StorageError; @@ -77,7 +78,8 @@ mod imp { /// Parse the request's search condition with the extended grammar when /// the setting enables it for the caller. `None` when it does not, or when /// the request has no search condition; the handler then runs its - /// equality-only validator. + /// equality-only validator. A name that neither the search condition nor + /// `projection` uses is refused once the condition parses. /// /// Taking the backend's vector search engine means the grammar is only /// parsed once the backend has been found to serve vector search: a @@ -92,6 +94,7 @@ mod imp { expr: Option<&str>, names: Option<&HashMap>, values: Option<&HashMap>, + projection: Option<&str>, ) -> Result, DynamoDbError> { let Some(expr) = expr else { return Ok(None); @@ -101,8 +104,12 @@ mod imp { if !enabled_accounts().await.enabled_for(account_id, None) { return Ok(None); } - parse_search_filter(expr, names, values, DEFAULT_MAX_CONDITIONS) - .map(|filter| Some(Extended(Arc::new(filter)))) + with_unused_names( + parse_search_filter(expr, names, values, DEFAULT_MAX_CONDITIONS), + names, + &[expr, projection.unwrap_or_default()], + ) + .map(|filter| Some(Extended(Arc::new(filter)))) } /// The partition the HASH condition selects and the filter the backend @@ -161,6 +168,7 @@ mod imp { _expr: Option<&str>, _names: Option<&HashMap>, _values: Option<&HashMap>, + _projection: Option<&str>, ) -> Result, DynamoDbError> { Ok(None) } diff --git a/crates/engine/src/search_vectors_extended_tests.rs b/crates/engine/src/search_vectors_extended_tests.rs index d0779e7ad..c6af45554 100644 --- a/crates/engine/src/search_vectors_extended_tests.rs +++ b/crates/engine/src/search_vectors_extended_tests.rs @@ -76,7 +76,7 @@ const INEQUALITY: &str = "Country = :c AND Price > :p"; async fn parsed(expr: Option<&str>) -> Result { let values = values(); - parse_request(&Served, CALLER, expr, None, Some(&values)) + parse_request(&Served, CALLER, expr, None, Some(&values), None) .await .map(|parsed| parsed.is_some()) } @@ -143,7 +143,7 @@ async fn the_scope_selects_the_hash_partition_and_filters_items() { let _serial = SERIAL.lock().await; install(Ok(Some("all"))); let values = values(); - let extended = parse_request(&Served, CALLER, Some(INEQUALITY), None, Some(&values)) + let extended = parse_request(&Served, CALLER, Some(INEQUALITY), None, Some(&values), None) .await .unwrap() .expect("parsed with the extended grammar"); diff --git a/crates/engine/src/search_vectors_params.rs b/crates/engine/src/search_vectors_params.rs new file mode 100644 index 000000000..00b264af4 --- /dev/null +++ b/crates/engine/src/search_vectors_params.rs @@ -0,0 +1,71 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The request-level expression checks of `SearchVectors`, shared by the +//! equality-only grammar and the extended grammar. +//! +//! The handler calls [`check`] once `TopK` and `SearchVector` are valid. It +//! checks both expression maps (see `extenddb_core::expression::search_params`), +//! then the projection, so a projection fault answers ahead of any search +//! condition fault. A request without a search condition then gets the +//! unused-names check here; a request with one gets it after its condition +//! parses, through [`equality_conditions`] or the extended parser. + +use std::collections::HashMap; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::expression::search_params::{ + check_search_maps, check_unused_names, with_unused_names, +}; +use extenddb_core::expression::{ + ExpressionMaps, Projection, SearchCondition, validate_search_condition_expression, +}; +use extenddb_core::limits::LimitsConfig; +use extenddb_core::types::AttributeValue; + +/// Check the expression maps and the projection of a `SearchVectors` +/// request. +/// +/// # Errors +/// +/// Returns the `ValidationException` of the first failed check. +pub(crate) fn check( + names: Option<&HashMap>, + values: Option<&HashMap>, + condition: Option<&str>, + projection: Option<&str>, + limits: &LimitsConfig, +) -> Result<(), DynamoDbError> { + check_search_maps(names, values, condition.is_some(), projection.is_some())?; + if let Some(projection) = projection { + let paths = crate::expression_helpers::parse_projection_expr(projection, limits)?; + let names = names + .into_iter() + .flatten() + .map(|(k, v)| (k.trim_start_matches('#').to_owned(), v.clone())) + .collect(); + Projection::compile(&paths, &ExpressionMaps::new(names, HashMap::new()), true)?; + } + if condition.is_none() { + check_unused_names(names, &[projection.unwrap_or_default()])?; + } + Ok(()) +} + +/// The equality-only grammar's conditions, with the unused-names check. +/// +/// # Errors +/// +/// Returns the `ValidationException` of the first failed check. +pub(crate) fn equality_conditions( + expr: &str, + names: Option<&HashMap>, + values: Option<&HashMap>, + projection: Option<&str>, +) -> Result, DynamoDbError> { + with_unused_names( + validate_search_condition_expression(expr, names, values), + names, + &[expr, projection.unwrap_or_default()], + ) +} From 2336a974f4df030a7f5eba895a9df8be1f8f15a7 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Sat, 21 Nov 2026 17:05:08 +0000 Subject: [PATCH 007/101] fix(core): compare SearchVectors inline filter numbers as binary64 The service compares the numbers of a search condition as the nearest IEEE 754 binary64 value of each side. Two Prices that differ only in the last of 38 digits are equal, and so are 9007199254740992 and 9007199254740993, while 1000000000000000 and 1000000000000001 differ. The BETWEEN check that the upper bound is not below the lower bound stays exact. ExtendDB compared them as exact decimals, so Price > 99999999999999999999999999999999999998 matched an item whose Price is 99999999999999999999999999999999999999, and live returned no item. The condition evaluator takes a number precision. The search filter uses binary64; condition, filter and key condition expressions keep exact decimals. Verified against live DynamoDB in eu-north-1 on 28 items in 14 pairs that differ in the last significant digit (8, 15, 16, 17, 20 and 38 digits, negatives, 1E-10, 0.1, 1E+100): 165 requests over >, >=, <, <=, =, <>, BETWEEN, IN, NOT and a value on the left, each sent twice with the same answer. Binary64 on both sides agrees with all 151 result sets; exact decimals disagree with 111, 16 significant digits with 14, binary32 with 57. Unit tests replay the pairs. --- crates/core/src/expression/evaluator.rs | 69 +++++++++++--- crates/core/src/expression/mod.rs | 4 +- .../core/src/expression/search_filter/mod.rs | 13 ++- .../expression/search_filter/tests_eval.rs | 92 +++++++++++++++++-- 4 files changed, 152 insertions(+), 26 deletions(-) mode change 100644 => 100755 crates/core/src/expression/mod.rs diff --git a/crates/core/src/expression/evaluator.rs b/crates/core/src/expression/evaluator.rs index 7db0635b0..56b226d03 100755 --- a/crates/core/src/expression/evaluator.rs +++ b/crates/core/src/expression/evaluator.rs @@ -18,7 +18,19 @@ use super::resolver::{ ExpressionMaps, ParsedNumber, attribute_type_code, number_value, resolve_path, }; -/// Evaluate a condition expression against an item. +/// How two `N` values compare. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NumberPrecision { + /// As decimals, exactly: condition, filter and key condition expressions. + Exact, + /// As the nearest IEEE 754 binary64 value of each side: the inline + /// filters of a `SearchVectors` search condition. The validity of each + /// number, and the BETWEEN bound check, stay exact. + Binary64, +} + +/// Evaluate a condition expression against an item, comparing numbers +/// exactly. /// /// Returns `true` if the condition is satisfied, `false` otherwise. /// @@ -29,6 +41,21 @@ pub fn evaluate_condition( expr: &Expr, item: &BTreeMap, maps: &ExpressionMaps, +) -> Result { + evaluate_condition_at(expr, item, maps, NumberPrecision::Exact) +} + +/// Evaluate a condition expression against an item, comparing numbers at +/// `precision`. +/// +/// # Errors +/// +/// Returns `ValidationException` for unresolvable placeholders or type errors. +pub fn evaluate_condition_at( + expr: &Expr, + item: &BTreeMap, + maps: &ExpressionMaps, + precision: NumberPrecision, ) -> Result { match expr { Expr::Compare { left, op, right } => { @@ -38,18 +65,16 @@ pub fn evaluate_condition( (Some(l), Some(r)) => { let lpn = placeholder_numeric(left, maps); let rpn = placeholder_numeric(right, maps); - Ok(compare_values(l, r, *op, lpn, rpn)) + Ok(compare_values(l, r, *op, lpn, rpn, precision)) } _ => Ok(*op == CompareOp::Ne), } } - Expr::And(left, right) => { - Ok(evaluate_condition(left, item, maps)? && evaluate_condition(right, item, maps)?) - } - Expr::Or(left, right) => { - Ok(evaluate_condition(left, item, maps)? || evaluate_condition(right, item, maps)?) - } - Expr::Not(inner) => Ok(!evaluate_condition(inner, item, maps)?), + Expr::And(left, right) => Ok(evaluate_condition_at(left, item, maps, precision)? + && evaluate_condition_at(right, item, maps, precision)?), + Expr::Or(left, right) => Ok(evaluate_condition_at(left, item, maps, precision)? + || evaluate_condition_at(right, item, maps, precision)?), + Expr::Not(inner) => Ok(!evaluate_condition_at(inner, item, maps, precision)?), Expr::Function { name, args } => evaluate_function(name, args, item, maps), Expr::Between { operand, low, high } => { let val = resolve_to_value(operand, item, maps)?; @@ -71,7 +96,7 @@ pub fn evaluate_condition( } let lpn = placeholder_numeric(low, maps); let hpn = placeholder_numeric(high, maps); - if compare_values(l, h, CompareOp::Gt, lpn, hpn) { + if compare_values(l, h, CompareOp::Gt, lpn, hpn, NumberPrecision::Exact) { return Err(DynamoDbError::ValidationException(format!( "Invalid ConditionExpression: The BETWEEN operator requires upper bound to be greater than or equal to lower bound; lower bound operand: AttributeValue: {{{}}}, upper bound operand: AttributeValue: {{{}}}", format_attribute_value(l), @@ -84,8 +109,8 @@ pub fn evaluate_condition( let vpn = placeholder_numeric(operand, maps); let lpn = placeholder_numeric(low, maps); let hpn = placeholder_numeric(high, maps); - Ok(compare_values(v, l, CompareOp::Ge, vpn, lpn) - && compare_values(v, h, CompareOp::Le, vpn, hpn)) + Ok(compare_values(v, l, CompareOp::Ge, vpn, lpn, precision) + && compare_values(v, h, CompareOp::Le, vpn, hpn, precision)) } _ => Ok(false), } @@ -98,7 +123,7 @@ pub fn evaluate_condition( let cv = resolve_to_value(candidate, item, maps)?; if let Some(ref c) = cv { let cpn = placeholder_numeric(candidate, maps); - if compare_values(v, c, CompareOp::Eq, vpn, cpn) { + if compare_values(v, c, CompareOp::Eq, vpn, cpn, precision) { return Ok(true); } } @@ -160,7 +185,8 @@ fn comparison_number<'a>( /// `DynamoDB` comparison rules: /// - Same-type comparisons only (except N vs N which is numeric) /// - S: lexicographic UTF-8 -/// - N: numeric comparison via `BigDecimal` (pre-parsed values used when available). +/// - N: numeric comparison via `BigDecimal` (pre-parsed values used when available), +/// or of the nearest binary64 values under [`NumberPrecision::Binary64`]. /// An `N` that is not a number the service can store compares as a value of /// another type: only `<>` is true, so `a <> b` agrees with `NOT (a = b)`. /// - B: lexicographic byte comparison @@ -171,6 +197,7 @@ fn compare_values( op: CompareOp, left_parsed: Option>, right_parsed: Option>, + precision: NumberPrecision, ) -> bool { match (left, right) { (AttributeValue::S(l), AttributeValue::S(r)) => apply_op(l.cmp(r), op), @@ -181,7 +208,11 @@ fn compare_values( let Some(rd) = comparison_number(r, right_parsed) else { return matches!(op, CompareOp::Ne); }; - apply_op(ld.as_ref().cmp(rd.as_ref()), op) + let ordering = match precision { + NumberPrecision::Exact => None, + NumberPrecision::Binary64 => binary64_ordering(l, r), + }; + apply_op(ordering.unwrap_or_else(|| ld.as_ref().cmp(rd.as_ref())), op) } (AttributeValue::B(l), AttributeValue::B(r)) => apply_op(l.cmp(r), op), // For non-orderable types, only equality is meaningful @@ -190,6 +221,14 @@ fn compare_values( } } +/// The order of the nearest binary64 values of two numbers. Rust's parse +/// rounds to nearest, ties to even, as IEEE 754 does. +fn binary64_ordering(left: &str, right: &str) -> Option { + let left: f64 = left.trim().parse().ok()?; + let right: f64 = right.trim().parse().ok()?; + left.partial_cmp(&right) +} + fn apply_op(ordering: Ordering, op: CompareOp) -> bool { match op { CompareOp::Eq => ordering == Ordering::Equal, diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs old mode 100644 new mode 100755 index 993a3ac4e..39bc966a0 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -20,9 +20,9 @@ mod projection; mod reserved_words; mod resolver; mod search_condition; -pub mod search_params; #[cfg(feature = "search-inequality-filters")] pub mod search_filter; +pub mod search_params; #[cfg(test)] mod test_timeout; mod tokenizer; @@ -30,7 +30,7 @@ mod update_evaluator; mod update_parser; pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only}; -pub use evaluator::evaluate_condition; +pub use evaluator::{NumberPrecision, evaluate_condition, evaluate_condition_at}; pub use key_condition::{ KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands, parse_key_condition, diff --git a/crates/core/src/expression/search_filter/mod.rs b/crates/core/src/expression/search_filter/mod.rs index 6f2039159..0e55527a6 100644 --- a/crates/core/src/expression/search_filter/mod.rs +++ b/crates/core/src/expression/search_filter/mod.rs @@ -23,8 +23,10 @@ //! known, and its messages carry no prefix either. //! //! Evaluation uses the condition evaluator that FilterExpression uses, so a -//! missing attribute, a number comparison and a type mismatch behave as they -//! do in a Query or Scan filter. +//! missing attribute and a type mismatch behave as they do in a Query or Scan +//! filter. Numbers compare as the nearest binary64 value of each side, as the +//! service compares inline filters: `99999999999999999999999999999999999999 > +//! 99999999999999999999999999999999999998` is false. //! //! Pure synchronous Rust: no async, no I/O. @@ -187,7 +189,12 @@ impl SearchFilter { /// condition the evaluator would refuse, so this does not happen for a /// parsed filter. pub fn matches(&self, item: &Item) -> Result { - crate::expression::evaluate_condition(&self.expr, item, &self.maps) + crate::expression::evaluate_condition_at( + &self.expr, + item, + &self.maps, + crate::expression::NumberPrecision::Binary64, + ) } } diff --git a/crates/core/src/expression/search_filter/tests_eval.rs b/crates/core/src/expression/search_filter/tests_eval.rs index 6a5facb6b..a85c222d9 100644 --- a/crates/core/src/expression/search_filter/tests_eval.rs +++ b/crates/core/src/expression/search_filter/tests_eval.rs @@ -4,10 +4,12 @@ //! Which items a search condition matches. //! //! Evaluation uses the FilterExpression semantics: a comparison with a -//! missing attribute is false except `<>`, which is true; numbers compare as -//! decimals, so `1E2` equals `100` and 38-digit values keep their order; a -//! value of another type than the attribute's compares unequal. Not yet -//! measured against the live service for SearchVectors. +//! missing attribute is false except `<>`, which is true; a value of another +//! type than the attribute's compares unequal. Numbers compare as the nearest +//! binary64 value of each side, so `1E2` equals `100` and two 38-digit values +//! that share a binary64 value are equal. The number cases were measured +//! against the live service (eu-north-1, 2026-11-21, each request twice); the +//! others are not yet measured for SearchVectors. use std::collections::{BTreeMap, HashMap}; @@ -193,10 +195,11 @@ fn a_missing_attribute_under_not_equal_and_not() { /// Unmeasured, needs live confirmation: `1E2` against `100`, and 38-digit /// values. #[test] -fn numbers_compare_as_decimals() { +fn numbers_compare_as_binary64() { let cases = [ (h("Price = :p100"), vec!["i6", "i7"]), - (h("Price > :big"), vec!["i9"]), + (h("Price > :big"), vec![]), + (h("Price >= :big"), vec!["i9"]), ]; let refs: Vec<(&str, &[&str])> = cases .iter() @@ -205,6 +208,83 @@ fn numbers_compare_as_decimals() { assert_matches(&refs); } +/// Live: two items whose Prices differ in the last significant digit, and +/// whether the service tells them apart. Pairs that share a binary64 value +/// compare equal under every operator. +#[test] +fn a_last_digit_difference_counts_only_beyond_binary64() { + let pairs = [ + ("16777216", "16777217", true), + ("100000000000000", "100000000000001", true), + ("1000000000000000", "1000000000000001", true), + ("9007199254740992", "9007199254740993", false), + ("10000000000000000", "10000000000000001", false), + ("10000000000000000000", "10000000000000000001", false), + ( + "99999999999999999999999999999999999998", + "99999999999999999999999999999999999999", + false, + ), + ("-1000000000000001", "-1000000000000000", true), + ("-10000000000000001", "-10000000000000000", false), + ("1E-10", "1.00000000000001E-10", true), + ("1E-10", "1.0000000000000001E-10", false), + ("0.1", "0.10000000000000001", false), + ("1E+100", "1.0000000000000001E+100", false), + ]; + let mut mismatches = Vec::new(); + for (lo, hi, distinct) in pairs { + let rows = [("lo", lo), ("hi", hi)]; + let values: HashMap = + [(":us", s("US")), (":lo", n(lo)), (":hi", n(hi))] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect(); + let both = vec!["lo", "hi"]; + let cases = [ + ("Price > :lo", if distinct { vec!["hi"] } else { vec![] }), + ("Price < :hi", if distinct { vec!["lo"] } else { vec![] }), + ( + "Price = :lo", + if distinct { vec!["lo"] } else { both.clone() }, + ), + ("Price <> :lo", if distinct { vec!["hi"] } else { vec![] }), + ( + "Price BETWEEN :hi AND :hi", + if distinct { vec!["hi"] } else { both.clone() }, + ), + ( + "Price IN (:lo)", + if distinct { vec!["lo"] } else { both.clone() }, + ), + (":lo < Price", if distinct { vec!["hi"] } else { vec![] }), + ]; + for (rest, expected) in cases { + let expr = h(rest); + let used = used_values(&expr, &values); + let filter = parse_search_filter(&expr, None, Some(&used), 50) + .unwrap_or_else(|e| panic!("{expr}: {e:?}")); + let actual: Vec<&str> = rows + .iter() + .filter(|(_, price)| { + let item: Item = [("Country", s("US")), ("Price", n(price))] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect(); + filter.matches(&item).unwrap() + }) + .map(|(id, _)| *id) + .collect(); + if actual != expected { + mismatches.push(format!( + "{lo} / {hi}: {rest}: expected {expected:?}, got {actual:?}" + )); + } + } + } + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + /// Unmeasured, needs live confirmation: an item whose attribute has another /// type than the schema declares matches no ordering and no equality, and /// does match `<>`. From cd5d7cfd49110f3b4f7afcf383ddf59a3df70051 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Sat, 21 Nov 2026 17:14:00 +0000 Subject: [PATCH 008/101] test(search): pin the expression maps, binary64 numbers, both grammars The service answers the condition-limit shapes differently for an account with the extended grammar: the 20th comparison is no fault of its own, and the schema, HASH and unused-value checks answer instead. The module expected the equality-only answers, so it failed 21 of 43 cases under the extended grammar, on the service and on ExtendDB alike. The module now asks the target which grammar it serves, by sending h = :v0 AND f1 <> :v1, which the equality-only grammar refuses with the comparator message and the extended grammar answers. Each case then asserts that grammar's answer. The inequality filter module gains the expression map checks (empty maps, keys, name values, maps without their expression, unused names, the projection read first) and the binary64 number comparison, and omits ExpressionAttributeValues when the condition uses no value. Verified against live DynamoDB in eu-north-1, each module twice: condition limit 43 passed, inequality filters 21 passed and 1 skipped (the backend-without-vectors case). On ExtendDB SQLite both modules pass with the grammar on and off. --- tests/test_search_vectors_condition_limit.py | 158 +++++++++++++----- .../test_search_vectors_inequality_filters.py | 117 ++++++++++++- 2 files changed, 221 insertions(+), 54 deletions(-) diff --git a/tests/test_search_vectors_condition_limit.py b/tests/test_search_vectors_condition_limit.py index 0f3f873f4..6a06fa4d1 100644 --- a/tests/test_search_vectors_condition_limit.py +++ b/tests/test_search_vectors_condition_limit.py @@ -28,6 +28,16 @@ ExtendDB's wording differs from the service's. Those tests assert that the check, not the count, answers. +An account can have the extended grammar instead (comparators other than +``=``, OR, NOT, IN, BETWEEN, up to 50 conditions). The ``grammar`` fixture +asks the target which grammar it serves, by sending ``h = :v0 AND f1 <> :v1``: +the equality-only grammar refuses it with the comparator message and the +extended grammar answers 200. Each test then asserts the answer of that +grammar. The extended answers were measured on 2026-11-21 in eu-north-1, on an +account with the extended grammar, each request twice: under it the 20th +comparison is no fault of its own, and the schema, HASH and unused-value +checks answer instead. + Tests post raw SigV4-signed JSON. Against the service, SearchVectors is sent to the ``search-dynamodb`` host the SDKs use for it. The module skips when the target backend does not support vector indexes, unless @@ -82,6 +92,31 @@ NESTED = "SearchConditionExpression cannot have conditions on nested attributes" OPERATOR = "Invalid operator used in SearchConditionExpression" +# The extended grammar's answers. +X_NESTED = PREFIX + ": " + NESTED +X_MULTIPLE_NAMES = ( + "Invalid SearchConditionExpression: Invalid condition in " + "SearchConditionExpression: Multiple attribute names used in one condition" +) +X_HASH_IN_OR = ( + "SearchConditionExpression must use = on the HASH attribute, not inside OR or " + "NOT; HASH attribute: h" +) +X_STRING_ORDERING = ( + "SearchConditionExpression allows this operator only on Number (N) " + "attributes; operator: <, attribute: f1, attribute type: S" +) +X_UNUSED = ( + "Value provided in ExpressionAttributeValues unused in expressions: keys: {:unused}" +) + + +def _not_in_schema(attribute: str) -> str: + return ( + "SearchConditionExpression must not contain any attributes that is not in " + f"SearchSchema. Invalid attribute: {attribute}" + ) + INLINE = [f"f{i}" for i in range(1, 19)] NINETEEN = ["h", *INLINE] @@ -221,6 +256,30 @@ def search_table(): _delete_table(name) +@pytest.fixture(scope="module") +def grammar(search_table) -> str: + """``equality`` or ``extended``: the grammar the target serves this account.""" + resp = _search_expr(search_table, ["h = :v0", "f1 <> :v1"]) + if resp.status_code == 200: + return "extended" + if resp.status_code == 400 and _error_message(resp) == COMPARATOR: + return "equality" + pytest.fail(f"neither grammar answered the probe: {resp.status_code} {resp.text}") + + +def _either(grammar: str, equality, extended): + return equality if grammar == "equality" else extended + + +def _answers(resp: requests.Response, grammar: str, equality: str | None, extended: str | None) -> None: + """Refused with the grammar's message, or 200 where the message is None.""" + message = _either(grammar, equality, extended) + if message is None: + assert resp.status_code == 200, resp.text + else: + _refused_with(resp, message) + + def _comparisons(attrs: list[str]) -> list[str]: return [f"{a} = :v{i}" for i, a in enumerate(attrs)] @@ -297,40 +356,42 @@ def test_nineteen_conditions_are_accepted(self, search_table): assert resp.status_code == 200, resp.text def test_twentieth_condition_repeating_an_attribute_gets_count_message( - self, search_table + self, search_table, grammar ): - _refused_with(_search(search_table, [*NINETEEN, "f1"]), TOO_MANY) + _answers(_search(search_table, [*NINETEEN, "f1"]), grammar, TOO_MANY, None) - def test_twentieth_condition_outside_schema_gets_count_message(self, search_table): - _refused_with(_search(search_table, [*NINETEEN, "x"]), TOO_MANY) + def test_twentieth_condition_outside_schema_gets_count_message(self, search_table, grammar): + _answers(_search(search_table, [*NINETEEN, "x"]), grammar, TOO_MANY, NOT_IN_SCHEMA) - def test_twenty_one_conditions_get_count_message(self, search_table): - _refused_with(_search(search_table, [*NINETEEN, "x", "y"]), TOO_MANY) + def test_twenty_one_conditions_get_count_message(self, search_table, grammar): + resp = _search(search_table, [*NINETEEN, "x", "y"]) + _answers(resp, grammar, TOO_MANY, NOT_IN_SCHEMA) def test_count_is_checked_before_an_early_out_of_schema_attribute( - self, search_table + self, search_table, grammar ): - _refused_with(_search(search_table, ["h", "x", *INLINE]), TOO_MANY) + resp = _search(search_table, ["h", "x", *INLINE]) + _answers(resp, grammar, TOO_MANY, NOT_IN_SCHEMA) def test_out_of_schema_attribute_within_limit_gets_schema_message( self, search_table ): _refused_with(_search(search_table, [*NINETEEN[:-1], "x"]), NOT_IN_SCHEMA) - def test_repeat_within_limit_gets_duplicate_message(self, search_table): - _refused_with(_search(search_table, [*NINETEEN[:-1], "f1"]), DUPLICATE) + def test_repeat_within_limit_gets_duplicate_message(self, search_table, grammar): + resp = _search(search_table, [*NINETEEN[:-1], "f1"]) + _answers(resp, grammar, DUPLICATE, None) - def test_twenty_plus_an_unused_value_gets_count_message(self, search_table): - _refused_with( - _search_expr(search_table, [*_base(), "x = :v19"], unused=(":unused",)), - TOO_MANY, - ) + def test_twenty_plus_an_unused_value_gets_count_message(self, search_table, grammar): + resp = _search_expr(search_table, [*_base(), "x = :v19"], unused=(":unused",)) + _answers(resp, grammar, TOO_MANY, X_UNUSED) - def test_count_ignores_case_and_spacing(self, search_table): + def test_count_ignores_case_and_spacing(self, search_table, grammar): lower = [*_base(), "x = :v19"] - _refused_with(_search_expr(search_table, lower, joiner=" and "), TOO_MANY) + expected = _either(grammar, TOO_MANY, NOT_IN_SCHEMA) + _refused_with(_search_expr(search_table, lower, joiner=" and "), expected) tight = [c.replace(" = ", "=") for c in lower] - _refused_with(_search_expr(search_table, tight, joiner=" AND "), TOO_MANY) + _refused_with(_search_expr(search_table, tight, joiner=" AND "), expected) resp = _search_expr(search_table, _base(), joiner=" and ") assert resp.status_code == 200, resp.text @@ -436,21 +497,26 @@ def test_syntax_is_checked_before_values(self, search_table): assert _error_message(resp) != _undefined_value(":v1"), resp.text @pytest.mark.parametrize( - "comparisons", + "comparisons,extended", [ pytest.param( - [*_base()[:-1], _base()[-1] + " OR x = :v19"], id="OR-before-20th" + [*_base()[:-1], _base()[-1] + " OR x = :v19"], X_HASH_IN_OR, id="OR-before-20th" ), pytest.param( [_base()[0] + " OR " + _base()[1], *_base()[2:], "x = :v19"], + X_HASH_IN_OR, id="OR-before-2nd", ), - pytest.param([*_base(), "NOT x = :v19"], id="NOT-in-20th"), - pytest.param([*_base(), "x IN (:v19)"], id="IN-in-20th"), + pytest.param([*_base(), "NOT x = :v19"], NOT_IN_SCHEMA, id="NOT-in-20th"), + pytest.param([*_base(), "x IN (:v19)"], NOT_IN_SCHEMA, id="IN-in-20th"), ], ) - def test_logical_operator_past_the_limit(self, search_table, comparisons): - _refused_not_for_count(_search_expr(search_table, comparisons), OPERATOR) + def test_logical_operator_past_the_limit(self, search_table, grammar, comparisons, extended): + resp = _search_expr(search_table, comparisons) + if grammar == "equality": + _refused_not_for_count(resp, OPERATOR) + else: + _refused_with(resp, extended) def test_names_and_values_resolve_in_written_order(self, search_table): reserved_first = _with(2, "bucket = :v1") @@ -468,41 +534,41 @@ class TestPerComparisonPhase: """Faults that the count preempts in the 20th comparison.""" @pytest.mark.parametrize( - "comparison,names", + "comparison,names,extended", [ - pytest.param("a.b = :v19", None, id="nested"), - pytest.param("#nn = :v19", {"#nn": "a.b"}, id="nested-through-alias"), - pytest.param("x = v19", None, id="value-without-colon"), - pytest.param("x < :v19", None, id="less-than"), - pytest.param("x <> :v19", None, id="not-equal-comparator"), - pytest.param("x <= :v19", None, id="less-or-equal"), - pytest.param("x = :v0", None, id="placeholder-reused"), + pytest.param("a.b = :v19", None, X_NESTED, id="nested"), + pytest.param("#nn = :v19", {"#nn": "a.b"}, _not_in_schema("a.b"), id="nested-through-alias"), + pytest.param("x = v19", None, X_MULTIPLE_NAMES, id="value-without-colon"), + pytest.param("x < :v19", None, NOT_IN_SCHEMA, id="less-than"), + pytest.param("x <> :v19", None, NOT_IN_SCHEMA, id="not-equal-comparator"), + pytest.param("x <= :v19", None, NOT_IN_SCHEMA, id="less-or-equal"), + pytest.param("x = :v0", None, NOT_IN_SCHEMA, id="placeholder-reused"), ], ) - def test_twentieth_gets_count_message(self, search_table, comparison, names): - _refused_with( - _search_expr(search_table, [*_base(), comparison], names=names), TOO_MANY - ) + def test_twentieth_gets_count_message(self, search_table, grammar, comparison, names, extended): + resp = _search_expr(search_table, [*_base(), comparison], names=names) + _answers(resp, grammar, TOO_MANY, extended) - def test_repeat_at_third_of_twenty_gets_duplicate_message(self, search_table): - _refused_with( - _search_expr(search_table, [*_with(3, "f1 = :v2"), "x = :v19"]), DUPLICATE - ) + def test_repeat_at_third_of_twenty_gets_duplicate_message(self, search_table, grammar): + resp = _search_expr(search_table, [*_with(3, "f1 = :v2"), "x = :v19"]) + _answers(resp, grammar, DUPLICATE, NOT_IN_SCHEMA) - def test_less_than_at_second_gets_comparator_message(self, search_table): + def test_less_than_at_second_gets_comparator_message(self, search_table, grammar): + expected = _either(grammar, COMPARATOR, X_STRING_ORDERING) _refused_with( - _search_expr(search_table, [*_with(2, "f1 < :v1"), "x = :v19"]), COMPARATOR + _search_expr(search_table, [*_with(2, "f1 < :v1"), "x = :v19"]), expected ) - _refused_with(_search_expr(search_table, _with(2, "f1 < :v1")), COMPARATOR) + _refused_with(_search_expr(search_table, _with(2, "f1 < :v1")), expected) def test_nested_at_second_gets_nested_message(self, search_table): _refused_not_for_count( _search_expr(search_table, [*_with(2, "a.b = :v1"), "x = :v19"]), NESTED ) - def test_comparator_is_checked_before_nested_and_repeat(self, search_table): - _refused_with(_search_expr(search_table, _with(2, "a.b < :v1")), COMPARATOR) - _refused_with(_search_expr(search_table, _with(3, "f1 < :v2")), COMPARATOR) + def test_comparator_is_checked_before_nested_and_repeat(self, search_table, grammar): + _answers(_search_expr(search_table, _with(2, "a.b < :v1")), grammar, COMPARATOR, X_NESTED) + resp = _search_expr(search_table, _with(3, "f1 < :v2")) + _answers(resp, grammar, COMPARATOR, X_STRING_ORDERING) nested_then_less = _with(2, "a.b = :v1") nested_then_less[2] = "f2 < :v2" _refused_not_for_count(_search_expr(search_table, nested_then_less), NESTED) diff --git a/tests/test_search_vectors_inequality_filters.py b/tests/test_search_vectors_inequality_filters.py index 0dbc67f8f..7b3d80ad0 100644 --- a/tests/test_search_vectors_inequality_filters.py +++ b/tests/test_search_vectors_inequality_filters.py @@ -8,10 +8,11 @@ ``attribute_exists`` and ``attribute_not_exists``, and more than one condition on an attribute, up to 50 conditions. -None of the expected responses here has been measured against the live -service yet. Each one is a prediction of the service's answer, and a live run -on an enabled account confirms or corrects it before these tests are relied -on. +The number comparisons in ``TestEvaluation`` and every case in +``TestExpressionMaps`` were measured against the live service on 2026-11-21 in +eu-north-1, on an account with the extended grammar, each request twice with +the same answer. The other expected responses are predictions of the +service's answer. Against ExtendDB the module turns the grammar on for every account through the management API, as the admin in ``EXTENDDB_ADMIN_USER`` and @@ -195,8 +196,9 @@ def _search(table: str, expr: str, top_k: int = 100, names=None) -> requests.Res "SearchVector": [{"N": "1"}, {"N": "0"}, {"N": "0"}, {"N": "0"}], "TopK": top_k, "SearchConditionExpression": expr, - "ExpressionAttributeValues": {k: v for k, v in VALUES.items() if k in used}, } + if used: + body["ExpressionAttributeValues"] = {k: v for k, v in VALUES.items() if k in used} if names: body["ExpressionAttributeNames"] = names return _signed_post("SearchVectors", body) @@ -319,7 +321,8 @@ def test_a_range_on_one_attribute(self, grammar_table): class TestEvaluation: - """Not yet measured: a missing attribute, ``1E2`` against ``100``, 38 digits.""" + """Measured: numbers compare as the nearest binary64 value of each side, so the + two 38-digit Prices are equal. Not yet measured: a missing attribute.""" def test_a_missing_attribute_under_not_equal_and_not(self, grammar_table): assert "i4" in _ids(_search(grammar_table, H + "Price <> :p10")) @@ -331,9 +334,11 @@ def test_existence_functions(self, grammar_table): assert _ids(_search(grammar_table, H + "attribute_not_exists(Price)")) == {"i4"} assert _ids(_search(grammar_table, H + "attribute_exists(Price)")) == US - {"i4"} - def test_numbers_compare_as_decimals(self, grammar_table): + def test_numbers_compare_as_binary64(self, grammar_table): assert _ids(_search(grammar_table, H + "Price = :p100")) == {"i6", "i7"} - assert _ids(_search(grammar_table, H + "Price > :big")) == {"i9"} + assert _ids(_search(grammar_table, H + "Price > :big")) == set() + assert _ids(_search(grammar_table, H + "Price >= :big")) == {"i9"} + assert _ids(_search(grammar_table, H + "Price = :big")) == {"i9"} assert _ids(_search(grammar_table, H + "Price < :p0")) == {"i5"} assert _ids(_search(grammar_table, H + "Price > :p0 AND Price < :p5")) == {"i10"} @@ -445,6 +450,102 @@ def test_the_condition_limit(self, grammar_table): ) +def _raw(table: str, **fields) -> requests.Response: + body = { + "TableName": table, + "IndexName": "vix", + "SearchVector": [{"N": "1"}, {"N": "0"}, {"N": "0"}, {"N": "0"}], + "TopK": 10, + } + body.update(fields) + return _signed_post("SearchVectors", body) + + +class TestExpressionMaps: + """The two maps, checked before either expression is read.""" + + def test_empty_maps_names_first(self, grammar_table): + cond = {"SearchConditionExpression": "Country = :us"} + _refused(_raw(grammar_table, **cond, ExpressionAttributeValues={}), + "ExpressionAttributeValues must not be empty") + _refused( + _raw(grammar_table, **cond, ExpressionAttributeNames={}, ExpressionAttributeValues={}), + "ExpressionAttributeNames must not be empty", + ) + _refused(_raw(grammar_table, ExpressionAttributeValues={}), + "ExpressionAttributeValues must not be empty") + resp = _raw(grammar_table, TopK=0, **cond, ExpressionAttributeValues={}) + assert "TopK" in _message(resp), resp.text + + def test_keys_and_names(self, grammar_table): + us = {":us": {"S": "US"}} + cases = [ + ({"#c": ""}, {}, "#c = :us", + "ExpressionAttributeNames contains invalid value: Empty attribute name for key #c"), + ({"#a-b": "x"}, {**us, ":b-k": {"S": "y"}}, "Country = :us", + 'ExpressionAttributeNames contains invalid key: Syntax error; key: "#a-b"'), + ({"": "x"}, us, "Country = :us", + "ExpressionAttributeNames contains invalid key: The expression attribute map " + "contains an empty key;"), + ({"#" + "k" * 300: "x"}, us, "Country = :us", + "ExpressionAttributeNames contains invalid key: The expression attribute map " + "contains a key that is too long; size of key: 301"), + ({"#c": "C" * 65536}, us, "#c = :us", + "Attribute name is too large, must be less than 65536 bytes for key #c"), + (None, {**us, ":": {"S": "y"}}, "Country = :us", + 'ExpressionAttributeValues contains invalid key: Syntax error; key: ":"'), + ] + for names, values, cond, message in cases: + fields = {"SearchConditionExpression": cond, "ExpressionAttributeValues": values} + if names is not None: + fields["ExpressionAttributeNames"] = names + _refused(_raw(grammar_table, **fields), message) + + def test_maps_need_their_expression(self, grammar_table): + names, us = {"#p": "Price"}, {":us": {"S": "US"}} + only = "can only be specified when using expressions" + _refused(_raw(grammar_table, ExpressionAttributeNames=names), + "ExpressionAttributeNames " + only) + _refused(_raw(grammar_table, ExpressionAttributeNames=names, ExpressionAttributeValues=us), + "ExpressionAttributeNames " + only) + _refused(_raw(grammar_table, ExpressionAttributeValues=us), + "ExpressionAttributeValues " + only) + _refused( + _raw(grammar_table, ProjectionExpression="#p", ExpressionAttributeNames=names, + ExpressionAttributeValues=us), + "ExpressionAttributeValues " + only, + ) + + def test_unused_names(self, grammar_table): + us = {":us": {"S": "US"}} + unused = "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}" + u = {"#u": "x"} + _refused(_raw(grammar_table, SearchConditionExpression="Country = :us", + ExpressionAttributeNames=u, + ExpressionAttributeValues={**us, ":w": {"S": "w"}}), unused) + _refused(_raw(grammar_table, SearchConditionExpression="Country = :us", + ProjectionExpression="Price", ExpressionAttributeNames=u, + ExpressionAttributeValues=us), unused) + _refused(_raw(grammar_table, SearchConditionExpression="Price > :p", + ExpressionAttributeNames=u, ExpressionAttributeValues={":p": {"N": "0"}}), + unused) + _refused(_raw(grammar_table, SearchConditionExpression="Country = = :us", + ExpressionAttributeNames=u, ExpressionAttributeValues=us), + P + 'Syntax error; token: "=", near: "= = :us"') + resp = _raw(grammar_table, SearchConditionExpression="Country = :us", + ProjectionExpression="#p", ExpressionAttributeNames={"#p": "Price"}, + ExpressionAttributeValues=us) + assert resp.status_code == 200, resp.text + + def test_the_projection_is_read_before_the_condition(self, grammar_table): + _refused( + _raw(grammar_table, ProjectionExpression="#p", SearchConditionExpression="Country = = :us", + ExpressionAttributeValues={":us": {"S": "US"}}), + "Invalid ProjectionExpression: An expression attribute name used in the document " + "path is not defined; attribute name: #p", + ) + + class TestBackendWithoutVectors: def test_the_backend_refuses_before_the_grammar_runs(self): """On a backend without vector search the refusal is the backend's.""" From 1ea4a1dba166d6314114d85e579b0e7227e3d812 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Sat, 21 Nov 2026 17:16:00 +0000 Subject: [PATCH 009/101] test(engine): cover the SearchVectors projection and unused-name wiring The service reads the projection before the search condition, counts a name the projection uses as used, and refuses an unused name ahead of an unused value under either grammar. Unit tests drive the handler's check, the equality-only grammar and the extended grammar's parse with the requests measured against live DynamoDB in eu-north-1 (each twice): an undefined projection name ahead of a condition syntax error, an unused name with only a projection, an unused name ahead of an unused value, and a name used only by the projection. --- .../src/search_vectors_extended_tests.rs | 35 ++++++++ crates/engine/src/search_vectors_params.rs | 4 + .../engine/src/search_vectors_params_tests.rs | 81 +++++++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 crates/engine/src/search_vectors_params_tests.rs diff --git a/crates/engine/src/search_vectors_extended_tests.rs b/crates/engine/src/search_vectors_extended_tests.rs index c6af45554..be7e5b032 100644 --- a/crates/engine/src/search_vectors_extended_tests.rs +++ b/crates/engine/src/search_vectors_extended_tests.rs @@ -130,6 +130,41 @@ async fn an_enabled_account_gets_the_extended_messages() { ); } +#[tokio::test] +async fn a_name_neither_expression_uses_is_refused() { + let _serial = SERIAL.lock().await; + install(Ok(Some("all"))); + let values = values(); + let names: HashMap = [("#u".to_owned(), "x".to_owned())].into(); + let err = parse_request( + &Served, + CALLER, + Some(INEQUALITY), + Some(&names), + Some(&values), + None, + ) + .await + .err() + .expect("refused"); + assert!( + matches!(&err, DynamoDbError::ValidationException(m) + if m == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}"), + "{err:?}" + ); + let used: HashMap = [("#u".to_owned(), "Price".to_owned())].into(); + let projected = parse_request( + &Served, + CALLER, + Some(INEQUALITY), + Some(&used), + Some(&values), + Some("#u"), + ) + .await; + assert!(projected.is_ok_and(|e| e.is_some())); +} + fn item(country: &str, price: &str) -> Item { [ ("Country".to_owned(), AttributeValue::S(country.to_owned())), diff --git a/crates/engine/src/search_vectors_params.rs b/crates/engine/src/search_vectors_params.rs index 00b264af4..f6b3b80db 100644 --- a/crates/engine/src/search_vectors_params.rs +++ b/crates/engine/src/search_vectors_params.rs @@ -69,3 +69,7 @@ pub(crate) fn equality_conditions( &[expr, projection.unwrap_or_default()], ) } + +#[cfg(test)] +#[path = "search_vectors_params_tests.rs"] +mod tests; diff --git a/crates/engine/src/search_vectors_params_tests.rs b/crates/engine/src/search_vectors_params_tests.rs new file mode 100644 index 000000000..47a81231e --- /dev/null +++ b/crates/engine/src/search_vectors_params_tests.rs @@ -0,0 +1,81 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The projection and unused-name checks of both grammars. Each expectation +//! is a live SearchVectors answer, measured twice in eu-north-1 on +//! 2026-11-21. + +use std::collections::HashMap; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::limits::LimitsConfig; +use extenddb_core::types::AttributeValue; + +use super::{check, equality_conditions}; + +const UNUSED_U: &str = + "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}"; + +fn names(pairs: &[(&str, &str)]) -> HashMap { + pairs + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect() +} + +fn us() -> HashMap { + [(":us".to_owned(), AttributeValue::S("US".to_owned()))].into() +} + +fn message(result: Result) -> String { + match result { + Err(DynamoDbError::ValidationException(m)) => m, + other => format!("not a ValidationException: {other:?}"), + } +} + +#[test] +fn the_projection_answers_before_the_condition() { + let limits = LimitsConfig::default(); + assert_eq!( + message(check( + None, + Some(&us()), + Some("Country = = :us"), + Some("#p"), + &limits + )), + "Invalid ProjectionExpression: An expression attribute name used in the document \ + path is not defined; attribute name: #p" + ); +} + +#[test] +fn without_a_condition_a_name_must_be_used_by_the_projection() { + let limits = LimitsConfig::default(); + let unused = names(&[("#u", "x")]); + assert_eq!( + message(check(Some(&unused), None, None, Some("Price"), &limits)), + UNUSED_U + ); + let used = names(&[("#p", "Price")]); + assert!(check(Some(&used), None, None, Some("#p"), &limits).is_ok()); +} + +#[test] +fn the_equality_grammar_refuses_an_unused_name_before_an_unused_value() { + let unused = names(&[("#u", "x")]); + let mut values = us(); + values.insert(":w".to_owned(), AttributeValue::S("w".to_owned())); + assert_eq!( + message(equality_conditions( + "Country = :us", + Some(&unused), + Some(&values), + None + )), + UNUSED_U + ); + let used = names(&[("#p", "Price")]); + assert!(equality_conditions("Country = :us", Some(&used), Some(&us()), Some("#p")).is_ok()); +} From 8f98069508ee3ef0d35b363ef95619b8a524c7dd Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Sat, 21 Nov 2026 17:22:32 +0000 Subject: [PATCH 010/101] test(core): pin exact number comparison in condition expressions A Scan FilterExpression tells apart numbers that share a binary64 value: Price > 99999999999999999999999999999999999998 matches Price 99999999999999999999999999999999999999, and Price > 9007199254740992 matches 9007199254740993. Only the SearchVectors inline filters compare at binary64. No test failed when evaluate_condition was switched to the binary64 mode, so a test now pins the exact comparison. Verified against live DynamoDB in eu-north-1: both Scans twice, with the same answer each time. --- crates/core/src/expression/evaluator_tests.rs | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/core/src/expression/evaluator_tests.rs b/crates/core/src/expression/evaluator_tests.rs index b08150044..3fbf228d8 100755 --- a/crates/core/src/expression/evaluator_tests.rs +++ b/crates/core/src/expression/evaluator_tests.rs @@ -44,6 +44,29 @@ fn string_equality_false() { assert!(!eval("name = :v", &item, HashMap::new(), values).unwrap()); } +/// Live (eu-north-1, 2026-11-21, each Scan twice): a FilterExpression tells +/// apart numbers that share a binary64 value. Only the SearchVectors inline +/// filters compare at binary64. +#[test] +fn numbers_compare_exactly_past_binary64() { + for (price, bound) in [ + ( + "99999999999999999999999999999999999999", + "99999999999999999999999999999999999998", + ), + ("9007199254740993", "9007199254740992"), + ] { + let mut item = BTreeMap::new(); + item.insert("Price".into(), AttributeValue::N(price.into())); + let values: HashMap = + [("v".to_owned(), AttributeValue::N(bound.into()))].into(); + assert!( + eval("Price > :v", &item, HashMap::new(), values).unwrap(), + "{price} > {bound}" + ); + } +} + #[test] fn numeric_greater_than() { let item = simple_item(); From 3c1532316c7f4b57ed1fa0cd60e336e3d965e4e0 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 17:31:27 +0000 Subject: [PATCH 011/101] fix(core): parse and check search conditions without recursion The service answers a search condition nested as deep as the 4096-byte limit allows with an ordinary ValidationException: 4089 unclosed `(` before `a = :v` give `Syntax error; token: "", near: ":v"`, 818 nested `NOT(` give the operator count, and 1365 nested calls give the function name error. The extended grammar parsed with recursive descent, checked the tree with recursive walks and dropped it with the recursive drop glue, all before the 300-operator limit applied. About 1500 unclosed `(` overflowed a 2 MiB tokio worker stack in a release server, and about 200 nested `NOT(` did in a debug server. A stack overflow aborts the process, so one request stopped the server for every account. The parser now keeps its open groups and open calls on explicit stacks, the tree-building checks, the operator count and the combined size walk the tree with their own stacks, and dropping a node or a call moves its children to a heap stack. The tokens consumed and the token a syntax error names are unchanged. Every phase that still recurses runs after the operator limit, so it sees at most 300 levels. Verified with new tests in the debug test profile: each nesting form at and past the byte limit is rejected on a thread with a 64 KiB stack, and the deepest accepted condition parses, evaluates and drops on a 2 MiB stack, the stack of a tokio worker. Restoring the recursive parser, the recursive walks or the recursive drop each aborts the test process with a stack overflow. The expected answers were measured on the live service, two requests each. --- .../src/expression/search_filter/grammar.rs | 180 ++++++++++++----- .../core/src/expression/search_filter/mod.rs | 3 + .../expression/search_filter/tests_depth.rs | 185 +++++++++++++++++ .../core/src/expression/search_filter/walk.rs | 189 ++++++++++++------ 4 files changed, 445 insertions(+), 112 deletions(-) create mode 100644 crates/core/src/expression/search_filter/tests_depth.rs diff --git a/crates/core/src/expression/search_filter/grammar.rs b/crates/core/src/expression/search_filter/grammar.rs index 20a8af866..04abac578 100644 --- a/crates/core/src/expression/search_filter/grammar.rs +++ b/crates/core/src/expression/search_filter/grammar.rs @@ -72,6 +72,49 @@ pub(super) enum Node { Function(Call), } +// A tree can be as deep as the expression is long, and the drop glue of a +// `Box` chain recurses once per level. These drops move the children onto a +// heap stack instead, so dropping never recurses. + +impl Drop for Node { + fn drop(&mut self) { + let mut pending = Vec::new(); + detach(self, &mut pending); + while let Some(mut node) = pending.pop() { + detach(&mut node, &mut pending); + } + } +} + +/// Move the child nodes of `node` onto `pending`, leaving childless leaves. +fn detach(node: &mut Node, pending: &mut Vec) { + let leaf = || { + Node::Function(Call { + name: String::new(), + args: Vec::new(), + }) + }; + match node { + Node::Or(l, r) | Node::And(l, r) => { + pending.push(std::mem::replace(&mut **l, leaf())); + pending.push(std::mem::replace(&mut **r, leaf())); + } + Node::Not(inner) => pending.push(std::mem::replace(&mut **inner, leaf())), + Node::Compare { .. } | Node::Between { .. } | Node::In { .. } | Node::Function(_) => {} + } +} + +impl Drop for Call { + fn drop(&mut self) { + let mut pending = std::mem::take(&mut self.args); + while let Some(operand) = pending.pop() { + if let Operand::Call(mut call) = operand { + pending.append(&mut call.args); + } + } + } +} + /// Parse the whole expression. /// /// # Errors @@ -110,6 +153,15 @@ fn check_redundant_parens(toks: &[Tok]) -> Result<(), String> { Ok(()) } +/// One open group of [`Parser::condition`]: the OR and AND operands that +/// wait for their right side, and the NOTs that wait for their operand. +#[derive(Default)] +struct Group { + or: Option, + and: Option, + nots: usize, +} + struct Parser<'a> { src: &'a str, toks: &'a [Tok], @@ -151,41 +203,61 @@ impl Parser<'_> { } } + /// `condition`, with an explicit stack in place of recursion, so the + /// nesting depth of the input never reaches the thread stack. Each `(` that + /// opens a group pushes a [`Group`]; the group's pending OR and AND + /// operands and its pending NOT count live there. The tokens consumed and + /// the token an error names are those of the recursive grammar in the + /// module documentation. fn condition(&mut self) -> Result { - let mut left = self.and()?; - while self.kind() == &Kind::Or { - self.bump(); - let right = self.and()?; - left = Node::Or(Box::new(left), Box::new(right)); - } - Ok(left) - } - - fn and(&mut self) -> Result { - let mut left = self.not()?; - while self.kind() == &Kind::And { - self.bump(); - let right = self.not()?; - left = Node::And(Box::new(left), Box::new(right)); - } - Ok(left) - } - - fn not(&mut self) -> Result { - if self.kind() == &Kind::Not { - self.bump(); - return Ok(Node::Not(Box::new(self.not()?))); + let mut groups = vec![Group::default()]; + loop { + // The start of a `not`: NOT* then a primary. + let top = groups.last_mut().unwrap_or_else(|| unreachable!()); + while self.kind() == &Kind::Not { + self.bump(); + top.nots += 1; + } + if self.kind() == &Kind::LParen { + self.bump(); + groups.push(Group::default()); + continue; + } + let mut node = self.primary()?; + // Fold the finished primary into the open groups. A group that + // ends at `)` becomes a primary of the group around it. + loop { + let group = groups.last_mut().unwrap_or_else(|| unreachable!()); + for _ in 0..std::mem::take(&mut group.nots) { + node = Node::Not(Box::new(node)); + } + if let Some(left) = group.and.take() { + node = Node::And(Box::new(left), Box::new(node)); + } + if self.kind() == &Kind::And { + self.bump(); + group.and = Some(node); + break; + } + if let Some(left) = group.or.take() { + node = Node::Or(Box::new(left), Box::new(node)); + } + if self.kind() == &Kind::Or { + self.bump(); + group.or = Some(node); + break; + } + if groups.len() == 1 { + return Ok(node); + } + self.expect(&Kind::RParen)?; + groups.pop(); + } } - self.primary() } + /// A primary that does not open a group. fn primary(&mut self) -> Result { - if self.kind() == &Kind::LParen { - self.bump(); - let inner = self.condition()?; - self.expect(&Kind::RParen)?; - return Ok(inner); - } let subject = self.operand()?; let op = match self.kind() { Kind::Eq => CompareOp::Eq, @@ -229,27 +301,43 @@ impl Parser<'_> { }) } + /// `operand`, with an explicit stack of the calls that are open, so a + /// nested call such as `f(f(f(x)))` never recurses. fn operand(&mut self) -> Result { - match self.kind() { - Kind::ValueRef => { - let value = self.text().to_owned(); - self.bump(); - Ok(Operand::Value(value)) - } - Kind::Name if self.peek_kind(1) == &Kind::LParen => { - let name = self.text().to_owned(); - self.bump(); - self.bump(); - let mut args = vec![self.operand()?]; - while self.kind() == &Kind::Comma { + let mut calls: Vec = Vec::new(); + loop { + let mut done = match self.kind() { + Kind::ValueRef => { + let value = self.text().to_owned(); + self.bump(); + Operand::Value(value) + } + Kind::Name if self.peek_kind(1) == &Kind::LParen => { + let name = self.text().to_owned(); + self.bump(); + self.bump(); + calls.push(Call { + name, + args: Vec::new(), + }); + continue; + } + Kind::Name | Kind::NameRef => self.path()?, + _ => return Err(self.error()), + }; + loop { + let Some(open) = calls.last_mut() else { + return Ok(done); + }; + open.args.push(done); + if self.kind() == &Kind::Comma { self.bump(); - args.push(self.operand()?); + break; } self.expect(&Kind::RParen)?; - Ok(Operand::Call(Call { name, args })) + let call = calls.pop().unwrap_or_else(|| unreachable!()); + done = Operand::Call(call); } - Kind::Name | Kind::NameRef => self.path(), - _ => Err(self.error()), } } diff --git a/crates/core/src/expression/search_filter/mod.rs b/crates/core/src/expression/search_filter/mod.rs index 0e55527a6..da42e005a 100644 --- a/crates/core/src/expression/search_filter/mod.rs +++ b/crates/core/src/expression/search_filter/mod.rs @@ -212,3 +212,6 @@ mod tests_schema; #[cfg(test)] mod tests_eval; + +#[cfg(test)] +mod tests_depth; diff --git a/crates/core/src/expression/search_filter/tests_depth.rs b/crates/core/src/expression/search_filter/tests_depth.rs new file mode 100644 index 000000000..30925b819 --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_depth.rs @@ -0,0 +1,185 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Deeply nested expressions up to the 4096-byte limit. +//! +//! A tokio worker gets a 2 MiB stack, and in a server the handler frames +//! above the parse take part of it. So an expression the checks reject must +//! need no stack in proportion to its depth: each rejected case runs on a +//! thread with a 64 KiB stack, and the deepest accepted condition, whose +//! evaluation still recurses once per level, runs on 2 MiB. In the test +//! profile's debug build a phase that recurses once per nesting level +//! overflows these stacks below the byte limit, which aborts the test +//! process. The expected answers were measured on the live service on +//! 2026-11-23, two requests each. + +use std::collections::HashMap; + +use super::{DEFAULT_MAX_CONDITIONS, parse_search_filter}; +use crate::error::DynamoDbError; +use crate::types::{AttributeValue, Item}; + +const WORKER_STACK: usize = 2 << 20; +const SMALL_STACK: usize = 64 << 10; +const OK: &str = "Ok"; + +fn on_stack(stack: usize, f: impl FnOnce() -> T + Send) -> T { + std::thread::scope(|scope| { + std::thread::Builder::new() + .stack_size(stack) + .spawn_scoped(scope, f) + .unwrap_or_else(|e| panic!("spawn: {e}")) + .join() + .unwrap_or_else(|_| panic!("the parse panicked")) + }) +} + +/// The values an expression names: `:v` is a string, `:w` a number. +fn values_for(expr: &str) -> HashMap { + let mut values = HashMap::new(); + if expr.contains(":v") { + values.insert(":v".to_owned(), AttributeValue::S("x".to_owned())); + } + if expr.contains(":w") { + values.insert(":w".to_owned(), AttributeValue::N("2".to_owned())); + } + values +} + +/// `Ok`, or the message of the error, parsed on a thread with `stack` bytes. +fn outcome_on(stack: usize, expr: &str) -> String { + let expr = expr.to_owned(); + on_stack(stack, move || { + let values = values_for(&expr); + match parse_search_filter(&expr, None, Some(&values), DEFAULT_MAX_CONDITIONS) { + Ok(_) => OK.to_owned(), + Err(DynamoDbError::ValidationException(m)) => m, + Err(other) => format!("{other:?}"), + } + }) +} + +fn outcome(expr: &str) -> String { + outcome_on(SMALL_STACK, expr) +} + +fn p(body: &str) -> String { + format!("Invalid SearchConditionExpression: {body}") +} + +fn syntax(token: &str, near: &str) -> String { + p(&format!( + "Syntax error; token: \"{token}\", near: \"{near}\"" + )) +} + +fn operators(count: usize) -> String { + p(&format!( + "The expression contains too many operators; operator count: {count}" + )) +} + +fn nested(open: &str, inner: &str, close: &str, depth: usize) -> String { + format!("{}{inner}{}", open.repeat(depth), close.repeat(depth)) +} + +fn assert_cases(cases: &[(String, String)]) { + let mismatches: Vec = cases + .iter() + .filter_map(|(expr, expected)| { + let actual = outcome(expr); + (&actual != expected).then(|| { + format!( + "{} bytes starting {:?}: expected {expected:?}, got {actual:?}", + expr.len(), + &expr[..expr.len().min(24)] + ) + }) + }) + .collect(); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +#[test] +fn unclosed_parentheses_answer_a_syntax_error_at_the_end() { + let eof = syntax("", ":v"); + let mut cases: Vec<(String, String)> = [1, 2, 10, 100, 299, 300, 301, 1000, 1500, 4089] + .into_iter() + .map(|depth| ("(".repeat(depth) + "a = :v", eof.clone())) + .collect(); + cases.extend([ + ("(".repeat(4090) + "a = :v", eof.clone()), + ( + format!("a = :v AND {}b = :v", "(".repeat(2000)), + eof.clone(), + ), + ("NOT (".repeat(800) + "a = :v", eof.clone()), + ("NOT (".repeat(818) + "a = :v", eof), + ( + "(".repeat(4091) + "a = :v", + p("Expression size has exceeded the maximum allowed size;"), + ), + ("a = :v".to_owned() + &")".repeat(1500), syntax(")", ":v))")), + ]); + assert_eq!(cases[10].0.len(), 4096); + assert_cases(&cases); +} + +#[test] +fn closed_nesting_answers_the_operator_count_or_redundant_parentheses() { + let redundant = p("The expression has redundant parentheses;"); + let cases = [ + (nested("(", "a = :v", ")", 2), redundant.clone()), + (nested("(", "a = :v", ")", 1000), redundant.clone()), + (nested("(", "a = :v", ")", 2045), redundant), + (nested("(a=:v OR ", "a=:v", ")", 300), operators(601)), + (nested("(a=:v OR ", "a=:v", ")", 409), operators(819)), + (nested("NOT(", "a=:v", ")", 300), operators(301)), + (nested("NOT(", "a=:v", ")", 818), operators(819)), + ("NOT ".repeat(300) + "a = :v", operators(301)), + ("NOT ".repeat(1022) + "a = :v", operators(1023)), + ("NOT ".repeat(1000) + "a = = :v", syntax("=", "= = :v")), + ( + nested("(a=:v AND ", "b=:u", ")", 350), + p( + "An expression attribute value used in expression is not defined; \ + attribute value: :u", + ), + ), + ]; + assert_eq!(cases[2].0.len(), 4096); + assert_cases(&cases); +} + +#[test] +fn deeply_nested_calls_answer_as_the_service_does() { + let expr = nested("f(", "x", ")", 1365); + assert_eq!(expr.len(), 4096); + assert_eq!(outcome(&expr), p("Invalid function name; function: f")); + let expr = "attribute_exists(".to_owned() + &"size(".repeat(815) + "a"; + assert_eq!(outcome(&expr), syntax("", "a")); +} + +/// 300 operators is the most the grammar takes, so the deepest accepted tree +/// is 300 levels. It parses, evaluates and drops on the worker stack. +#[test] +fn the_deepest_accepted_condition_parses_and_evaluates() { + let accepted = nested("NOT(", "a=:v", ")", 299); + assert_eq!(outcome_on(WORKER_STACK, &accepted), OK); + let matched = on_stack(WORKER_STACK, move || { + let values = values_for(&accepted); + let filter = parse_search_filter(&accepted, None, Some(&values), DEFAULT_MAX_CONDITIONS) + .unwrap_or_else(|e| panic!("{e:?}")); + let item: Item = Item::from([("a".to_owned(), AttributeValue::S("x".to_owned()))]); + let matched = filter.matches(&item).unwrap_or_else(|e| panic!("{e:?}")); + drop(filter); + matched + }); + // 299 NOTs over a true comparison. + assert!(!matched); + assert_eq!( + outcome_on(WORKER_STACK, &("NOT ".repeat(299) + "a = :v")), + OK, + "299 NOTs and one comparison are 300 operators" + ); +} diff --git a/crates/core/src/expression/search_filter/walk.rs b/crates/core/src/expression/search_filter/walk.rs index c29b99cbc..46d17d556 100644 --- a/crates/core/src/expression/search_filter/walk.rs +++ b/crates/core/src/expression/search_filter/walk.rs @@ -43,16 +43,31 @@ impl<'a> Maps<'a> { /// Run the tree-building checks over `node`. /// +/// The tree can be as deep as the expression is long, so the walk keeps its +/// own stack rather than recursing. AND, OR and NOT carry no check of their +/// own, so visiting the leaves left to right is the post-order walk. +/// /// # Errors /// /// Returns the first failure's message body, without the expression prefix. pub(super) fn check(node: &Node, maps: &Maps<'_>) -> Result<(), String> { - match node { - Node::Or(l, r) | Node::And(l, r) => { - check(l, maps)?; - check(r, maps) + let mut pending = vec![node]; + while let Some(node) = pending.pop() { + match node { + Node::Or(l, r) | Node::And(l, r) => { + pending.push(r); + pending.push(l); + } + Node::Not(inner) => pending.push(inner), + leaf => check_leaf(leaf, maps)?, } - Node::Not(inner) => check(inner, maps), + } + Ok(()) +} + +fn check_leaf(node: &Node, maps: &Maps<'_>) -> Result<(), String> { + match node { + Node::Or(..) | Node::And(..) | Node::Not(_) => Ok(()), Node::Compare { left, op, right } => { operand(left, maps)?; operand(right, maps)?; @@ -86,22 +101,53 @@ pub(super) fn check(node: &Node, maps: &Maps<'_>) -> Result<(), String> { } distinct_first_operand("IN", subject, list.iter(), maps) } - Node::Function(call) => function(call, true, maps), + Node::Function(call) => calls(Visit::Exit(call, true), maps), } } +/// A step of the operand walk: check an operand, or run a call's own checks +/// once its operands passed. The flag is true for a call that stands as a +/// condition. +enum Visit<'a> { + Enter(&'a Operand), + Exit(&'a Call, bool), +} + fn operand(o: &Operand, maps: &Maps<'_>) -> Result<(), String> { - match o { - Operand::Path(elements) => path(elements, maps), - Operand::Value(reference) => match maps.value(reference) { - Some(_) => Ok(()), - None => Err(format!( - "An expression attribute value used in expression is not defined; \ - attribute value: {reference}" - )), - }, - Operand::Call(call) => function(call, false, maps), + calls(Visit::Enter(o), maps) +} + +/// Check an operand tree post-order, left to right, with its own stack: a +/// call's operands before the call. Calls nest as deep as the expression is +/// long. +fn calls(start: Visit<'_>, maps: &Maps<'_>) -> Result<(), String> { + let mut pending = Vec::new(); + match start { + Visit::Exit(call, condition) => { + pending.push(Visit::Exit(call, condition)); + pending.extend(call.args.iter().rev().map(Visit::Enter)); + } + enter @ Visit::Enter(_) => pending.push(enter), } + while let Some(step) = pending.pop() { + match step { + Visit::Enter(Operand::Path(elements)) => path(elements, maps)?, + Visit::Enter(Operand::Value(reference)) => { + if maps.value(reference).is_none() { + return Err(format!( + "An expression attribute value used in expression is not defined; \ + attribute value: {reference}" + )); + } + } + Visit::Enter(Operand::Call(call)) => { + pending.push(Visit::Exit(call, false)); + pending.extend(call.args.iter().rev().map(Visit::Enter)); + } + Visit::Exit(call, condition) => function(call, condition, maps)?, + } + } + Ok(()) } fn path(elements: &[Element], maps: &Maps<'_>) -> Result<(), String> { @@ -139,11 +185,8 @@ fn arity(name: &str) -> Option { const TYPE_NAMES: [&str; 10] = ["S", "SS", "N", "NS", "B", "BS", "BOOL", "NULL", "L", "M"]; /// `condition` is true when the call stands as a condition and false when it -/// is an operand. +/// is an operand. The operands were already checked by [`calls`]. fn function(call: &Call, condition: bool, maps: &Maps<'_>) -> Result<(), String> { - for arg in &call.args { - operand(arg, maps)?; - } let name = call.name.as_str(); let Some(expected) = arity(name) else { return Err(if matches!(name, "if_not_exists" | "list_append") { @@ -359,58 +402,72 @@ fn shown(value: &AttributeValue) -> String { /// IN and function is one, a function used as an operand included. /// Parentheses are none. pub(super) fn operators(node: &Node) -> usize { - fn in_operand(o: &Operand) -> usize { - match o { - Operand::Call(call) => 1 + call.args.iter().map(in_operand).sum::(), - Operand::Path(_) | Operand::Value(_) => 0, - } - } - match node { - Node::Or(l, r) | Node::And(l, r) => 1 + operators(l) + operators(r), - Node::Not(inner) => 1 + operators(inner), - Node::Compare { left, right, .. } => 1 + in_operand(left) + in_operand(right), - Node::Between { subject, low, high } => { - 1 + in_operand(subject) + in_operand(low) + in_operand(high) + let (mut calls, mut nodes) = (0, 0); + each_operand( + node, + |o| { + if matches!(o, Operand::Call(_)) { + calls += 1; + } + }, + |_| nodes += 1, + ); + calls + nodes +} + +/// Visit every node and every operand of `node`, calls and their operands +/// included, with an explicit stack. +fn each_operand<'a>( + node: &'a Node, + mut on_operand: impl FnMut(&'a Operand), + mut on_node: impl FnMut(&'a Node), +) { + let mut nodes = vec![node]; + let mut operands: Vec<&'a Operand> = Vec::new(); + while let Some(node) = nodes.pop() { + on_node(node); + match node { + Node::Or(l, r) | Node::And(l, r) => nodes.extend([&**l, &**r]), + Node::Not(inner) => nodes.push(inner), + Node::Compare { left, right, .. } => operands.extend([left, right]), + Node::Between { subject, low, high } => operands.extend([subject, low, high]), + Node::In { subject, list } => { + operands.push(subject); + operands.extend(list); + } + Node::Function(call) => operands.extend(&call.args), } - Node::In { subject, list } => { - 1 + in_operand(subject) + list.iter().map(in_operand).sum::() + while let Some(o) = operands.pop() { + on_operand(o); + if let Operand::Call(call) = o { + operands.extend(&call.args); + } } - Node::Function(call) => 1 + call.args.iter().map(in_operand).sum::(), } } /// The expression's bytes plus the bytes each substitution adds, counted at /// every use. pub(super) fn combined_bytes(src: &str, node: &Node, maps: &Maps<'_>) -> usize { - fn in_operand(o: &Operand, maps: &Maps<'_>) -> usize { - match o { - Operand::Path(elements) => elements - .iter() - .map(|e| match e { - Element::Name(n) if n.starts_with('#') => maps.name(n).map_or(0, str::len), - Element::Name(_) | Element::Index(_) => 0, - }) - .sum(), - Operand::Value(reference) => maps - .value(reference) - .map_or(0, crate::types::attribute_value_size), - Operand::Call(call) => call.args.iter().map(|a| in_operand(a, maps)).sum(), - } - } - fn in_node(node: &Node, maps: &Maps<'_>) -> usize { - match node { - Node::Or(l, r) | Node::And(l, r) => in_node(l, maps) + in_node(r, maps), - Node::Not(inner) => in_node(inner, maps), - Node::Compare { left, right, .. } => in_operand(left, maps) + in_operand(right, maps), - Node::Between { subject, low, high } => [subject, low, high] - .into_iter() - .map(|o| in_operand(o, maps)) - .sum(), - Node::In { subject, list } => { - in_operand(subject, maps) + list.iter().map(|o| in_operand(o, maps)).sum::() - } - Node::Function(call) => call.args.iter().map(|a| in_operand(a, maps)).sum(), - } - } - src.len() + in_node(node, maps) + let mut total = src.len(); + each_operand( + node, + |o| { + total += match o { + Operand::Path(elements) => elements + .iter() + .map(|e| match e { + Element::Name(n) if n.starts_with('#') => maps.name(n).map_or(0, str::len), + Element::Name(_) | Element::Index(_) => 0, + }) + .sum(), + Operand::Value(reference) => maps + .value(reference) + .map_or(0, crate::types::attribute_value_size), + Operand::Call(_) => 0, + }; + }, + |_| {}, + ); + total } From 997476954eb1b298cc9dbd12f2d4ce267bcae453 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 17:53:06 +0000 Subject: [PATCH 012/101] fix(core): reject a search condition name that starts with an underscore The service does not start a bare name with `_`. `Country = :us AND _Cat = :v` answers `Invalid SearchConditionExpression: Syntax error; token: "_", near: "AND _Cat"`: the `_` is a token of its own, and the near text runs on to the token after it, so `__a = :v` gives near `__`. The same holds for a name after `.`, a function name, and a name inside a call, an IN list or a BETWEEN. An underscore inside or at the end of a name, and in a `#name` or `:value` reference, is accepted. The extended grammar's lexer started a name on a letter or `_`, so `_Cat` lexed as one name and the request failed later with the search schema message. A name now starts on a letter only. A leading `_` becomes a one-byte token that no rule takes, which the parser reports as the syntax error at that byte. Verified with a new test of 21 expressions measured on the live service, two requests each, against a missing table and an existing vector table. --- .../src/expression/search_filter/lexer.rs | 4 +- .../expression/search_filter/tests_grammar.rs | 65 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/crates/core/src/expression/search_filter/lexer.rs b/crates/core/src/expression/search_filter/lexer.rs index 579e866a3..dc4c03eb2 100644 --- a/crates/core/src/expression/search_filter/lexer.rs +++ b/crates/core/src/expression/search_filter/lexer.rs @@ -131,7 +131,9 @@ pub(super) fn lex(src: &str) -> Vec { } Kind::Number } - b if b.is_ascii_alphabetic() || b == b'_' => { + // A name starts with a letter. An underscore may follow but not lead, + // so a leading `_` is a token of its own that no rule takes. + b if b.is_ascii_alphabetic() => { while i < bytes.len() && is_word_byte(bytes[i]) { i += 1; } diff --git a/crates/core/src/expression/search_filter/tests_grammar.rs b/crates/core/src/expression/search_filter/tests_grammar.rs index 1fa3d921e..a48bc6799 100644 --- a/crates/core/src/expression/search_filter/tests_grammar.rs +++ b/crates/core/src/expression/search_filter/tests_grammar.rs @@ -335,3 +335,68 @@ fn an_unused_value_is_named_without_the_prefix() { p("Syntax error; token: \"\", near: \"OR\"") ); } + +/// Measured on the live service on 2026-11-23, two requests each: a bare +/// name, a function name and a path element cannot start with `_`, and the +/// syntax error names the `_` alone. An underscore inside or at the end of a +/// name, and in a `#name` or `:value` reference, is accepted. +#[test] +fn a_name_cannot_start_with_an_underscore() { + use std::collections::HashMap; + + use super::parse_search_filter; + use super::tests_support::used_values; + use crate::error::DynamoDbError; + use crate::types::AttributeValue; + + let syntax = |token: &str, near: &str| { + p(&format!( + "Syntax error; token: \"{token}\", near: \"{near}\"" + )) + }; + let cases = [ + ("Country = :us AND _Cat = :v", syntax("_", "AND _Cat")), + ("_ = :v", syntax("_", "_ =")), + ("_a = :v", syntax("_", "_a")), + ("__a = :v", syntax("_", "__")), + ("a._b = :v", syntax("_", "._b")), + ("attribute_exists(_a)", syntax("_", "(_a")), + ("_f(a)", syntax("_", "_f")), + ("size(_a) = :v", syntax("_", "(_a")), + ("a IN (_b)", syntax("_", "(_b")), + ("a = _b", syntax("_", "= _b")), + ("NOT _a = :v", syntax("_", "NOT _a")), + ("(_a = :v)", syntax("_", "(_a")), + ("a BETWEEN _b AND :v", syntax("_", "BETWEEN _b")), + ("1a = :v", syntax("1", "1a")), + ("a.1b = :v", syntax("1", ".1b")), + ("a_ = :v", OK.to_owned()), + ("a_b = :v", OK.to_owned()), + ("a1 = :v", OK.to_owned()), + ("#_x = :v", OK.to_owned()), + ("#_ = :v", OK.to_owned()), + ("a = :_v", OK.to_owned()), + ]; + let names: HashMap = [("#_x", "Category"), ("#_", "Category")] + .into_iter() + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + let all: HashMap = [":v", ":us", ":_v"] + .into_iter() + .map(|k| (k.to_owned(), AttributeValue::S("x".to_owned()))) + .collect(); + let mismatches: Vec = cases + .iter() + .filter_map(|(expr, expected)| { + let values = used_values(expr, &all); + let actual = match parse_search_filter(expr, Some(&names), Some(&values), 50) { + Ok(_) => OK.to_owned(), + Err(DynamoDbError::ValidationException(m)) => m, + Err(other) => format!("{other:?}"), + }; + (&actual != expected) + .then(|| format!("{expr:?}: expected {expected:?}, got {actual:?}")) + }) + .collect(); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} From 7322ed5442d4a0e6177d7de71ce5d8e7f14d745c Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 17:56:57 +0000 Subject: [PATCH 013/101] fix(core): accept a parenthesised operand in a search condition The service takes `( operand )` wherever an operand goes: `(a) = :v`, `a = (:v)`, `NOT (a) = :v`, `a BETWEEN (:v) AND (:w)`, `a IN ((:v), (:w))`, `size((a))` and `(attribute_exists(a))` all pass the expression checks. No path step follows the `)`: `(a).b = :v` answers `Syntax error; token: ".", near: ").b"`. The `(` of a call or an IN list is not a group for the redundant parentheses rule, so `attribute_exists((a))` and `a IN ((:v))` pass while `attribute_exists(((a)))` and `((a)) = :v` answer `The expression has redundant parentheses;`. The extended grammar took `(` only as the start of a group, so each of these requests answered a syntax error, and the redundant parentheses rule counted the `(` of a call or a list as a group. An operand may now be a parenthesised operand. Where a condition starts, a run of `(` opens a parenthesised operand when an operand and its `)` follow, and groups otherwise; the parser decides from one attempt at the operand, so a run costs at most two passes over it. The redundant parentheses rule skips a `(` that follows a function name or IN. Verified with new tests of 33 expressions measured on the live service, two requests each, and with depth tests of 2000 `(` inside a BETWEEN bound, an IN list and a call argument on a 64 KiB stack. --- .../src/expression/search_filter/grammar.rs | 127 ++++++++++++++---- .../core/src/expression/search_filter/mod.rs | 3 + .../expression/search_filter/tests_depth.rs | 19 +++ .../search_filter/tests_operands.rs | 108 +++++++++++++++ 4 files changed, 231 insertions(+), 26 deletions(-) create mode 100644 crates/core/src/expression/search_filter/tests_operands.rs diff --git a/crates/core/src/expression/search_filter/grammar.rs b/crates/core/src/expression/search_filter/grammar.rs index 04abac578..6a723dc61 100644 --- a/crates/core/src/expression/search_filter/grammar.rs +++ b/crates/core/src/expression/search_filter/grammar.rs @@ -13,13 +13,18 @@ //! | operand comparator operand //! | operand BETWEEN operand AND operand //! | operand IN '(' operand ( ',' operand )* ')' -//! operand := path | :value | call +//! operand := '(' operand ')' | path | :value | call //! call := name '(' operand ( ',' operand )* ')' //! path := ( name | #name ) ( '.' ( name | #name ) | '[' digits ']' )* //! ``` //! //! Keywords are case-insensitive. A number is a token, but no rule takes //! one outside a list index, so `a = 10` is a syntax error at `10`. +//! +//! A `(` where a condition starts opens a parenthesised operand when an +//! operand and its `)` follow, as in `(a) = :v` or `(attribute_exists(a))`, +//! and a group otherwise, as in `(a = :v)`. No path step follows a +//! parenthesised operand: `(a).b` is a syntax error at `.`. use super::lexer::{Kind, Tok, syntax_error}; use crate::expression::CompareOp; @@ -135,12 +140,18 @@ pub(super) fn parse(src: &str, toks: &[Tok]) -> Result { } /// A parenthesised group whose whole content is another parenthesised group, -/// such as `((a = :v))`. The same rule as the other expression parsers. +/// such as `((a = :v))` or `((a)) = :v`. The `(` of a call and of an IN list +/// is not a group, so `attribute_exists((a))` and `a IN ((:v))` pass, while +/// `attribute_exists(((a)))` does not. fn check_redundant_parens(toks: &[Tok]) -> Result<(), String> { + let group = |i: usize| { + toks[i].kind == Kind::LParen + && !(i > 0 && matches!(toks[i - 1].kind, Kind::Name | Kind::In)) + }; let mut stack: Vec = Vec::new(); for (i, tok) in toks.iter().enumerate() { match tok.kind { - Kind::LParen => stack.push(i > 0 && toks[i - 1].kind == Kind::LParen), + Kind::LParen => stack.push(i > 0 && group(i - 1)), Kind::RParen => { let doubled = stack.pop() == Some(true); if doubled && toks.get(i + 1).map(|t| &t.kind) == Some(&Kind::RParen) { @@ -162,6 +173,23 @@ struct Group { nots: usize, } +/// A failed [`Parser::operand`]. `unclosed` is the number of open +/// parentheses when the operand inside them was complete and the next token +/// was not `)`, and no call was open. +struct Unparsed { + message: String, + unclosed: Option, +} + +impl Unparsed { + fn other(message: String) -> Self { + Self { + message, + unclosed: None, + } + } +} + struct Parser<'a> { src: &'a str, toks: &'a [Tok], @@ -218,12 +246,33 @@ impl Parser<'_> { self.bump(); top.nots += 1; } - if self.kind() == &Kind::LParen { - self.bump(); - groups.push(Group::default()); - continue; - } - let mut node = self.primary()?; + let mut node = if self.kind() == &Kind::LParen { + let start = self.pos; + let subject = match self.operand_traced() { + Ok(subject) => subject, + Err(failed) => { + // When an operand followed the run of `(` but lacked a + // `)` for each of the first `unclosed` of them, those + // open groups and the rest open the operand. Otherwise + // the whole run opens groups. + let count = failed.unclosed.unwrap_or_else(|| { + self.toks[start..] + .iter() + .take_while(|t| t.kind == Kind::LParen) + .count() + }); + self.pos = start; + for _ in 0..count { + self.bump(); + groups.push(Group::default()); + } + continue; + } + }; + self.primary_after(subject)? + } else { + self.primary()? + }; // Fold the finished primary into the open groups. A group that // ends at `)` becomes a primary of the group around it. loop { @@ -259,6 +308,11 @@ impl Parser<'_> { /// A primary that does not open a group. fn primary(&mut self) -> Result { let subject = self.operand()?; + self.primary_after(subject) + } + + /// The rest of a primary whose first operand is `subject`. + fn primary_after(&mut self, subject: Operand) -> Result { let op = match self.kind() { Kind::Eq => CompareOp::Eq, Kind::Ne => CompareOp::Ne, @@ -301,12 +355,21 @@ impl Parser<'_> { }) } - /// `operand`, with an explicit stack of the calls that are open, so a - /// nested call such as `f(f(f(x)))` never recurses. fn operand(&mut self) -> Result { - let mut calls: Vec = Vec::new(); + self.operand_traced().map_err(|e| e.message) + } + + /// `operand`, with an explicit stack of the calls and parentheses that are + /// open, so a nested call such as `f(f(f(x)))` never recurses. + fn operand_traced(&mut self) -> Result { + let mut open: Vec> = Vec::new(); loop { let mut done = match self.kind() { + Kind::LParen => { + self.bump(); + open.push(None); + continue; + } Kind::ValueRef => { let value = self.text().to_owned(); self.bump(); @@ -316,27 +379,39 @@ impl Parser<'_> { let name = self.text().to_owned(); self.bump(); self.bump(); - calls.push(Call { + open.push(Some(Call { name, args: Vec::new(), - }); + })); continue; } - Kind::Name | Kind::NameRef => self.path()?, - _ => return Err(self.error()), + Kind::Name | Kind::NameRef => self.path().map_err(Unparsed::other)?, + _ => return Err(Unparsed::other(self.error())), }; loop { - let Some(open) = calls.last_mut() else { - return Ok(done); - }; - open.args.push(done); - if self.kind() == &Kind::Comma { - self.bump(); - break; + match open.last_mut() { + None => return Ok(done), + // A parenthesised operand is the operand inside. + Some(None) => { + if let Err(message) = self.expect(&Kind::RParen) { + let unclosed = open.iter().all(Option::is_none).then_some(open.len()); + return Err(Unparsed { message, unclosed }); + } + open.pop(); + } + Some(Some(call)) => { + call.args.push(done); + if self.kind() == &Kind::Comma { + self.bump(); + break; + } + self.expect(&Kind::RParen).map_err(Unparsed::other)?; + let Some(Some(call)) = open.pop() else { + unreachable!() + }; + done = Operand::Call(call); + } } - self.expect(&Kind::RParen)?; - let call = calls.pop().unwrap_or_else(|| unreachable!()); - done = Operand::Call(call); } } } diff --git a/crates/core/src/expression/search_filter/mod.rs b/crates/core/src/expression/search_filter/mod.rs index da42e005a..a8e0d9101 100644 --- a/crates/core/src/expression/search_filter/mod.rs +++ b/crates/core/src/expression/search_filter/mod.rs @@ -215,3 +215,6 @@ mod tests_eval; #[cfg(test)] mod tests_depth; + +#[cfg(test)] +mod tests_operands; diff --git a/crates/core/src/expression/search_filter/tests_depth.rs b/crates/core/src/expression/search_filter/tests_depth.rs index 30925b819..c1fd5413e 100644 --- a/crates/core/src/expression/search_filter/tests_depth.rs +++ b/crates/core/src/expression/search_filter/tests_depth.rs @@ -160,6 +160,25 @@ fn deeply_nested_calls_answer_as_the_service_does() { assert_eq!(outcome(&expr), syntax("", "a")); } +#[test] +fn parentheses_inside_between_in_and_function_arguments() { + let cases = [ + ( + "a BETWEEN ".to_owned() + &"(".repeat(2000) + ":v AND :w", + syntax("AND", ":v AND :w"), + ), + ( + "a IN (".to_owned() + &"(".repeat(2000) + ":v)", + syntax("", ")"), + ), + ( + "attribute_exists(".to_owned() + &"(".repeat(2000) + "a)", + syntax("", ")"), + ), + ]; + assert_cases(&cases); +} + /// 300 operators is the most the grammar takes, so the deepest accepted tree /// is 300 levels. It parses, evaluates and drops on the worker stack. #[test] diff --git a/crates/core/src/expression/search_filter/tests_operands.rs b/crates/core/src/expression/search_filter/tests_operands.rs new file mode 100644 index 000000000..3184d8910 --- /dev/null +++ b/crates/core/src/expression/search_filter/tests_operands.rs @@ -0,0 +1,108 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Parenthesised operands. +//! +//! The expected answers were measured on the live service on 2026-11-23, +//! two requests each, against a missing table and an existing vector table. +//! `Ok` stands for a request the service passed to the table lookup. + +use std::collections::HashMap; + +use super::parse_search_filter; +use super::tests_support::{OK, p, used_values}; +use crate::error::DynamoDbError; +use crate::types::AttributeValue; + +/// `:v` is a string and `:w` a number, as in the measured requests. +pub(super) fn assert_measured(cases: &[(&str, String)]) { + let all: HashMap = [ + (":v".to_owned(), AttributeValue::S("x".to_owned())), + (":w".to_owned(), AttributeValue::N("2".to_owned())), + ] + .into(); + let mismatches: Vec = cases + .iter() + .filter_map(|(expr, expected)| { + let values = used_values(expr, &all); + let actual = match parse_search_filter(expr, None, Some(&values), 50) { + Ok(_) => OK.to_owned(), + Err(DynamoDbError::ValidationException(m)) => m, + Err(other) => format!("{other:?}"), + }; + (&actual != expected) + .then(|| format!("{expr:?}: expected {expected:?}, got {actual:?}")) + }) + .collect(); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +pub(super) fn syntax(token: &str, near: &str) -> String { + p(&format!( + "Syntax error; token: \"{token}\", near: \"{near}\"" + )) +} + +#[test] +fn an_operand_may_be_parenthesised() { + let mixed_bounds = p( + "The BETWEEN operator requires same data type for lower and upper \ + bounds; lower bound operand: AttributeValue: {S:x}, upper bound \ + operand: AttributeValue: {N:2}", + ); + let not_allowed = |f: &str| { + p(&format!( + "The function is not allowed in a search condition; function: {f}" + )) + }; + assert_measured(&[ + ("(a) = :v", OK.to_owned()), + ("a = (:v)", OK.to_owned()), + ("(:v) = a", OK.to_owned()), + ("NOT (a) = :v", OK.to_owned()), + ("(a) = :v AND b = :v", OK.to_owned()), + ("((a) = :v)", OK.to_owned()), + ("(a = :v) OR (b) = :v", OK.to_owned()), + ("(a = :v OR b = :v) AND (c) = :v", OK.to_owned()), + ("(a = (:v))", OK.to_owned()), + ("(a) IN (:v)", OK.to_owned()), + ("a IN ((:v), (:w))", OK.to_owned()), + ("a IN ((:v))", OK.to_owned()), + ("a BETWEEN (:v) AND :w", mixed_bounds.clone()), + ("a BETWEEN (:v) AND (:w)", mixed_bounds.clone()), + ("(a) BETWEEN :v AND :w", mixed_bounds), + ("attribute_exists((a))", OK.to_owned()), + ("(attribute_exists(a))", OK.to_owned()), + ("(size(a)) = :w", not_allowed("size")), + ("size((a)) = :w", not_allowed("size")), + ("begins_with((a), (:v))", not_allowed("begins_with")), + ]); +} + +#[test] +fn a_parenthesised_operand_ends_the_operand() { + assert_measured(&[ + ("(a)", syntax("", ")")), + ("(a).b = :v", syntax(".", ").b")), + ("(a)[0] = :v", syntax("[", ")[0")), + ("a.(b) = :v", syntax("(", ".(b")), + ("(a) = :v)", syntax(")", ":v)")), + ("(a = :v) = :v", syntax("=", ") = :v")), + ("() = :v", syntax(")", "() =")), + ]); +} + +/// A group whose whole content is a group is redundant. The `(` of a call and +/// of an IN list does not count as a group. +#[test] +fn only_doubled_groups_are_redundant() { + let redundant = p("The expression has redundant parentheses;"); + assert_measured(&[ + ("((a)) = :v", redundant.clone()), + ("(((a))) = :v", redundant.clone()), + ("a BETWEEN ((:v)) AND :w", redundant.clone()), + ("attribute_exists(((a)))", redundant), + ("attribute_exists((a))", OK.to_owned()), + ("a IN ((:v))", OK.to_owned()), + ]); +} From 30488c7034416179a70721ef5e5c6dd12833a1da Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 18:00:24 +0000 Subject: [PATCH 014/101] fix(core): check search condition function operands by type The service checks each function operand against the types the function takes. size takes a string, binary, set, list or map and returns a number, so `size(size(a)) = :w` answers `Incorrect operand type for operator or function; operator or function: size, operand type: N`. begins_with takes strings and binaries on either side, so `begins_with(a, size(b))` and `begins_with(:w, a)` answer the same for begins_with. attribute_type takes a type name as its second operand and answers the operand type for anything else, a path included. Only attribute_exists and attribute_not_exists require a path. A function that passes, such as `size(:v) = :w` or `begins_with(:v, :v)`, then meets the search rule that allows only the existence functions. The extended grammar required a path as the first operand of every function, so each of these requests answered `Operator or function requires a document path`. The tree-building check now applies the service's order: the operand count, the place a function may stand, the operand types, the distinct first operand, then the existence functions' path and the attribute type name. Verified with new tests of 32 expressions measured on the live service, two requests each, and with depth tests of up to 681 nested size calls inside a comparison, a BETWEEN bound, an IN list and begins_with. --- .../expression/search_filter/tests_depth.rs | 27 ++++ .../search_filter/tests_operands.rs | 142 ++++++++++++++++-- .../core/src/expression/search_filter/walk.rs | 80 ++++++---- 3 files changed, 209 insertions(+), 40 deletions(-) diff --git a/crates/core/src/expression/search_filter/tests_depth.rs b/crates/core/src/expression/search_filter/tests_depth.rs index c1fd5413e..4a5d326ae 100644 --- a/crates/core/src/expression/search_filter/tests_depth.rs +++ b/crates/core/src/expression/search_filter/tests_depth.rs @@ -179,6 +179,33 @@ fn parentheses_inside_between_in_and_function_arguments() { assert_cases(&cases); } +/// A size of a size answers the operand type of the innermost call that +/// takes a number. +#[test] +fn nested_size_calls_answer_the_operand_type() { + let size_of_n = p( + "Incorrect operand type for operator or function; operator or \ + function: size, operand type: N", + ); + let cases = [ + ( + "a BETWEEN ".to_owned() + &nested("size(", "b", ")", 678) + " AND :w", + size_of_n.clone(), + ), + ( + "a IN (".to_owned() + &nested("size(", "b", ")", 680) + ")", + size_of_n.clone(), + ), + (nested("size(", "a", ")", 681) + " = :v", size_of_n.clone()), + (nested("size(", "a", ")", 150) + " = :v", size_of_n.clone()), + ( + "begins_with(".to_owned() + &nested("size(", "a", ")", 600) + ", :v)", + size_of_n, + ), + ]; + assert_cases(&cases); +} + /// 300 operators is the most the grammar takes, so the deepest accepted tree /// is 300 levels. It parses, evaluates and drops on the worker stack. #[test] diff --git a/crates/core/src/expression/search_filter/tests_operands.rs b/crates/core/src/expression/search_filter/tests_operands.rs index 3184d8910..32799eb93 100644 --- a/crates/core/src/expression/search_filter/tests_operands.rs +++ b/crates/core/src/expression/search_filter/tests_operands.rs @@ -1,7 +1,7 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! Parenthesised operands. +//! Parenthesised operands, and the operands a function takes. //! //! The expected answers were measured on the live service on 2026-11-23, //! two requests each, against a missing table and an existing vector table. @@ -10,17 +10,20 @@ use std::collections::HashMap; use super::parse_search_filter; -use super::tests_support::{OK, p, used_values}; +use super::tests_support::{OK, n, p, s, used_values}; use crate::error::DynamoDbError; use crate::types::AttributeValue; /// `:v` is a string and `:w` a number, as in the measured requests. -pub(super) fn assert_measured(cases: &[(&str, String)]) { - let all: HashMap = [ - (":v".to_owned(), AttributeValue::S("x".to_owned())), - (":w".to_owned(), AttributeValue::N("2".to_owned())), - ] - .into(); +fn assert_measured(cases: &[(&str, String)]) { + assert_measured_with(&[(":v", s("x")), (":w", n("2"))], cases); +} + +fn assert_measured_with(values: &[(&str, AttributeValue)], cases: &[(&str, String)]) { + let all: HashMap = values + .iter() + .map(|(k, v)| ((*k).to_owned(), v.clone())) + .collect(); let mismatches: Vec = cases .iter() .filter_map(|(expr, expected)| { @@ -37,7 +40,7 @@ pub(super) fn assert_measured(cases: &[(&str, String)]) { assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); } -pub(super) fn syntax(token: &str, near: &str) -> String { +fn syntax(token: &str, near: &str) -> String { p(&format!( "Syntax error; token: \"{token}\", near: \"{near}\"" )) @@ -106,3 +109,124 @@ fn only_doubled_groups_are_redundant() { ("a IN ((:v))", OK.to_owned()), ]); } + +fn operand_type(function: &str, code: &str) -> String { + p(&format!( + "Incorrect operand type for operator or function; operator or function: {function}, \ + operand type: {code}" + )) +} + +fn not_allowed(function: &str) -> String { + p(&format!( + "The function is not allowed in a search condition; function: {function}" + )) +} + +/// size takes a string, binary, set, list or map, and returns a number; +/// begins_with takes strings and binaries. A path may hold any type. Only the +/// existence functions require a path. A function that passes these checks +/// meets the search rules, which allow only the existence functions. +#[test] +fn function_operands_are_checked_by_type() { + let path = |f: &str| { + p(&format!( + "Operator or function requires a document path; operator or function: {f}" + )) + }; + assert_measured(&[ + ("size(size(a)) = :w", operand_type("size", "N")), + ("size(size(size(a))) = :w", operand_type("size", "N")), + ("a = size(size(b))", operand_type("size", "N")), + ("size(size(:v)) = :w", operand_type("size", "N")), + ("begins_with(size(a), :v)", operand_type("begins_with", "N")), + ("begins_with(a, size(b))", operand_type("begins_with", "N")), + ("begins_with(size(a), :w)", operand_type("begins_with", "N")), + ( + "begins_with(size(a), size(a))", + operand_type("begins_with", "N"), + ), + ("begins_with(:w, a)", operand_type("begins_with", "N")), + ( + "attribute_type(size(a), :w)", + operand_type("attribute_type", "N"), + ), + ( + "attribute_type(a, size(b))", + operand_type("attribute_type", "N"), + ), + ( + "attribute_type(a, b)", + operand_type( + "attribute_type", + "{S,SS,N,NS,B,BS,BOOL,NULL,L,M,HD,DOUBLE,FLOAT,HDS,FS,DOUBLESET,DICT,DECIMAL,\ + INT,DECIMALSET,INTSET}", + ), + ), + ( + "attribute_type(a, a)", + p( + "The first operand must be distinct from the remaining operands for this \ + operator or function; operator: attribute_type, first operand: [a]", + ), + ), + ( + "begins_with(a, a)", + p( + "The first operand must be distinct from the remaining operands for this \ + operator or function; operator: begins_with, first operand: [a]", + ), + ), + ( + "attribute_type(size(a), :v)", + p("Invalid attribute type name found; type: x, valid types: \ + {S,SS,N,NS,B,BS,BOOL,NULL,L,M}"), + ), + ( + "size(attribute_exists(a)) = :w", + p( + "The function is not allowed to be used this way in an expression; \ + function: attribute_exists", + ), + ), + ("attribute_exists(:v)", path("attribute_exists")), + ("attribute_exists(size(a))", path("attribute_exists")), + ( + "attribute_not_exists(size(a))", + path("attribute_not_exists"), + ), + ("attribute_not_exists(:v)", path("attribute_not_exists")), + ("size(:v) = :w", not_allowed("size")), + ("begins_with(:v, :v)", not_allowed("begins_with")), + ("begins_with(:v, a)", not_allowed("begins_with")), + ("contains(size(a), :v)", not_allowed("contains")), + ("contains(:w, a)", not_allowed("contains")), + ]); + assert_measured_with( + &[(":t", s("S")), (":v", s("x"))], + &[ + ("attribute_type(size(a), :t)", not_allowed("attribute_type")), + ("attribute_type(:v, :t)", not_allowed("attribute_type")), + ], + ); + assert_measured_with( + &[ + (":n", n("2")), + (":w", n("2")), + (":t", AttributeValue::Bool(true)), + (":ss", AttributeValue::SS(["x".to_owned()].into())), + (":x", s("X")), + ], + &[ + ("size(:n) = :w", operand_type("size", "N")), + ("size(:t) = :w", operand_type("size", "BOOL")), + ("size(:ss) = :w", not_allowed("size")), + ("begins_with(a, :t)", operand_type("begins_with", "BOOL")), + ( + "attribute_type(a, :x)", + p("Invalid attribute type name found; type: X, valid types: \ + {S,SS,N,NS,B,BS,BOOL,NULL,L,M}"), + ), + ], + ); +} diff --git a/crates/core/src/expression/search_filter/walk.rs b/crates/core/src/expression/search_filter/walk.rs index 46d17d556..e5ccf0154 100644 --- a/crates/core/src/expression/search_filter/walk.rs +++ b/crates/core/src/expression/search_filter/walk.rs @@ -208,47 +208,62 @@ fn function(call: &Call, condition: bool, maps: &Maps<'_>) -> Result<(), String> "The function is not allowed to be used this way in an expression; function: {name}" )); } + // A nested call other than size failed above, when it was checked as an + // operand. Each operand's type must fit the function: a value has its + // own type, size returns a number, and a path may hold any type. + let fits: &[&str] = match name { + "size" => &["S", "B", "SS", "NS", "BS", "L", "M"], + "begins_with" => &["S", "B"], + _ => &TYPE_NAMES, + }; for arg in &call.args { - if let Operand::Call(inner) = arg - && inner.name != "size" + if let Some(code) = operand_code(arg, maps) + && !fits.contains(&code) { - return Err(format!( - "The function is not allowed to be used this way in an expression; \ - function: {}", - inner.name - )); + return Err(operand_type_code(name, code)); } } - if !matches!(call.args[0], Operand::Path(_)) { - return Err(format!( - "Operator or function requires a document path; operator or function: {name}" - )); + if expected == 2 { + distinct_first_operand(name, &call.args[0], [&call.args[1]], maps)?; } match name { - "begins_with" => { - if let Some(value) = literal(&call.args[1], maps) - && !matches!(value, AttributeValue::S(_) | AttributeValue::B(_)) - { - return Err(operand_type(name, value)); - } + "attribute_exists" | "attribute_not_exists" + if !matches!(call.args[0], Operand::Path(_)) => + { + Err(format!( + "Operator or function requires a document path; operator or function: {name}" + )) } "attribute_type" => match literal(&call.args[1], maps) { - Some(AttributeValue::S(type_name)) if TYPE_NAMES.contains(&type_name.as_str()) => {} - Some(AttributeValue::S(type_name)) => { - return Err(format!( - "Invalid attribute type name found; type: {type_name}, valid types: {{{}}}", - TYPE_NAMES.join(",") - )); + Some(AttributeValue::S(type_name)) if TYPE_NAMES.contains(&type_name.as_str()) => { + Ok(()) } - Some(other) => return Err(operand_type(name, other)), - None => {} + Some(AttributeValue::S(type_name)) => Err(format!( + "Invalid attribute type name found; type: {type_name}, valid types: {{{}}}", + TYPE_NAMES.join(",") + )), + Some(other) => Err(operand_type(name, other)), + None => Err(operand_type_code( + name, + operand_code(&call.args[1], maps).unwrap_or(ANY_TYPE), + )), }, - _ => {} + _ => Ok(()), } - if expected == 2 { - distinct_first_operand(name, &call.args[0], [&call.args[1]], maps)?; +} + +/// The type of every attribute a path may name, as the service lists it. +const ANY_TYPE: &str = "{S,SS,N,NS,B,BS,BOOL,NULL,L,M,HD,DOUBLE,FLOAT,HDS,FS,DOUBLESET,DICT,\ + DECIMAL,INT,DECIMALSET,INTSET}"; + +/// The type code of an operand whose type is known before evaluation: a +/// value's own type, and `N` for a call, which can only be size. +fn operand_code(o: &Operand, maps: &Maps<'_>) -> Option<&'static str> { + match o { + Operand::Value(_) => literal(o, maps).map(attribute_type_code), + Operand::Call(_) => Some("N"), + Operand::Path(_) => None, } - Ok(()) } fn literal<'a>(o: &Operand, maps: &Maps<'a>) -> Option<&'a AttributeValue> { @@ -259,10 +274,13 @@ fn literal<'a>(o: &Operand, maps: &Maps<'a>) -> Option<&'a AttributeValue> { } fn operand_type(operator: &str, value: &AttributeValue) -> String { + operand_type_code(operator, attribute_type_code(value)) +} + +fn operand_type_code(operator: &str, code: &str) -> String { format!( "Incorrect operand type for operator or function; operator or function: {operator}, \ - operand type: {}", - attribute_type_code(value) + operand type: {code}" ) } From 856a3146fcf008f5c965dfe5a77f7064984c96a9 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 18:02:11 +0000 Subject: [PATCH 015/101] test(core): pin the exact BETWEEN bound check of the search grammar The service compares BETWEEN bounds exactly, even though it evaluates an inline filter in binary64. `Price BETWEEN :lo AND :hi` with `:lo = 9007199254740993` and `:hi = 9007199254740992` answers `The BETWEEN operator requires upper bound to be greater than or equal to lower bound`, as do 38-digit neighbours, 1.0000000000000001E+100 over 1E+100, 0.10000000000000001 over 0.1, 1.0000000000000001E-10 over 1E-10 and -1E16 over -(1E16 + 1). `1.0` and `1`, and 2^53 and 2^53 + 1 in order, pass. ExtendDB already checks the bounds exactly, but no test held it: a bound check switched to binary64 passed every test. The new test sends those pairs, in the plain decimal form the engine passes numbers in, and checks the measured messages. Verified on the live service, two requests each, against a missing table and an existing vector table; switching the bound check to binary64 fails the test. --- .../expression/search_filter/tests_grammar.rs | 78 ++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/crates/core/src/expression/search_filter/tests_grammar.rs b/crates/core/src/expression/search_filter/tests_grammar.rs index a48bc6799..1831faca7 100644 --- a/crates/core/src/expression/search_filter/tests_grammar.rs +++ b/crates/core/src/expression/search_filter/tests_grammar.rs @@ -6,7 +6,7 @@ //! Not yet measured against the live service: every expected message here is //! a prediction, and a live run confirms or corrects it. -use super::tests_support::{OK, and_chain, assert_outcomes, in_list, outcome, p}; +use super::tests_support::{OK, and_chain, assert_outcomes, in_list, n, outcome, p}; const IN_LIST_ATTRIBUTE: &str = "The IN operator list must contain only expression attribute \ values (:value), not attribute names"; @@ -145,6 +145,82 @@ fn between_bounds_are_checked_while_the_tree_is_built() { ); } +/// The bound check compares numbers exactly, while evaluation compares them +/// as binary64: each pair below is equal in binary64 and out of order exactly. +/// The requests sent `1.0000000000000001E+100` and `1E+100`, and +/// `1.0000000000000001E-10` and `1E-10`; the engine passes numbers here in +/// the plain decimal form the service shows. Measured on the live service on +/// 2026-11-23, two requests each. +#[test] +fn between_bounds_compare_numbers_exactly() { + use std::collections::HashMap; + + use super::parse_search_filter; + use crate::error::DynamoDbError; + + let out_of_order = |lo: &str, hi: &str| { + p(&format!( + "The BETWEEN operator requires upper bound to be greater than or equal to lower \ + bound; lower bound operand: AttributeValue: {{N:{lo}}}, upper bound operand: \ + AttributeValue: {{N:{hi}}}" + )) + }; + let e100 = format!("10000000000000001{}", "0".repeat(84)); + let e100_hi = format!("1{}", "0".repeat(100)); + let cases = [ + ( + "9007199254740993", + "9007199254740992", + out_of_order("9007199254740993", "9007199254740992"), + ), + ( + "99999999999999999999999999999999999999", + "99999999999999999999999999999999999998", + out_of_order( + "99999999999999999999999999999999999999", + "99999999999999999999999999999999999998", + ), + ), + ( + e100.as_str(), + e100_hi.as_str(), + out_of_order(&e100, &e100_hi), + ), + ( + "0.10000000000000001", + "0.1", + out_of_order("0.10000000000000001", "0.1"), + ), + ( + "0.00000000010000000000000001", + "0.0000000001", + out_of_order("0.00000000010000000000000001", "0.0000000001"), + ), + ( + "-10000000000000000", + "-10000000000000001", + out_of_order("-10000000000000000", "-10000000000000001"), + ), + ("1.0", "1", OK.to_owned()), + ("9007199254740992", "9007199254740993", OK.to_owned()), + ]; + let mismatches: Vec = cases + .iter() + .filter_map(|(lo, hi, expected)| { + let values = HashMap::from([(":lo".to_owned(), n(lo)), (":hi".to_owned(), n(hi))]); + let actual = + match parse_search_filter("Price BETWEEN :lo AND :hi", None, Some(&values), 50) { + Ok(_) => OK.to_owned(), + Err(DynamoDbError::ValidationException(m)) => m, + Err(other) => format!("{other:?}"), + }; + (&actual != expected) + .then(|| format!("{lo} / {hi}: expected {expected:?}, got {actual:?}")) + }) + .collect(); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + #[test] fn ordering_takes_only_string_number_and_binary_values() { assert_outcomes( From 87b9c2c79e1cad3bde3c47b3377480a80acda49f Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 17:43:09 +0000 Subject: [PATCH 016/101] refactor(engine): move the search condition dispatch into its own module The handler parsed the search condition with one of two grammars and then resolved the scope with the matching schema check, inline. That dispatch and the equality-only scope resolution now live in search_vectors_condition.rs, a child module of the handler. This is a pure move: the checks, their order and their messages are unchanged. search_vectors.rs goes from 834 to 723 lines. Verified: cargo test -p extenddb-engine --lib search_vectors, feature off 19 passed, feature on 24 passed. --- crates/engine/src/search_vectors.rs | 135 ++----------- crates/engine/src/search_vectors_condition.rs | 181 ++++++++++++++++++ crates/engine/src/search_vectors_extended.rs | 2 +- 3 files changed, 194 insertions(+), 124 deletions(-) create mode 100644 crates/engine/src/search_vectors_condition.rs diff --git a/crates/engine/src/search_vectors.rs b/crates/engine/src/search_vectors.rs index 8362f623c..90755380a 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -14,14 +14,14 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use extenddb_core::error::DynamoDbError; -use extenddb_core::expression::{ - ExpressionMaps, Projection, validate_conditions_against_search_schema, -}; +use extenddb_core::expression::{ExpressionMaps, Projection}; use extenddb_core::types::{ - AttributeValue, DescribeTableInput, Item, ReturnConsumedCapacity, SearchSchemaElementType, - item_size_bytes, + AttributeValue, DescribeTableInput, Item, ReturnConsumedCapacity, item_size_bytes, }; +#[path = "search_vectors_condition.rs"] +mod condition; + use crate::OperationContext; use crate::create_table::storage_err_to_dynamo; use crate::serialize_output; @@ -130,9 +130,7 @@ pub async fn handle_search_vectors( &ctx.limits, )?; - // Structural validation of the filter expression (schema-independent). - // An account the extended grammar is enabled for gets that parser instead. - let extended = crate::search_vectors_extended::parse_request( + let parsed = condition::parse( vector_search, &ctx.account_id, input.search_condition_expression.as_deref(), @@ -141,16 +139,6 @@ pub async fn handle_search_vectors( input.projection_expression.as_deref(), ) .await?; - let conditions = match input.search_condition_expression.as_deref() { - Some(_) if extended.is_some() => Vec::new(), - Some(expr) => crate::search_vectors_params::equality_conditions( - expr, - input.expression_attribute_names.as_ref(), - input.expression_attribute_values.as_ref(), - input.projection_expression.as_deref(), - )?, - None => Vec::new(), - }; let key_info = ctx .table_key_info(&input.table_name) @@ -204,24 +192,11 @@ pub async fn handle_search_vectors( ))); } - let (hash_key, filters, item_filter) = match &extended { - Some(extended) => { - let (hash_key, item_filter) = crate::search_vectors_extended::resolve_scope( - extended, - vector_index.search_schema.as_deref(), - &table.attribute_definitions, - )?; - (hash_key, Vec::new(), Some(item_filter)) - } - None => { - let (hash_key, filters) = resolve_search_scope( - &conditions, - vector_index.search_schema.as_deref(), - &table.attribute_definitions, - )?; - (hash_key, filters, None) - } - }; + let (hash_key, filters, item_filter) = condition::resolve( + &parsed, + vector_index.search_schema.as_deref(), + &table.attribute_definitions, + )?; let search_output = vector_search .search_vectors(extenddb_storage::VectorSearch { @@ -471,95 +446,9 @@ fn search_request_bytes( .max(MIN_SEARCH_BYTES) } -/// Resolved search scope: the partition-scoping HASH equality, if the index -/// declares one, and the remaining inline-filter equalities. -type SearchScope<'a> = ( - Option<(&'a str, &'a AttributeValue)>, - Vec<(&'a str, &'a AttributeValue)>, -); - -/// Validate a search's conditions against the index search schema, then split -/// them into the partition scope and the remaining inline filters. -/// -/// The index's HASH element scopes the search to one partition; the remaining -/// conditions narrow within it. Declaring a HASH element is optional, but when -/// the index has one the service requires the search to supply it. -/// -/// Validation runs unconditionally, including when the caller supplied no -/// `SearchConditionExpression` at all. That is the whole point of doing it here -/// rather than at the call site behind a non-empty check: an index declaring a -/// HASH element and a search with no expression is a validation failure, and -/// skipping the check for empty conditions would return `None` for `hash_key` -/// and hand the backend an unscoped search. `VectorSearch::hash_key` promises -/// backend authors that `Some` is a mandatory predicate whenever the index -/// declares a HASH element, so that promise has to hold on every path. -/// -/// # Errors -/// -/// Returns `DynamoDbError::ValidationException` when the conditions reference an -/// attribute outside the search schema, omit a declared HASH attribute, or carry -/// a value whose type disagrees with the table's attribute definitions. -fn resolve_search_scope<'a>( - conditions: &'a [extenddb_core::expression::SearchCondition], - search_schema: Option<&'a [extenddb_core::types::SearchSchemaElement]>, - attribute_definitions: &[extenddb_core::types::AttributeDefinition], -) -> Result, DynamoDbError> { - let hash_attr = search_schema - .unwrap_or_default() - .iter() - .find(|e| e.element_type == SearchSchemaElementType::Hash) - .map(|e| e.attribute_name.as_str()); - - let hash_key: Option<(&str, &AttributeValue)> = hash_attr.and_then(|name| { - conditions - .iter() - .find(|c| c.attribute_name == name) - .map(|c| (c.attribute_name.as_str(), &c.value)) - }); - - // Refuse rather than search unscoped, and do it BEFORE the schema validation - // below so the caller gets the service's own wording. An earlier comment here - // asserted that "validation upstream guarantees it is present", which was - // untrue: no such validation existed, so a search that omitted the condition - // ran without a partition scope and returned HTTP 200 with ZERO results. That - // is the worst available failure mode, a silent wrong answer, and it told the - // caller "no matches" for a request the service rejects outright. - // - // The service distinguishes the two missing-HASH failure modes, both - // measured against the service 2026-08-19 in us-east-1 (table - // msgprobe-hashvix): omitting the SearchConditionExpression entirely gets - // the message below, while an expression that is supplied but omits the - // HASH attribute gets the validator's "must have all HASH attributes in - // configured SearchSchema". So this guard fires only for the empty case, - // and the omits-HASH case falls through to the validator. - if hash_attr.is_some() && conditions.is_empty() { - return Err(DynamoDbError::ValidationException( - "SearchConditionExpression must be provided when SearchSchema has a HASH key" - .to_owned(), - )); - } - - validate_conditions_against_search_schema(conditions, search_schema, attribute_definitions)?; - - // The validation above is what makes this hold; assert it so a future - // change that weakens the validator fails here rather than silently - // serving an unscoped search. - debug_assert!( - hash_attr.is_none() || hash_key.is_some(), - "index declares a HASH element but the resolved scope has no hash_key" - ); - - let filters: Vec<(&str, &AttributeValue)> = conditions - .iter() - .filter(|c| Some(c.attribute_name.as_str()) != hash_attr) - .map(|c| (c.attribute_name.as_str(), &c.value)) - .collect(); - - Ok((hash_key, filters)) -} - #[cfg(test)] mod tests { + use super::condition::resolve_search_scope; use super::*; use extenddb_core::expression::SearchCondition; use extenddb_core::types::{ diff --git a/crates/engine/src/search_vectors_condition.rs b/crates/engine/src/search_vectors_condition.rs new file mode 100644 index 000000000..bca75461b --- /dev/null +++ b/crates/engine/src/search_vectors_condition.rs @@ -0,0 +1,181 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The `SearchConditionExpression` of a `SearchVectors` request: the grammar +//! that parses it, and the scope it hands the backend. + +use std::collections::HashMap; +use std::sync::Arc; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::expression::{SearchCondition, validate_conditions_against_search_schema}; +use extenddb_core::types::{ + AttributeDefinition, AttributeValue, SearchSchemaElement, SearchSchemaElementType, +}; +use extenddb_storage::{VectorItemFilter, VectorSearchEngine}; + +use crate::search_vectors_extended::Extended; + +/// A search condition parsed by one of the two grammars. +pub(crate) struct Parsed { + extended: Option, + conditions: Vec, +} + +/// The HASH equality that selects the partition, the inline-filter +/// equalities, and the filter the backend applies to each candidate. +pub(crate) type Scope<'a> = ( + Option<(&'a str, &'a AttributeValue)>, + Vec<(&'a str, &'a AttributeValue)>, + Option>, +); + +/// Structural validation of the filter expression (schema-independent). +/// An account the extended grammar is enabled for gets that parser instead. +/// +/// # Errors +/// +/// Returns the `ValidationException` of the first failed check. +pub(crate) async fn parse( + vector_search: &dyn VectorSearchEngine, + account_id: &str, + expr: Option<&str>, + names: Option<&HashMap>, + values: Option<&HashMap>, + projection: Option<&str>, +) -> Result { + let extended = crate::search_vectors_extended::parse_request( + vector_search, + account_id, + expr, + names, + values, + projection, + ) + .await?; + let conditions = match expr { + Some(_) if extended.is_some() => Vec::new(), + Some(expr) => { + crate::search_vectors_params::equality_conditions(expr, names, values, projection)? + } + None => Vec::new(), + }; + Ok(Parsed { + extended, + conditions, + }) +} + +/// The scope of the search, once the schema checks pass. +/// +/// # Errors +/// +/// Returns the `ValidationException` of the first failed schema check. +pub(crate) fn resolve<'a>( + parsed: &'a Parsed, + search_schema: Option<&'a [SearchSchemaElement]>, + attribute_definitions: &[AttributeDefinition], +) -> Result, DynamoDbError> { + Ok(match &parsed.extended { + Some(extended) => { + let (hash_key, item_filter) = crate::search_vectors_extended::resolve_scope( + extended, + search_schema, + attribute_definitions, + )?; + (hash_key, Vec::new(), Some(item_filter)) + } + None => { + let (hash_key, filters) = + resolve_search_scope(&parsed.conditions, search_schema, attribute_definitions)?; + (hash_key, filters, None) + } + }) +} + +/// Resolved search scope: the partition-scoping HASH equality, if the index +/// declares one, and the remaining inline-filter equalities. +type SearchScope<'a> = ( + Option<(&'a str, &'a AttributeValue)>, + Vec<(&'a str, &'a AttributeValue)>, +); + +/// Validate a search's conditions against the index search schema, then split +/// them into the partition scope and the remaining inline filters. +/// +/// The index's HASH element scopes the search to one partition; the remaining +/// conditions narrow within it. Declaring a HASH element is optional, but when +/// the index has one the service requires the search to supply it. +/// +/// Validation runs unconditionally, including when the caller supplied no +/// `SearchConditionExpression` at all. That is the whole point of doing it here +/// rather than at the call site behind a non-empty check: an index declaring a +/// HASH element and a search with no expression is a validation failure, and +/// skipping the check for empty conditions would return `None` for `hash_key` +/// and hand the backend an unscoped search. `VectorSearch::hash_key` promises +/// backend authors that `Some` is a mandatory predicate whenever the index +/// declares a HASH element, so that promise has to hold on every path. +/// +/// # Errors +/// +/// Returns `DynamoDbError::ValidationException` when the conditions reference an +/// attribute outside the search schema, omit a declared HASH attribute, or carry +/// a value whose type disagrees with the table's attribute definitions. +pub(crate) fn resolve_search_scope<'a>( + conditions: &'a [extenddb_core::expression::SearchCondition], + search_schema: Option<&'a [extenddb_core::types::SearchSchemaElement]>, + attribute_definitions: &[extenddb_core::types::AttributeDefinition], +) -> Result, DynamoDbError> { + let hash_attr = search_schema + .unwrap_or_default() + .iter() + .find(|e| e.element_type == SearchSchemaElementType::Hash) + .map(|e| e.attribute_name.as_str()); + + let hash_key: Option<(&str, &AttributeValue)> = hash_attr.and_then(|name| { + conditions + .iter() + .find(|c| c.attribute_name == name) + .map(|c| (c.attribute_name.as_str(), &c.value)) + }); + + // Refuse rather than search unscoped, and do it BEFORE the schema validation + // below so the caller gets the service's own wording. An earlier comment here + // asserted that "validation upstream guarantees it is present", which was + // untrue: no such validation existed, so a search that omitted the condition + // ran without a partition scope and returned HTTP 200 with ZERO results. That + // is the worst available failure mode, a silent wrong answer, and it told the + // caller "no matches" for a request the service rejects outright. + // + // The service distinguishes the two missing-HASH failure modes, both + // measured against the service 2026-08-19 in us-east-1 (table + // msgprobe-hashvix): omitting the SearchConditionExpression entirely gets + // the message below, while an expression that is supplied but omits the + // HASH attribute gets the validator's "must have all HASH attributes in + // configured SearchSchema". So this guard fires only for the empty case, + // and the omits-HASH case falls through to the validator. + if hash_attr.is_some() && conditions.is_empty() { + return Err(DynamoDbError::ValidationException( + "SearchConditionExpression must be provided when SearchSchema has a HASH key" + .to_owned(), + )); + } + + validate_conditions_against_search_schema(conditions, search_schema, attribute_definitions)?; + + // The validation above is what makes this hold; assert it so a future + // change that weakens the validator fails here rather than silently + // serving an unscoped search. + debug_assert!( + hash_attr.is_none() || hash_key.is_some(), + "index declares a HASH element but the resolved scope has no hash_key" + ); + + let filters: Vec<(&str, &AttributeValue)> = conditions + .iter() + .filter(|c| Some(c.attribute_name.as_str()) != hash_attr) + .map(|c| (c.attribute_name.as_str(), &c.value)) + .collect(); + + Ok((hash_key, filters)) +} diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs index 64023fbcf..57e0d00f2 100644 --- a/crates/engine/src/search_vectors_extended.rs +++ b/crates/engine/src/search_vectors_extended.rs @@ -14,7 +14,7 @@ //! [`install_search_filter_settings`], so a change applies without a restart. //! Until a store is installed, no account gets the grammar. -pub(crate) use imp::{parse_request, resolve_scope}; +pub(crate) use imp::{Extended, parse_request, resolve_scope}; #[cfg(feature = "search-inequality-filters")] pub use imp::install_search_filter_settings; From f78cd31cb5fecd0ae23c91d3127047014707fe92 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 17:49:52 +0000 Subject: [PATCH 017/101] fix(engine): read the search filter setting per server, cached, bounded The extended SearchConditionExpression grammar is enabled per account by the search_inequality_filters runtime setting. A fault in the service's own configuration path is never answered as a caller error. ExtendDB read the setting from the catalog on every SearchVectors request that carried a condition, with no timeout, and treated a failed read as "off". A transient catalog fault therefore answered an inequality request with a non-retryable ValidationException. The store sat in one process-wide slot: the last server to install one won, and a poisoned lock read as "no store" without a log line. Each server now installs its settings store against its own storage engine. A read is kept for one second and shared by concurrent requests, bounded at two seconds, and a failed or late read answers ServiceUnavailableException, the classified error ExtendDB uses for transient storage faults. A write through the management API drops the kept reads, so the change applies at once; a write through the CLI applies within the refresh interval. A malformed value is logged once per change instead of once per request. A storage engine with no installed store enables no account. Verified: engine unit tests for each property (per-server stores, no store, failed read, read past the timeout, refresh interval, one shared read for 16 concurrent requests, management write); cargo test -p extenddb-engine --lib search_vectors, feature on 33 passed, feature off 19 passed; clippy -D warnings on engine and server with the feature. --- crates/engine/src/lib.rs | 2 +- crates/engine/src/search_vectors.rs | 1 + crates/engine/src/search_vectors_condition.rs | 4 +- crates/engine/src/search_vectors_extended.rs | 62 ++--- .../src/search_vectors_extended_tests.rs | 98 +++++--- crates/engine/src/search_vectors_settings.rs | 186 +++++++++++++++ .../src/search_vectors_settings_tests.rs | 213 ++++++++++++++++++ crates/server/src/management/ops_settings.rs | 4 + crates/server/src/serve.rs | 4 +- 9 files changed, 497 insertions(+), 77 deletions(-) create mode 100644 crates/engine/src/search_vectors_settings.rs create mode 100644 crates/engine/src/search_vectors_settings_tests.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d7df9944a..dfa231aca 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -82,7 +82,7 @@ pub use request_limits::check_request_item_counts; pub use scan::handle_scan; pub use search_vectors::handle_search_vectors; #[cfg(feature = "search-inequality-filters")] -pub use search_vectors_extended::install_search_filter_settings; +pub use search_vectors_extended::{install_search_filter_settings, search_filter_settings_changed}; pub use streams::{SHARD_ITERATOR_EXPIRED_MESSAGE, ShardIteratorClass, classify_shard_iterator}; pub use streams::{ShardIterator, decode_shard_iterator, encode_shard_iterator}; pub use streams::{ diff --git a/crates/engine/src/search_vectors.rs b/crates/engine/src/search_vectors.rs index 90755380a..5c6422836 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -131,6 +131,7 @@ pub async fn handle_search_vectors( )?; let parsed = condition::parse( + &ctx.storage, vector_search, &ctx.account_id, input.search_condition_expression.as_deref(), diff --git a/crates/engine/src/search_vectors_condition.rs b/crates/engine/src/search_vectors_condition.rs index bca75461b..586a3b909 100644 --- a/crates/engine/src/search_vectors_condition.rs +++ b/crates/engine/src/search_vectors_condition.rs @@ -12,7 +12,7 @@ use extenddb_core::expression::{SearchCondition, validate_conditions_against_sea use extenddb_core::types::{ AttributeDefinition, AttributeValue, SearchSchemaElement, SearchSchemaElementType, }; -use extenddb_storage::{VectorItemFilter, VectorSearchEngine}; +use extenddb_storage::{StorageEngine, VectorItemFilter, VectorSearchEngine}; use crate::search_vectors_extended::Extended; @@ -37,6 +37,7 @@ pub(crate) type Scope<'a> = ( /// /// Returns the `ValidationException` of the first failed check. pub(crate) async fn parse( + storage: &Arc, vector_search: &dyn VectorSearchEngine, account_id: &str, expr: Option<&str>, @@ -45,6 +46,7 @@ pub(crate) async fn parse( projection: Option<&str>, ) -> Result { let extended = crate::search_vectors_extended::parse_request( + storage, vector_search, account_id, expr, diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs index 57e0d00f2..4c63ce615 100644 --- a/crates/engine/src/search_vectors_extended.rs +++ b/crates/engine/src/search_vectors_extended.rs @@ -9,33 +9,33 @@ //! `None` and the handler runs exactly as it does without this module. //! //! With the feature on, the `search_inequality_filters` runtime setting says -//! which accounts get the grammar. It is read on every request through the -//! settings store the server installs with -//! [`install_search_filter_settings`], so a change applies without a restart. +//! which accounts get the grammar. It is read through the settings store the +//! server installs with [`install_search_filter_settings`] (see +//! `search_vectors_settings.rs`), so a change applies without a restart. //! Until a store is installed, no account gets the grammar. pub(crate) use imp::{Extended, parse_request, resolve_scope}; #[cfg(feature = "search-inequality-filters")] -pub use imp::install_search_filter_settings; +#[path = "search_vectors_settings.rs"] +mod settings; + +#[cfg(feature = "search-inequality-filters")] +pub use settings::{install_search_filter_settings, search_filter_settings_changed}; #[cfg(feature = "search-inequality-filters")] mod imp { use std::collections::HashMap; - use std::sync::{Arc, RwLock}; + use std::sync::Arc; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::search_filter::{ - DEFAULT_MAX_CONDITIONS, EnabledAccounts, SearchFilter, parse_search_filter, + DEFAULT_MAX_CONDITIONS, SearchFilter, parse_search_filter, }; use extenddb_core::expression::search_params::with_unused_names; - use extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS; use extenddb_core::types::{AttributeDefinition, AttributeValue, Item, SearchSchemaElement}; use extenddb_storage::error::StorageError; - use extenddb_storage::management_store::SettingsStore; - use extenddb_storage::{VectorItemFilter, VectorSearchEngine}; - - static SETTINGS: RwLock>> = RwLock::new(None); + use extenddb_storage::{StorageEngine, VectorItemFilter, VectorSearchEngine}; /// The HASH attribute and the value that selects its partition, and the /// filter the backend applies to each candidate. @@ -44,34 +44,6 @@ mod imp { Arc, ); - /// Read the `search_inequality_filters` setting from `store` on every - /// SearchVectors request. The server calls this once at startup. - pub fn install_search_filter_settings(store: Arc) { - if let Ok(mut slot) = SETTINGS.write() { - *slot = Some(store); - } - } - - /// The accounts the setting enables. An absent, unreadable or malformed - /// value enables none, so a fault never widens the grammar. - async fn enabled_accounts() -> EnabledAccounts { - let store = SETTINGS.read().ok().and_then(|slot| slot.clone()); - let Some(store) = store else { - return EnabledAccounts::Off; - }; - match store.get_setting(SEARCH_INEQUALITY_FILTERS).await { - Ok(Some(value)) => EnabledAccounts::parse(&value).unwrap_or_else(|reason| { - tracing::warn!("{SEARCH_INEQUALITY_FILTERS} = {value:?} ignored: {reason}"); - EnabledAccounts::Off - }), - Ok(None) => EnabledAccounts::Off, - Err(e) => { - tracing::warn!("{SEARCH_INEQUALITY_FILTERS} could not be read: {e:?}"); - EnabledAccounts::Off - } - } - } - /// A search condition parsed with the extended grammar. pub(crate) struct Extended(Arc); @@ -87,8 +59,10 @@ mod imp { /// /// # Errors /// - /// Returns the `ValidationException` of the first failed check. + /// Returns the `ValidationException` of the first failed check, and + /// `ServiceUnavailableException` when the setting cannot be read. pub(crate) async fn parse_request( + storage: &Arc, _served_by: &dyn VectorSearchEngine, account_id: &str, expr: Option<&str>, @@ -101,7 +75,10 @@ mod imp { }; // Cross-account access is refused before dispatch, so the caller is // the table owner. - if !enabled_accounts().await.enabled_for(account_id, None) { + if !super::settings::enabled_accounts(storage) + .await? + .enabled_for(account_id, None) + { return Ok(None); } with_unused_names( @@ -149,7 +126,7 @@ mod imp { use extenddb_core::error::DynamoDbError; use extenddb_core::types::{AttributeDefinition, AttributeValue, SearchSchemaElement}; - use extenddb_storage::{VectorItemFilter, VectorSearchEngine}; + use extenddb_storage::{StorageEngine, VectorItemFilter, VectorSearchEngine}; /// The HASH attribute and the value that selects its partition, and the /// filter the backend applies to each candidate. @@ -163,6 +140,7 @@ mod imp { #[allow(clippy::unused_async)] pub(crate) async fn parse_request( + _storage: &Arc, _served_by: &dyn VectorSearchEngine, _account_id: &str, _expr: Option<&str>, diff --git a/crates/engine/src/search_vectors_extended_tests.rs b/crates/engine/src/search_vectors_extended_tests.rs index be7e5b032..26405ca79 100644 --- a/crates/engine/src/search_vectors_extended_tests.rs +++ b/crates/engine/src/search_vectors_extended_tests.rs @@ -4,8 +4,7 @@ //! Which requests the extended grammar parses, and the filter it hands the //! backend. //! -//! The settings store is process-wide, so the tests that install one hold -//! `SERIAL` for their whole run. +//! Each test installs its store against a storage engine of its own. use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -17,13 +16,14 @@ use extenddb_core::types::{ }; use extenddb_storage::management_store::{OpError, OpResult, SettingsStore}; use extenddb_storage::{ - BoxedFuture, VectorSearch, VectorSearchEngine, VectorSearchOutput, VectorSearchResult, + BoxedFuture, StorageEngine, VectorSearch, VectorSearchEngine, VectorSearchOutput, + VectorSearchResult, }; +use extenddb_storage_sqlite::SqliteEngine; use futures::future::BoxFuture; -use super::imp::{install_search_filter_settings, parse_request, resolve_scope}; - -static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +use super::imp::{parse_request, resolve_scope}; +use super::install_search_filter_settings; const CALLER: &str = "111111111111"; @@ -46,9 +46,16 @@ impl SettingsStore for Store { } } -fn install(value: Result, ()>) { +/// A storage engine whose server reads `value` for the setting. +async fn install(value: Result, ()>) -> Arc { + let storage: Arc = Arc::new( + SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) + .await + .expect("an in-memory database opens"), + ); let value = value.map(|v| v.map(str::to_owned)); - install_search_filter_settings(Arc::new(Store(Mutex::new(value)))); + install_search_filter_settings(&storage, Arc::new(Store(Mutex::new(value)))); + storage } struct Served; @@ -74,16 +81,18 @@ fn values() -> HashMap { const INEQUALITY: &str = "Country = :c AND Price > :p"; -async fn parsed(expr: Option<&str>) -> Result { +async fn parsed( + storage: &Arc, + expr: Option<&str>, +) -> Result { let values = values(); - parse_request(&Served, CALLER, expr, None, Some(&values), None) + parse_request(storage, &Served, CALLER, expr, None, Some(&values), None) .await .map(|parsed| parsed.is_some()) } #[tokio::test] async fn the_setting_selects_the_accounts() { - let _serial = SERIAL.lock().await; for (value, expected) in [ (Ok(None), false), (Ok(Some("off")), false), @@ -91,33 +100,52 @@ async fn the_setting_selects_the_accounts() { (Ok(Some("111111111111")), true), (Ok(Some("222222222222,111111111111")), true), (Ok(Some("222222222222")), false), - // a value that does not parse, and a store that fails, read as off + // a value that does not parse reads as off (Ok(Some("on")), false), - (Err(()), false), ] { - install(value); + let storage = install(value).await; assert_eq!( - parsed(Some(INEQUALITY)).await.unwrap(), + parsed(&storage, Some(INEQUALITY)).await.unwrap(), expected, "{value:?}" ); } } +#[tokio::test] +async fn a_store_that_fails_answers_a_retryable_fault() { + let storage = install(Err(())).await; + let err = parsed(&storage, Some(INEQUALITY)).await.unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ServiceUnavailable(m) + if m == "Service is temporarily unavailable"), + "{err:?}" + ); +} + +#[tokio::test] +async fn without_an_installed_store_no_account_gets_the_grammar() { + let storage: Arc = Arc::new( + SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) + .await + .expect("an in-memory database opens"), + ); + assert!(!parsed(&storage, Some(INEQUALITY)).await.unwrap()); +} + #[tokio::test] async fn no_expression_is_left_to_the_equality_path() { - let _serial = SERIAL.lock().await; - install(Ok(Some("all"))); - assert!(!parsed(None).await.unwrap()); + let storage = install(Ok(Some("all"))).await; + assert!(!parsed(&storage, None).await.unwrap()); } #[tokio::test] async fn an_enabled_account_gets_the_extended_messages() { - let _serial = SERIAL.lock().await; - install(Ok(Some("all"))); - let err = parsed(Some( - "Country = :c AND Price > :p AND begins_with(Category, :c)", - )) + let storage = install(Ok(Some("all"))).await; + let err = parsed( + &storage, + Some("Country = :c AND Price > :p AND begins_with(Category, :c)"), + ) .await .unwrap_err(); let DynamoDbError::ValidationException(message) = err else { @@ -132,11 +160,11 @@ async fn an_enabled_account_gets_the_extended_messages() { #[tokio::test] async fn a_name_neither_expression_uses_is_refused() { - let _serial = SERIAL.lock().await; - install(Ok(Some("all"))); + let storage = install(Ok(Some("all"))).await; let values = values(); let names: HashMap = [("#u".to_owned(), "x".to_owned())].into(); let err = parse_request( + &storage, &Served, CALLER, Some(INEQUALITY), @@ -154,6 +182,7 @@ async fn a_name_neither_expression_uses_is_refused() { ); let used: HashMap = [("#u".to_owned(), "Price".to_owned())].into(); let projected = parse_request( + &storage, &Served, CALLER, Some(INEQUALITY), @@ -175,13 +204,20 @@ fn item(country: &str, price: &str) -> Item { #[tokio::test] async fn the_scope_selects_the_hash_partition_and_filters_items() { - let _serial = SERIAL.lock().await; - install(Ok(Some("all"))); + let storage = install(Ok(Some("all"))).await; let values = values(); - let extended = parse_request(&Served, CALLER, Some(INEQUALITY), None, Some(&values), None) - .await - .unwrap() - .expect("parsed with the extended grammar"); + let extended = parse_request( + &storage, + &Served, + CALLER, + Some(INEQUALITY), + None, + Some(&values), + None, + ) + .await + .unwrap() + .expect("parsed with the extended grammar"); let schema = [ SearchSchemaElement { attribute_name: "Country".to_owned(), diff --git a/crates/engine/src/search_vectors_settings.rs b/crates/engine/src/search_vectors_settings.rs new file mode 100644 index 000000000..1d3b4dadd --- /dev/null +++ b/crates/engine/src/search_vectors_settings.rs @@ -0,0 +1,186 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The `search_inequality_filters` setting, as each server reads it. +//! +//! The server installs its settings store against its storage engine with +//! [`install_search_filter_settings`], so two servers in one process read +//! their own catalogs. A storage engine without an installed store enables no +//! account. +//! +//! A read is kept for [`REFRESH`], so a busy server reads the catalog about +//! once per interval rather than once per request, and a change made through +//! the management API applies at once through +//! [`search_filter_settings_changed`]. A read that fails or outlasts +//! [`READ_TIMEOUT`] answers `ServiceUnavailableException`, as other transient +//! storage faults do; it never changes which grammar an account gets. + +use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::time::Duration; + +use tokio::time::Instant; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::expression::search_filter::EnabledAccounts; +use extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS; +use extenddb_storage::StorageEngine; +use extenddb_storage::management_store::SettingsStore; + +/// How long a read of the setting is used before the next request reads it +/// again. +pub(crate) const REFRESH: Duration = Duration::from_secs(1); + +/// How long a read of the setting may take before the request is answered +/// with `ServiceUnavailableException`. +pub(crate) const READ_TIMEOUT: Duration = Duration::from_secs(2); + +/// Each storage engine of this process with the settings of its server. +type Servers = Vec<(Weak, Arc)>; + +/// The servers of this process. +static SERVERS: Mutex = Mutex::new(Vec::new()); + +/// Read the `search_inequality_filters` setting from `store` for the +/// SearchVectors requests that `storage` serves. The server calls this once +/// at startup. +pub fn install_search_filter_settings( + storage: &Arc, + store: Arc, +) { + let mut servers = SERVERS.lock().unwrap_or_else(PoisonError::into_inner); + servers.retain(|(engine, _)| engine.strong_count() > 0 && !same(engine, storage)); + servers.push((Arc::downgrade(storage), Arc::new(Settings::new(store)))); +} + +/// Drop every kept read of the setting, so the next request reads it. The +/// management API calls this after it writes the setting. +pub fn search_filter_settings_changed() { + let servers = SERVERS.lock().unwrap_or_else(PoisonError::into_inner); + for (_, settings) in servers.iter() { + *settings.kept.lock().unwrap_or_else(PoisonError::into_inner) = None; + } +} + +/// The accounts the setting enables on the server that `storage` belongs +/// to. An absent or malformed value enables none. +/// +/// # Errors +/// +/// Returns `ServiceUnavailableException` when the setting cannot be read. +pub(crate) async fn enabled_accounts( + storage: &Arc, +) -> Result { + let settings = SERVERS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .find(|(engine, _)| same(engine, storage)) + .map(|(_, settings)| Arc::clone(settings)); + match settings { + Some(settings) => settings.enabled_accounts().await, + None => Ok(EnabledAccounts::Off), + } +} + +fn same(engine: &Weak, storage: &Arc) -> bool { + std::ptr::addr_eq(engine.as_ptr(), Arc::as_ptr(storage)) +} + +/// One read of the setting. +struct Kept { + read_at: Instant, + /// The stored value, so a malformed value is logged once per change. + raw: Option, + /// `None` when the read failed. + accounts: Option, +} + +struct Settings { + store: Arc, + kept: Mutex>, + /// Held by the one request that reads the store when the kept read is + /// stale, so concurrent requests wait for that read instead of sending + /// their own. + reading: tokio::sync::Mutex<()>, +} + +impl Settings { + fn new(store: Arc) -> Self { + Self { + store, + kept: Mutex::new(None), + reading: tokio::sync::Mutex::new(()), + } + } + + /// The kept answer, while it is fresh. + fn fresh(&self) -> Option> { + let kept = self.kept.lock().unwrap_or_else(PoisonError::into_inner); + let kept = kept.as_ref().filter(|k| k.read_at.elapsed() < REFRESH)?; + Some(kept.accounts.clone().ok_or_else(unavailable)) + } + + async fn enabled_accounts(&self) -> Result { + if let Some(answer) = self.fresh() { + return answer; + } + let _reading = self.reading.lock().await; + if let Some(answer) = self.fresh() { + return answer; + } + let read = tokio::time::timeout( + READ_TIMEOUT, + self.store.get_setting(SEARCH_INEQUALITY_FILTERS), + ) + .await; + let previous = self + .kept + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take() + .and_then(|k| k.raw); + let (raw, accounts) = match read { + Ok(Ok(raw)) => { + let accounts = Self::parse(raw.as_deref(), previous.as_deref()); + (raw, Some(accounts)) + } + Ok(Err(e)) => { + tracing::warn!("{SEARCH_INEQUALITY_FILTERS} could not be read: {e:?}"); + (previous, None) + } + Err(_) => { + tracing::warn!( + "{SEARCH_INEQUALITY_FILTERS} could not be read within {READ_TIMEOUT:?}" + ); + (previous, None) + } + }; + let answer = accounts.clone().ok_or_else(unavailable); + *self.kept.lock().unwrap_or_else(PoisonError::into_inner) = Some(Kept { + read_at: Instant::now(), + raw, + accounts, + }); + answer + } + + fn parse(raw: Option<&str>, previous: Option<&str>) -> EnabledAccounts { + let Some(value) = raw else { + return EnabledAccounts::Off; + }; + EnabledAccounts::parse(value).unwrap_or_else(|reason| { + if previous != Some(value) { + tracing::warn!("{SEARCH_INEQUALITY_FILTERS} = {value:?} ignored: {reason}"); + } + EnabledAccounts::Off + }) + } +} + +fn unavailable() -> DynamoDbError { + DynamoDbError::ServiceUnavailable("Service is temporarily unavailable".to_owned()) +} + +#[cfg(test)] +#[path = "search_vectors_settings_tests.rs"] +mod tests; diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs new file mode 100644 index 000000000..a112cd65c --- /dev/null +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -0,0 +1,213 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! How a server reads the `search_inequality_filters` setting: per server, +//! kept for a short interval, bounded in time, and a fault answered as a +//! retryable error. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::expression::search_filter::EnabledAccounts; +use extenddb_storage::StorageEngine; +use extenddb_storage::management_store::{OpError, OpResult, SettingsStore}; +use extenddb_storage_sqlite::SqliteEngine; +use futures::future::BoxFuture; + +use super::{ + READ_TIMEOUT, REFRESH, Settings, enabled_accounts, install_search_filter_settings, + search_filter_settings_changed, +}; + +/// How a read of the store answers. +#[derive(Clone)] +enum Answer { + Value(Option), + Fail, + Hang, +} + +/// A settings store with one answer for every read, counting the reads. +struct Store { + answer: Mutex, + reads: AtomicUsize, +} + +impl Store { + fn new(answer: Answer) -> Arc { + Arc::new(Self { + answer: Mutex::new(answer), + reads: AtomicUsize::new(0), + }) + } + + fn value(value: &str) -> Arc { + Self::new(Answer::Value(Some(value.to_owned()))) + } + + fn set(&self, answer: Answer) { + *self.answer.lock().unwrap() = answer; + } + + fn reads(&self) -> usize { + self.reads.load(Ordering::SeqCst) + } +} + +impl SettingsStore for Store { + fn get_setting(&self, _key: &str) -> BoxFuture<'_, OpResult>> { + self.reads.fetch_add(1, Ordering::SeqCst); + let answer = self.answer.lock().unwrap().clone(); + Box::pin(async move { + match answer { + Answer::Value(v) => Ok(v), + Answer::Fail => Err(OpError::Internal("connection reset".to_owned())), + Answer::Hang => std::future::pending().await, + } + }) + } + + fn set_setting(&self, _key: &str, _value: &str) -> BoxFuture<'_, OpResult<()>> { + Box::pin(async { Ok(()) }) + } + + fn list_settings(&self) -> BoxFuture<'_, OpResult>> { + Box::pin(async { Ok(Vec::new()) }) + } +} + +async fn storage() -> Arc { + Arc::new( + SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) + .await + .expect("an in-memory database opens"), + ) +} + +fn is_unavailable(answer: &Result) -> bool { + matches!(answer, Err(DynamoDbError::ServiceUnavailable(m)) + if m == "Service is temporarily unavailable") +} + +#[tokio::test] +async fn a_server_without_a_store_enables_no_account() { + let storage = storage().await; + assert_eq!( + enabled_accounts(&storage).await.unwrap(), + EnabledAccounts::Off + ); +} + +#[tokio::test] +async fn each_server_reads_its_own_store() { + let (first, second, third) = (storage().await, storage().await, storage().await); + install_search_filter_settings(&first, Store::value("all")); + install_search_filter_settings(&second, Store::value("111111111111")); + assert_eq!( + enabled_accounts(&first).await.unwrap(), + EnabledAccounts::All + ); + assert_eq!( + enabled_accounts(&second).await.unwrap(), + EnabledAccounts::parse("111111111111").unwrap() + ); + assert_eq!( + enabled_accounts(&third).await.unwrap(), + EnabledAccounts::Off + ); + // installing again replaces the server's store + install_search_filter_settings(&first, Store::value("off")); + assert_eq!( + enabled_accounts(&first).await.unwrap(), + EnabledAccounts::Off + ); +} + +#[tokio::test] +async fn a_failed_read_is_a_retryable_fault() { + let store = Store::new(Answer::Fail); + let settings = Settings::new(store.clone()); + assert!(is_unavailable(&settings.enabled_accounts().await)); +} + +#[tokio::test(start_paused = true)] +async fn a_read_that_does_not_finish_is_a_retryable_fault() { + let store = Store::new(Answer::Hang); + let settings = Settings::new(store.clone()); + let started = tokio::time::Instant::now(); + assert!(is_unavailable(&settings.enabled_accounts().await)); + assert_eq!(started.elapsed(), READ_TIMEOUT); +} + +#[tokio::test(start_paused = true)] +async fn a_read_is_kept_for_the_refresh_interval() { + let store = Store::value("all"); + let settings = Settings::new(store.clone()); + for _ in 0..5 { + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::All + ); + } + assert_eq!(store.reads(), 1); + + store.set(Answer::Value(Some("off".to_owned()))); + tokio::time::advance(REFRESH / 2).await; + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::All + ); + tokio::time::advance(REFRESH / 2).await; + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + assert_eq!(store.reads(), 2); + + // a fault is kept as briefly, then the next read recovers + store.set(Answer::Fail); + tokio::time::advance(REFRESH).await; + assert!(is_unavailable(&settings.enabled_accounts().await)); + store.set(Answer::Value(None)); + assert!(is_unavailable(&settings.enabled_accounts().await)); + tokio::time::advance(REFRESH).await; + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + assert_eq!(store.reads(), 4); +} + +#[tokio::test(start_paused = true)] +async fn concurrent_requests_share_one_read() { + let store = Store::value("all"); + let settings = Arc::new(Settings::new(store.clone())); + let tasks: Vec<_> = (0..16) + .map(|_| { + let settings = Arc::clone(&settings); + tokio::spawn(async move { settings.enabled_accounts().await }) + }) + .collect(); + for task in tasks { + assert_eq!(task.await.unwrap().unwrap(), EnabledAccounts::All); + } + assert_eq!(store.reads(), 1); +} + +#[tokio::test] +async fn a_change_through_the_management_api_applies_at_once() { + let storage = storage().await; + let store = Store::value("off"); + install_search_filter_settings(&storage, store.clone()); + assert_eq!( + enabled_accounts(&storage).await.unwrap(), + EnabledAccounts::Off + ); + store.set(Answer::Value(Some("all".to_owned()))); + search_filter_settings_changed(); + assert_eq!( + enabled_accounts(&storage).await.unwrap(), + EnabledAccounts::All + ); +} diff --git a/crates/server/src/management/ops_settings.rs b/crates/server/src/management/ops_settings.rs index 407593f7e..c6d52c401 100755 --- a/crates/server/src/management/ops_settings.rs +++ b/crates/server/src/management/ops_settings.rs @@ -198,6 +198,10 @@ pub async fn set_setting( // the read path actually consults instead of adding a second, ignored one. let key = extenddb_core::settings_keys::canonical_key(key); store.set_setting(key, value).await?; + #[cfg(feature = "search-inequality-filters")] + if key == extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS { + extenddb_engine::search_filter_settings_changed(); + } tracing::warn!( target: "extenddb::audit::settings", diff --git a/crates/server/src/serve.rs b/crates/server/src/serve.rs index 48832a263..1b64336f6 100644 --- a/crates/server/src/serve.rs +++ b/crates/server/src/serve.rs @@ -735,9 +735,9 @@ async fn serve_inner(params: ServeParams, port: u16) -> anyhow::Result<()> { .map_or(config_throttling, |v| v == "true"); // SearchVectors reads the `search_inequality_filters` setting from this - // store on every request, so a change applies without a restart. + // store, so a change applies without a restart. #[cfg(feature = "search-inequality-filters")] - extenddb_engine::install_search_filter_settings(catalog_store.clone()); + extenddb_engine::install_search_filter_settings(&storage, catalog_store.clone()); let throttle = Arc::new(extenddb_core::throttle::ThrottleManager::new( limits.per_account_max_rcu, From 2787d2017a7855b9fc4e0edf408167fcac098456 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 17:53:36 +0000 Subject: [PATCH 018/101] fix(engine): keep equality-only search conditions as equality pairs DynamoDB compares inline-filter strings and binary values exactly and inline-filter numbers as binary64 in a SearchConditionExpression made of equalities only. Measured on 2026-11-23, two runs: Price = 9007199254740993 matches a stored 9007199254740992, 1 matches 1.00000000000000000001, 0.3 does not match 0.30000000000000004; Cat = "A", "a " and the decomposed form of a composed string each match only themselves; the numeric HASH value selects its partition exactly. For an account the extended grammar is enabled for, ExtendDB sent every search condition to the backend as an item filter, including Country = :c alone and Country = :c AND Cat = :s. On PostgreSQL that dropped the SQL equality filter and the LIMIT, so the backend read and sorted the whole partition for requests it had answered with a top-k query before the setting was turned on. A condition that the equality-only grammar also accepts, on distinct attributes, with no number among its inline-filter values, now reaches the backend as equality pairs with no item filter; the HASH value still selects the partition. Any other condition, a number equality included, goes to the item filter, which compares numbers as binary64 as the service does. Accounts the setting leaves out are unchanged. Verified: engine tests for each route (string and binary pairs with and without a HASH element, the HASH equality alone, a number equality matching its binary64 neighbour through the item filter, inequality, OR, attribute_exists and IN, and the setting off); cargo test -p extenddb-engine --lib search_vectors, feature on 38 passed, feature off 19 passed. --- crates/engine/src/search_vectors_condition.rs | 61 ++++- .../src/search_vectors_condition_tests.rs | 236 ++++++++++++++++++ 2 files changed, 294 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/search_vectors_condition_tests.rs diff --git a/crates/engine/src/search_vectors_condition.rs b/crates/engine/src/search_vectors_condition.rs index 586a3b909..6b6d91e63 100644 --- a/crates/engine/src/search_vectors_condition.rs +++ b/crates/engine/src/search_vectors_condition.rs @@ -3,12 +3,23 @@ //! The `SearchConditionExpression` of a `SearchVectors` request: the grammar //! that parses it, and the scope it hands the backend. +//! +//! A condition that the extended grammar parses still goes to the backend as +//! equality pairs when that gives the same results, so the backend can apply +//! it in its own query. The service compares inline-filter strings and binary +//! values exactly and inline-filter numbers as binary64, and the equality +//! pairs compare every value exactly. So the pairs carry a condition of +//! equalities on distinct attributes when no inline-filter value is a +//! number; any other condition goes to the backend as an item filter. use std::collections::HashMap; use std::sync::Arc; use extenddb_core::error::DynamoDbError; -use extenddb_core::expression::{SearchCondition, validate_conditions_against_search_schema}; +use extenddb_core::expression::{ + SearchCondition, validate_conditions_against_search_schema, + validate_search_condition_expression, +}; use extenddb_core::types::{ AttributeDefinition, AttributeValue, SearchSchemaElement, SearchSchemaElementType, }; @@ -17,6 +28,9 @@ use extenddb_storage::{StorageEngine, VectorItemFilter, VectorSearchEngine}; use crate::search_vectors_extended::Extended; /// A search condition parsed by one of the two grammars. +/// +/// With the extended grammar, `conditions` holds the equality pairs of the +/// same condition when the equality-only grammar also accepts it. pub(crate) struct Parsed { extended: Option, conditions: Vec, @@ -56,7 +70,9 @@ pub(crate) async fn parse( ) .await?; let conditions = match expr { - Some(_) if extended.is_some() => Vec::new(), + Some(expr) if extended.is_some() => { + validate_search_condition_expression(expr, names, values).unwrap_or_default() + } Some(expr) => { crate::search_vectors_params::equality_conditions(expr, names, values, projection)? } @@ -85,7 +101,10 @@ pub(crate) fn resolve<'a>( search_schema, attribute_definitions, )?; - (hash_key, Vec::new(), Some(item_filter)) + match equality_pairs(&parsed.conditions, search_schema) { + Some(filters) => (hash_key, filters, None), + None => (hash_key, Vec::new(), Some(item_filter)), + } } None => { let (hash_key, filters) = @@ -95,6 +114,38 @@ pub(crate) fn resolve<'a>( }) } +/// The inline-filter equalities of an extended-grammar condition that the +/// equality pairs express with the same results, or `None` when the backend +/// needs the item filter. The HASH equality selects the partition and is not +/// among them. +fn equality_pairs<'a>( + conditions: &'a [SearchCondition], + search_schema: Option<&[SearchSchemaElement]>, +) -> Option> { + let hash_attr = search_schema + .unwrap_or_default() + .iter() + .find(|e| e.element_type == SearchSchemaElementType::Hash) + .map(|e| e.attribute_name.as_str()); + let mut filters: Vec<(&str, &AttributeValue)> = Vec::with_capacity(conditions.len()); + for (i, c) in conditions.iter().enumerate() { + if conditions[..i] + .iter() + .any(|seen| seen.attribute_name == c.attribute_name) + { + return None; + } + if Some(c.attribute_name.as_str()) == hash_attr { + continue; + } + if !matches!(c.value, AttributeValue::S(_) | AttributeValue::B(_)) { + return None; + } + filters.push((c.attribute_name.as_str(), &c.value)); + } + (!conditions.is_empty()).then_some(filters) +} + /// Resolved search scope: the partition-scoping HASH equality, if the index /// declares one, and the remaining inline-filter equalities. type SearchScope<'a> = ( @@ -181,3 +232,7 @@ pub(crate) fn resolve_search_scope<'a>( Ok((hash_key, filters)) } + +#[cfg(all(test, feature = "search-inequality-filters"))] +#[path = "search_vectors_condition_tests.rs"] +mod tests; diff --git a/crates/engine/src/search_vectors_condition_tests.rs b/crates/engine/src/search_vectors_condition_tests.rs new file mode 100644 index 000000000..723842559 --- /dev/null +++ b/crates/engine/src/search_vectors_condition_tests.rs @@ -0,0 +1,236 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Which conditions reach the backend as equality pairs and which as an item +//! filter, for an account the extended grammar is enabled for. +//! +//! The service compares inline-filter strings and binary values exactly and +//! inline-filter numbers as binary64. Measured on DynamoDB on 2026-11-23 with +//! conditions of equalities only, two runs: `Price = 9007199254740993` matches +//! a stored 9007199254740992, and `Cat = "A"` does not match a stored "a". + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use extenddb_core::types::{ + AttributeDefinition, AttributeValue, Item, ScalarAttributeType, SearchSchemaElement, + SearchSchemaElementType, +}; +use extenddb_storage::StorageEngine; +use extenddb_storage::management_store::{OpResult, SettingsStore}; +use extenddb_storage_sqlite::SqliteEngine; +use futures::future::BoxFuture; + +use super::{Scope, parse, resolve}; + +struct Store(Mutex); + +impl SettingsStore for Store { + fn get_setting(&self, _key: &str) -> BoxFuture<'_, OpResult>> { + let value = self.0.lock().unwrap().clone(); + Box::pin(async move { Ok(Some(value)) }) + } + + fn set_setting(&self, _key: &str, _value: &str) -> BoxFuture<'_, OpResult<()>> { + Box::pin(async { Ok(()) }) + } + + fn list_settings(&self) -> BoxFuture<'_, OpResult>> { + Box::pin(async { Ok(Vec::new()) }) + } +} + +async fn server(setting: &str) -> Arc { + let storage: Arc = Arc::new( + SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) + .await + .expect("an in-memory database opens"), + ); + crate::install_search_filter_settings(&storage, Arc::new(Store(Mutex::new(setting.into())))); + storage +} + +fn values() -> HashMap { + [ + (":c", AttributeValue::S("US".to_owned())), + (":s", AttributeValue::S("a".to_owned())), + (":t", AttributeValue::B(vec![1])), + (":p", AttributeValue::N("9007199254740993".to_owned())), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect() +} + +fn schema(hash: bool) -> Vec { + let element = |name: &str, element_type| SearchSchemaElement { + attribute_name: name.to_owned(), + element_type, + }; + let mut schema = vec![ + element("Price", SearchSchemaElementType::InlineFilter), + element("Cat", SearchSchemaElementType::InlineFilter), + element("Tag", SearchSchemaElementType::InlineFilter), + ]; + if hash { + schema.insert(0, element("Country", SearchSchemaElementType::Hash)); + } + schema +} + +fn definitions() -> Vec { + [ + ("Country", ScalarAttributeType::S), + ("Price", ScalarAttributeType::N), + ("Cat", ScalarAttributeType::S), + ("Tag", ScalarAttributeType::B), + ] + .into_iter() + .map(|(name, attribute_type)| AttributeDefinition { + attribute_name: name.to_owned(), + attribute_type, + }) + .collect() +} + +/// What the backend receives: the HASH value, the equality pairs, and +/// whether it gets an item filter. The filter, when present, is applied to +/// `item`. +type Routed = ( + Option, + Vec<(String, AttributeValue)>, + Option, +); + +async fn routed(setting: &str, hash: bool, expr: &str, item: &Item) -> Routed { + let storage = server(setting).await; + let served = storage + .as_vector_search() + .expect("SQLite serves vector search"); + let values: HashMap = values() + .into_iter() + .filter(|(k, _)| expr.contains(k.as_str())) + .collect(); + let parsed = parse( + &storage, + served, + "111111111111", + Some(expr), + None, + Some(&values), + None, + ) + .await + .unwrap(); + let schema = schema(hash); + let (hash_key, filters, item_filter): Scope<'_> = + resolve(&parsed, Some(&schema), &definitions()).unwrap(); + ( + hash_key.map(|(_, v)| v.clone()), + filters + .into_iter() + .map(|(n, v)| (n.to_owned(), v.clone())) + .collect(), + item_filter.map(|f| f.matches(item).unwrap()), + ) +} + +/// An item whose `Price` equals `:p` in binary64 and not exactly. +fn item() -> Item { + [ + ("Country", AttributeValue::S("US".to_owned())), + ("Price", AttributeValue::N("9007199254740992".to_owned())), + ("Cat", AttributeValue::S("a".to_owned())), + ("Tag", AttributeValue::B(vec![1])), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect() +} + +fn us() -> Option { + Some(AttributeValue::S("US".to_owned())) +} + +fn pair(name: &str, value: &str) -> Vec<(String, AttributeValue)> { + values() + .get(value) + .map(|v| vec![(name.to_owned(), v.clone())]) + .unwrap() +} + +#[tokio::test] +async fn string_and_binary_equalities_stay_equality_pairs() { + assert_eq!( + routed("all", true, "Country = :c AND Cat = :s", &item()).await, + (us(), pair("Cat", ":s"), None) + ); + let tag_then_cat = [pair("Tag", ":t"), pair("Cat", ":s")].concat(); + assert_eq!( + routed( + "all", + true, + "Tag = :t AND Country = :c AND Cat = :s", + &item() + ) + .await, + (us(), tag_then_cat, None) + ); + let cat_then_tag = [pair("Cat", ":s"), pair("Tag", ":t")].concat(); + assert_eq!( + routed("all", false, "Cat = :s AND Tag = :t", &item()).await, + (None, cat_then_tag, None) + ); +} + +#[tokio::test] +async fn the_hash_equality_alone_needs_no_filter() { + assert_eq!( + routed("all", true, "Country = :c", &item()).await, + (us(), Vec::new(), None) + ); +} + +#[tokio::test] +async fn a_number_equality_goes_to_the_item_filter_and_compares_as_binary64() { + assert_eq!( + routed("all", true, "Country = :c AND Price = :p", &item()).await, + (us(), Vec::new(), Some(true)) + ); + assert_eq!( + routed( + "all", + true, + "Country = :c AND Cat = :s AND Price = :p", + &item() + ) + .await, + (us(), Vec::new(), Some(true)) + ); + assert_eq!( + routed("all", false, "Price = :p", &item()).await, + (None, Vec::new(), Some(true)) + ); +} + +#[tokio::test] +async fn a_condition_beyond_equality_goes_to_the_item_filter() { + for expr in [ + "Country = :c AND Cat <> :s", + "Country = :c AND (Cat = :s OR Tag = :t)", + "Country = :c AND attribute_exists(Cat)", + "Country = :c AND Cat IN (:s)", + ] { + let (hash_key, filters, filter) = routed("all", true, expr, &item()).await; + assert_eq!((hash_key, filters), (us(), Vec::new()), "{expr}"); + assert!(filter.is_some(), "{expr}"); + } +} + +#[tokio::test] +async fn an_account_the_setting_leaves_out_keeps_the_equality_grammar() { + assert_eq!( + routed("off", true, "Country = :c AND Price = :p", &item()).await, + (us(), pair("Price", ":p"), None) + ); +} From a0662091dfccf9d1d443dcb9592c0bb4a0b52aa7 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 17:56:55 +0000 Subject: [PATCH 019/101] test(engine): pin the search map checks ahead of table and vector checks DynamoDB answers an empty ExpressionAttributeValues or ExpressionAttributeNames with " must not be empty" ahead of a missing table and ahead of a SearchVector whose length does not match the index. Measured on 2026-11-23, two runs each; with valid maps the same requests answer ResourceNotFoundException and "Input search vector dimension 2 does not match vector index dimension 4". ExtendDB answers in that order, but only unit tests of the map checks pinned it, and those cannot see where the handler runs them. Two handler tests on a SQLite catalog now send each request and its valid-map control. The settings tests also gain a deadline of their own around the bounded read and a store that answers after a delay, so concurrent readers interleave; the equality-pair route no longer checks for a repeated attribute, since repeated pairs combine with AND as the item filter does. Verified: cargo test -p extenddb-engine --lib search_vectors, feature on 40 passed, feature off 21 passed. --- crates/engine/src/search_vectors.rs | 4 + crates/engine/src/search_vectors_condition.rs | 12 +- .../engine/src/search_vectors_order_tests.rs | 178 ++++++++++++++++++ .../src/search_vectors_settings_tests.rs | 14 +- 4 files changed, 197 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/search_vectors_order_tests.rs diff --git a/crates/engine/src/search_vectors.rs b/crates/engine/src/search_vectors.rs index 5c6422836..4c74ecb8a 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -447,6 +447,10 @@ fn search_request_bytes( .max(MIN_SEARCH_BYTES) } +#[cfg(test)] +#[path = "search_vectors_order_tests.rs"] +mod order_tests; + #[cfg(test)] mod tests { use super::condition::resolve_search_scope; diff --git a/crates/engine/src/search_vectors_condition.rs b/crates/engine/src/search_vectors_condition.rs index 6b6d91e63..954992e90 100644 --- a/crates/engine/src/search_vectors_condition.rs +++ b/crates/engine/src/search_vectors_condition.rs @@ -9,8 +9,8 @@ //! it in its own query. The service compares inline-filter strings and binary //! values exactly and inline-filter numbers as binary64, and the equality //! pairs compare every value exactly. So the pairs carry a condition of -//! equalities on distinct attributes when no inline-filter value is a -//! number; any other condition goes to the backend as an item filter. +//! equalities when no inline-filter value is a number; any other condition +//! goes to the backend as an item filter. use std::collections::HashMap; use std::sync::Arc; @@ -128,13 +128,7 @@ fn equality_pairs<'a>( .find(|e| e.element_type == SearchSchemaElementType::Hash) .map(|e| e.attribute_name.as_str()); let mut filters: Vec<(&str, &AttributeValue)> = Vec::with_capacity(conditions.len()); - for (i, c) in conditions.iter().enumerate() { - if conditions[..i] - .iter() - .any(|seen| seen.attribute_name == c.attribute_name) - { - return None; - } + for c in conditions { if Some(c.attribute_name.as_str()) == hash_attr { continue; } diff --git a/crates/engine/src/search_vectors_order_tests.rs b/crates/engine/src/search_vectors_order_tests.rs new file mode 100644 index 000000000..a5c1a9e05 --- /dev/null +++ b/crates/engine/src/search_vectors_order_tests.rs @@ -0,0 +1,178 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The expression-map checks of `SearchVectors` answer ahead of a missing +//! table and a dimension mismatch, under either grammar. +//! +//! Measured on DynamoDB on 2026-11-23, two runs each: an empty +//! `ExpressionAttributeValues` or `ExpressionAttributeNames` answers +//! " must not be empty" against a missing table and with a two-element +//! `SearchVector` on a four-dimension index; with valid maps the same +//! requests answer ResourceNotFoundException and the dimension message. + +use std::sync::Arc; +use std::time::Duration; + +use serde_json::{Value, json}; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::limits::LimitsConfig; +use extenddb_storage::server_components::ServerComponentsOptions; +use extenddb_storage_sqlite::SqliteConfig; +use tempfile::TempDir; + +use crate::{AuthorizedKeyInfo, BackupRuntime, OperationContext}; + +/// A context on a bootstrapped SQLite catalog in `dir`, where a table is +/// created ACTIVE. +async fn context(dir: &TempDir) -> OperationContext { + let config = SqliteConfig { + path: dir.path().join("catalog.sqlite").display().to_string(), + pool_size: 2, + }; + let mut options = ServerComponentsOptions::default(); + options.bootstrap_if_uninitialized = true; + options.release = "test"; + let components = + (extenddb_storage_sqlite::backend().server_components)(&config, "us-east-1", options) + .await + .unwrap_or_else(|e| panic!("server components: {e:?}")); + let account_id = components + .catalog_store + .default_account_id() + .await + .unwrap() + .expect("the bootstrapped account"); + components + .catalog_store + .set_setting("control_plane_delay_seconds", "0") + .await + .unwrap(); + OperationContext { + storage: components.engine, + backup: Arc::new(BackupRuntime::new(1)), + limits: Arc::new(LimitsConfig::default()), + region: Arc::from("us-east-1"), + account_id: Arc::from(account_id), + 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, + } +} + +/// A table "tbl" with a four-dimension vector index "vix" whose HASH element +/// is `Country`, once the index serves searches. +async fn table(ctx: &OperationContext) { + crate::handle_create_table( + json!({ + "TableName": "tbl", + "BillingMode": "PAY_PER_REQUEST", + "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], + "AttributeDefinitions": [ + {"AttributeName": "id", "AttributeType": "S"}, + {"AttributeName": "Country", "AttributeType": "S"} + ], + "VectorIndexes": [{ + "IndexName": "vix", + "Dimensions": 4, + "DistanceFunction": "COSINE", + "VectorAttribute": {"AttributeName": "emb"}, + "SearchSchema": [ + {"AttributeName": "Country", "SearchSchemaElementType": "HASH"} + ], + "Projection": {"ProjectionType": "ALL"} + }] + }), + ctx, + ) + .await + .expect("CreateTable"); + let probe = request("tbl", 4, Some(json!({":us": {"S": "US"}})), None); + for _ in 0..200 { + match crate::handle_search_vectors(probe.clone(), ctx).await { + Ok(_) => return, + Err(_) => tokio::time::sleep(Duration::from_millis(25)).await, + } + } + panic!("the vector index did not become ACTIVE"); +} + +fn request(table: &str, dims: usize, values: Option, names: Option) -> Value { + let mut body = json!({ + "TableName": table, + "IndexName": "vix", + "SearchVector": vec![json!({"N": "1"}); dims], + "TopK": 5, + "SearchConditionExpression": "Country = :us", + }); + if let Some(values) = values { + body["ExpressionAttributeValues"] = values; + } + if let Some(names) = names { + body["ExpressionAttributeNames"] = names; + } + body +} + +async fn answer(ctx: &OperationContext, body: Value) -> DynamoDbError { + match crate::handle_search_vectors(body, ctx).await { + Ok(_) => panic!("the request was answered"), + Err(e) => e, + } +} + +fn validation(message: &str) -> impl Fn(&DynamoDbError) -> bool + '_ { + move |e| matches!(e, DynamoDbError::ValidationException(m) if m == message) +} + +fn us() -> Option { + Some(json!({":us": {"S": "US"}})) +} + +#[tokio::test] +async fn an_empty_map_answers_before_a_missing_table() { + let dir = TempDir::new().unwrap(); + let ctx = context(&dir).await; + let values_empty = answer(&ctx, request("missing", 4, Some(json!({})), None)).await; + assert!( + validation("ExpressionAttributeValues must not be empty")(&values_empty), + "{values_empty:?}" + ); + let names_empty = answer(&ctx, request("missing", 4, us(), Some(json!({})))).await; + assert!( + validation("ExpressionAttributeNames must not be empty")(&names_empty), + "{names_empty:?}" + ); + let missing = answer(&ctx, request("missing", 4, us(), None)).await; + assert!( + matches!(missing, DynamoDbError::ResourceNotFoundException(_)), + "{missing:?}" + ); +} + +#[tokio::test] +async fn an_empty_map_answers_before_a_dimension_mismatch() { + let dir = TempDir::new().unwrap(); + let ctx = context(&dir).await; + table(&ctx).await; + let values_empty = answer(&ctx, request("tbl", 2, Some(json!({})), None)).await; + assert!( + validation("ExpressionAttributeValues must not be empty")(&values_empty), + "{values_empty:?}" + ); + let names_empty = answer(&ctx, request("tbl", 2, us(), Some(json!({})))).await; + assert!( + validation("ExpressionAttributeNames must not be empty")(&names_empty), + "{names_empty:?}" + ); + let mismatch = answer(&ctx, request("tbl", 2, us(), None)).await; + assert!( + validation("Input search vector dimension 2 does not match vector index dimension 4")( + &mismatch + ), + "{mismatch:?}" + ); +} diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index a112cd65c..f6aaaeda8 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -24,6 +24,8 @@ use super::{ #[derive(Clone)] enum Answer { Value(Option), + /// The value, after a delay that lets concurrent readers interleave. + Slow(String), Fail, Hang, } @@ -62,6 +64,10 @@ impl SettingsStore for Store { Box::pin(async move { match answer { Answer::Value(v) => Ok(v), + Answer::Slow(v) => { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + Ok(Some(v)) + } Answer::Fail => Err(OpError::Internal("connection reset".to_owned())), Answer::Hang => std::future::pending().await, } @@ -136,7 +142,11 @@ async fn a_read_that_does_not_finish_is_a_retryable_fault() { let store = Store::new(Answer::Hang); let settings = Settings::new(store.clone()); let started = tokio::time::Instant::now(); - assert!(is_unavailable(&settings.enabled_accounts().await)); + // the test's own deadline, so a read without a bound fails here + let answer = tokio::time::timeout(READ_TIMEOUT * 2, settings.enabled_accounts()) + .await + .expect("the read is bounded"); + assert!(is_unavailable(&answer)); assert_eq!(started.elapsed(), READ_TIMEOUT); } @@ -181,7 +191,7 @@ async fn a_read_is_kept_for_the_refresh_interval() { #[tokio::test(start_paused = true)] async fn concurrent_requests_share_one_read() { - let store = Store::value("all"); + let store = Store::new(Answer::Slow("all".to_owned())); let settings = Arc::new(Settings::new(store.clone())); let tasks: Vec<_> = (0..16) .map(|_| { From 3ca3985f1f6f85fd3b827c9a31016bd0cf65deac Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 18:39:48 +0000 Subject: [PATCH 020/101] fix(storage-postgres): read a filtered vector search in bounded pages A SearchVectors condition that the backend evaluates on each decoded item cuts top_k after the condition, so a search reads the score ordering until top_k rows match. On PostgreSQL that search ran the search statement with no limit: the server sorted the whole partition with every row's item and embedding, sent all of it, and kept sending after the search had its top_k rows. The connection stayed busy until the last row was read, and a dropped request left the statement running to the end. The search now reads the ordering in pages. Each page is the ordering after the last row of the page before, compared on the score and the whole base key, with a limit, and carries only each row's score and address, so the server runs a bounded top-N sort that may run in parallel. Pages start at four times top_k (at least 64 rows) and grow eight times per step to 65,536. The items of a page are read by address 1,024 at a time, in page order, and the search stops at the top_k-th match. The embeddings of the kept rows are read last. Every statement runs in one REPEATABLE READ READ ONLY transaction, so they read one snapshot and the result is the one a single statement would give, ties included. A search that is dropped closes its connection instead of returning it to the pool, and sends pg_cancel_backend to the backend, so the statement in flight stops. Measured on pgvector pg16, one partition, 64 dimensions, a 2,000-byte attribute per item, top_k 10, one pooled connection, ten searches in a row (so work left on the connection counts), median of three interleaved runs, before and after, at 100,000 rows: - a condition that every row satisfies: 1,370 ms, 264 ms - one that 1 percent of rows satisfy: 1,363 ms, 1,011 ms - one that 0.1 percent satisfy: 2,067 ms, 2,376 ms - one that no row satisfies: 9,731 ms, 12,895 ms Sort spill for twelve searches went from 172 to 516 MB to at most 13 MB, and the server's peak memory during a run from up to 786 MB to 261 MB. At 10,000 rows the four cases take 236, 278, 977 and 1,035 ms before and 90, 486, 1,316 and 1,301 ms after. A search dropped after 5 ms or 60 ms left no active statement at the first check, 1 ms later; before, the statement ran for about 0.9 s at 100,000 rows. The result equals the unfiltered ordering filtered and cut at top_k, ids and scores, for top_k 1, 10, 50, 100 and 1,000 at 10,000 and 100,000 rows with groups of seven equal scores. --- crates/storage-postgres/src/lib.rs | 1 + crates/storage-postgres/src/vector_search.rs | 139 +++++++--- .../src/vector_search_filtered.rs | 262 ++++++++++++++++-- .../src/vector_search_scan.rs | 208 ++++++++++++++ 4 files changed, 538 insertions(+), 72 deletions(-) create mode 100644 crates/storage-postgres/src/vector_search_scan.rs diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index 735c7f90e..234e07a98 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -45,6 +45,7 @@ mod update_table; mod vector; mod vector_search; mod vector_search_filtered; +mod vector_search_scan; mod warm_throughput; mod worker_store; mod workers; diff --git a/crates/storage-postgres/src/vector_search.rs b/crates/storage-postgres/src/vector_search.rs index 9925a4f81..73a706010 100644 --- a/crates/storage-postgres/src/vector_search.rs +++ b/crates/storage-postgres/src/vector_search.rs @@ -5,7 +5,9 @@ //! //! The whole search is one query. Distance, partition scoping, inline filters, //! ordering and the row limit all evaluate in the server, so the wire carries the -//! `top_k` hits rather than every candidate row. That is the reason the embedding +//! `top_k` hits rather than every candidate row. A search with a condition that +//! this process evaluates reads the ordering in bounded pages instead, as +//! `vector_search_filtered` describes. Scoring in the server is the reason the embedding //! is stored in pgvector's own column type: the SQLite backend has to stream every //! row of a partition and compute distances in process, which is the cost //! ADR-0004 accepted for a backend that cannot load an extension. @@ -156,6 +158,42 @@ fn report_score(function: DistanceFunction, ordered: f64) -> f64 { } } +/// Map a search statement's failure to the error the search reports. +fn map_search_error(e: sqlx::Error, index_name: &str) -> StorageError { + let mapped = crate::vector::map_vector_sql_error(e); + // The data table is gone, which happens when the index is deleted between + // the catalog read and the search statement. That is a deleted index, so + // it answers like one instead of reporting an internal failure the caller + // can do nothing about. + if crate::gsi_queue::is_undefined_table(&mapped) { + StorageError::IndexNotFound(index_name.to_owned()) + } else { + mapped + } +} + +/// One hit: the stored item with its vector attribute, and the reported score. +fn hit( + mut item: extenddb_core::types::Item, + vector_attribute_name: &str, + embedding: &Vector, + function: DistanceFunction, + ordered: f64, +) -> VectorHit { + // Reinstated from the stored f32s rather than from a second copy in the + // payload, so what comes back is the narrowed value that was actually + // indexed. The engine drops it again unless a projection expression names + // it. + item.insert( + vector_attribute_name.to_owned(), + extenddb_core::validation::vector_item::vector_attribute(embedding.as_slice()), + ); + VectorHit { + item, + score: report_score(function, ordered), + } +} + impl VectorSearchEngine for PostgresEngine { fn search_vectors(&self, req: VectorSearch<'_>) -> BoxedFuture<'_, VectorSearchResult> { // The request borrows from the caller's frame, so own what the future needs. @@ -256,17 +294,56 @@ impl VectorSearchEngine for PostgresEngine { // alone leaves their relative order up to the plan, and two identical // searches can disagree about which of them the top_k cut keeps. let base_sks = crate::data::all_sort_key_info(&base_key_schema, &base_attr_defs); - let tie_break = crate::data::vector_index::base_key_columns(&base_sks) - .into_iter() + let key_columns = crate::data::vector_index::base_key_columns(&base_sks); + let tie_break = key_columns + .iter() .map(|col| format!("{col} ASC")) .collect::>() .join(", "); + let score = score_expression(function, 4); + if let Some(condition) = &item_filter { + let filters = filters + .iter() + .map(|(name, value)| { + serde_json::to_string(value) + .map(|json| (name.clone(), json)) + .map_err(|e| StorageError::Internal(format!("filter value: {e}"))) + }) + .collect::, _>>()?; + let statement = crate::vector_search_filtered::ScanStatement { + score, + from: format!("FROM {vec_table} WHERE part = $2{predicates}"), + key_columns, + vec_table, + vector: Vector::from(query_vector), + partition: partition.into_bytes(), + norm: query_norm, + filters, + }; + let rows = crate::vector_search_filtered::fetch_matching( + &statement, + &self.data_pool, + condition.as_ref(), + top_k, + &|e| map_search_error(e, &index_name), + ) + .await?; + return Ok(VectorSearchOutput { + hits: rows + .into_iter() + .map(|(ordered, embedding, item)| { + hit(item, &vector_attribute_name, &embedding, function, ordered) + }) + .collect(), + distance_function: function, + }); + } + let sql = format!( "SELECT {score} AS score, embedding, item_data \ FROM {vec_table} WHERE part = $2{predicates} \ - ORDER BY score ASC, {tie_break} LIMIT $3", - score = score_expression(function, 4), + ORDER BY score ASC, {tie_break} LIMIT $3" ); // Bound as a typed vector rather than a text literal, so the value that @@ -276,9 +353,7 @@ impl VectorSearchEngine for PostgresEngine { // Bytes, matching the BYTEA column: the unscoped sentinel contains // a NUL, so a text comparison would not even be storable. .bind(partition.into_bytes()) - // NULL is no limit: with a condition the stream below stops at - // the top_k-th matching row instead. - .bind(item_filter.is_none().then_some(top_k)) + .bind(top_k) .bind(query_norm); for (name, value) in &filters { let value_json = serde_json::to_string(value) @@ -286,48 +361,22 @@ impl VectorSearchEngine for PostgresEngine { query = query.bind(name).bind(value_json); } - let map_sql = |e: sqlx::Error| { - let mapped = crate::vector::map_vector_sql_error(e); - // The data table is gone, which happens when the index is deleted - // between the catalog read above and this statement. That is a - // deleted index, so it answers like one instead of reporting an - // internal failure the caller can do nothing about. - if crate::gsi_queue::is_undefined_table(&mapped) { - StorageError::IndexNotFound(index_name.clone()) - } else { - mapped - } - }; - let rows = match &item_filter { - None => query.fetch_all(&self.data_pool).await.map_err(map_sql)?, - Some(condition) => { - crate::vector_search_filtered::fetch_matching( - query, - &self.data_pool, - condition.as_ref(), - top_k, - map_sql, - ) - .await? - } - }; + let rows = query + .fetch_all(&self.data_pool) + .await + .map_err(|e| map_search_error(e, &index_name))?; let mut hits = Vec::with_capacity(rows.len()); for (ordered, embedding, item_json) in rows { - let mut item: extenddb_core::types::Item = serde_json::from_value(item_json) + let item: extenddb_core::types::Item = serde_json::from_value(item_json) .map_err(|e| StorageError::Internal(format!("stored item: {e}")))?; - // Reinstated from the stored f32s rather than from a second copy in - // the payload, so what comes back is the narrowed value that was - // actually indexed. The engine drops it again unless a projection - // expression names it. - item.insert( - vector_attribute_name.clone(), - extenddb_core::validation::vector_item::vector_attribute(embedding.as_slice()), - ); - hits.push(VectorHit { + hits.push(hit( item, - score: report_score(function, ordered), - }); + &vector_attribute_name, + &embedding, + function, + ordered, + )); } Ok(VectorSearchOutput { diff --git a/crates/storage-postgres/src/vector_search_filtered.rs b/crates/storage-postgres/src/vector_search_filtered.rs index fcbce4ccd..b251ee98f 100644 --- a/crates/storage-postgres/src/vector_search_filtered.rs +++ b/crates/storage-postgres/src/vector_search_filtered.rs @@ -8,57 +8,265 @@ //! give a second implementation of those semantics, and the two would drift //! on a missing attribute, a number comparison or a type mismatch. //! -//! The statement is the unfiltered one with `LIMIT NULL`, which PostgreSQL -//! reads as no limit. Rows arrive in score order with the same tie break, and -//! the stream stops at the `top_k`-th matching row. So the cut applies to -//! matching rows only, as it does for the equality filters in SQL. +//! So the server returns candidates in score order, with the same tie break +//! as the unfiltered statement, and the search keeps the first `top_k` that +//! match. It reads the ordering in pages and stops at the `top_k`-th match: +//! +//! - A page is the ordering after the last row of the page before, compared +//! on the whole sort key (`(score, base key) > (last score, last base +//! key)`), with a `LIMIT`. It carries each row's score and address only, so +//! it is a top-N sort of narrow rows that fits in the server's sort memory, +//! which PostgreSQL may run in parallel, and it never sorts again the rows +//! that earlier pages returned. +//! - The first page holds four times `top_k` rows, at least +//! [`FIRST_PAGE_MIN`], and each next page eight times the one before, up +//! to [`MAX_PAGE`]. A condition that most rows satisfy finishes after one +//! page; one that few rows satisfy needs a number of pages that grows with +//! the logarithm of the rows it reads. +//! - The items of a page are read by address, [`ITEM_BATCH`] at a time and in +//! page order, so the search decodes items only up to the row where it +//! stops. +//! +//! The kept rows' embeddings are read at the end by address. Every statement +//! runs in one transaction ([`ScanConnection`]), so all of them read one +//! snapshot, the addresses stay valid between them, and the result is the one +//! a single statement would give. Dropping the search future cancels the +//! statement in flight. + +use std::collections::HashMap; use futures::TryStreamExt; use pgvector::Vector; use sqlx::PgPool; use sqlx::postgres::{PgArguments, Postgres}; use sqlx::query::QueryAs; +use sqlx::types::Json; use extenddb_core::types::Item; use extenddb_storage::VectorItemFilter; use extenddb_storage::error::StorageError; -/// One row of the search statement: the ordered score, the stored vector and -/// the stored item. -pub(crate) type SearchRow = (f64, Vector, serde_json::Value); +use crate::vector_search_scan::ScanConnection; + +/// Rows of the first page, at least. +const FIRST_PAGE_MIN: i64 = 64; +/// Rows of a page, at most. Bounds what one statement sorts and sends. +const MAX_PAGE: i64 = 65_536; +/// Items read per statement. Bounds the items decoded past the row where the +/// search stops. +const ITEM_BATCH: usize = 1024; + +/// Turns a statement failure into the error the search reports. +pub(crate) type MapSql<'a> = dyn Fn(sqlx::Error) -> StorageError + Send + Sync + 'a; + +/// One kept row: the ordered score, the stored vector and the stored item. +pub(crate) type MatchedRow = (f64, Vector, Item); + +/// The search statement without its embedding, and what it binds. +/// +/// `score` is the scoring expression, `from` the `FROM ... WHERE ...` clause +/// and `key_columns` the base key columns that break score ties, in order. +/// They read the parameters in the unfiltered statement's numbering: `$1` the +/// query vector, `$2` the partition, `$3` the limit, `$4` the query norm, then +/// two per equality filter. A page after the first binds the last score and +/// the last row address after those. +pub(crate) struct ScanStatement { + pub(crate) score: String, + pub(crate) from: String, + pub(crate) key_columns: Vec, + pub(crate) vec_table: String, + pub(crate) vector: Vector, + pub(crate) partition: Vec, + pub(crate) norm: f64, + /// Each equality filter's name and its value as JSON text. + pub(crate) filters: Vec<(String, String)>, +} + +impl ScanStatement { + /// The first page (`after` false) or a page after a given row (`after` + /// true), at most `$3` rows. + fn page_sql(&self, after: bool) -> String { + let keys = self.key_columns.join(", "); + let order = self + .key_columns + .iter() + .map(|col| format!("{col} ASC")) + .collect::>() + .join(", "); + let after = if after { + // The last row's key is read by its address, which is valid in + // this snapshot, so the key needs no bind of its own type. + let last_score = 5 + 2 * self.filters.len(); + format!( + " WHERE (score, {keys}) > (SELECT ${last_score}::float8, {keys} FROM {} \ + WHERE ctid = ${}::text::tid)", + self.vec_table, + last_score + 1 + ) + } else { + String::new() + }; + format!( + "SELECT score, rid FROM (SELECT {} AS score, ctid::text AS rid, {keys} {}) \ + AS candidates{after} ORDER BY score ASC, {order} LIMIT $3", + self.score, self.from + ) + } + + fn bind<'q>( + &self, + sql: &'q str, + limit: i64, + after: Option<(f64, String)>, + ) -> QueryAs<'q, Postgres, (f64, String), PgArguments> { + let mut query = sqlx::query_as::<_, (f64, String)>(sql) + .bind(self.vector.clone()) + .bind(self.partition.clone()) + .bind(limit) + .bind(self.norm); + for (name, value) in &self.filters { + query = query.bind(name.clone()).bind(value.clone()); + } + if let Some((score, rid)) = after { + query = query.bind(score).bind(rid); + } + query + } +} + +/// Keep each row of `page` whose item matches, in order, until `kept` holds +/// `wanted` rows. Returns whether it does. +/// +/// The items are read by address, [`ITEM_BATCH`] at a time, so a search that +/// stops early in a page decodes only the items up to that point. +async fn offer_page( + scan: &mut ScanConnection, + statement: &ScanStatement, + page: &[(f64, String)], + filter: &dyn VectorItemFilter, + wanted: usize, + kept: &mut Vec<(f64, String, Item)>, + map_sql: &MapSql<'_>, +) -> Result { + // In the order of `rids`: the ordinality is the position in the array. + let sql = format!( + "SELECT page.n, item_data FROM unnest($1::text[]) WITH ORDINALITY AS page(rid, n) \ + JOIN {} AS v ON v.ctid = page.rid::tid ORDER BY page.n", + statement.vec_table + ); + for batch in page.chunks(ITEM_BATCH) { + let rids: Vec<&str> = batch.iter().map(|(_, rid)| rid.as_str()).collect(); + let mut items = sqlx::query_as::<_, (i64, Json)>(&sql) + .bind(rids) + .fetch(scan.connection()); + let mut position = 0usize; + while let Some((n, Json(item))) = items.try_next().await.map_err(map_sql)? { + let Some((score, rid)) = batch.get(position) else { + return Err(vanished("past the end of the page")); + }; + // The join drops a row whose address no longer resolves, which + // one snapshot rules out; a gap in the positions would show it. + if usize::try_from(n).ok() != Some(position + 1) { + return Err(vanished(rid)); + } + position += 1; + if filter.matches(&item)? { + kept.push((*score, rid.clone(), item)); + if kept.len() == wanted { + return Ok(true); + } + } + } + if let Some((_, rid)) = batch.get(position) { + return Err(vanished(rid)); + } + } + Ok(false) +} + +fn vanished(rid: &str) -> StorageError { + StorageError::Internal(format!("vector row {rid} vanished inside one snapshot")) +} -/// Run `query` and return the first `top_k` rows whose item satisfies -/// `filter`, in the order the statement returns them. +/// Return the first `top_k` rows of `statement`'s ordering whose item +/// satisfies `filter`, in that order. /// /// `map_sql` turns a statement failure into the error the unfiltered path /// reports for it. /// /// # Errors /// -/// Returns the mapped statement error, [`StorageError::Internal`] for a stored -/// item that does not decode, or the error of [`VectorItemFilter::matches`]. -pub(crate) async fn fetch_matching<'q>( - query: QueryAs<'q, Postgres, SearchRow, PgArguments>, +/// Returns the mapped statement error, which covers a stored item that does +/// not decode, or the error of [`VectorItemFilter::matches`]. +pub(crate) async fn fetch_matching( + statement: &ScanStatement, pool: &PgPool, filter: &dyn VectorItemFilter, top_k: i64, - map_sql: impl Fn(sqlx::Error) -> StorageError, -) -> Result, StorageError> { + map_sql: &MapSql<'_>, +) -> Result, StorageError> { let wanted = usize::try_from(top_k.max(0)).unwrap_or(0); - let mut kept = Vec::with_capacity(wanted.min(128)); if wanted == 0 { - return Ok(kept); + return Ok(Vec::new()); } - let mut rows = query.fetch(pool); - while let Some(row) = rows.try_next().await.map_err(&map_sql)? { - let item: Item = serde_json::from_value(row.2.clone()) - .map_err(|e| StorageError::Internal(format!("stored item: {e}")))?; - if filter.matches(&item)? { - kept.push(row); - if kept.len() == wanted { - break; - } + let mut scan = ScanConnection::begin(pool).await.map_err(map_sql)?; + let mut kept = Vec::with_capacity(wanted.min(128)); + + let (first, next) = (statement.page_sql(false), statement.page_sql(true)); + let mut page = top_k.saturating_mul(4).clamp(FIRST_PAGE_MIN, MAX_PAGE); + let mut after = None; + loop { + let sql = if after.is_some() { &next } else { &first }; + let rows: Vec<(f64, String)> = statement + .bind(sql, page, after.take()) + .fetch_all(scan.connection()) + .await + .map_err(map_sql)?; + let full = offer_page( + &mut scan, statement, &rows, filter, wanted, &mut kept, map_sql, + ) + .await?; + // A page shorter than its limit ends the ordering. + if full || i64::try_from(rows.len()).unwrap_or(i64::MAX) < page { + break; } + after = rows.last().cloned(); + page = page.saturating_mul(8).min(MAX_PAGE); + } + + let embeddings = read_embeddings(&mut scan, statement, &kept, map_sql).await?; + scan.commit().await.map_err(map_sql)?; + + kept.into_iter() + .map(|(score, rid, item)| { + let embedding = embeddings + .get(&rid) + .cloned() + .ok_or_else(|| vanished(&rid))?; + Ok((score, embedding, item)) + }) + .collect() +} + +/// The stored vectors of the kept rows, by row address. +async fn read_embeddings( + scan: &mut ScanConnection, + statement: &ScanStatement, + kept: &[(f64, String, Item)], + map_sql: &MapSql<'_>, +) -> Result, StorageError> { + if kept.is_empty() { + return Ok(HashMap::new()); } - Ok(kept) + let rids: Vec<&str> = kept.iter().map(|(_, rid, _)| rid.as_str()).collect(); + let sql = format!( + "SELECT ctid::text, embedding FROM {} WHERE ctid = ANY($1::text[]::tid[])", + statement.vec_table + ); + let rows: Vec<(String, Vector)> = sqlx::query_as(&sql) + .bind(rids) + .fetch_all(scan.connection()) + .await + .map_err(map_sql)?; + Ok(rows.into_iter().collect()) } diff --git a/crates/storage-postgres/src/vector_search_scan.rs b/crates/storage-postgres/src/vector_search_scan.rs new file mode 100644 index 000000000..fe961b696 --- /dev/null +++ b/crates/storage-postgres/src/vector_search_scan.rs @@ -0,0 +1,208 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The connection a filtered vector search reads through. +//! +//! The search runs several statements, and they have to agree on which rows +//! exist and in which order, so they share one `REPEATABLE READ READ ONLY` +//! transaction and therefore one snapshot. A read-only transaction at that +//! level never fails to serialize. +//! +//! A connection that leaves this type normally has committed. Every other +//! exit, an error or a dropped future, closes the connection instead of +//! returning it to the pool, so the pool never hands out a connection that is +//! inside this transaction or still running one of its statements. On a drop +//! the backend is also sent `pg_cancel_backend`, so a request the caller has +//! abandoned stops its statement in the server instead of running it to the +//! end on a connection nobody reads. + +use sqlx::pool::PoolConnection; +use sqlx::{PgConnection, PgPool, Postgres}; + +/// One pooled connection inside the search transaction. +pub(crate) struct ScanConnection { + conn: Option>, + backend_pid: Option, + pool: PgPool, +} + +impl ScanConnection { + /// Take a connection from `pool` and open the transaction on it. + /// + /// # Errors + /// + /// Returns the error of the acquire or of the opening statement. The + /// connection is closed in that case. + pub(crate) async fn begin(pool: &PgPool) -> Result { + let conn = pool.acquire().await?; + // Built before the first statement, so a drop while it runs is + // handled like any other drop. + let mut scan = Self { + conn: Some(conn), + backend_pid: None, + pool: pool.clone(), + }; + sqlx::query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY") + .execute(scan.connection()) + .await?; + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(scan.connection()) + .await?; + scan.backend_pid = Some(pid); + Ok(scan) + } + + /// The connection, for running a statement of the search. + pub(crate) fn connection(&mut self) -> &mut PgConnection { + // Only `commit` and `drop` take the connection, and both consume or + // end `self`. + self.conn + .as_deref_mut() + .expect("the connection is held until commit or drop") + } + + /// Commit and return the connection to the pool. + /// + /// # Errors + /// + /// Returns the error of the commit. The connection is closed in that case. + pub(crate) async fn commit(mut self) -> Result<(), sqlx::Error> { + sqlx::query("COMMIT").execute(self.connection()).await?; + // Released here, so `drop` finds nothing to close or cancel. + drop(self.conn.take()); + Ok(()) + } +} + +impl Drop for ScanConnection { + fn drop(&mut self) { + let Some(conn) = self.conn.take() else { + return; + }; + // Detached first, so this backend can serve no other request: the + // cancel below then reaches only the statement this search started. + drop(conn.detach()); + let (Some(pid), Ok(runtime)) = (self.backend_pid, tokio::runtime::Handle::try_current()) + else { + return; + }; + let pool = self.pool.clone(); + runtime.spawn(async move { + // The backend may already have exited on the closed socket, and + // then PostgreSQL answers false. Neither answer changes anything. + let _ = sqlx::query("SELECT pg_cancel_backend($1)") + .bind(pid) + .execute(&pool) + .await; + }); + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use sqlx::postgres::PgPoolOptions; + + use super::ScanConnection; + + /// A pool on the server's maintenance database, or `None` to skip. + async fn pool(max: u32) -> Option { + let base = std::env::var("EXTENDDB_TEST_PG_CONNECTION_STRING").unwrap_or_default(); + if base.trim().is_empty() { + eprintln!("SKIP: EXTENDDB_TEST_PG_CONNECTION_STRING is not set"); + return None; + } + let url = format!("{}/postgres", base.trim().trim_end_matches('/')); + Some( + PgPoolOptions::new() + .max_connections(max) + .connect(&url) + .await + .expect("connect to the server"), + ) + } + + /// Whether any backend still runs `query`, polled until `deadline`. + async fn still_running(observer: &sqlx::PgPool, query: &str, deadline: Duration) -> bool { + let start = std::time::Instant::now(); + loop { + let running: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity \ + WHERE state = 'active' AND query = $1)", + ) + .bind(query) + .fetch_one(observer) + .await + .expect("read pg_stat_activity"); + if !running || start.elapsed() > deadline { + return running; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + } + + #[tokio::test] + async fn dropping_a_scan_stops_its_statement_in_the_server() { + let (Some(pool), Some(observer)) = (pool(2).await, pool(1).await) else { + return; + }; + // Unique text, so the observer finds this statement and no other. + let query = format!("SELECT pg_sleep(30), '{}'", uuid::Uuid::new_v4().simple()); + let scan_query = query.clone(); + let search = async { + let mut scan = ScanConnection::begin(&pool).await.expect("begin"); + sqlx::query(&scan_query) + .execute(scan.connection()) + .await + .expect("the statement"); + }; + let dropped = tokio::time::timeout(Duration::from_millis(500), search).await; + assert!(dropped.is_err(), "the statement finished before the drop"); + assert!( + !still_running(&observer, &query, Duration::from_secs(5)).await, + "the statement still runs 5 s after its scan was dropped" + ); + } + + #[tokio::test] + async fn a_dropped_scan_never_returns_its_transaction_to_the_pool() { + let Some(pool) = pool(1).await else { + return; + }; + let mut scan = ScanConnection::begin(&pool).await.expect("begin"); + sqlx::query("SELECT 1") + .execute(scan.connection()) + .await + .expect("a statement"); + drop(scan); + // The pool's one connection: a fresh one, or one that is no longer + // inside the scan's transaction. + let isolation: String = + sqlx::query_scalar("SELECT current_setting('transaction_isolation')") + .fetch_one(&pool) + .await + .expect("read the isolation level"); + assert_eq!(isolation, "read committed"); + } + + #[tokio::test] + async fn a_committed_scan_returns_its_connection_outside_a_transaction() { + let Some(pool) = pool(1).await else { + return; + }; + let mut scan = ScanConnection::begin(&pool).await.expect("begin"); + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(scan.connection()) + .await + .expect("the backend"); + scan.commit().await.expect("commit"); + let (again, isolation): (i32, String) = + sqlx::query_as("SELECT pg_backend_pid(), current_setting('transaction_isolation')") + .fetch_one(&pool) + .await + .expect("reuse the connection"); + assert_eq!(again, pid, "a committed scan keeps its connection pooled"); + assert_eq!(isolation, "read committed"); + } +} From 245bca8dbdbd059da0e57d7bbe414f1504d4a0ec Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 18:39:48 +0000 Subject: [PATCH 021/101] test(storage-postgres): pin the paged filtered vector search The PostgreSQL condition tests used distinct scores and one HASH value, and kept their database pair between runs. The search now reads the ordering in pages inside one snapshot, and no test data reached a second page or a tie. The fixture now creates a database pair per test and drops both when the test ends, also when the setup or the test body panics. The condition test data has two items with one vector, and a second HASH value whose items are nearer than every item of the first and match its conditions. A second file loads 600 items whose scores tie in groups of seven, so a group straddles both page boundaries a top_k of 10 reaches, and checks conditions whose matches sit in those groups, in every page and in none against the backend's own unfiltered ordering, ids and scores. Another test deletes the rows the second page reads while the search runs, and checks that the search answers from its first snapshot and a later search sees the delete. --- .../tests/common/vector_filter_fixture.rs | 354 +++++++++++++++ .../tests/vector_search_filter.rs | 427 +++++------------- .../tests/vector_search_filter_pages.rs | 235 ++++++++++ 3 files changed, 704 insertions(+), 312 deletions(-) create mode 100644 crates/storage-postgres/tests/common/vector_filter_fixture.rs create mode 100644 crates/storage-postgres/tests/vector_search_filter_pages.rs diff --git a/crates/storage-postgres/tests/common/vector_filter_fixture.rs b/crates/storage-postgres/tests/common/vector_filter_fixture.rs new file mode 100644 index 000000000..2834e8a6b --- /dev/null +++ b/crates/storage-postgres/tests/common/vector_filter_fixture.rs @@ -0,0 +1,354 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! A PostgreSQL engine on a database pair of its own, with one table whose +//! vector index has HASH `Country` (S) and inline filter `Price` (N), for the +//! vector search condition tests. +//! +//! Needs `EXTENDDB_TEST_PG_CONNECTION_STRING`, a base URL with no database, +//! for a role that may create databases and the pgvector extension. Without +//! it a test reports a skip and passes. [`run`] creates the pair, runs the +//! test body and drops both databases afterwards, also when the body or the +//! setup panics. + +#![allow(dead_code)] + +use std::collections::HashMap; +use std::panic::AssertUnwindSafe; +use std::sync::Arc; + +use extenddb_core::expression::ExpressionMaps; +use extenddb_core::expression::search_filter::{SearchFilter, parse_search_filter}; +use extenddb_core::types::{AttributeValue, Item, TableKeyInfo}; +use extenddb_storage::error::StorageError; +use extenddb_storage::migrations::Runner; +use extenddb_storage::{ + DataEngine, TableEngine, VectorItemFilter, VectorSearch, VectorSearchEngine, +}; +use extenddb_storage_postgres::migrations::{ + PostgresMigrations, PostgresTarget, try_create_vector_extension, +}; +use extenddb_storage_postgres::{PostgresConfig, PostgresEngine}; +use futures::FutureExt; +use serde_json::json; +use sqlx::postgres::PgPoolOptions; + +pub const ACCOUNT: &str = "123456789012"; +pub const TABLE: &str = "vf"; + +/// What a test body receives. +pub struct Fixture { + pub engine: PostgresEngine, + pub key_info: TableKeyInfo, + /// The data database's URL, for statements a test runs beside the engine. + pub data_url: String, +} + +/// One item: id, Country, the two vector components, and Price if any. +pub type Row<'a> = (&'a str, &'a str, f64, f64, Option<&'a str>); + +pub struct Matcher(pub SearchFilter); + +impl VectorItemFilter for Matcher { + fn matches(&self, item: &Item) -> Result { + self.0 + .matches(item) + .map_err(|e| StorageError::Internal(format!("{e:?}"))) + } +} + +fn base() -> Option { + let conn = std::env::var("EXTENDDB_TEST_PG_CONNECTION_STRING").unwrap_or_default(); + if conn.trim().is_empty() { + eprintln!("SKIP: EXTENDDB_TEST_PG_CONNECTION_STRING is not set"); + return None; + } + Some(conn.trim_end_matches('/').to_owned()) +} + +/// Create the database pair, load `rows` into a table whose index uses +/// `distance`, run `body`, then drop the pair whatever `body` did. +pub async fn run(distance: &str, rows: &[Row<'_>], body: B) +where + B: AsyncFnOnce(&Fixture), +{ + let Some(base) = base() else { + return; + }; + let id = &uuid::Uuid::new_v4().simple().to_string()[..12]; + let (catalog, data) = (format!("vf_{id}_catalog"), format!("vf_{id}_data")); + let admin = PgPoolOptions::new() + .max_connections(1) + .connect(&format!("{base}/postgres")) + .await + .expect("connect to the server"); + let outcome = AssertUnwindSafe(async { + for db in [&catalog, &data] { + sqlx::query(&format!("CREATE DATABASE \"{db}\"")) + .execute(&admin) + .await + .expect("create the database"); + } + if let Some(fixture) = setup(&base, &catalog, &data, distance, rows).await { + body(&fixture).await; + } + }) + .catch_unwind() + .await; + for db in [&catalog, &data] { + // FORCE ends the engine's pooled connections, which a panic leaves + // open. + let dropped = sqlx::query(&format!("DROP DATABASE IF EXISTS \"{db}\" WITH (FORCE)")) + .execute(&admin) + .await; + if let Err(e) = dropped { + eprintln!("could not drop {db}: {e}"); + } + } + admin.close().await; + if let Err(panic) = outcome { + std::panic::resume_unwind(panic); + } +} + +async fn setup( + base: &str, + catalog: &str, + data: &str, + distance: &str, + rows: &[Row<'_>], +) -> Option { + let (catalog_url, data_url) = (format!("{base}/{catalog}"), format!("{base}/{data}")); + let line = try_create_vector_extension(&data_url.parse().expect("a URL"), None).await; + if !line.starts_with("pgvector available") { + eprintln!("SKIP: {line}"); + return None; + } + let target = PostgresTarget::new(catalog_url.parse().expect("a URL"), data) + .with_data_connection_row(&data_url); + let runner = PostgresMigrations::open_unlocked(&target) + .await + .expect("open the migration runner"); + let report = Runner::new(&runner, "test").migrate().await; + runner.close().await; + report.expect("migrate"); + let pool = PgPoolOptions::new() + .max_connections(1) + .connect(&catalog_url) + .await + .expect("connect to the catalog"); + for key in ["control_plane_delay_seconds", "index_propagation_delay_ms"] { + sqlx::query( + "INSERT INTO settings (key, value) VALUES ($1, '0') \ + ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value", + ) + .bind(key) + .execute(&pool) + .await + .expect("write a setting"); + } + sqlx::query("INSERT INTO accounts (account_id, account_name) VALUES ($1, 'ineq')") + .bind(ACCOUNT) + .execute(&pool) + .await + .expect("seed the account"); + pool.close().await; + let engine = PostgresEngine::new( + &PostgresConfig { + connection_string: catalog_url, + pool_size: 4, + max_item_size_bytes: 400_000, + }, + "us-east-1", + ) + .await + .expect("open the engine"); + let input = serde_json::from_value(json!({ + "TableName": TABLE, + "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], + "AttributeDefinitions": [ + {"AttributeName": "id", "AttributeType": "S"}, + {"AttributeName": "Country", "AttributeType": "S"}, + {"AttributeName": "Price", "AttributeType": "N"} + ], + "BillingMode": "PAY_PER_REQUEST", + "VectorIndexes": [{ + "IndexName": "vix", + "Dimensions": 2, + "DistanceFunction": distance, + "VectorAttribute": {"AttributeName": "emb"}, + "SearchSchema": [ + {"AttributeName": "Country", "SearchSchemaElementType": "HASH"}, + {"AttributeName": "Price", "SearchSchemaElementType": "INLINE_FILTER"} + ], + "Projection": {"ProjectionType": "ALL"} + }] + })) + .expect("input"); + engine + .create_table(ACCOUNT, input) + .await + .expect("create the table"); + let key_info = wait_active(&engine).await; + for &(id, country, x, y, price) in rows { + let mut item = Item::new(); + item.insert("id".to_owned(), AttributeValue::S(id.to_owned())); + item.insert("Country".to_owned(), AttributeValue::S(country.to_owned())); + item.insert( + "emb".to_owned(), + AttributeValue::L(vec![ + AttributeValue::N(x.to_string()), + AttributeValue::N(y.to_string()), + ]), + ); + if let Some(p) = price { + item.insert("Price".to_owned(), AttributeValue::N(p.to_owned())); + } + engine + .put_item( + &key_info, + item, + false, + None, + &ExpressionMaps::default(), + None, + ) + .await + .expect("put item"); + } + Some(Fixture { + engine, + key_info, + data_url, + }) +} + +async fn wait_active(engine: &PostgresEngine) -> TableKeyInfo { + for _ in 0..100 { + if let Ok(key_info) = engine.table_key_info(ACCOUNT, TABLE).await + && key_info.vector_indexes.len() == 1 + { + let desc = engine + .describe_table( + ACCOUNT, + extenddb_core::types::DescribeTableInput { + table_name: TABLE.to_owned(), + }, + ) + .await + .expect("describe"); + let ready = desc + .vector_indexes + .as_deref() + .unwrap_or_default() + .iter() + .all(|vi| vi.index_status.is_active()); + if ready { + return key_info; + } + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + panic!("the vector index of {TABLE} did not become ACTIVE in 10 s"); +} + +/// Parse `expr` with the values among `values` that it names, and check it +/// against the index's search schema. Returns the filter and the HASH pair. +pub fn parse( + fixture: &Fixture, + expr: &str, + values: &HashMap, +) -> (SearchFilter, Option<(String, AttributeValue)>) { + let used: HashMap = values + .iter() + .filter(|(k, _)| { + expr.match_indices(k.as_str()).any(|(at, _)| { + !expr[at + k.len()..] + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphanumeric()) + }) + }) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + let filter = parse_search_filter(expr, None, Some(&used), 50).expect("parse"); + let hash = filter + .validate_against_schema( + Some(fixture.key_info.vector_indexes[0].search_schema.as_slice()), + &fixture.key_info.attribute_definitions, + ) + .expect("schema") + .map(|(n, v)| (n.to_owned(), v.clone())); + (filter, hash) +} + +/// Search with `item_filter`, or without a condition when it is `None`, and +/// return the hits' ids and scores in order. +pub async fn search_with( + fixture: &Fixture, + hash: Option<(&str, &AttributeValue)>, + item_filter: Option>, + query: &[f32], + top_k: i64, +) -> Vec<(String, f64)> { + let out = fixture + .engine + .search_vectors(VectorSearch { + key_info: &fixture.key_info, + index_name: "vix", + query_vector: query, + top_k, + hash_key: hash, + filters: &[], + item_filter, + }) + .await + .expect("search"); + out.hits + .iter() + .map(|hit| match hit.item.get("id") { + Some(AttributeValue::S(id)) => (id.clone(), hit.score), + other => panic!("id: {other:?}"), + }) + .collect() +} + +/// Search with the condition `expr`, and return the hits' ids and scores. +pub async fn search( + fixture: &Fixture, + expr: &str, + values: &HashMap, + query: &[f32], + top_k: i64, +) -> Vec<(String, f64)> { + let (filter, hash) = parse(fixture, expr, values); + let item_filter: Arc = Arc::new(Matcher(filter)); + search_with( + fixture, + hash.as_ref().map(|(n, v)| (n.as_str(), v)), + Some(item_filter), + query, + top_k, + ) + .await +} + +/// The ids of `hits`. +pub fn ids(hits: &[(String, f64)]) -> Vec<&str> { + hits.iter().map(|(id, _)| id.as_str()).collect() +} + +/// Named values: each `(name, number)` becomes `:name` bound to that number, +/// each `(name, string)` with a leading `S:` to that string. +pub fn values(pairs: &[(&str, &str)]) -> HashMap { + pairs + .iter() + .map(|&(name, value)| { + let value = match value.strip_prefix("S:") { + Some(s) => AttributeValue::S(s.to_owned()), + None => AttributeValue::N(value.to_owned()), + }; + (format!(":{name}"), value) + }) + .collect() +} diff --git a/crates/storage-postgres/tests/vector_search_filter.rs b/crates/storage-postgres/tests/vector_search_filter.rs index 3b0c4fd8e..d19b52496 100644 --- a/crates/storage-postgres/tests/vector_search_filter.rs +++ b/crates/storage-postgres/tests/vector_search_filter.rs @@ -4,336 +4,139 @@ //! A vector search with a search condition parsed by the extended grammar, //! on PostgreSQL. //! -//! The backend streams the rows in score order and keeps the first `top_k` -//! that satisfy the condition, so `top_k` counts matching items only. The -//! match semantics are the FilterExpression ones; the cases that turn on a -//! missing attribute or a number written two ways are not yet measured -//! against the live service. +//! The backend reads the rows in score order and keeps the first `top_k` +//! that satisfy the condition, so `top_k` counts matching items only. Equal +//! scores are ordered by the base key. The match semantics are the +//! FilterExpression ones; the cases that turn on a missing attribute or a +//! number written two ways are not yet measured against the live service. //! -//! Needs `EXTENDDB_TEST_PG_CONNECTION_STRING`, a base URL with no database, -//! for a role that may create databases and the pgvector extension. Without -//! it the tests report a skip and pass. The tests use one database pair, -//! `ineq_vf_catalog` and `ineq_vf_data`, created on first use and kept, and a -//! table of their own that they delete when they pass. +//! The fixture is in `common/vector_filter_fixture.rs`. #![cfg(feature = "search-inequality-filters")] -use std::collections::HashMap; -use std::sync::Arc; - -use extenddb_core::expression::ExpressionMaps; -use extenddb_core::expression::search_filter::{SearchFilter, parse_search_filter}; -use extenddb_core::types::{AttributeValue, Item, TableKeyInfo}; -use extenddb_storage::error::StorageError; -use extenddb_storage::migrations::Runner; -use extenddb_storage::{ - DataEngine, TableEngine, VectorItemFilter, VectorSearch, VectorSearchEngine, -}; -use extenddb_storage_postgres::migrations::{ - PostgresMigrations, PostgresTarget, try_create_vector_extension, -}; -use extenddb_storage_postgres::{PostgresConfig, PostgresEngine}; -use serde_json::json; -use sqlx::postgres::PgPoolOptions; +#[path = "common/vector_filter_fixture.rs"] +mod fixture; -const ACCOUNT: &str = "123456789012"; -const CATALOG: &str = "ineq_vf_catalog"; -const DATA: &str = "ineq_vf_data"; +use std::sync::Arc; -static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +use extenddb_core::expression::search_filter::parse_search_filter; +use extenddb_core::types::AttributeValue; +use fixture::{Fixture, Matcher, Row, ids, run, search, search_with, values}; -struct Matcher(SearchFilter); +/// Query `[1, 0]` under cosine: the distance grows with the second +/// component. `t2` has the vector of `n2`, so the two tie and `n2` ranks +/// first by its key. The `CA` partition holds the nearest vector and a +/// `Price` of 100, so a condition that leaked across partitions would return +/// it. +const ROWS: &[Row<'static>] = &[ + ("n1", "US", 1.0, 0.0, Some("5")), + ("n2", "US", 1.0, 0.1, Some("10")), + ("t2", "US", 1.0, 0.1, Some("10")), + ("n3", "US", 1.0, 0.2, None), + ("n4", "US", 1.0, 0.3, Some("1E2")), + ("n5", "US", 1.0, 0.4, Some("15")), + ("c1", "CA", 1.0, 0.05, Some("50")), + ("c2", "CA", 1.0, 0.0, Some("100")), +]; -impl VectorItemFilter for Matcher { - fn matches(&self, item: &Item) -> Result { - self.0 - .matches(item) - .map_err(|e| StorageError::Internal(format!("{e:?}"))) - } +async fn ids_for(fixture: &Fixture, expr: &str, top_k: i64) -> Vec { + let values = values(&[ + ("us", "S:US"), + ("ca", "S:CA"), + ("p5", "5"), + ("p10", "10"), + ("p100", "100"), + ]); + let hits = search(fixture, expr, &values, &[1.0, 0.0], top_k).await; + ids(&hits).into_iter().map(str::to_owned).collect() } -fn base() -> Option { - let conn = std::env::var("EXTENDDB_TEST_PG_CONNECTION_STRING").unwrap_or_default(); - if conn.trim().is_empty() { - eprintln!("SKIP: EXTENDDB_TEST_PG_CONNECTION_STRING is not set"); - return None; - } - Some(conn.trim_end_matches('/').to_owned()) -} - -/// The engine on the database pair, migrated, with a fresh table `name` -/// whose index has HASH `Country` (S) and inline filter `Price` (N). -async fn fixture(base: &str, name: &str) -> Option<(PostgresEngine, TableKeyInfo)> { - let admin = PgPoolOptions::new() - .max_connections(1) - .connect(&format!("{base}/postgres")) - .await - .expect("connect to the server"); - for db in [CATALOG, DATA] { - let exists: bool = - sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pg_database WHERE datname = $1)") - .bind(db) - .fetch_one(&admin) - .await - .expect("look up the database"); - if !exists { - sqlx::query(&format!("CREATE DATABASE \"{db}\"")) - .execute(&admin) - .await - .expect("create the database"); - } - } - admin.close().await; - let (catalog_url, data_url) = (format!("{base}/{CATALOG}"), format!("{base}/{DATA}")); - let line = try_create_vector_extension(&data_url.parse().expect("a URL"), None).await; - if !line.starts_with("pgvector available") { - eprintln!("SKIP: {line}"); - return None; - } - let target = PostgresTarget::new(catalog_url.parse().expect("a URL"), DATA) - .with_data_connection_row(&data_url); - let runner = PostgresMigrations::open_unlocked(&target) - .await - .expect("open the migration runner"); - let report = Runner::new(&runner, "test").migrate().await; - runner.close().await; - report.expect("migrate"); - let catalog = PgPoolOptions::new() - .max_connections(1) - .connect(&catalog_url) - .await - .expect("connect to the catalog"); - for key in ["control_plane_delay_seconds", "index_propagation_delay_ms"] { - sqlx::query( - "INSERT INTO settings (key, value) VALUES ($1, '0') \ - ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value", - ) - .bind(key) - .execute(&catalog) - .await - .expect("write a setting"); - } - sqlx::query( - "INSERT INTO accounts (account_id, account_name) VALUES ($1, 'ineq') \ - ON CONFLICT DO NOTHING", - ) - .bind(ACCOUNT) - .execute(&catalog) - .await - .expect("seed the account"); - catalog.close().await; - let engine = PostgresEngine::new( - &PostgresConfig { - connection_string: catalog_url, - pool_size: 4, - max_item_size_bytes: 400_000, - }, - "us-east-1", - ) - .await - .expect("open the engine"); - let input = serde_json::from_value(json!({ - "TableName": name, - "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], - "AttributeDefinitions": [ - {"AttributeName": "id", "AttributeType": "S"}, - {"AttributeName": "Country", "AttributeType": "S"}, - {"AttributeName": "Price", "AttributeType": "N"} - ], - "BillingMode": "PAY_PER_REQUEST", - "VectorIndexes": [{ - "IndexName": "vix", - "Dimensions": 2, - "DistanceFunction": "COSINE", - "VectorAttribute": {"AttributeName": "emb"}, - "SearchSchema": [ - {"AttributeName": "Country", "SearchSchemaElementType": "HASH"}, - {"AttributeName": "Price", "SearchSchemaElementType": "INLINE_FILTER"} - ], - "Projection": {"ProjectionType": "ALL"} - }] - })) - .expect("input"); - engine - .create_table(ACCOUNT, input) - .await - .expect("create the table"); - let key_info = wait_active(&engine, name).await; - for (id, country, slope, price) in [ - ("n1", "US", "0", Some("5")), - ("n2", "US", "0.1", Some("10")), - ("n3", "US", "0.2", None), - ("n4", "US", "0.3", Some("1E2")), - ("n5", "US", "0.4", Some("15")), - ("c1", "CA", "0.05", Some("50")), - ] { - let mut item = Item::new(); - item.insert("id".to_owned(), AttributeValue::S(id.to_owned())); - item.insert("Country".to_owned(), AttributeValue::S(country.to_owned())); - item.insert( - "emb".to_owned(), - AttributeValue::L(vec![ - AttributeValue::N("1".to_owned()), - AttributeValue::N(slope.to_owned()), - ]), +#[tokio::test] +async fn conditions_are_evaluated_before_the_top_k_cut() { + run("COSINE", ROWS, async |f: &Fixture| { + // unfiltered, the two nearest would be n1 and n2; the cut falls + // between the tied n2 and t2 and the next match n4 + assert_eq!( + ids_for(f, "Country = :us AND Price > :p5", 2).await, + ["n2", "t2"] + ); + assert_eq!( + ids_for(f, "Country = :us AND Price >= :p5", 10).await, + ["n1", "n2", "t2", "n4", "n5"] + ); + // not yet measured: a missing Price under <>, and 1E2 equal to 100 + assert_eq!( + ids_for(f, "Country = :us AND Price <> :p10", 10).await, + ["n1", "n3", "n4", "n5"] ); - if let Some(p) = price { - item.insert("Price".to_owned(), AttributeValue::N(p.to_owned())); - } - engine - .put_item( - &key_info, - item, - false, - None, - &ExpressionMaps::default(), - None, + assert_eq!( + ids_for( + f, + "Country = :us AND (attribute_not_exists(Price) OR Price = :p100)", + 10 ) - .await - .expect("put item"); - } - Some((engine, key_info)) -} - -async fn wait_active(engine: &PostgresEngine, name: &str) -> TableKeyInfo { - for _ in 0..100 { - if let Ok(key_info) = engine.table_key_info(ACCOUNT, name).await - && key_info.vector_indexes.len() == 1 - { - let desc = engine - .describe_table( - ACCOUNT, - extenddb_core::types::DescribeTableInput { - table_name: name.to_owned(), - }, - ) - .await - .expect("describe"); - let ready = desc - .vector_indexes - .as_deref() - .unwrap_or_default() - .iter() - .all(|vi| vi.index_status.is_active()); - if ready { - return key_info; - } - } - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - } - panic!("the vector index of {name} did not become ACTIVE in 10 s"); + .await, + ["n3", "n4"] + ); + assert_eq!( + ids_for(f, "Country = :us AND NOT Price BETWEEN :p5 AND :p10", 10).await, + ["n3", "n4", "n5"] + ); + }) + .await; } -fn values() -> HashMap { - [ - (":us", AttributeValue::S("US".to_owned())), - (":p5", AttributeValue::N("5".to_owned())), - (":p10", AttributeValue::N("10".to_owned())), - (":p100", AttributeValue::N("100".to_owned())), - ] - .into_iter() - .map(|(k, v)| (k.to_owned(), v)) - .collect() +#[tokio::test] +async fn equal_scores_are_cut_in_base_key_order() { + run("COSINE", ROWS, async |f: &Fixture| { + assert_eq!( + ids_for(f, "Country = :us AND Price = :p10", 1).await, + ["n2"] + ); + assert_eq!( + ids_for(f, "Country = :us AND Price = :p10", 2).await, + ["n2", "t2"] + ); + }) + .await; } -async fn search( - engine: &PostgresEngine, - key_info: &TableKeyInfo, - expr: &str, - top_k: i64, -) -> Vec { - let used: HashMap = values() - .into_iter() - .filter(|(k, _)| { - expr.match_indices(k.as_str()).any(|(at, _)| { - !expr[at + k.len()..] - .chars() - .next() - .is_some_and(|c| c.is_ascii_alphanumeric()) - }) - }) - .collect(); - let filter = parse_search_filter(expr, None, Some(&used), 50).expect("parse"); - let hash = filter - .validate_against_schema( - Some(key_info.vector_indexes[0].search_schema.as_slice()), - &key_info.attribute_definitions, - ) - .expect("schema") - .map(|(n, v)| (n.to_owned(), v.clone())); - let item_filter: Arc = Arc::new(Matcher(filter)); - let out = engine - .search_vectors(VectorSearch { - key_info, - index_name: "vix", - query_vector: &[1.0, 0.0], - top_k, - hash_key: hash.as_ref().map(|(n, v)| (n.as_str(), v)), - filters: &[], - item_filter: Some(item_filter), - }) - .await - .expect("search"); - out.hits - .iter() - .map(|hit| match hit.item.get("id") { - Some(AttributeValue::S(id)) => id.clone(), - other => panic!("id: {other:?}"), - }) - .collect() +#[tokio::test] +async fn the_hash_value_scopes_the_search() { + run("COSINE", ROWS, async |f: &Fixture| { + assert_eq!( + ids_for(f, "Country = :ca AND Price >= :p5", 10).await, + ["c2", "c1"] + ); + assert_eq!( + ids_for(f, "Country = :ca AND Price = :p100", 10).await, + ["c2"] + ); + // n4 holds 1E2, and c2 in the other partition holds 100 + assert_eq!( + ids_for(f, "Country = :us AND Price = :p100", 10).await, + ["n4"] + ); + }) + .await; } #[tokio::test] -async fn conditions_are_evaluated_before_the_top_k_cut() { - let Some(base) = base() else { - return; - }; - let _serial = SERIAL.lock().await; - let name = format!("vf_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]); - let Some((engine, key_info)) = fixture(&base, &name).await else { - return; - }; - // unfiltered, the two nearest would be n1 and n2 - assert_eq!( - search(&engine, &key_info, "Country = :us AND Price > :p5", 2).await, - ["n2", "n4"] - ); - assert_eq!( - search(&engine, &key_info, "Country = :us AND Price >= :p5", 10).await, - ["n1", "n2", "n4", "n5"] - ); - // not yet measured: a missing Price under <>, and 1E2 equal to 100 - assert_eq!( - search(&engine, &key_info, "Country = :us AND Price <> :p10", 10).await, - ["n1", "n3", "n4", "n5"] - ); - assert_eq!( - search( - &engine, - &key_info, - "Country = :us AND (attribute_not_exists(Price) OR Price = :p100)", - 10 - ) - .await, - ["n3", "n4"] - ); - assert_eq!( - search( - &engine, - &key_info, - "Country = :us AND NOT Price BETWEEN :p5 AND :p10", - 10 - ) - .await, - ["n3", "n4", "n5"] - ); - engine - .delete_table( - ACCOUNT, - extenddb_core::types::DeleteTableInput { - table_name: name.clone(), - }, +async fn the_partition_scopes_the_search_without_the_condition() { + run("COSINE", ROWS, async |f: &Fixture| { + // A condition with no HASH term, so only the partition keeps c2 out. + let v = values(&[("p100", "100")]); + let filter = parse_search_filter("Price = :p100", None, Some(&v), 50).expect("parse"); + let us = AttributeValue::S("US".to_owned()); + let hits = search_with( + f, + Some(("Country", &us)), + Some(Arc::new(Matcher(filter))), + &[1.0, 0.0], + 10, ) - .await - .expect("delete the table"); + .await; + assert_eq!(ids(&hits), ["n4"]); + }) + .await; } diff --git a/crates/storage-postgres/tests/vector_search_filter_pages.rs b/crates/storage-postgres/tests/vector_search_filter_pages.rs new file mode 100644 index 000000000..83a292506 --- /dev/null +++ b/crates/storage-postgres/tests/vector_search_filter_pages.rs @@ -0,0 +1,235 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! A vector search with a search condition that the first page of the +//! ordering does not satisfy, on PostgreSQL. +//! +//! The backend reads the ordering in pages of growing size. These tests use a +//! partition large enough to need three pages, with groups of equal scores +//! that straddle each page boundary, and check the result against the +//! backend's own unfiltered ordering. The fixture is in +//! `common/vector_filter_fixture.rs`. + +#![cfg(feature = "search-inequality-filters")] + +#[path = "common/vector_filter_fixture.rs"] +mod fixture; + +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use extenddb_core::types::{AttributeValue, Item}; +use extenddb_storage::VectorItemFilter; +use extenddb_storage::error::StorageError; +use fixture::{Fixture, Matcher, Row, ids, parse, run, search, search_with, values}; +use sqlx::postgres::PgPoolOptions; + +/// Rows in the `US` partition. With `top_k` 10 the first page holds 64 rows +/// and the second 512, so a scan to the end reads three pages. +const ROWS: usize = 600; +/// Rows that share one vector, and so one score. 64 and 576 are not +/// multiples of it, so a group straddles each page boundary. +const GROUP: usize = 7; + +/// `iNNN` in the `US` partition at Euclidean distance `NNN / GROUP` from the +/// query, with `Price` `NNN`, and 20 `CA` rows nearer than all of them. +fn rows(ids: &[String]) -> Vec> { + let mut rows: Vec> = ids[..ROWS] + .iter() + .enumerate() + .map(|(i, id)| { + let price: &str = &id[1..]; + (id.as_str(), "US", (i / GROUP) as f64, 0.0, Some(price)) + }) + .collect(); + rows.extend( + ids[ROWS..] + .iter() + .map(|id| (id.as_str(), "CA", 0.0, 0.0, Some(&id[1..]))), + ); + rows +} + +fn row_ids() -> Vec { + let mut ids: Vec = (0..ROWS).map(|i| format!("i{i:03}")).collect(); + ids.extend((0..20).map(|i| format!("c{:03}", 590 + i))); + ids +} + +fn us() -> AttributeValue { + AttributeValue::S("US".to_owned()) +} + +/// The whole `US` partition, unfiltered, in the backend's order. +async fn ranking(f: &Fixture) -> Vec<(String, f64)> { + let us = us(); + search_with(f, Some(("Country", &us)), None, &[0.0, 0.0], 10_000).await +} + +/// The first `top_k` rows of `ranking` whose `Price` satisfies `keep`. +fn expected( + ranking: &[(String, f64)], + keep: impl Fn(u32) -> bool, + top_k: usize, +) -> Vec<(String, f64)> { + ranking + .iter() + .filter(|(id, _)| keep(id[1..].parse().expect("a numeric id"))) + .take(top_k) + .cloned() + .collect() +} + +#[tokio::test] +async fn the_cut_is_the_unfiltered_ordering_filtered_across_pages() { + let names = row_ids(); + run("EUCLIDEAN", &rows(&names), async |f: &Fixture| { + let all = ranking(f).await; + // Equal scores in base key order, so the ordering is the ids sorted. + assert_eq!(ids(&all), ids(&expected(&all, |_| true, ROWS))); + let mut sorted = ids(&all); + sorted.sort_unstable(); + assert_eq!(ids(&all), sorted); + + let v = values(&[ + ("us", "S:US"), + ("a", "64"), + ("b", "66"), + ("c", "577"), + ("p3", "3"), + ("p590", "590"), + ("p0", "0"), + ("e1", "63"), + ("e2", "575"), + ]); + let q = [0.0, 0.0]; + // 64 to 66 tie with 63, the last row of the first page, and 576 to + // 580 tie with 575, the last row of the second. + let straddling = "Country = :us AND (Price BETWEEN :a AND :b OR Price >= :c)"; + for top_k in [1, 3, 4, 10] { + assert_eq!( + search(f, straddling, &v, &q, top_k).await, + expected(&all, |p| (64..=66).contains(&p) || p >= 577, top_k as usize), + "top_k {top_k}" + ); + } + // 63 and 575 end the first and the second page, so a page that + // repeated the row it starts after would keep it twice. + let page_ends = "Country = :us AND (Price = :e1 OR Price = :e2 OR Price >= :p590)"; + assert_eq!( + search(f, page_ends, &v, &q, 10).await, + expected(&all, |p| p == 63 || p == 575 || p >= 590, 10) + ); + // Rows from every page, and a scan to the end of the partition. + assert_eq!( + search(f, "Country = :us AND Price < :p3", &v, &q, 100).await, + expected(&all, |p| p < 3, 100) + ); + assert_eq!( + search(f, "Country = :us AND Price >= :p590", &v, &q, 10).await, + expected(&all, |p| p >= 590, 10) + ); + assert_eq!( + search(f, "Country = :us AND Price >= :p590", &v, &q, 100).await, + expected(&all, |p| p >= 590, 100) + ); + assert!( + search(f, "Country = :us AND Price < :p0", &v, &q, 10) + .await + .is_empty() + ); + }) + .await; +} + +/// Deletes rows from the index's data table the first time it is asked to +/// match, then answers as `inner` does. +struct DeletesOnFirstCall { + inner: Matcher, + data_url: String, + ids: Vec<&'static str>, + done: AtomicBool, +} + +impl VectorItemFilter for DeletesOnFirstCall { + fn matches(&self, item: &Item) -> Result { + if !self.done.swap(true, Ordering::SeqCst) { + let (url, ids) = (self.data_url.clone(), self.ids.clone()); + // A separate runtime on a separate thread, so the delete commits + // while the search waits here between two of its statements. + std::thread::spawn(move || { + tokio::runtime::Runtime::new() + .expect("a runtime") + .block_on(delete_rows(&url, &ids)); + }) + .join() + .expect("the delete thread"); + } + self.inner.matches(item) + } +} + +async fn delete_rows(url: &str, ids: &[&str]) { + let pool = PgPoolOptions::new() + .max_connections(1) + .connect(url) + .await + .expect("connect to the data database"); + let tables: Vec = sqlx::query_scalar( + "SELECT tablename::text FROM pg_tables WHERE tablename LIKE '\\_ddb\\_vec\\_%'", + ) + .fetch_all(&pool) + .await + .expect("find the vector table"); + assert_eq!(tables.len(), 1, "{tables:?}"); + let deleted = sqlx::query(&format!( + "DELETE FROM \"{}\" WHERE item_data -> 'id' ->> 'S' = ANY($1)", + tables[0] + )) + .bind(ids) + .execute(&pool) + .await + .expect("delete the rows"); + assert_eq!(deleted.rows_affected(), ids.len() as u64); + pool.close().await; +} + +#[tokio::test] +async fn every_page_reads_the_snapshot_of_the_first() { + let names = row_ids(); + run("EUCLIDEAN", &rows(&names), async |f: &Fixture| { + let v: HashMap = + values(&[("a", "64"), ("b", "66"), ("us", "S:US")]); + let (filter, _) = parse(f, "Country = :us AND Price BETWEEN :a AND :b", &v); + // i063 ends the first page, whose key the second page starts after; + // i064 to i066 are the second page's matches. + let item_filter: Arc = Arc::new(DeletesOnFirstCall { + inner: Matcher(filter), + data_url: f.data_url.clone(), + ids: vec!["i063", "i064", "i065", "i066"], + done: AtomicBool::new(false), + }); + let us = us(); + let hits = search_with( + f, + Some(("Country", &us)), + Some(item_filter), + &[0.0, 0.0], + 10, + ) + .await; + assert_eq!(ids(&hits), ["i064", "i065", "i066"]); + // A later search sees the delete. + let hits = search( + f, + "Country = :us AND Price BETWEEN :a AND :b", + &v, + &[0.0, 0.0], + 10, + ) + .await; + assert!(hits.is_empty(), "{hits:?}"); + }) + .await; +} From 0ff14403a5f40371f1873022f2855d431a032eb8 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 17:44:04 +0000 Subject: [PATCH 022/101] test(search): read the grammar setting instead of writing it The service checks ExpressionAttributeNames and ExpressionAttributeValues before it parses the search condition, under either grammar. Measured in eu-north-1, each request twice: keys of 254 and 255 bytes in either map answer 200, and a 256-byte key answers "contains a key that is too long; size of key: 256". The value-shape requests of the condition limit module answer "Multiple attribute names used in one condition" under the extended grammar. The inequality module wrote the search_inequality_filters setting for the whole server while it ran and wrote "off" back when the setting had been absent. A condition limit run started 0.8 s earlier on the same server got 17 failures. It skipped, rather than failed, when the server took the setting and still served the equality grammar; neither module checked the grammar against the setting; the inequality module ignored EXTENDDB_EXPECT_VECTORS; its backend refusal test could not fail; and the map tests skipped on every build without the feature. The modules now share tests/search_vectors_wire.py. They read the setting and never write it; devtools/run-tests writes it before any suite starts from EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS and stops when the server refuses it. Against ExtendDB each module fails when the probe gets the other grammar's answer. The map checks moved to test_search_vectors_expression_maps.py, which uses conditions both grammars accept and pins the 255-byte key limit on both sides. The backend refusal test asserts the CreateTable and SearchVectors refusals with a condition neither grammar parses. DeleteTable answers are asserted. The value-shape test asserts the measured extended answer. devtools/provision-test-credentials exports EXTENDDB_TEST_ACCOUNT_ID for an account-list setting. A --filter that selects no test of the CLI lifecycle or backup store wire block no longer fails the run. test_authz_search_vectors_index.py takes the EXTENDDB_EXPECT_VECTORS helper from search_vectors_wire, where it now lives. Verified on SQLite and PostgreSQL builds with the feature, setting absent and all, a SQLite build without it, MongoDB and Cassandra, and twice against the live service in eu-north-1, with a negative control per new assertion. --- devtools/provision-test-credentials | 1 + devtools/run-tests | 38 +- tests/search_vectors_wire.py | 223 ++++++++++++ tests/test_authz_search_vectors_index.py | 2 +- tests/test_search_vectors_condition_limit.py | 147 +------- tests/test_search_vectors_expression_maps.py | 194 +++++++++++ .../test_search_vectors_inequality_filters.py | 328 ++++++------------ 7 files changed, 575 insertions(+), 358 deletions(-) create mode 100644 tests/search_vectors_wire.py create mode 100644 tests/test_search_vectors_expression_maps.py diff --git a/devtools/provision-test-credentials b/devtools/provision-test-credentials index 189fea3dd..417280c3a 100755 --- a/devtools/provision-test-credentials +++ b/devtools/provision-test-credentials @@ -131,6 +131,7 @@ def main() -> int: print(f"export AWS_ACCESS_KEY_ID={access_key}") print(f"export AWS_SECRET_ACCESS_KEY={secret_key}") print(f"export AWS_DEFAULT_REGION=us-east-1") + print(f"export EXTENDDB_TEST_ACCOUNT_ID={ACCOUNT_ID}") return 0 diff --git a/devtools/run-tests b/devtools/run-tests index c778f3b40..f91aff0ca 100755 --- a/devtools/run-tests +++ b/devtools/run-tests @@ -47,6 +47,12 @@ # expected outcome from it, so it is required # (the Rust integration suite's backup tests read # it too and fail when it is unset). +# EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS +# when set, the value of the +# search_inequality_filters runtime setting +# (off, all, or account IDs), written before any +# suite starts; a server that refuses it is an +# error. Unset leaves the setting as it is. # # REQ-TEST-001, D-1, D-2, D-3, D-4, D-5 @@ -123,6 +129,9 @@ Environment (--extenddb with an integration suite): EXTENDDB_TEST_BACKUP_STORE where the server writes its backups: filesystem, s3 or none (required for --pytest; the Rust integration suite's backup tests read it too) + EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS + value for the search_inequality_filters setting, + written before any suite starts (optional) Environment (--real-dynamodb): EXTENDDB_TEST_ENDPOINT and EXTENDDB_ADMIN_PASSWORD unset; AWS credentials from the SDK's chain or AWS_ACCESS_KEY_ID. EOF @@ -408,6 +417,19 @@ if $NEEDS_INTEGRATION && [[ "$TARGET" != "real-dynamodb" ]]; then echo " ✓ allow_credential_import set to true" fi fi + # The SearchVectors grammar setting. The suites read it and never write it, + # so parallel workers all see the value written here. + if [[ -n "${EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS:-}" ]]; then + if [[ ! -x "$BINARY" || ! -f "$CONFIG_FOR_SETTINGS" ]]; then + echo "error: EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS is set and there is no $BINARY or $CONFIG_FOR_SETTINGS to write it with." + exit 1 + fi + if ! "$BINARY" settings --config "$CONFIG_FOR_SETTINGS" set search_inequality_filters "$EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS"; then + echo "error: the server refused search_inequality_filters=$EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS (a build without the search-inequality-filters feature refuses the key)." + exit 1 + fi + echo " ✓ search_inequality_filters set to $EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS" + fi # Import/export paths. The Python tests write fixtures via tempfile, which # honours $TMPDIR — on macOS that is under /var/folders, not /tmp. Allow @@ -697,8 +719,14 @@ if $RUN_PYTEST \ CLI_ARGS+=(-k "$FILTER") fi if [[ -n "$SHARD" ]]; then shard_suite cli "${CLI_ARGS[@]}"; CLI_ARGS=("${SHARD_CMD[@]}"); fi - if "${CLI_ARGS[@]}" 2>&1 | tee "$CLI_OUTFILE"; then + # pytest exits 5 when it selects no test, which a --filter aimed at + # another suite does here. + CLI_RC=0 + "${CLI_ARGS[@]}" 2>&1 | tee "$CLI_OUTFILE" || CLI_RC=${PIPESTATUS[0]} + if (( CLI_RC == 0 )); then echo " ✓ CLI lifecycle tests passed" + elif (( CLI_RC == 5 )) && [[ -n "$FILTER" ]]; then + echo " - CLI lifecycle tests: none matches the filter" else echo " ✗ CLI lifecycle tests failed" PASS=false @@ -727,8 +755,14 @@ if $RUN_PYTEST && [[ "$TARGET" != "real-dynamodb" ]]; then if [[ -n "$FILTER" ]]; then WIRE_ARGS+=(-k "$FILTER") fi - if EXTENDDB_BINARY="$WIRE_BINARY" "${WIRE_ARGS[@]}" 2>&1 | tee "$WIRE_OUTFILE"; then + # pytest exits 5 when it selects no test, which a --filter aimed at + # another suite does here. + WIRE_RC=0 + EXTENDDB_BINARY="$WIRE_BINARY" "${WIRE_ARGS[@]}" 2>&1 | tee "$WIRE_OUTFILE" || WIRE_RC=${PIPESTATUS[0]} + if (( WIRE_RC == 0 )); then echo " ✓ Backup store wire tests passed" + elif (( WIRE_RC == 5 )) && [[ -n "$FILTER" ]]; then + echo " - Backup store wire tests: none matches the filter" else echo " ✗ Backup store wire tests failed" PASS=false diff --git a/tests/search_vectors_wire.py b/tests/search_vectors_wire.py new file mode 100644 index 000000000..fd123bd3c --- /dev/null +++ b/tests/search_vectors_wire.py @@ -0,0 +1,223 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Wire helpers shared by the SearchVectors condition modules. + +Requests are raw SigV4-signed JSON. Against the service, SearchVectors goes to +the ``search-dynamodb`` host the SDKs use for it and every other operation to +the ``dynamodb`` host; against ExtendDB both go to ``EXTENDDB_TEST_ENDPOINT``. + +The grammar a target serves an account is the equality-only grammar or the +extended grammar. Against ExtendDB with admin credentials in the environment, +``expected_grammar`` reads it from the ``search_inequality_filters`` setting, +and ``grammar_of`` fails when the target answers with the other grammar. +These helpers only read the setting. ``devtools/run-tests`` writes it, from +``EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS``, before any suite starts. +""" + +from __future__ import annotations + +import json +import os +import time +import uuid +from collections.abc import Callable + +import boto3 +import pytest +import requests +from botocore.auth import SigV4Auth +from botocore.awsrequest import AWSRequest + +ENDPOINT_VAR = os.environ.get("EXTENDDB_TEST_ENDPOINT", "").strip() +REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") +ENDPOINT = ENDPOINT_VAR or f"https://dynamodb.{REGION}.amazonaws.com/" +SEARCH_ENDPOINT = ENDPOINT_VAR or f"https://search-dynamodb.{REGION}.amazonaws.com/" +SETTING = "search_inequality_filters" + +EQUALITY_ONLY = ( + "Invalid SearchConditionExpression: Invalid comparator used in " + "SearchConditionExpression" +) +INDEX_NOT_SUPPORTED = "Vector indexes are not supported by this storage backend" +SEARCH_NOT_SUPPORTED = "SearchVectors is not supported by this storage backend" + +# How long a changed setting may take to reach the request path. +GRAMMAR_DEADLINE_S = 15.0 + + +def table_name() -> str: + """A fresh table name; ``EXTENDDB_TEST_TABLE_PREFIX`` replaces ``extenddb-test``.""" + prefix = os.environ.get("EXTENDDB_TEST_TABLE_PREFIX", "").strip() or "extenddb-test" + return f"{prefix}-{uuid.uuid4().hex[:12]}" + + +def signed_post(operation: str, body: dict) -> requests.Response: + """POST ``body`` under the DynamoDB JSON-1.0 protocol, SigV4-signed.""" + url = SEARCH_ENDPOINT if operation == "SearchVectors" else ENDPOINT + body_bytes = json.dumps(body).encode("utf-8") + headers = { + "X-Amz-Target": f"DynamoDB_20120810.{operation}", + "Content-Type": "application/x-amz-json-1.0", + } + creds = boto3.Session().get_credentials() + if creds is not None: + aws_req = AWSRequest(method="POST", url=url, data=body_bytes, headers=headers) + SigV4Auth(creds.get_frozen_credentials(), "dynamodb", REGION).add_auth(aws_req) + headers = dict(aws_req.headers) + verify = True if not ENDPOINT_VAR else not url.startswith("https://") + return requests.post(url, data=body_bytes, headers=headers, verify=verify, timeout=30) + + +def message(resp: requests.Response) -> str: + payload = resp.json() + return payload.get("message", payload.get("Message", "")) + + +def refused(resp: requests.Response, expected: str) -> None: + """Refused with a ValidationException carrying exactly ``expected``.""" + assert resp.status_code == 400, resp.text + assert resp.json()["__type"].endswith("ValidationException"), resp.text + assert message(resp) == expected, resp.text + + +def expect_vectors() -> bool | None: + """``EXTENDDB_EXPECT_VECTORS``: 1 requires vector support, 0 forbids it.""" + value = os.environ.get("EXTENDDB_EXPECT_VECTORS") + if value is None or not ENDPOINT_VAR: + return None + if value not in ("0", "1"): + pytest.fail(f"EXTENDDB_EXPECT_VECTORS must be 0 or 1, got {value!r}") + return value == "1" + + +def wait_active(name: str) -> None: + """Poll until the table and its vector indexes are all ACTIVE. + + The service takes minutes to build a vector index; ExtendDB takes well + under a second. + """ + timeout = 180.0 if ENDPOINT_VAR else 1800.0 + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + resp = signed_post("DescribeTable", {"TableName": name}) + if resp.status_code == 200: + table = resp.json()["Table"] + if table["TableStatus"] == "ACTIVE" and all( + vi.get("IndexStatus") == "ACTIVE" for vi in table.get("VectorIndexes", []) + ): + return + time.sleep(0.05 if ENDPOINT_VAR else 10.0) + raise TimeoutError(f"table {name} did not become ACTIVE within {timeout}s") + + +def delete_table(name: str) -> None: + """Delete a table, retrying only on connection errors.""" + for attempt in range(3): + try: + resp = signed_post("DeleteTable", {"TableName": name}) + except requests.exceptions.ConnectionError: + if attempt == 2: + raise + time.sleep(5.0) + continue + assert resp.status_code == 200, f"DeleteTable {name} failed: {resp.text}" + return + + +def create_vector_table(name: str, create_body: dict) -> None: + """Create a table with one vector index and wait for it. + + Skips when the backend refuses vector indexes, unless + ``EXTENDDB_EXPECT_VECTORS=1``; fails when that is 0 and the backend + accepts one. Deletes the table when anything after the create fails. + """ + expected = expect_vectors() + resp = signed_post("CreateTable", {"TableName": name, **create_body}) + if resp.status_code == 400 and message(resp) == INDEX_NOT_SUPPORTED: + if expected is True: + pytest.fail("EXTENDDB_EXPECT_VECTORS=1 but the backend refuses vector indexes") + pytest.skip("target backend does not support vector indexes") + assert resp.status_code == 200, f"CreateTable failed: {resp.text}" + try: + assert expected is not False, ( + "EXTENDDB_EXPECT_VECTORS=0 but the backend accepted a vector index" + ) + wait_active(name) + # A target may accept CreateTable while ignoring VectorIndexes, and the + # wait above then passes with no index to search. + describe = signed_post("DescribeTable", {"TableName": name}) + assert describe.status_code == 200, describe.text + if not describe.json()["Table"].get("VectorIndexes"): + if expected is True: + pytest.fail("EXTENDDB_EXPECT_VECTORS=1 but the vector index was not created") + pytest.skip("target accepted CreateTable but did not create the vector index") + except BaseException: + delete_table(name) + raise + + +def _settings_api() -> tuple[str, tuple[str, str]] | None: + password = os.environ.get("EXTENDDB_ADMIN_PASSWORD", "").strip() + if not ENDPOINT_VAR or not password: + return None + user = os.environ.get("EXTENDDB_ADMIN_USER", "").strip() or "admin" + return f"{ENDPOINT_VAR.rstrip('/')}/management/settings/{SETTING}", (user, password) + + +def expected_grammar() -> str | None: + """``equality`` or ``extended`` from the setting; ``None`` when it cannot be read. + + An absent setting is ``off``, which is also what a build without the + feature serves. A list of accounts names the account in + ``EXTENDDB_TEST_ACCOUNT_ID``, which ``devtools/provision-test-credentials`` + exports. + """ + api = _settings_api() + if api is None: + return None + url, auth = api + resp = requests.get(url, auth=auth, timeout=30, verify=False) + if resp.status_code == 404: + return "equality" + assert resp.status_code == 200, f"GET {url}: {resp.status_code} {resp.text}" + value = resp.json()["value"].strip() + if value == "off": + return "equality" + if value == "all": + return "extended" + account = os.environ.get("EXTENDDB_TEST_ACCOUNT_ID", "").strip() + if not account: + pytest.fail( + f"{SETTING} lists accounts ({value!r}) and EXTENDDB_TEST_ACCOUNT_ID is unset" + ) + listed = {entry.strip() for entry in value.split(",")} + return "extended" if account in listed else "equality" + + +def grammar_of(probe: Callable[[], requests.Response]) -> str: + """The grammar the target serves, from ``probe``: an inequality search. + + The extended grammar answers the probe with 200 and the equality-only + grammar refuses it with the comparator message. Against ExtendDB the + answer must match the setting; a setting written just before the run may + take ``GRAMMAR_DEADLINE_S`` to reach the request path. + """ + expected = expected_grammar() + deadline = time.monotonic() + GRAMMAR_DEADLINE_S + while True: + resp = probe() + if resp.status_code == 200: + served = "extended" + elif resp.status_code == 400 and message(resp) == EQUALITY_ONLY: + served = "equality" + else: + pytest.fail(f"neither grammar answered the probe: {resp.status_code} {resp.text}") + if expected is None or served == expected: + return served + if time.monotonic() > deadline: + pytest.fail( + f"the {SETTING} setting gives this account the {expected} grammar, " + f"and the target serves the {served} grammar: {resp.status_code} {resp.text}" + ) + time.sleep(0.2) diff --git a/tests/test_authz_search_vectors_index.py b/tests/test_authz_search_vectors_index.py index f379bb1a3..a6d036bca 100644 --- a/tests/test_authz_search_vectors_index.py +++ b/tests/test_authz_search_vectors_index.py @@ -38,7 +38,7 @@ from botocore.credentials import Credentials from management_helpers import ManagementClient -from test_search_vectors_condition_limit import _expect_vectors +from search_vectors_wire import expect_vectors as _expect_vectors REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") VECTOR = [{"N": "0.1"}, {"N": "0.2"}, {"N": "0.3"}, {"N": "0.4"}] diff --git a/tests/test_search_vectors_condition_limit.py b/tests/test_search_vectors_condition_limit.py index 6a06fa4d1..8ba6fc6c5 100644 --- a/tests/test_search_vectors_condition_limit.py +++ b/tests/test_search_vectors_condition_limit.py @@ -32,8 +32,10 @@ ``=``, OR, NOT, IN, BETWEEN, up to 50 conditions). The ``grammar`` fixture asks the target which grammar it serves, by sending ``h = :v0 AND f1 <> :v1``: the equality-only grammar refuses it with the comparator message and the -extended grammar answers 200. Each test then asserts the answer of that -grammar. The extended answers were measured on 2026-11-21 in eu-north-1, on an +extended grammar answers 200. Against ExtendDB the fixture also reads the +``search_inequality_filters`` setting and fails when the answer is the other +grammar's. Each test then asserts the answer of that grammar. The extended +answers were measured on 2026-11-21 and 2026-11-23 in eu-north-1, on an account with the extended grammar, each request twice: under it the 20th comparison is no fault of its own, and the schema, HASH and unused-value checks answer instead. @@ -48,25 +50,15 @@ from __future__ import annotations -import json -import os import re -import time -import uuid - -import boto3 import pytest import requests -from botocore.auth import SigV4Auth -from botocore.awsrequest import AWSRequest -_ENDPOINT_VAR = os.environ.get("EXTENDDB_TEST_ENDPOINT", "").strip() -_REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") -ENDPOINT = _ENDPOINT_VAR or f"https://dynamodb.{_REGION}.amazonaws.com/" -# The helpers in test_vector_index_query_scan.py post every operation to one -# endpoint. The service serves SearchVectors from its own host, so this module -# keeps its own copy that routes by operation. -SEARCH_ENDPOINT = _ENDPOINT_VAR or f"https://search-dynamodb.{_REGION}.amazonaws.com/" +from search_vectors_wire import EQUALITY_ONLY as COMPARATOR +from search_vectors_wire import create_vector_table, delete_table, grammar_of, table_name +from search_vectors_wire import message as _error_message +from search_vectors_wire import refused as _refused_with +from search_vectors_wire import signed_post as _signed_post PREFIX = "Invalid SearchConditionExpression" TOO_MANY = ( @@ -77,10 +69,6 @@ "Invalid SearchConditionExpression: SearchConditionExpression must only " "contain one condition per attribute" ) -COMPARATOR = ( - "Invalid SearchConditionExpression: Invalid comparator used in " - "SearchConditionExpression" -) RESERVED_BUCKET = ( "Invalid SearchConditionExpression: Attribute name is a reserved keyword; " "reserved keyword: bucket" @@ -128,82 +116,14 @@ def _undefined_value(placeholder: str) -> str: ) -def _expect_vectors() -> bool | None: - """``EXTENDDB_EXPECT_VECTORS``: 1 requires vector support, 0 forbids it.""" - value = os.environ.get("EXTENDDB_EXPECT_VECTORS") - if value is None or not _ENDPOINT_VAR: - return None - if value not in ("0", "1"): - pytest.fail(f"EXTENDDB_EXPECT_VECTORS must be 0 or 1, got {value!r}") - return value == "1" - - -def _signed_post(operation: str, body: dict) -> requests.Response: - """POST ``body`` under the DynamoDB JSON-1.0 protocol, SigV4-signed.""" - url = SEARCH_ENDPOINT if operation == "SearchVectors" else ENDPOINT - body_bytes = json.dumps(body).encode("utf-8") - headers = { - "X-Amz-Target": f"DynamoDB_20120810.{operation}", - "Content-Type": "application/x-amz-json-1.0", - } - creds = boto3.Session().get_credentials() - if creds is not None: - aws_req = AWSRequest(method="POST", url=url, data=body_bytes, headers=headers) - SigV4Auth(creds.get_frozen_credentials(), "dynamodb", _REGION).add_auth(aws_req) - headers = dict(aws_req.headers) - verify = True if not _ENDPOINT_VAR else not url.startswith("https://") - return requests.post(url, data=body_bytes, headers=headers, verify=verify, timeout=30) - - -def _error_message(resp: requests.Response) -> str: - payload = resp.json() - return payload.get("message", payload.get("Message", "")) - - -def _wait_for_vector_table_active(name: str) -> None: - """Poll until the table and its vector indexes are all ACTIVE. - - The service takes minutes to build a vector index; ExtendDB takes well - under a second. - """ - timeout = 180.0 if _ENDPOINT_VAR else 1800.0 - deadline = time.monotonic() + timeout - while time.monotonic() < deadline: - resp = _signed_post("DescribeTable", {"TableName": name}) - if resp.status_code == 200: - table = resp.json()["Table"] - if table["TableStatus"] == "ACTIVE" and all( - vi.get("IndexStatus") == "ACTIVE" for vi in table.get("VectorIndexes", []) - ): - return - time.sleep(0.05 if _ENDPOINT_VAR else 10.0) - raise TimeoutError(f"table {name} did not become ACTIVE within {timeout}s") - - -def _delete_table(name: str) -> None: - """Delete the fixture table, retrying only on connection errors.""" - for attempt in range(3): - try: - resp = _signed_post("DeleteTable", {"TableName": name}) - except requests.exceptions.ConnectionError: - if attempt == 2: - raise - time.sleep(5.0) - continue - assert resp.status_code == 200, f"DeleteTable {name} failed: {resp.text}" - return - - @pytest.fixture(scope="module") def search_table(): """A table whose vector index declares a HASH and 18 inline filters.""" - expected = _expect_vectors() - name = f"extenddb-test-{uuid.uuid4().hex[:12]}" + name = table_name() attrs = ["pk", "h", *INLINE] - resp = _signed_post( - "CreateTable", + create_vector_table( + name, { - "TableName": name, "AttributeDefinitions": [ {"AttributeName": a, "AttributeType": "S"} for a in attrs ], @@ -227,44 +147,16 @@ def search_table(): ], }, ) - if resp.status_code == 400 and "not supported" in _error_message(resp): - if expected is True: - pytest.fail( - "EXTENDDB_EXPECT_VECTORS=1 but the backend refuses vector indexes: " - + _error_message(resp) - ) - pytest.skip("target backend does not support vector indexes") - assert resp.status_code == 200, f"CreateTable failed: {resp.text}" try: - assert expected is not False, ( - "EXTENDDB_EXPECT_VECTORS=0 but the backend accepted a vector index" - ) - _wait_for_vector_table_active(name) - # A target may accept CreateTable while ignoring VectorIndexes, and the - # wait above then passes with no index to search. - describe = _signed_post("DescribeTable", {"TableName": name}) - assert describe.status_code == 200, describe.text - index_names = [ - vi.get("IndexName") for vi in describe.json()["Table"].get("VectorIndexes", []) - ] - if "vidx" not in index_names: - if expected is True: - pytest.fail("EXTENDDB_EXPECT_VECTORS=1 but the vector index was not created") - pytest.skip("target accepted CreateTable but did not create the vector index") yield name finally: - _delete_table(name) + delete_table(name) @pytest.fixture(scope="module") def grammar(search_table) -> str: """``equality`` or ``extended``: the grammar the target serves this account.""" - resp = _search_expr(search_table, ["h = :v0", "f1 <> :v1"]) - if resp.status_code == 200: - return "extended" - if resp.status_code == 400 and _error_message(resp) == COMPARATOR: - return "equality" - pytest.fail(f"neither grammar answered the probe: {resp.status_code} {resp.text}") + return grammar_of(lambda: _search_expr(search_table, ["h = :v0", "f1 <> :v1"])) def _either(grammar: str, equality, extended): @@ -332,12 +224,6 @@ def _with(position: int, comparison: str, n: int = 19) -> list[str]: return parts -def _refused_with(resp: requests.Response, message: str) -> None: - assert resp.status_code == 400, resp.text - assert resp.json()["__type"].endswith("ValidationException"), resp.text - assert _error_message(resp) == message - - def _refused_not_for_count(resp: requests.Response, *fragments: str) -> None: """Refused by a check other than the count, whose message has ``fragments``.""" assert resp.status_code == 400, resp.text @@ -573,8 +459,11 @@ def test_comparator_is_checked_before_nested_and_repeat(self, search_table, gram nested_then_less[2] = "f2 < :v2" _refused_not_for_count(_search_expr(search_table, nested_then_less), NESTED) - def test_value_shape_is_checked_before_nested_and_repeat(self, search_table): + def test_value_shape_is_checked_before_nested_and_repeat(self, search_table, grammar): for comparisons in (_with(2, "a.b = v1"), _with(3, "f1 = v2")): resp = _search_expr(search_table, comparisons) + if grammar == "extended": + _refused_with(resp, X_MULTIPLE_NAMES) + continue _refused_not_for_count(resp, PREFIX) assert _error_message(resp) not in (NESTED, DUPLICATE), resp.text diff --git a/tests/test_search_vectors_expression_maps.py b/tests/test_search_vectors_expression_maps.py new file mode 100644 index 000000000..335032911 --- /dev/null +++ b/tests/test_search_vectors_expression_maps.py @@ -0,0 +1,194 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""SearchVectors checks on ExpressionAttributeNames and ExpressionAttributeValues. + +The service checks the two maps before it reads either expression, so these +answers do not depend on the grammar the account has. Every request here uses +conditions both grammars accept, and the module runs under either one. + +Measured against the live service in eu-north-1, on an account with the +extended grammar, each request twice with the same answer: on 2026-11-21, and +the 254, 255 and 256 byte keys on 2026-11-23. + +The module skips when the target backend does not support vector indexes, +unless ``EXTENDDB_EXPECT_VECTORS=1``, which makes that a failure. +""" + +from __future__ import annotations + +import pytest +import requests + +from search_vectors_wire import ( + create_vector_table, + delete_table, + message, + refused, + signed_post, + table_name, +) + +US = {":us": {"S": "US"}} +ONLY = "can only be specified when using expressions" + + +@pytest.fixture(scope="module") +def table(): + """HASH Country (S) and inline filter Price (N), with one item.""" + name = table_name() + create_vector_table( + name, + { + "AttributeDefinitions": [ + {"AttributeName": "id", "AttributeType": "S"}, + {"AttributeName": "Country", "AttributeType": "S"}, + {"AttributeName": "Price", "AttributeType": "N"}, + ], + "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], + "BillingMode": "PAY_PER_REQUEST", + "VectorIndexes": [ + { + "IndexName": "vix", + "Dimensions": 4, + "DistanceFunction": "COSINE", + "VectorAttribute": {"AttributeName": "emb"}, + "SearchSchema": [ + {"AttributeName": "Country", "SearchSchemaElementType": "HASH"}, + {"AttributeName": "Price", "SearchSchemaElementType": "INLINE_FILTER"}, + ], + "Projection": {"ProjectionType": "ALL"}, + } + ], + }, + ) + try: + put = signed_post( + "PutItem", + { + "TableName": name, + "Item": { + "id": {"S": "i1"}, + "Country": {"S": "US"}, + "Price": {"N": "5"}, + "emb": {"L": [{"N": "1"}, {"N": "0"}, {"N": "0"}, {"N": "0"}]}, + }, + }, + ) + assert put.status_code == 200, put.text + yield name + finally: + delete_table(name) + + +def _raw(table: str, **fields) -> requests.Response: + body = { + "TableName": table, + "IndexName": "vix", + "SearchVector": [{"N": "1"}, {"N": "0"}, {"N": "0"}, {"N": "0"}], + "TopK": 10, + } + body.update(fields) + return signed_post("SearchVectors", body) + + +def _accepted(resp: requests.Response) -> None: + assert resp.status_code == 200, resp.text + assert "SearchResults" in resp.json(), resp.text + + +def _too_long(map_name: str, size: int) -> str: + return ( + f"{map_name} contains invalid key: The expression attribute map contains a key " + f"that is too long; size of key: {size}" + ) + + +class TestEmptyMaps: + def test_empty_maps_names_first(self, table): + cond = {"SearchConditionExpression": "Country = :us"} + refused(_raw(table, **cond, ExpressionAttributeValues={}), + "ExpressionAttributeValues must not be empty") + refused( + _raw(table, **cond, ExpressionAttributeNames={}, ExpressionAttributeValues={}), + "ExpressionAttributeNames must not be empty", + ) + refused(_raw(table, ExpressionAttributeValues={}), + "ExpressionAttributeValues must not be empty") + resp = _raw(table, TopK=0, **cond, ExpressionAttributeValues={}) + assert resp.status_code == 400, resp.text + assert "TopK" in message(resp), resp.text + + +class TestKeysAndNames: + def test_keys_and_names(self, table): + cases = [ + ({"#c": ""}, {}, "#c = :us", + "ExpressionAttributeNames contains invalid value: Empty attribute name for key #c"), + ({"#a-b": "x"}, {**US, ":b-k": {"S": "y"}}, "Country = :us", + 'ExpressionAttributeNames contains invalid key: Syntax error; key: "#a-b"'), + ({"": "x"}, US, "Country = :us", + "ExpressionAttributeNames contains invalid key: The expression attribute map " + "contains an empty key;"), + ({"#" + "k" * 300: "x"}, US, "Country = :us", _too_long("ExpressionAttributeNames", 301)), + ({"#c": "C" * 65536}, US, "#c = :us", + "Attribute name is too large, must be less than 65536 bytes for key #c"), + (None, {**US, ":": {"S": "y"}}, "Country = :us", + 'ExpressionAttributeValues contains invalid key: Syntax error; key: ":"'), + ] + for names, values, cond, expected in cases: + fields = {"SearchConditionExpression": cond, "ExpressionAttributeValues": values} + if names is not None: + fields["ExpressionAttributeNames"] = names + refused(_raw(table, **fields), expected) + + @pytest.mark.parametrize("size", [254, 255, 256]) + def test_a_key_is_at_most_255_bytes(self, table, size): + name_key = "#" + "a" * (size - 1) + names = _raw( + table, + SearchConditionExpression=f"{name_key} = :us", + ExpressionAttributeNames={name_key: "Country"}, + ExpressionAttributeValues=US, + ) + value_key = ":" + "v" * (size - 1) + values = _raw( + table, + SearchConditionExpression=f"Country = {value_key}", + ExpressionAttributeValues={value_key: {"S": "US"}}, + ) + if size <= 255: + _accepted(names) + _accepted(values) + else: + refused(names, _too_long("ExpressionAttributeNames", size)) + refused(values, _too_long("ExpressionAttributeValues", size)) + + +class TestMapsNeedTheirExpression: + def test_maps_need_their_expression(self, table): + names = {"#p": "Price"} + refused(_raw(table, ExpressionAttributeNames=names), "ExpressionAttributeNames " + ONLY) + refused(_raw(table, ExpressionAttributeNames=names, ExpressionAttributeValues=US), + "ExpressionAttributeNames " + ONLY) + refused(_raw(table, ExpressionAttributeValues=US), "ExpressionAttributeValues " + ONLY) + refused( + _raw(table, ProjectionExpression="#p", ExpressionAttributeNames=names, + ExpressionAttributeValues=US), + "ExpressionAttributeValues " + ONLY, + ) + + +class TestUnusedNames: + def test_unused_names(self, table): + unused = "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}" + u = {"#u": "x"} + refused(_raw(table, SearchConditionExpression="Country = :us", + ExpressionAttributeNames=u, + ExpressionAttributeValues={**US, ":w": {"S": "w"}}), unused) + refused(_raw(table, SearchConditionExpression="Country = :us", + ProjectionExpression="Price", ExpressionAttributeNames=u, + ExpressionAttributeValues=US), unused) + _accepted(_raw(table, SearchConditionExpression="Country = :us", + ProjectionExpression="#p", ExpressionAttributeNames={"#p": "Price"}, + ExpressionAttributeValues=US)) diff --git a/tests/test_search_vectors_inequality_filters.py b/tests/test_search_vectors_inequality_filters.py index 7b3d80ad0..3920ab3ca 100644 --- a/tests/test_search_vectors_inequality_filters.py +++ b/tests/test_search_vectors_inequality_filters.py @@ -8,51 +8,50 @@ ``attribute_exists`` and ``attribute_not_exists``, and more than one condition on an attribute, up to 50 conditions. -The number comparisons in ``TestEvaluation`` and every case in -``TestExpressionMaps`` were measured against the live service on 2026-11-21 in +Every expected response was measured against the live service in eu-north-1, on an account with the extended grammar, each request twice with -the same answer. The other expected responses are predictions of the -service's answer. +the same answer, on 2026-11-19 and 2026-11-21. -Against ExtendDB the module turns the grammar on for every account through the -management API, as the admin in ``EXTENDDB_ADMIN_USER`` and -``EXTENDDB_ADMIN_PASSWORD``, and restores the previous value afterwards. A -build without the feature refuses the setting. The module then probes one -inequality search, and skips when the target answers it with the -equality-only message, which is the answer of a build without the feature and -of an account the service has not enabled. +The module probes one inequality search to learn the grammar the target +serves. Against ExtendDB it also reads the ``search_inequality_filters`` +setting, as the admin in ``EXTENDDB_ADMIN_USER`` and +``EXTENDDB_ADMIN_PASSWORD``, and fails when the probe gets the other grammar's +answer. It never writes the setting: ``devtools/run-tests`` sets it from +``EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS`` before any suite starts. Under the +equality-only grammar the tests of the extended grammar skip; +``test_the_grammar_matches_the_setting`` runs under both. On a backend without vector search, every SearchVectors request is refused by -the backend, the extended grammar included; ``TestBackendWithoutVectors`` -pins that. +the backend before the grammar runs; ``TestBackendWithoutVectors`` pins that. +The module skips when the target backend does not support vector indexes, +unless ``EXTENDDB_EXPECT_VECTORS=1``, which makes that a failure. -Tests post raw SigV4-signed JSON. Against the service, SearchVectors is sent to -the ``search-dynamodb`` host the SDKs use for it. +The checks on the expression maps are in ``test_search_vectors_expression_maps.py``, +which runs under both grammars. """ from __future__ import annotations -import json -import os import re import time -import uuid - -import boto3 import pytest import requests -from botocore.auth import SigV4Auth -from botocore.awsrequest import AWSRequest -_ENDPOINT_VAR = os.environ.get("EXTENDDB_TEST_ENDPOINT", "").strip() -_REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") -ENDPOINT = _ENDPOINT_VAR or f"https://dynamodb.{_REGION}.amazonaws.com/" -SEARCH_ENDPOINT = _ENDPOINT_VAR or f"https://search-dynamodb.{_REGION}.amazonaws.com/" -SETTING = "search_inequality_filters" +from search_vectors_wire import ( + ENDPOINT_VAR, + EQUALITY_ONLY, + INDEX_NOT_SUPPORTED, + SEARCH_NOT_SUPPORTED, + create_vector_table, + delete_table, + expect_vectors, + grammar_of, + refused as _refused, + table_name, + signed_post as _signed_post, +) P = "Invalid SearchConditionExpression: " -EQUALITY_ONLY = P + "Invalid comparator used in SearchConditionExpression" -NOT_SUPPORTED = "SearchVectors is not supported by this storage backend" HASH_NOT_EQUALS = ( "SearchConditionExpression must use = on the HASH attribute, not inside OR or " "NOT; HASH attribute: Country" @@ -89,58 +88,6 @@ def _wrong_type(attribute: str, given: str, declared: str) -> str: ) -def _signed_post(operation: str, body: dict) -> requests.Response: - """POST ``body`` under the DynamoDB JSON-1.0 protocol, SigV4-signed.""" - url = SEARCH_ENDPOINT if operation == "SearchVectors" else ENDPOINT - body_bytes = json.dumps(body).encode("utf-8") - headers = { - "X-Amz-Target": f"DynamoDB_20120810.{operation}", - "Content-Type": "application/x-amz-json-1.0", - } - creds = boto3.Session().get_credentials() - if creds is not None: - aws_req = AWSRequest(method="POST", url=url, data=body_bytes, headers=headers) - SigV4Auth(creds.get_frozen_credentials(), "dynamodb", _REGION).add_auth(aws_req) - headers = dict(aws_req.headers) - verify = True if not _ENDPOINT_VAR else not url.startswith("https://") - return requests.post(url, data=body_bytes, headers=headers, verify=verify, timeout=30) - - -def _message(resp: requests.Response) -> str: - payload = resp.json() - return payload.get("message", payload.get("Message", "")) - - -def _settings_api(): - """The settings URL and admin credentials, or ``None`` against the service.""" - password = os.environ.get("EXTENDDB_ADMIN_PASSWORD", "").strip() - if not _ENDPOINT_VAR or not password: - return None - user = os.environ.get("EXTENDDB_ADMIN_USER", "").strip() or "admin" - return f"{_ENDPOINT_VAR.rstrip('/')}/management/settings/{SETTING}", (user, password) - - -def _set_setting(value: str | None) -> bool: - """Write the setting; ``False`` when the target cannot take it.""" - api = _settings_api() - if api is None: - return False - url, auth = api - if value is None: - value = "off" - resp = requests.put(url, auth=auth, json={"value": value}, timeout=30, verify=False) - return resp.status_code == 200 - - -def _previous_setting() -> str | None: - api = _settings_api() - if api is None: - return None - url, auth = api - resp = requests.get(url, auth=auth, timeout=30, verify=False) - return resp.json().get("value") if resp.status_code == 200 else None - - # id: (Country, Category, Price, Tag); None is an absent attribute. ITEMS = { "i1": ("US", "a", "5", "AQ=="), @@ -174,20 +121,6 @@ def _previous_setting() -> str | None: US = {k for k, v in ITEMS.items() if v[0] == "US"} -def _wait_active(name: str) -> None: - deadline = time.monotonic() + (180.0 if _ENDPOINT_VAR else 1800.0) - while time.monotonic() < deadline: - resp = _signed_post("DescribeTable", {"TableName": name}) - if resp.status_code == 200: - table = resp.json()["Table"] - if table["TableStatus"] == "ACTIVE" and all( - vi.get("IndexStatus") == "ACTIVE" for vi in table.get("VectorIndexes", []) - ): - return - time.sleep(0.05 if _ENDPOINT_VAR else 10.0) - raise TimeoutError(f"table {name} did not become ACTIVE") - - def _search(table: str, expr: str, top_k: int = 100, names=None) -> requests.Response: used = set(re.findall(r":[A-Za-z0-9_]+", expr)) body = { @@ -209,55 +142,40 @@ def _ids(resp: requests.Response) -> set[str]: return {r["Item"]["id"]["S"] for r in resp.json()["SearchResults"]} -def _refused(resp: requests.Response, message: str) -> None: - assert resp.status_code == 400, resp.text - assert resp.json()["__type"].endswith("ValidationException"), resp.text - assert _message(resp) == message +CREATE = { + "AttributeDefinitions": [ + {"AttributeName": "id", "AttributeType": "S"}, + {"AttributeName": "Country", "AttributeType": "S"}, + {"AttributeName": "Category", "AttributeType": "S"}, + {"AttributeName": "Price", "AttributeType": "N"}, + {"AttributeName": "Tag", "AttributeType": "B"}, + ], + "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], + "BillingMode": "PAY_PER_REQUEST", + "VectorIndexes": [ + { + "IndexName": "vix", + "Dimensions": 4, + "DistanceFunction": "COSINE", + "VectorAttribute": {"AttributeName": "emb"}, + "SearchSchema": [ + {"AttributeName": "Country", "SearchSchemaElementType": "HASH"}, + {"AttributeName": "Category", "SearchSchemaElementType": "INLINE_FILTER"}, + {"AttributeName": "Price", "SearchSchemaElementType": "INLINE_FILTER"}, + {"AttributeName": "Tag", "SearchSchemaElementType": "INLINE_FILTER"}, + ], + "Projection": {"ProjectionType": "ALL"}, + } + ], +} @pytest.fixture(scope="module") -def grammar_table(): +def vector_table(): """Table with HASH Country (S), inline filters Category (S), Price (N), Tag (B).""" - previous = _previous_setting() - managed = _set_setting("all") - name = f"extenddb-test-{uuid.uuid4().hex[:12]}" - created = False + name = table_name() + create_vector_table(name, CREATE) try: - resp = _signed_post( - "CreateTable", - { - "TableName": name, - "AttributeDefinitions": [ - {"AttributeName": "id", "AttributeType": "S"}, - {"AttributeName": "Country", "AttributeType": "S"}, - {"AttributeName": "Category", "AttributeType": "S"}, - {"AttributeName": "Price", "AttributeType": "N"}, - {"AttributeName": "Tag", "AttributeType": "B"}, - ], - "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], - "BillingMode": "PAY_PER_REQUEST", - "VectorIndexes": [ - { - "IndexName": "vix", - "Dimensions": 4, - "DistanceFunction": "COSINE", - "VectorAttribute": {"AttributeName": "emb"}, - "SearchSchema": [ - {"AttributeName": "Country", "SearchSchemaElementType": "HASH"}, - {"AttributeName": "Category", "SearchSchemaElementType": "INLINE_FILTER"}, - {"AttributeName": "Price", "SearchSchemaElementType": "INLINE_FILTER"}, - {"AttributeName": "Tag", "SearchSchemaElementType": "INLINE_FILTER"}, - ], - "Projection": {"ProjectionType": "ALL"}, - } - ], - }, - ) - if resp.status_code == 400 and "not supported" in _message(resp): - pytest.skip("target backend does not support vector indexes") - assert resp.status_code == 200, resp.text - created = True - _wait_active(name) for rank, (item_id, (country, category, price, tag)) in enumerate(ITEMS.items()): item = { "id": {"S": item_id}, @@ -273,23 +191,38 @@ def grammar_table(): item["Tag"] = {"B": tag} put = _signed_post("PutItem", {"TableName": name, "Item": item}) assert put.status_code == 200, put.text - probe = _search(name, H + "Price > :p5") - if probe.status_code == 400 and _message(probe) == EQUALITY_ONLY: - pytest.skip("the extended grammar is off for this account") # Vector index maintenance may lag the write by the propagation delay. + # An equality search, so the wait holds under both grammars. deadline = time.monotonic() + 30 - while _ids(_search(name, H + "Price <> :p0")) != US: + while _ids(_search(name, "Country = :us")) != US: if time.monotonic() > deadline: raise TimeoutError("items did not reach the vector index") time.sleep(0.1) yield name finally: - if created: - _signed_post("DeleteTable", {"TableName": name}) - if managed: - _set_setting(previous) + delete_table(name) + + +@pytest.fixture(scope="module") +def grammar(vector_table) -> str: + """``equality`` or ``extended``, checked against the setting on ExtendDB.""" + return grammar_of(lambda: _search(vector_table, H + "Price > :p5")) + + +@pytest.fixture(scope="module") +def grammar_table(vector_table, grammar): + if grammar == "equality": + pytest.skip("the extended grammar is off for this account") + return vector_table +class TestGate: + def test_the_grammar_matches_the_setting(self, vector_table, grammar): + resp = _search(vector_table, H + "Price > :p5") + if grammar == "equality": + _refused(resp, EQUALITY_ONLY) + else: + assert _ids(resp) == {"i2", "i3", "i6", "i7", "i9"} class TestOperators: @@ -321,8 +254,8 @@ def test_a_range_on_one_attribute(self, grammar_table): class TestEvaluation: - """Measured: numbers compare as the nearest binary64 value of each side, so the - two 38-digit Prices are equal. Not yet measured: a missing attribute.""" + """Numbers compare as the nearest binary64 value of each side, so the two + 38-digit Prices are equal. A missing attribute satisfies ``<>`` and NOT.""" def test_a_missing_attribute_under_not_equal_and_not(self, grammar_table): assert "i4" in _ids(_search(grammar_table, H + "Price <> :p10")) @@ -347,6 +280,7 @@ def test_the_hash_value_scopes_the_search(self, grammar_table): def test_the_filter_applies_before_top_k(self, grammar_table): resp = _search(grammar_table, H + "Price > :p5", top_k=2) + assert resp.status_code == 200, resp.text assert [r["Item"]["id"]["S"] for r in resp.json()["SearchResults"]] == ["i2", "i3"] @@ -461,81 +395,18 @@ def _raw(table: str, **fields) -> requests.Response: return _signed_post("SearchVectors", body) -class TestExpressionMaps: - """The two maps, checked before either expression is read.""" - - def test_empty_maps_names_first(self, grammar_table): - cond = {"SearchConditionExpression": "Country = :us"} - _refused(_raw(grammar_table, **cond, ExpressionAttributeValues={}), - "ExpressionAttributeValues must not be empty") - _refused( - _raw(grammar_table, **cond, ExpressionAttributeNames={}, ExpressionAttributeValues={}), - "ExpressionAttributeNames must not be empty", - ) - _refused(_raw(grammar_table, ExpressionAttributeValues={}), - "ExpressionAttributeValues must not be empty") - resp = _raw(grammar_table, TopK=0, **cond, ExpressionAttributeValues={}) - assert "TopK" in _message(resp), resp.text - - def test_keys_and_names(self, grammar_table): - us = {":us": {"S": "US"}} - cases = [ - ({"#c": ""}, {}, "#c = :us", - "ExpressionAttributeNames contains invalid value: Empty attribute name for key #c"), - ({"#a-b": "x"}, {**us, ":b-k": {"S": "y"}}, "Country = :us", - 'ExpressionAttributeNames contains invalid key: Syntax error; key: "#a-b"'), - ({"": "x"}, us, "Country = :us", - "ExpressionAttributeNames contains invalid key: The expression attribute map " - "contains an empty key;"), - ({"#" + "k" * 300: "x"}, us, "Country = :us", - "ExpressionAttributeNames contains invalid key: The expression attribute map " - "contains a key that is too long; size of key: 301"), - ({"#c": "C" * 65536}, us, "#c = :us", - "Attribute name is too large, must be less than 65536 bytes for key #c"), - (None, {**us, ":": {"S": "y"}}, "Country = :us", - 'ExpressionAttributeValues contains invalid key: Syntax error; key: ":"'), - ] - for names, values, cond, message in cases: - fields = {"SearchConditionExpression": cond, "ExpressionAttributeValues": values} - if names is not None: - fields["ExpressionAttributeNames"] = names - _refused(_raw(grammar_table, **fields), message) - - def test_maps_need_their_expression(self, grammar_table): - names, us = {"#p": "Price"}, {":us": {"S": "US"}} - only = "can only be specified when using expressions" - _refused(_raw(grammar_table, ExpressionAttributeNames=names), - "ExpressionAttributeNames " + only) - _refused(_raw(grammar_table, ExpressionAttributeNames=names, ExpressionAttributeValues=us), - "ExpressionAttributeNames " + only) - _refused(_raw(grammar_table, ExpressionAttributeValues=us), - "ExpressionAttributeValues " + only) - _refused( - _raw(grammar_table, ProjectionExpression="#p", ExpressionAttributeNames=names, - ExpressionAttributeValues=us), - "ExpressionAttributeValues " + only, - ) +class TestExpressionMapsUnderTheExtendedGrammar: + """Map checks whose request only the extended grammar parses.""" def test_unused_names(self, grammar_table): - us = {":us": {"S": "US"}} unused = "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}" - u = {"#u": "x"} - _refused(_raw(grammar_table, SearchConditionExpression="Country = :us", - ExpressionAttributeNames=u, - ExpressionAttributeValues={**us, ":w": {"S": "w"}}), unused) - _refused(_raw(grammar_table, SearchConditionExpression="Country = :us", - ProjectionExpression="Price", ExpressionAttributeNames=u, - ExpressionAttributeValues=us), unused) + us, u = {":us": {"S": "US"}}, {"#u": "x"} _refused(_raw(grammar_table, SearchConditionExpression="Price > :p", ExpressionAttributeNames=u, ExpressionAttributeValues={":p": {"N": "0"}}), unused) _refused(_raw(grammar_table, SearchConditionExpression="Country = = :us", ExpressionAttributeNames=u, ExpressionAttributeValues=us), P + 'Syntax error; token: "=", near: "= = :us"') - resp = _raw(grammar_table, SearchConditionExpression="Country = :us", - ProjectionExpression="#p", ExpressionAttributeNames={"#p": "Price"}, - ExpressionAttributeValues=us) - assert resp.status_code == 200, resp.text def test_the_projection_is_read_before_the_condition(self, grammar_table): _refused( @@ -548,16 +419,21 @@ def test_the_projection_is_read_before_the_condition(self, grammar_table): class TestBackendWithoutVectors: def test_the_backend_refuses_before_the_grammar_runs(self): - """On a backend without vector search the refusal is the backend's.""" - if not _ENDPOINT_VAR: + """On a backend without vector search the refusal is the backend's. + + The condition is a syntax error under both grammars, so a grammar that + ran before the backend check would answer with its own message. + """ + if not ENDPOINT_VAR: pytest.skip("requires EXTENDDB_TEST_ENDPOINT") - previous = _previous_setting() - managed = _set_setting("all") - try: - resp = _search(f"extenddb-test-{uuid.uuid4().hex[:12]}", H + "Price > :p5") - if resp.status_code == 400 and _message(resp) == NOT_SUPPORTED: - return + expected = expect_vectors() + name = table_name() + resp = _signed_post("CreateTable", {"TableName": name, **CREATE}) + if resp.status_code == 200: + delete_table(name) + assert expected is not False, ( + "EXTENDDB_EXPECT_VECTORS=0 but the backend accepted a vector index" + ) pytest.skip("target backend supports vector search") - finally: - if managed: - _set_setting(previous) + _refused(resp, INDEX_NOT_SUPPORTED) + _refused(_search(name, "Country = = :us"), SEARCH_NOT_SUPPORTED) From cc2850af7e088d1fdb915bf5a6507fee7f7c2f4b Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 17:44:11 +0000 Subject: [PATCH 023/101] ci: build, lint and test the search-inequality-filters feature No workflow built the search-inequality-filters feature. Its unit tests are compiled only with it, and the inequality wire module skipped on every CI server, so neither ran in CI and clippy never saw the feature's code. search-inequality-filters.yml runs clippy 1.97.0 on the workspace with the feature and on the SQLite-only binary with it, an MSRV 1.88 build, the unit tests of core, engine, server and the SQLite store with it, the PostgreSQL storage tests with it against pgvector, and the vector wire tests through devtools/run-tests against SQLite and PostgreSQL servers built with it, with the setting at all and EXTENDDB_EXPECT_VECTORS=1. The CLI catalog migration file, which builds its own catalogs, is left out of that run. The PostgreSQL and SQLite pytest steps of integration.yml set EXTENDDB_EXPECT_VECTORS=1, so the SearchVectors modules fail there rather than skip when vector indexes are refused. Checked with actionlint and shellcheck and the repository's pinned-action check; the commands of each job ran locally. --- .github/workflows/integration.yml | 6 + .../workflows/search-inequality-filters.yml | 191 ++++++++++++++++++ 2 files changed, 197 insertions(+) create mode 100644 .github/workflows/search-inequality-filters.yml diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 47567ef56..16bd29758 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -243,6 +243,9 @@ jobs: EXTENDDB_ADMIN_PASSWORD: ${{ steps.init.outputs.admin_password }} EXTENDDB_TEST_PG_ADMIN_CONNECTION_STRING: postgresql://postgres:devpass@127.0.0.1:5432 EXTENDDB_TEST_BACKUP_STORE: filesystem + # pgvector is present, so the SearchVectors suites fail rather than + # skip when the backend refuses vector indexes. + EXTENDDB_EXPECT_VECTORS: "1" run: devtools/run-tests --extenddb --pytest --comprehensive --terraform --parallel # moto for the job suite's store-outage cell, the one cell that @@ -422,6 +425,9 @@ jobs: # A file-backed SQLite server without [backup.store] writes to the # defaulted root beside the database file. EXTENDDB_TEST_BACKUP_STORE: filesystem + # SQLite serves vector search, so the SearchVectors suites fail + # rather than skip when the backend refuses vector indexes. + EXTENDDB_EXPECT_VECTORS: "1" run: devtools/run-tests --extenddb --pytest --comprehensive --terraform --parallel - name: Run the backup store and job suites diff --git a/.github/workflows/search-inequality-filters.yml b/.github/workflows/search-inequality-filters.yml new file mode 100644 index 000000000..bd2132f06 --- /dev/null +++ b/.github/workflows/search-inequality-filters.yml @@ -0,0 +1,191 @@ +name: Search inequality filters +on: + pull_request: + merge_group: + push: + branches: [main] + +permissions: + contents: read + +# Same grouping as the other workflows: a new push to a pull request +# supersedes its in-flight run, and every other run has a group of its own. +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +# The search-inequality-filters Cargo feature is off by default, so no other +# workflow compiles its code or its tests. These jobs build it, lint it, run +# its unit tests, and run the SearchVectors wire tests against a server built +# with it and the search_inequality_filters setting at `all`. +env: + FEATURES: >- + extenddb-core/search-inequality-filters,extenddb-engine/search-inequality-filters,extenddb-server/search-inequality-filters,extenddb-storage-sqlite/search-inequality-filters,extenddb-storage-postgres/search-inequality-filters + +jobs: + lint: + runs-on: extenddb_ubuntu-2404_4-core + timeout-minutes: 30 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: 1.97.0 + components: clippy + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo clippy --workspace --all-targets --features "$FEATURES" -- -D warnings + # The SQLite-only binary, whose backend selection differs from the + # workspace build's PostgreSQL default. + - run: cargo clippy -p extenddb --all-targets --no-default-features --features sqlite,search-inequality-filters -- -D warnings + + msrv: + runs-on: extenddb_ubuntu-2404_4-core + timeout-minutes: 30 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: "1.91.1" + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + save-if: ${{ github.ref == 'refs/heads/main' }} + - run: cargo build --locked --workspace --features "$FEATURES" + + unit: + runs-on: extenddb_ubuntu-2404_4-core + timeout-minutes: 40 + services: + postgres: + image: pgvector/pgvector:pg16 + env: + POSTGRES_PASSWORD: devpass + options: >- + --health-cmd "pg_isready -U postgres" + --health-interval 5s + --health-timeout 5s + --health-retries 5 + ports: + - 127.0.0.1:5432:5432 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Unit tests of the crates the feature changes + run: >- + cargo test --locked --no-fail-fast + -p extenddb-core -p extenddb-engine -p extenddb-server -p extenddb-storage-sqlite + --features "extenddb-core/search-inequality-filters,extenddb-engine/search-inequality-filters,extenddb-server/search-inequality-filters,extenddb-storage-sqlite/search-inequality-filters" + # Same environment as the PostgreSQL storage-level job in + # integration.yml: the tests create and drop their own databases, and + # EXTENDDB_TEST_PG_REQUIRED turns a missing connection into a failure. + - name: PostgreSQL storage tests + env: + EXTENDDB_TEST_PG_CONNECTION_STRING: postgresql://postgres:devpass@127.0.0.1:5432 + EXTENDDB_TEST_PG_REQUIRED: "1" + run: cargo test --locked --no-fail-fast --release -p extenddb-storage-postgres --features search-inequality-filters --tests + + wire: + runs-on: extenddb_ubuntu-2404_4-core + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + backend: [sqlite, postgres] + services: + postgres: + image: pgvector/pgvector:pg16 + env: + POSTGRES_PASSWORD: devpass + options: >- + --health-cmd "pg_isready -U postgres" + --health-interval 5s + --health-timeout 5s + --health-retries 5 + ports: + - 127.0.0.1:5432:5432 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + cache-on-failure: true + save-if: ${{ github.ref == 'refs/heads/main' }} + + - name: Build release + run: cargo build --locked --release -p extenddb --no-default-features --features ${{ matrix.backend }},search-inequality-filters + + - name: Initialize ExtendDB + id: init + run: | + if [ "${{ matrix.backend }}" = sqlite ]; then + output=$(./target/release/extenddb init --backend sqlite --config extenddb.toml 2>&1) + else + output=$(./target/release/extenddb init --config extenddb.toml \ + --pg-host 127.0.0.1 --pg-port 5432 --pg-user postgres --pg-pass devpass 2>&1) + fi + echo "$output" + password=$(echo "$output" | grep -oP 'Password: \K\S+') + echo "admin_password=$password" >> "$GITHUB_OUTPUT" + + - name: Start ExtendDB + run: | + # --write-pid-file so devtools/run-tests can restart the server with + # 'extenddb stop' when it needs to apply a config change. + ./target/release/extenddb serve --config extenddb.toml --foreground --write-pid-file & + for _ in $(seq 1 30); do + if curl -sfk https://127.0.0.1:18443/health > /dev/null; then + echo "Server ready" + exit 0 + fi + sleep 1 + done + echo "Server failed to start" + exit 1 + + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.12" + + - name: Install Python dependencies + run: pip install -r requirements.txt + + # Every wire test with "vector" in its file or test name, in parallel by + # file, except the CLI catalog migration file, which builds catalogs of + # its own and does not depend on the feature. devtools/run-tests writes + # the setting before the suite starts; the modules read it and fail when + # the server serves the other grammar. + - name: Run the vector wire tests + env: + EXTENDDB_TEST_ENDPOINT: https://127.0.0.1:18443 + EXTENDDB_ADMIN_USER: admin + EXTENDDB_ADMIN_PASSWORD: ${{ steps.init.outputs.admin_password }} + EXTENDDB_TEST_BACKUP_STORE: ${{ matrix.backend == 'sqlite' && 'filesystem' || 'none' }} + EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS: all + EXTENDDB_EXPECT_VECTORS: "1" + run: devtools/run-tests --extenddb --pytest --parallel --filter "vector and not test_cli" + + - name: Dump server syslog on failure + if: failure() + run: sudo journalctl -t extenddb --no-pager -n 500 || true + + search-inequality-filters: + runs-on: extenddb_ubuntu-2404_4-core + timeout-minutes: 5 + needs: [lint, msrv, unit, wire] + if: always() + steps: + - run: | + if [ "${{ needs.lint.result }}" != "success" ] \ + || [ "${{ needs.msrv.result }}" != "success" ] \ + || [ "${{ needs.unit.result }}" != "success" ] \ + || [ "${{ needs.wire.result }}" != "success" ]; then + exit 1 + fi From 81967c4ea418a6747d3539eaefbc68affc50189f Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 20:01:46 +0000 Subject: [PATCH 024/101] fix(storage-postgres): cancel an abandoned search in its own transaction A dropped filtered vector search closed its connection and sent pg_cancel_backend for the backend process id it read at BEGIN. Behind a transaction-pooling proxy that returns a backend to its pool when the client disconnects, the backend can serve another client's transaction by the time the cancel arrives. Measured with a pgcat 1.2.0 proxy in transaction mode in front of PostgreSQL 16: in three of three runs the next client received the same backend and its statement failed with "canceling statement due to user request", and in three further runs the cancel query landed on that backend and cancelled itself. Directly and through pgbouncer 1.26.1 in transaction mode the backend was not reused. The search now records the backend process id together with the start of its transaction (now(), which pg_stat_activity reports as xact_start), and the cancel signals the backend only while pg_stat_activity shows it in that transaction. A process id that was reused, or a backend that serves another transaction, matches no row and receives nothing. Two new tests run two transactions on one backend, as a pooling proxy does: a cancel for the first transaction leaves the second one's pg_sleep running, and a cancel for the second stops it. The existing drop test still sees the dropped search's statement stop. With the proxy, the guarded cancel spared the next client in two of two runs; directly and through pgbouncer it still cancelled the dropped search's running statement in four of four runs. --- .../src/vector_search_scan.rs | 154 ++++++++++++++++-- 1 file changed, 138 insertions(+), 16 deletions(-) diff --git a/crates/storage-postgres/src/vector_search_scan.rs b/crates/storage-postgres/src/vector_search_scan.rs index fe961b696..56611ba21 100644 --- a/crates/storage-postgres/src/vector_search_scan.rs +++ b/crates/storage-postgres/src/vector_search_scan.rs @@ -15,6 +15,12 @@ //! the backend is also sent `pg_cancel_backend`, so a request the caller has //! abandoned stops its statement in the server instead of running it to the //! end on a connection nobody reads. +//! +//! The cancel names the backend by process id and by the start time of the +//! search transaction, and PostgreSQL signals it only while that backend is +//! still inside that transaction. A transaction-pooling proxy can hand the +//! backend to another client as soon as this one disconnects, and a process +//! id alone would then cancel that client's statement. use sqlx::pool::PoolConnection; use sqlx::{PgConnection, PgPool, Postgres}; @@ -22,7 +28,9 @@ use sqlx::{PgConnection, PgPool, Postgres}; /// One pooled connection inside the search transaction. pub(crate) struct ScanConnection { conn: Option>, - backend_pid: Option, + /// The backend's process id and the transaction's start, in + /// microseconds since the epoch. + backend: Option<(i32, i64)>, pool: PgPool, } @@ -39,16 +47,18 @@ impl ScanConnection { // handled like any other drop. let mut scan = Self { conn: Some(conn), - backend_pid: None, + backend: None, pool: pool.clone(), }; sqlx::query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY") .execute(scan.connection()) .await?; - let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + // `now()` is the transaction's start, the value `pg_stat_activity` + // reports as `xact_start` while the transaction runs. + let backend: (i32, i64) = sqlx::query_as(XACT_OF_THIS_BACKEND) .fetch_one(scan.connection()) .await?; - scan.backend_pid = Some(pid); + scan.backend = Some(backend); Ok(scan) } @@ -79,32 +89,49 @@ impl Drop for ScanConnection { let Some(conn) = self.conn.take() else { return; }; - // Detached first, so this backend can serve no other request: the - // cancel below then reaches only the statement this search started. + // Detached first, so the pool can lend this connection to no other + // request. drop(conn.detach()); - let (Some(pid), Ok(runtime)) = (self.backend_pid, tokio::runtime::Handle::try_current()) + let (Some(backend), Ok(runtime)) = (self.backend, tokio::runtime::Handle::try_current()) else { return; }; let pool = self.pool.clone(); - runtime.spawn(async move { - // The backend may already have exited on the closed socket, and - // then PostgreSQL answers false. Neither answer changes anything. - let _ = sqlx::query("SELECT pg_cancel_backend($1)") - .bind(pid) - .execute(&pool) - .await; - }); + runtime.spawn(cancel_if_in_transaction(pool, backend)); } } +/// The backend's process id and its transaction's start. +const XACT_OF_THIS_BACKEND: &str = + "SELECT pg_backend_pid(), (extract(epoch FROM now()) * 1000000)::bigint"; + +/// Cancel the statement of backend `pid` if that backend still runs the +/// transaction that started at `xact_start`. Returns whether a cancel was +/// sent. +/// +/// No row matches once the backend has exited, has ended the transaction, or +/// serves another client's transaction; then nothing is signalled. +async fn cancel_if_in_transaction(pool: PgPool, (pid, xact_start): (i32, i64)) -> bool { + sqlx::query_scalar::<_, bool>( + "SELECT pg_cancel_backend(pid) FROM pg_stat_activity \ + WHERE pid = $1 AND (extract(epoch FROM xact_start) * 1000000)::bigint = $2", + ) + .bind(pid) + .bind(xact_start) + .fetch_optional(&pool) + .await + .ok() + .flatten() + .unwrap_or(false) +} + #[cfg(test)] mod tests { use std::time::Duration; use sqlx::postgres::PgPoolOptions; - use super::ScanConnection; + use super::{ScanConnection, XACT_OF_THIS_BACKEND, cancel_if_in_transaction}; /// A pool on the server's maintenance database, or `None` to skip. async fn pool(max: u32) -> Option { @@ -205,4 +232,99 @@ mod tests { assert_eq!(again, pid, "a committed scan keeps its connection pooled"); assert_eq!(isolation, "read committed"); } + + /// One connection that ends a transaction and starts another, as a + /// transaction-pooling proxy hands a backend to its next client. Returns + /// the first transaction's stamp, the second's, the connection running + /// `pg_sleep(seconds)` in the second, and the pool to cancel through. + async fn reused_backend( + seconds: u32, + ) -> Option<( + (i32, i64), + (i32, i64), + tokio::task::JoinHandle, + sqlx::PgPool, + )> { + let (Some(pool), Some(observer)) = (pool(1).await, pool(1).await) else { + return None; + }; + let mut conn = pool.acquire().await.expect("acquire"); + sqlx::query("BEGIN") + .execute(&mut *conn) + .await + .expect("begin"); + let earlier: (i32, i64) = sqlx::query_as(XACT_OF_THIS_BACKEND) + .fetch_one(&mut *conn) + .await + .expect("the first stamp"); + sqlx::query("COMMIT") + .execute(&mut *conn) + .await + .expect("commit"); + tokio::time::sleep(Duration::from_millis(5)).await; + sqlx::query("BEGIN") + .execute(&mut *conn) + .await + .expect("begin again"); + let later: (i32, i64) = sqlx::query_as(XACT_OF_THIS_BACKEND) + .fetch_one(&mut *conn) + .await + .expect("the second stamp"); + assert_eq!(earlier.0, later.0, "one backend serves both transactions"); + assert_ne!(earlier.1, later.1, "the transactions start apart"); + let query = format!( + "SELECT pg_sleep({seconds}), '{}'", + uuid::Uuid::new_v4().simple() + ); + let statement = query.clone(); + let sleeper = + tokio::spawn(async move { sqlx::query(&statement).execute(&mut *conn).await.is_ok() }); + let start = std::time::Instant::now(); + while !still_running(&observer, &query, Duration::ZERO).await { + assert!( + start.elapsed() < Duration::from_secs(5), + "the statement never started" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + Some((earlier, later, sleeper, observer)) + } + + #[tokio::test] + async fn a_cancel_spares_a_backend_that_serves_another_transaction() { + let Some((earlier, _, sleeper, observer)) = reused_backend(2).await else { + return; + }; + assert!( + !cancel_if_in_transaction(observer, earlier).await, + "a cancel was sent for a transaction the backend no longer runs" + ); + assert!( + sleeper.await.expect("the statement task"), + "the other transaction's statement was cancelled" + ); + } + + #[tokio::test] + async fn a_cancel_stops_the_statement_of_its_own_transaction() { + // Long enough that the cancel reaches the statement while it runs on + // a loaded host; a cancel that arrives between statements is dropped. + let Some((_, later, sleeper, observer)) = reused_backend(30).await else { + return; + }; + let start = std::time::Instant::now(); + assert!( + cancel_if_in_transaction(observer, later).await, + "no cancel was sent for the running transaction" + ); + assert!( + !sleeper.await.expect("the statement task"), + "the statement ran to the end" + ); + assert!( + start.elapsed() < Duration::from_secs(20), + "the statement stopped only after {:?}", + start.elapsed() + ); + } } From 65f496a2274089f1cda536b5e2f2c1abbdf71572 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 22:21:47 +0000 Subject: [PATCH 025/101] fix(engine): send one read of the search filter setting at a time A SearchVectors request with a condition reads the search_inequality_filters setting from the catalog, kept for one second, with one request reading at a time. A read that took longer than two seconds was dropped by the engine, and the request answered ServiceUnavailableException. On PostgreSQL the dropped read kept its statement and its catalog connection waiting in the server. With the settings table locked for 80 seconds, a new read was sent about every three seconds, each holding another catalog connection, until all 20 were held at 45 seconds. From then searches answered InternalServerError as well as ServiceUnavailableException, and DescribeTable, which does not read the setting, answered InternalServerError after 30 seconds. The read now runs in its own task. A request that stops waiting for it leaves the task running, and the next request waits on the same read instead of sending another, so a catalog that does not answer holds at most one connection for the setting. A read sent before a change through the management API is left to end and a new read is sent. A failed or slow read still answers ServiceUnavailableException. Unit tests pin one read sent over 20 refresh intervals while it never ends, the late answer used by the next request, and a change applied while an earlier read has not ended. On a release PostgreSQL server with the settings table locked for 80 seconds, 8 searching clients and one DescribeTable client, three runs: at most one connection waited on the lock apart from the server's own 30 second setting pollers, every search answered ServiceUnavailableException within 1.1 s, and DescribeTable answered 200 on every call (346 to 370 calls, at most 125 ms). Before the change, two runs, 20 connections waited from 45 s and DescribeTable answered InternalServerError after 30 s. --- crates/engine/src/search_vectors_settings.rs | 98 ++++++++++++++----- .../src/search_vectors_settings_tests.rs | 68 ++++++++++++- 2 files changed, 140 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/search_vectors_settings.rs b/crates/engine/src/search_vectors_settings.rs index 1d3b4dadd..aad631c9b 100644 --- a/crates/engine/src/search_vectors_settings.rs +++ b/crates/engine/src/search_vectors_settings.rs @@ -14,17 +14,24 @@ //! [`search_filter_settings_changed`]. A read that fails or outlasts //! [`READ_TIMEOUT`] answers `ServiceUnavailableException`, as other transient //! storage faults do; it never changes which grammar an account gets. +//! +//! A server sends at most one read of the setting at a time. A read that +//! outlasts [`READ_TIMEOUT`] keeps running in its own task, and the next +//! request waits on that read rather than sending another, so a catalog +//! that does not answer holds at most one of its connections for the +//! setting while requests that do not read it keep the rest. use std::sync::{Arc, Mutex, PoisonError, Weak}; use std::time::Duration; +use tokio::task::JoinHandle; use tokio::time::Instant; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::search_filter::EnabledAccounts; use extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS; use extenddb_storage::StorageEngine; -use extenddb_storage::management_store::SettingsStore; +use extenddb_storage::management_store::{OpResult, SettingsStore}; /// How long a read of the setting is used before the next request reads it /// again. @@ -57,7 +64,7 @@ pub fn install_search_filter_settings( pub fn search_filter_settings_changed() { let servers = SERVERS.lock().unwrap_or_else(PoisonError::into_inner); for (_, settings) in servers.iter() { - *settings.kept.lock().unwrap_or_else(PoisonError::into_inner) = None; + settings.changed(); } } @@ -95,13 +102,24 @@ struct Kept { accounts: Option, } +/// A read of the store running in its own task. +struct InFlight { + /// The value of [`Settings::changes`] when the read was sent. + changes: u64, + task: JoinHandle>>, +} + struct Settings { store: Arc, kept: Mutex>, + /// How many times the management API changed the setting, so a read + /// sent before a change is not used after it. + changes: Mutex, /// Held by the one request that reads the store when the kept read is /// stale, so concurrent requests wait for that read instead of sending - /// their own. - reading: tokio::sync::Mutex<()>, + /// their own. It holds a read that outlasted [`READ_TIMEOUT`] until the + /// read ends, so the next request waits on it instead of sending another. + reading: tokio::sync::Mutex>, } impl Settings { @@ -109,7 +127,28 @@ impl Settings { Self { store, kept: Mutex::new(None), - reading: tokio::sync::Mutex::new(()), + changes: Mutex::new(0), + reading: tokio::sync::Mutex::new(None), + } + } + + fn changed(&self) { + let mut kept = self.kept.lock().unwrap_or_else(PoisonError::into_inner); + *self.changes.lock().unwrap_or_else(PoisonError::into_inner) += 1; + *kept = None; + } + + fn changes(&self) -> u64 { + *self.changes.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Send a read of the store in its own task, so it runs to its end when + /// the request that waits on it stops waiting. + fn send_read(&self) -> InFlight { + let store = Arc::clone(&self.store); + InFlight { + changes: self.changes(), + task: tokio::spawn(async move { store.get_setting(SEARCH_INEQUALITY_FILTERS).await }), } } @@ -124,30 +163,39 @@ impl Settings { if let Some(answer) = self.fresh() { return answer; } - let _reading = self.reading.lock().await; + let mut reading = self.reading.lock().await; if let Some(answer) = self.fresh() { return answer; } - let read = tokio::time::timeout( - READ_TIMEOUT, - self.store.get_setting(SEARCH_INEQUALITY_FILTERS), - ) - .await; - let previous = self - .kept - .lock() - .unwrap_or_else(PoisonError::into_inner) - .take() - .and_then(|k| k.raw); + // A read sent before a change through the management API may answer + // the old value: it is left to end on its own and a new one is sent. + if reading + .as_ref() + .is_some_and(|r| r.changes != self.changes()) + { + *reading = None; + } + let in_flight = reading.get_or_insert_with(|| self.send_read()); + let sent = in_flight.changes; + let read = tokio::time::timeout(READ_TIMEOUT, &mut in_flight.task).await; + if read.is_ok() { + *reading = None; + } + let mut kept = self.kept.lock().unwrap_or_else(PoisonError::into_inner); + let previous = kept.take().and_then(|k| k.raw); let (raw, accounts) = match read { - Ok(Ok(raw)) => { + Ok(Ok(Ok(raw))) => { let accounts = Self::parse(raw.as_deref(), previous.as_deref()); (raw, Some(accounts)) } - Ok(Err(e)) => { + Ok(Ok(Err(e))) => { tracing::warn!("{SEARCH_INEQUALITY_FILTERS} could not be read: {e:?}"); (previous, None) } + Ok(Err(e)) => { + tracing::warn!("{SEARCH_INEQUALITY_FILTERS} could not be read: {e}"); + (previous, None) + } Err(_) => { tracing::warn!( "{SEARCH_INEQUALITY_FILTERS} could not be read within {READ_TIMEOUT:?}" @@ -156,11 +204,13 @@ impl Settings { } }; let answer = accounts.clone().ok_or_else(unavailable); - *self.kept.lock().unwrap_or_else(PoisonError::into_inner) = Some(Kept { - read_at: Instant::now(), - raw, - accounts, - }); + if sent == self.changes() { + *kept = Some(Kept { + read_at: Instant::now(), + raw, + accounts, + }); + } answer } diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index f6aaaeda8..8c77d3cf1 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -2,8 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 //! How a server reads the `search_inequality_filters` setting: per server, -//! kept for a short interval, bounded in time, and a fault answered as a -//! retryable error. +//! kept for a short interval, bounded in time, one read at a time, and a +//! fault answered as a retryable error. use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; @@ -14,6 +14,7 @@ use extenddb_storage::StorageEngine; use extenddb_storage::management_store::{OpError, OpResult, SettingsStore}; use extenddb_storage_sqlite::SqliteEngine; use futures::future::BoxFuture; +use tokio::sync::Notify; use super::{ READ_TIMEOUT, REFRESH, Settings, enabled_accounts, install_search_filter_settings, @@ -28,6 +29,8 @@ enum Answer { Slow(String), Fail, Hang, + /// The value, once the gate is opened. + Gated(Arc, String), } /// A settings store with one answer for every read, counting the reads. @@ -70,6 +73,10 @@ impl SettingsStore for Store { } Answer::Fail => Err(OpError::Internal("connection reset".to_owned())), Answer::Hang => std::future::pending().await, + Answer::Gated(gate, v) => { + gate.notified().await; + Ok(Some(v)) + } } }) } @@ -221,3 +228,60 @@ async fn a_change_through_the_management_api_applies_at_once() { EnabledAccounts::All ); } + +/// A read that does not end is sent once: later requests wait on it rather +/// than sending reads of their own, each of which would hold a catalog +/// connection while it waits. +#[tokio::test(start_paused = true)] +async fn a_read_that_does_not_end_is_sent_once() { + let store = Store::new(Answer::Hang); + let settings = Arc::new(Settings::new(store.clone())); + for _ in 0..20 { + let tasks: Vec<_> = (0..4) + .map(|_| { + let settings = Arc::clone(&settings); + tokio::spawn(async move { settings.enabled_accounts().await }) + }) + .collect(); + for task in tasks { + assert!(is_unavailable(&task.await.unwrap())); + } + tokio::time::advance(REFRESH).await; + } + assert_eq!(store.reads(), 1, "reads sent while the first had not ended"); +} + +/// When the read that outlasted the timeout ends, the next request uses its +/// answer. +#[tokio::test(start_paused = true)] +async fn a_read_that_ends_late_answers_the_next_request() { + let gate = Arc::new(Notify::new()); + let store = Store::new(Answer::Gated(Arc::clone(&gate), "all".to_owned())); + let settings = Settings::new(store.clone()); + assert!(is_unavailable(&settings.enabled_accounts().await)); + tokio::time::advance(REFRESH).await; + gate.notify_one(); + let started = tokio::time::Instant::now(); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::All + ); + assert!(started.elapsed() < READ_TIMEOUT); + assert_eq!(store.reads(), 1); +} + +/// A read sent before a change through the management API is not waited on +/// after it: the next request sends a read of the changed value. +#[tokio::test(start_paused = true)] +async fn a_change_applies_while_an_earlier_read_has_not_ended() { + let store = Store::new(Answer::Hang); + let settings = Settings::new(store.clone()); + assert!(is_unavailable(&settings.enabled_accounts().await)); + store.set(Answer::Value(Some("all".to_owned()))); + settings.changed(); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::All + ); + assert_eq!(store.reads(), 2); +} From aac73cbb5008a7eb8c5244b33429df2806887828 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 22:21:54 +0000 Subject: [PATCH 026/101] fix(storage-postgres): bound a settings read on the server The PostgreSQL settings store read a setting with one statement that had no server-side bound. Behind a lock on the settings table the statement waited until the lock was released, and a caller that stopped waiting left it waiting in the server with its catalog connection. A settings read now runs in a read transaction that sets lock_timeout to 1 s and statement_timeout to 1.5 s for that transaction only, so a read behind a held lock fails in the server and gives its connection back, also when the caller has dropped it. A test locks the settings table from a second session, checks that a read fails within 3 s, that reads dropped after 100 ms leave no statement waiting on the lock 3 s later, and that a read after the unlock answers the stored value. On a release server with the settings table locked for 80 seconds, the server's 30 second pollers of log_level, sqlx_log_level and throttling_enabled, which read through the same store, held at most five waiting connections for under a second, where before the change their reads waited for the whole lock. --- crates/storage-postgres/src/catalog_store.rs | 25 ++++- .../tests/settings_read_bound.rs | 91 +++++++++++++++++++ 2 files changed, 111 insertions(+), 5 deletions(-) create mode 100644 crates/storage-postgres/tests/settings_read_bound.rs diff --git a/crates/storage-postgres/src/catalog_store.rs b/crates/storage-postgres/src/catalog_store.rs index fc5f3cd93..0c51903b3 100755 --- a/crates/storage-postgres/src/catalog_store.rs +++ b/crates/storage-postgres/src/catalog_store.rs @@ -76,20 +76,35 @@ impl PostgresCatalogStore { // ── SettingsStore ────────────────────────────────────────────────────── +/// The server-side bound on a settings read: how long it waits for a lock +/// on the `settings` table, and how long it runs in all. +const SETTING_READ_BOUND: &str = "SELECT set_config('lock_timeout', '1s', true), \ + set_config('statement_timeout', '1500ms', true)"; + impl extenddb_storage::management_store::SettingsStore for PostgresCatalogStore { fn get_setting(&self, key: &str) -> futures::future::BoxFuture<'_, OpResult>> { let key = key.to_string(); let pool = self.pool.clone(); Box::pin(async move { + let failed = |e: sqlx::Error| { + tracing::error!("get_setting: {e}"); + OpError::Internal("Database error".to_owned()) + }; + // The bound is set on the server, so a read that waits on a lock + // ends there and gives its connection back even when the caller + // has stopped waiting for it. + let mut tx = pool.begin().await.map_err(failed)?; + sqlx::query(SETTING_READ_BOUND) + .execute(&mut *tx) + .await + .map_err(failed)?; let row: Option<(String,)> = sqlx::query_as("SELECT value FROM settings WHERE key = $1") .bind(&key) - .fetch_optional(&pool) + .fetch_optional(&mut *tx) .await - .map_err(|e| { - tracing::error!("get_setting: {e}"); - OpError::Internal("Database error".to_owned()) - })?; + .map_err(failed)?; + tx.commit().await.map_err(failed)?; Ok(row.map(|(v,)| v)) }) } diff --git a/crates/storage-postgres/tests/settings_read_bound.rs b/crates/storage-postgres/tests/settings_read_bound.rs new file mode 100644 index 000000000..da9d9d91a --- /dev/null +++ b/crates/storage-postgres/tests/settings_read_bound.rs @@ -0,0 +1,91 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! A settings read on a catalog whose `settings` table another session +//! holds locked: the read fails within its server-side bound and leaves no +//! statement waiting on the lock, including when the caller stops waiting +//! for it first. See `migrations_support` for the database these tests need. + +mod migrations_support; + +use std::time::{Duration, Instant}; + +use extenddb_storage::management_store::SettingsStore; +use extenddb_storage::migrations::MigrationId; +use extenddb_storage_postgres::PostgresCatalogStore; +use migrations_support::{Scratch, base_conn, pool, skip}; +use sqlx::PgPool; + +/// The test's own deadline for one read, so an unbounded read fails here. +const DEADLINE: Duration = Duration::from_secs(10); + +/// Statements of the catalog database waiting on a lock. +async fn waiting(admin: &PgPool, catalog: &str) -> i64 { + sqlx::query_scalar( + "SELECT COUNT(*) FROM pg_stat_activity WHERE datname = $1 AND wait_event_type = 'Lock'", + ) + .bind(catalog) + .fetch_one(admin) + .await + .expect("read pg_stat_activity") +} + +#[tokio::test] +async fn a_read_behind_a_held_lock_fails_within_its_bound_and_leaves_nothing_waiting() { + let Some(base) = base_conn() else { + return skip("settings read bound"); + }; + let s = Scratch::new(&base, "pgm_settings_bound").await; + s.migrate_through(MigrationId::LATEST).await; + let catalog = pool(&s.catalog_url(), 4).await; + let admin = pool(&format!("{base}/postgres"), 1).await; + let store = PostgresCatalogStore::new(catalog.clone()); + store + .set_setting("search_inequality_filters", "all") + .await + .expect("write the setting"); + + let locker = pool(&s.catalog_url(), 1).await; + let mut lock = locker.begin().await.expect("begin the locking transaction"); + sqlx::query("LOCK TABLE settings IN ACCESS EXCLUSIVE MODE") + .execute(&mut *lock) + .await + .expect("lock the settings table"); + + // A read the caller waits for ends with an error within the bound. + let started = Instant::now(); + let read = tokio::time::timeout(DEADLINE, store.get_setting("search_inequality_filters")) + .await + .expect("a read behind the lock ends before the test's deadline"); + assert!(read.is_err(), "a read behind the lock fails: {read:?}"); + assert!( + started.elapsed() < Duration::from_secs(3), + "the read failed after {:?}", + started.elapsed() + ); + + // Reads the caller stops waiting for still end in the server. + for _ in 0..4 { + let _ = tokio::time::timeout( + Duration::from_millis(100), + store.get_setting("search_inequality_filters"), + ) + .await; + } + assert!(waiting(&admin, &s.catalog_name).await > 0); + tokio::time::sleep(Duration::from_secs(3)).await; + assert_eq!( + waiting(&admin, &s.catalog_name).await, + 0, + "a statement still waits on the lock 3 s after its read was dropped" + ); + + lock.rollback().await.expect("release the lock"); + let read = tokio::time::timeout(DEADLINE, store.get_setting("search_inequality_filters")) + .await + .expect("a read after the lock ends"); + assert_eq!(read.expect("the read succeeds"), Some("all".to_owned())); + + locker.close().await; + catalog.close().await; + admin.close().await; +} From e0da15bd5548260220cd4ca05934431e4b94b16a Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 22:21:58 +0000 Subject: [PATCH 027/101] test(engine): read the search filter setting through poisoned locks The setting is looked up in a process-wide server list and kept per server behind standard mutexes, and every lock recovers from poisoning. No test covered that: answering Off when the server list is poisoned passed every test. A test poisons the server list, the server's kept read and its change count with a thread that panics while holding each, then checks that the setting is read once, the kept read is used, and a change through the management API applies. --- .../src/search_vectors_settings_tests.rs | 53 +++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index 8c77d3cf1..734f4afa1 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -6,7 +6,7 @@ //! fault answered as a retryable error. use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, PoisonError}; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::search_filter::EnabledAccounts; @@ -17,8 +17,8 @@ use futures::future::BoxFuture; use tokio::sync::Notify; use super::{ - READ_TIMEOUT, REFRESH, Settings, enabled_accounts, install_search_filter_settings, - search_filter_settings_changed, + READ_TIMEOUT, REFRESH, SERVERS, Settings, enabled_accounts, install_search_filter_settings, + same, search_filter_settings_changed, }; /// How a read of the store answers. @@ -285,3 +285,50 @@ async fn a_change_applies_while_an_earlier_read_has_not_ended() { ); assert_eq!(store.reads(), 2); } + +/// Poison `lock` with a thread that panics while holding it. +fn poison(lock: &Mutex) { + std::thread::scope(|s| { + let held = s.spawn(|| { + let _held = lock.lock(); + panic!("poison the lock"); + }); + assert!(held.join().is_err()); + }); + assert!(lock.is_poisoned()); +} + +/// A thread that panicked while holding the server list or a server's kept +/// read leaves the setting readable. +#[tokio::test] +async fn a_poisoned_lock_leaves_the_setting_readable() { + let storage = storage().await; + let store = Store::value("all"); + install_search_filter_settings(&storage, store.clone()); + let settings = SERVERS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .find(|(engine, _)| same(engine, &storage)) + .map(|(_, settings)| Arc::clone(settings)) + .expect("the server is installed"); + poison(&SERVERS); + poison(&settings.kept); + poison(&settings.changes); + assert_eq!( + enabled_accounts(&storage).await.unwrap(), + EnabledAccounts::All + ); + assert_eq!( + enabled_accounts(&storage).await.unwrap(), + EnabledAccounts::All + ); + assert_eq!(store.reads(), 1, "the kept read is used"); + store.set(Answer::Value(Some("off".to_owned()))); + search_filter_settings_changed(); + assert_eq!( + enabled_accounts(&storage).await.unwrap(), + EnabledAccounts::Off + ); + assert_eq!(store.reads(), 2); +} From e4d2674756319c2b2652e6098cfdad1aadfaf22a Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 22:14:52 +0000 Subject: [PATCH 028/101] test(search): pin the exact BETWEEN bound check on the wire Under the extended grammar the service compares the two BETWEEN bounds exactly. A pair that is one binary64 value but out of order exactly, such as 9007199254740993 and 9007199254740992, gets the upper bound message, with each number shown in plain decimal. 1.0 and 1, and 2^53 and 2^53+1 in order, are accepted. ExtendDB answers the same, but no wire test sent such a pair, so a server that compared the bounds as binary64 passed every wire module. The inequality module now sends the six out-of-order pairs and the two in-order ones. Measured on the live service in eu-north-1 on 2026-11-23, two requests each. The module passes against the live service, and against SQLite and PostgreSQL servers with the setting at all; with the bound check at binary64 the new test fails. --- .../test_search_vectors_inequality_filters.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/tests/test_search_vectors_inequality_filters.py b/tests/test_search_vectors_inequality_filters.py index 3920ab3ca..c07093de2 100644 --- a/tests/test_search_vectors_inequality_filters.py +++ b/tests/test_search_vectors_inequality_filters.py @@ -355,6 +355,50 @@ def test_grammar_rules(self, grammar_table): P + 'Syntax error; token: "", near: "= "', ) + def test_between_bounds_compare_exactly(self, grammar_table): + """The bound check compares the two numbers exactly, and the message + shows each in plain decimal. Each out-of-order pair below is one + binary64 value. Measured on 2026-11-23, two requests each.""" + + def between(lo: str, hi: str) -> requests.Response: + return _raw( + grammar_table, + SearchConditionExpression=H + "Price BETWEEN :lo AND :hi", + ExpressionAttributeValues={ + ":us": {"S": "US"}, ":lo": {"N": lo}, ":hi": {"N": hi} + }, + ) + + e100 = "10000000000000001" + "0" * 84 + out_of_order = [ + ("9007199254740993", "9007199254740992", None, None), + ( + "99999999999999999999999999999999999999", + "99999999999999999999999999999999999998", + None, + None, + ), + ("1.0000000000000001E+100", "1E+100", e100, "1" + "0" * 100), + ("0.10000000000000001", "0.1", None, None), + ( + "1.0000000000000001E-10", + "1E-10", + "0.00000000010000000000000001", + "0.0000000001", + ), + ("-10000000000000000", "-10000000000000001", None, None), + ] + for lo, hi, shown_lo, shown_hi in out_of_order: + _refused( + between(lo, hi), + P + "The BETWEEN operator requires upper bound to be greater than or " + f"equal to lower bound; lower bound operand: AttributeValue: " + f"{{N:{shown_lo or lo}}}, upper bound operand: AttributeValue: " + f"{{N:{shown_hi or hi}}}", + ) + assert _ids(between("1.0", "1")) == set() + assert _ids(between("9007199254740992", "9007199254740993")) == set() + def test_schema_checks_in_written_order(self, grammar_table): _refused(_search(grammar_table, H + "Color = :a AND Category > :a"), _not_in_schema("Color")) _refused( From a866bee57e1422a9dbb43dcdbbd00ad42b4004fb Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 22:14:52 +0000 Subject: [PATCH 029/101] test(search): pin the empty map answer ahead of a missing table The service checks ExpressionAttributeValues and ExpressionAttributeNames before it looks up the table: an empty map sent to a missing table answers " must not be empty", and the same request with a valid map answers ResourceNotFoundException. The engine tests pinned this order, and no wire test did. The expression maps module now sends both empty maps and a valid map to a missing table. Measured on the live service in eu-north-1 on 2026-11-23, two requests each. With the table lookup moved ahead of the map checks the new test fails. --- tests/test_search_vectors_expression_maps.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/tests/test_search_vectors_expression_maps.py b/tests/test_search_vectors_expression_maps.py index 335032911..3b83f7a1d 100644 --- a/tests/test_search_vectors_expression_maps.py +++ b/tests/test_search_vectors_expression_maps.py @@ -9,7 +9,8 @@ Measured against the live service in eu-north-1, on an account with the extended grammar, each request twice with the same answer: on 2026-11-21, and -the 254, 255 and 256 byte keys on 2026-11-23. +the 254, 255 and 256 byte keys and the empty maps against a missing table on +2026-11-23. The module skips when the target backend does not support vector indexes, unless ``EXTENDDB_EXPECT_VECTORS=1``, which makes that a failure. @@ -119,6 +120,19 @@ def test_empty_maps_names_first(self, table): assert resp.status_code == 400, resp.text assert "TopK" in message(resp), resp.text + def test_an_empty_map_answers_before_a_missing_table(self, table): + """The map checks run before the table lookup. Measured on 2026-11-23.""" + missing = table_name() + cond = {"SearchConditionExpression": "Country = :us"} + refused(_raw(missing, **cond, ExpressionAttributeValues={}), + "ExpressionAttributeValues must not be empty") + refused(_raw(missing, **cond, ExpressionAttributeNames={}, ExpressionAttributeValues=US), + "ExpressionAttributeNames must not be empty") + resp = _raw(missing, **cond, ExpressionAttributeValues=US) + assert resp.status_code == 400, resp.text + assert resp.json()["__type"].endswith("ResourceNotFoundException"), resp.text + assert message(resp) == "Requested resource not found", resp.text + class TestKeysAndNames: def test_keys_and_names(self, table): From 44d2d89a23355deee58b77cefbb125b7a2a1b47a Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 22:14:52 +0000 Subject: [PATCH 030/101] test(search): send deeply nested search conditions on the wire Under the extended grammar the service refuses a search condition of 1500 or 4080 open parentheses, or 818 unclosed "NOT (", with the syntax error near the last operand, and 818 closed "NOT(" with the operator count message. It goes on answering. A server built before the parser stopped recursing aborted on 1500 open parentheses, and every account lost service. Unit tests pinned the parse; no wire test sent such a condition to a running server. The new module sends the four conditions to a vector table, asserts the answer under the extended grammar and a refusal under the equality-only grammar, and after each one sends a valid search and, against ExtendDB, reads /health. Measured on the live service in eu-north-1 on 2026-11-23, two requests each, on an existing and a missing table. A server built from before the change aborts and the test fails. --- tests/test_search_vectors_deep_conditions.py | 148 +++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 tests/test_search_vectors_deep_conditions.py diff --git a/tests/test_search_vectors_deep_conditions.py b/tests/test_search_vectors_deep_conditions.py new file mode 100644 index 000000000..5be644411 --- /dev/null +++ b/tests/test_search_vectors_deep_conditions.py @@ -0,0 +1,148 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""SearchVectors with deeply nested search conditions, up to the 4096-byte limit. + +Under the extended grammar the service answers each condition below with a +ValidationException, whatever its depth. A run of 4080 open parentheses gets +the same syntax error as a run of one. The server must go on answering: after +each request the test sends a valid search, and against ExtendDB it also +reads ``/health``. + +Measured against the live service in eu-north-1, on an account with the +extended grammar, each request twice with the same answer, on 2026-11-23 on +this table and on a missing table; the 1500 and 4080 open parentheses also on +2026-11-22. Under the equality-only grammar the test asserts only that each +condition is refused and that the server keeps answering. + +The module skips when the target backend does not support vector indexes, +unless ``EXTENDDB_EXPECT_VECTORS=1``, which makes that a failure. +""" + +from __future__ import annotations + +import pytest +import requests + +from search_vectors_wire import ( + ENDPOINT_VAR, + create_vector_table, + delete_table, + grammar_of, + refused, + signed_post, + table_name, +) + +P = "Invalid SearchConditionExpression: " +UNCLOSED = P + 'Syntax error; token: "", near: ":v"' +VALUES = {":v": {"S": "x"}} + +# (label, condition, the extended grammar's answer) +DEEP = [ + ("1500 open parentheses", "(" * 1500 + "a = :v", UNCLOSED), + ("4080 open parentheses", "(" * 4080 + "a = :v", UNCLOSED), + ("818 unclosed NOT (", "NOT (" * 818 + "a = :v", UNCLOSED), + ( + "818 closed NOT(", + "NOT(" * 818 + "a=:v" + ")" * 818, + P + "The expression contains too many operators; operator count: 819", + ), +] + + +@pytest.fixture(scope="module") +def table(): + """HASH Country (S) and inline filter Price (N), with one item.""" + name = table_name() + create_vector_table( + name, + { + "AttributeDefinitions": [ + {"AttributeName": "id", "AttributeType": "S"}, + {"AttributeName": "Country", "AttributeType": "S"}, + {"AttributeName": "Price", "AttributeType": "N"}, + ], + "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], + "BillingMode": "PAY_PER_REQUEST", + "VectorIndexes": [ + { + "IndexName": "vix", + "Dimensions": 4, + "DistanceFunction": "COSINE", + "VectorAttribute": {"AttributeName": "emb"}, + "SearchSchema": [ + {"AttributeName": "Country", "SearchSchemaElementType": "HASH"}, + {"AttributeName": "Price", "SearchSchemaElementType": "INLINE_FILTER"}, + ], + "Projection": {"ProjectionType": "ALL"}, + } + ], + }, + ) + try: + put = signed_post( + "PutItem", + { + "TableName": name, + "Item": { + "id": {"S": "i1"}, + "Country": {"S": "US"}, + "Price": {"N": "5"}, + "emb": {"L": [{"N": "1"}, {"N": "0"}, {"N": "0"}, {"N": "0"}]}, + }, + }, + ) + assert put.status_code == 200, put.text + yield name + finally: + delete_table(name) + + +def _search(table: str, condition: str, values: dict) -> requests.Response: + return signed_post( + "SearchVectors", + { + "TableName": table, + "IndexName": "vix", + "SearchVector": [{"N": "1"}, {"N": "0"}, {"N": "0"}, {"N": "0"}], + "TopK": 10, + "SearchConditionExpression": condition, + "ExpressionAttributeValues": values, + }, + ) + + +@pytest.fixture(scope="module") +def grammar(table) -> str: + return grammar_of(lambda: _search(table, "Country = :us AND Price > :p", + {":us": {"S": "US"}, ":p": {"N": "0"}})) + + +def _still_answering(table: str, after: str) -> None: + try: + resp = _search(table, "Country = :us", {":us": {"S": "US"}}) + if ENDPOINT_VAR: + health = requests.get(f"{ENDPOINT_VAR.rstrip('/')}/health", timeout=10, verify=False) + assert health.status_code == 200, f"/health after {after}: {health.status_code}" + except requests.exceptions.ConnectionError as e: + pytest.fail(f"the target stopped answering after {after}: {e}") + assert resp.status_code == 200, resp.text + assert [r["Item"]["id"]["S"] for r in resp.json()["SearchResults"]] == ["i1"] + + +@pytest.mark.parametrize(("label", "condition", "extended"), DEEP, ids=[d[0] for d in DEEP]) +def test_a_deep_condition_is_refused_and_the_server_answers( + table, grammar, label, condition, extended +): + assert len(condition.encode()) <= 4096 + try: + resp = _search(table, condition, VALUES) + except requests.exceptions.ConnectionError as e: + pytest.fail(f"the target dropped the connection on {label}: {e}") + if grammar == "extended": + refused(resp, extended) + else: + assert resp.status_code == 400, resp.text + assert resp.json()["__type"].endswith("ValidationException"), resp.text + _still_answering(table, label) From 734e7af1caeb1a84f5650c537e4f94b57549a10c Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Mon, 23 Nov 2026 22:23:12 +0000 Subject: [PATCH 031/101] test(search): date the search condition measurements The unit tests of the search condition grammar, its rules, the schema checks and evaluation, and the storage filter tests, still said their expected answers were predictions. They have been measured. Each header now states where and when its answers were measured on the live service. The grammar and rules cases were sent to a missing table, and the schema cases to vector tables with the search schema of the case, on 2026-11-23, two requests each; every case at the service limit of 50 conditions gets the answer the test expects. The evaluation cases were measured on 2026-11-19, 2026-11-21 and 2026-11-23 on a table with the same items. The service refuses a PutItem that stores a search schema attribute of another type than the schema declares ("Attribute 'Price' type mismatch"), so no stored item can hold one. The evaluation test of such an item and its row are removed. --- .../expression/search_filter/tests_eval.rs | 52 ++++++++----------- .../expression/search_filter/tests_grammar.rs | 11 +++- .../expression/search_filter/tests_rules.rs | 8 ++- .../expression/search_filter/tests_schema.rs | 9 +++- .../expression/search_filter/tests_support.rs | 7 +-- .../tests/vector_search_filter.rs | 8 +-- .../storage-sqlite/src/vector_filter_tests.rs | 8 +-- 7 files changed, 55 insertions(+), 48 deletions(-) diff --git a/crates/core/src/expression/search_filter/tests_eval.rs b/crates/core/src/expression/search_filter/tests_eval.rs index a85c222d9..29c5134fd 100644 --- a/crates/core/src/expression/search_filter/tests_eval.rs +++ b/crates/core/src/expression/search_filter/tests_eval.rs @@ -4,12 +4,16 @@ //! Which items a search condition matches. //! //! Evaluation uses the FilterExpression semantics: a comparison with a -//! missing attribute is false except `<>`, which is true; a value of another -//! type than the attribute's compares unequal. Numbers compare as the nearest -//! binary64 value of each side, so `1E2` equals `100` and two 38-digit values -//! that share a binary64 value are equal. The number cases were measured -//! against the live service (eu-north-1, 2026-11-21, each request twice); the -//! others are not yet measured for SearchVectors. +//! missing attribute is false except `<>`, which is true. Numbers compare as +//! the nearest binary64 value of each side, so `1E2` equals `100` and two +//! 38-digit values that share a binary64 value are equal. An item cannot hold +//! a search schema attribute of another type than the schema declares: the +//! service refuses that PutItem with "Attribute 'Price' type mismatch". +//! +//! Every case was measured against the live service in eu-north-1, on a table +//! with these items, each request twice with the same answer: on 2026-11-19 +//! and 2026-11-21, and `NOT (Category = :a)` and +//! `(Price BETWEEN :p5 AND :p10 OR Price > :p100)` on 2026-11-23. use std::collections::{BTreeMap, HashMap}; @@ -44,8 +48,6 @@ fn items() -> Vec { None, ), ("i10", "US", Some("b"), Some(n("0.1")), None), - // a Price of another type than the schema declares - ("i11", "US", Some("c"), Some(s("ten")), None), ]; rows.into_iter() .map(|(id, country, category, price, tag)| { @@ -146,7 +148,7 @@ fn each_comparator_on_a_number() { ), ( h("NOT Price BETWEEN :p5 AND :p10"), - vec!["i3", "i4", "i5", "i6", "i7", "i9", "i10", "i11"], + vec!["i3", "i4", "i5", "i6", "i7", "i9", "i10"], ), (h("Price IN (:p5, :p10)"), vec!["i1", "i2"]), ]; @@ -157,23 +159,22 @@ fn each_comparator_on_a_number() { assert_matches(&refs); } -/// Unmeasured, needs live confirmation: a missing attribute under `<>` and -/// under NOT. FilterExpression reads `<>` with a missing attribute as true, -/// and NOT of a false comparison as true. +/// A missing attribute under `<>` and under NOT. FilterExpression reads `<>` +/// with a missing attribute as true, and NOT of a false comparison as true. #[test] fn a_missing_attribute_under_not_equal_and_not() { let cases = [ ( h("Price <> :p10"), - vec!["i1", "i3", "i4", "i5", "i6", "i7", "i9", "i10", "i11"], + vec!["i1", "i3", "i4", "i5", "i6", "i7", "i9", "i10"], ), ( h("NOT (Price = :p10)"), - vec!["i1", "i3", "i4", "i5", "i6", "i7", "i9", "i10", "i11"], + vec!["i1", "i3", "i4", "i5", "i6", "i7", "i9", "i10"], ), ( h("Category <> :a"), - vec!["i2", "i3", "i5", "i7", "i9", "i10", "i11"], + vec!["i2", "i3", "i5", "i7", "i9", "i10"], ), ( h("Price > :p0"), @@ -182,7 +183,7 @@ fn a_missing_attribute_under_not_equal_and_not() { (h("attribute_not_exists(Price)"), vec!["i4"]), ( h("attribute_exists(Price)"), - vec!["i1", "i2", "i3", "i5", "i6", "i7", "i9", "i10", "i11"], + vec!["i1", "i2", "i3", "i5", "i6", "i7", "i9", "i10"], ), ]; let refs: Vec<(&str, &[&str])> = cases @@ -192,8 +193,7 @@ fn a_missing_attribute_under_not_equal_and_not() { assert_matches(&refs); } -/// Unmeasured, needs live confirmation: `1E2` against `100`, and 38-digit -/// values. +/// `1E2` against `100`, and 38-digit values. #[test] fn numbers_compare_as_binary64() { let cases = [ @@ -285,16 +285,6 @@ fn a_last_digit_difference_counts_only_beyond_binary64() { assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); } -/// Unmeasured, needs live confirmation: an item whose attribute has another -/// type than the schema declares matches no ordering and no equality, and -/// does match `<>`. -#[test] -fn a_stored_value_of_another_type() { - assert!(!matching(&h("Price >= :p0")).contains(&"i11".to_owned())); - assert!(!matching(&h("Price = :p0")).contains(&"i11".to_owned())); - assert!(matching(&h("Price <> :p0")).contains(&"i11".to_owned())); -} - #[test] fn strings_binaries_and_logic() { let cases = [ @@ -302,7 +292,7 @@ fn strings_binaries_and_logic() { (h("Tag = :t1"), vec!["i1"]), ( h("Tag <> :t1"), - vec!["i2", "i3", "i4", "i5", "i6", "i7", "i9", "i10", "i11"], + vec!["i2", "i3", "i4", "i5", "i6", "i7", "i9", "i10"], ), ( h("Category IN (:a, :b)"), @@ -311,7 +301,7 @@ fn strings_binaries_and_logic() { (h("(Price = :p5 OR Price = :p10)"), vec!["i1", "i2"]), ( h("NOT (Category = :a)"), - vec!["i2", "i3", "i5", "i7", "i9", "i10", "i11"], + vec!["i2", "i3", "i5", "i7", "i9", "i10"], ), ( h("(Category = :a OR (Price > :p5 AND NOT Price = :p15))"), @@ -320,7 +310,7 @@ fn strings_binaries_and_logic() { (h("NOT NOT Price = :p5"), vec!["i1"]), ( "Country = :us and (Price = :p5 or not Price = :p10)".to_owned(), - vec!["i1", "i3", "i4", "i5", "i6", "i7", "i9", "i10", "i11"], + vec!["i1", "i3", "i4", "i5", "i6", "i7", "i9", "i10"], ), ("Country = :ca AND Price = :p5".to_owned(), vec!["i8"]), ]; diff --git a/crates/core/src/expression/search_filter/tests_grammar.rs b/crates/core/src/expression/search_filter/tests_grammar.rs index 1831faca7..25b97b7a3 100644 --- a/crates/core/src/expression/search_filter/tests_grammar.rs +++ b/crates/core/src/expression/search_filter/tests_grammar.rs @@ -3,8 +3,15 @@ //! The grammar and the tree-building checks, before any search schema. //! -//! Not yet measured against the live service: every expected message here is -//! a prediction, and a live run confirms or corrects it. +//! Every expected answer was measured against the live service in +//! eu-north-1, on an account with the extended grammar, each request twice +//! with the same answer. The cases checked through `outcome` were sent on +//! 2026-11-23 to a missing table, with the names and values each case uses; +//! `Ok` stands for a request the service passed to the table lookup. The +//! combined size of substituted names was measured on 2026-11-19 against a +//! vector table, and the unused value message on 2026-11-19 against a vector +//! table and on 2026-11-23 against a missing table, with a parse failure +//! answering ahead of it. use super::tests_support::{OK, and_chain, assert_outcomes, in_list, n, outcome, p}; diff --git a/crates/core/src/expression/search_filter/tests_rules.rs b/crates/core/src/expression/search_filter/tests_rules.rs index 0b6914a03..ea2c60f2c 100644 --- a/crates/core/src/expression/search_filter/tests_rules.rs +++ b/crates/core/src/expression/search_filter/tests_rules.rs @@ -3,8 +3,12 @@ //! The conditions a search condition records, and the condition limit. //! -//! Not yet measured against the live service: every expected value here is -//! a prediction, and a live run confirms or corrects it. +//! The recorded conditions are internal and have no answer of their own on +//! the wire. Every answer under the limit of 50 was measured against the live +//! service in eu-north-1, on an account with the extended grammar, on +//! 2026-11-23, each request twice with the same answer, against a missing +//! table; `Ok` stands for a request the service passed to the table lookup. +//! A limit of 1 or 3 exists only in these tests. use super::rules::{Condition, Operator}; use super::tests_support::{ diff --git a/crates/core/src/expression/search_filter/tests_schema.rs b/crates/core/src/expression/search_filter/tests_schema.rs index 7b2c561a3..3f1b928b5 100644 --- a/crates/core/src/expression/search_filter/tests_schema.rs +++ b/crates/core/src/expression/search_filter/tests_schema.rs @@ -3,8 +3,13 @@ //! The search condition against the index search schema. //! -//! Not yet measured against the live service: every expected message here is -//! a prediction, and a live run confirms or corrects it. +//! Every expected answer was measured against the live service in +//! eu-north-1, on an account with the extended grammar, on 2026-11-23, each +//! request twice with the same answer, against a vector table with the +//! search schema of the case; `Ok` stands for a search the service answered +//! with 200, the accepted shapes of the two partition tests included. The +//! partition a condition selects is internal; the wire tests pin that the +//! HASH value scopes the search. use std::collections::HashMap; diff --git a/crates/core/src/expression/search_filter/tests_support.rs b/crates/core/src/expression/search_filter/tests_support.rs index 80cb24abe..315fb440c 100644 --- a/crates/core/src/expression/search_filter/tests_support.rs +++ b/crates/core/src/expression/search_filter/tests_support.rs @@ -1,11 +1,8 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! Fixtures shared by the search filter tests. -//! -//! None of the expected messages in these tests has been measured against the -//! live service yet. Each one is a prediction of the service's answer, and a -//! live run confirms or corrects it. +//! Fixtures shared by the search filter tests. Each test file states where +//! its expected answers were measured. use std::collections::HashMap; diff --git a/crates/storage-postgres/tests/vector_search_filter.rs b/crates/storage-postgres/tests/vector_search_filter.rs index d19b52496..9819fc15e 100644 --- a/crates/storage-postgres/tests/vector_search_filter.rs +++ b/crates/storage-postgres/tests/vector_search_filter.rs @@ -7,8 +7,10 @@ //! The backend reads the rows in score order and keeps the first `top_k` //! that satisfy the condition, so `top_k` counts matching items only. Equal //! scores are ordered by the base key. The match semantics are the -//! FilterExpression ones; the cases that turn on a missing attribute or a -//! number written two ways are not yet measured against the live service. +//! FilterExpression ones. The two that the cases below turn on, a missing +//! attribute satisfying `<>` and `1E2` equal to `100`, were measured against +//! the live service in eu-north-1 on 2026-11-19, each request twice, with the +//! items of the wire tests. //! //! The fixture is in `common/vector_filter_fixture.rs`. @@ -64,7 +66,7 @@ async fn conditions_are_evaluated_before_the_top_k_cut() { ids_for(f, "Country = :us AND Price >= :p5", 10).await, ["n1", "n2", "t2", "n4", "n5"] ); - // not yet measured: a missing Price under <>, and 1E2 equal to 100 + // a missing Price satisfies <>, and 1E2 equals 100 assert_eq!( ids_for(f, "Country = :us AND Price <> :p10", 10).await, ["n1", "n3", "n4", "n5"] diff --git a/crates/storage-sqlite/src/vector_filter_tests.rs b/crates/storage-sqlite/src/vector_filter_tests.rs index 59d660f5b..f6c24a01e 100644 --- a/crates/storage-sqlite/src/vector_filter_tests.rs +++ b/crates/storage-sqlite/src/vector_filter_tests.rs @@ -5,8 +5,10 @@ //! //! The backend applies the condition to each candidate before ranking, so //! `top_k` counts matching items only. The match semantics are the -//! FilterExpression ones; the cases that turn on a missing attribute or a -//! number written two ways are not yet measured against the live service. +//! FilterExpression ones. The two that the cases below turn on, a missing +//! attribute satisfying `<>` and `1E2` equal to `100`, were measured against +//! the live service in eu-north-1 on 2026-11-19, each request twice, with the +//! items of the wire tests. use std::collections::HashMap; use std::sync::Arc; @@ -202,7 +204,7 @@ async fn the_hash_value_scopes_the_search() { ); } -/// Not yet measured: a missing Price under `<>`, and `1E2` equal to `100`. +/// A missing Price satisfies `<>`, and `1E2` equals `100`. #[tokio::test] async fn a_missing_attribute_and_a_number_written_two_ways() { let (engine, key_info) = fixture().await; From efae1b75b87803d555b8b6322a68e4b84809b37f Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 05:46:05 +0000 Subject: [PATCH 032/101] feat(engine): serve the extended search grammar by default DynamoDB serves the extended SearchConditionExpression grammar to every account: comparators other than `=`, BETWEEN, IN, OR, NOT, parentheses, attribute_exists and attribute_not_exists. Measured on a new table in us-east-1 and in ap-southeast-2 on 2026-11-24, each of six shapes twice: every one answered 200 with the items the condition selects. ExtendDB compiled the grammar only with the search-inequality-filters Cargo feature, off by default, and served it only to the accounts the search_inequality_filters setting named. An absent setting enabled no account. The feature is now a default feature of every crate that declares it, so every build serves the grammar; removing it from those defaults compiles it out. An absent or empty setting now enables every account, as does a server that has not installed its settings store. `off` and a list of account IDs restrict the grammar as before. A malformed value is still logged once per change and is ignored, which now means every account. A failed or slow read of the setting still answers ServiceUnavailableException. The wire tests expect the extended grammar when the setting is absent or empty. The feature workflow now lints each crate with its own feature flag off, runs the core and engine unit tests that way, and runs the vector wire tests with the setting at `off` and at `all`; the other workflows build, lint and test the feature through the defaults. The admin guide lists the setting and the usage guide the grammar. Verified with unit tests of the parsed default, the absent, empty and malformed values, `off` and a list, and the server without a store, and with the wire suites on SQLite and PostgreSQL with the setting absent, `all` and `off`. --- .github/workflows/integration.yml | 8 +- .../workflows/search-inequality-filters.yml | 101 +++++----------- crates/app/Cargo.toml | 6 +- crates/bin/Cargo.toml | 6 +- crates/core/Cargo.toml | 7 +- .../core/src/expression/search_filter/gate.rs | 29 +++-- crates/core/src/settings_keys.rs | 7 +- crates/engine/Cargo.toml | 7 +- crates/engine/src/search_vectors_extended.rs | 2 +- .../src/search_vectors_extended_tests.rs | 12 +- crates/engine/src/search_vectors_settings.rs | 35 ++++-- .../src/search_vectors_settings_tests.rs | 113 +++++++++++++++++- crates/server/Cargo.toml | 6 +- crates/storage-postgres/Cargo.toml | 5 +- crates/storage-sqlite/Cargo.toml | 5 +- devtools/run-tests | 7 +- docs/manuals/03-usage-guide.md | 7 +- docs/manuals/05-admin-guide.md | 1 + tests/search_vectors_wire.py | 12 +- 19 files changed, 245 insertions(+), 131 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 16bd29758..1e0c34178 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -244,7 +244,9 @@ jobs: EXTENDDB_TEST_PG_ADMIN_CONNECTION_STRING: postgresql://postgres:devpass@127.0.0.1:5432 EXTENDDB_TEST_BACKUP_STORE: filesystem # pgvector is present, so the SearchVectors suites fail rather than - # skip when the backend refuses vector indexes. + # skip when the backend refuses vector indexes. The + # search_inequality_filters setting is absent, so they run under the + # extended grammar. EXTENDDB_EXPECT_VECTORS: "1" run: devtools/run-tests --extenddb --pytest --comprehensive --terraform --parallel @@ -426,7 +428,9 @@ jobs: # defaulted root beside the database file. EXTENDDB_TEST_BACKUP_STORE: filesystem # SQLite serves vector search, so the SearchVectors suites fail - # rather than skip when the backend refuses vector indexes. + # rather than skip when the backend refuses vector indexes. The + # search_inequality_filters setting is absent, so they run under the + # extended grammar. EXTENDDB_EXPECT_VECTORS: "1" run: devtools/run-tests --extenddb --pytest --comprehensive --terraform --parallel diff --git a/.github/workflows/search-inequality-filters.yml b/.github/workflows/search-inequality-filters.yml index bd2132f06..63e16d81a 100644 --- a/.github/workflows/search-inequality-filters.yml +++ b/.github/workflows/search-inequality-filters.yml @@ -14,18 +14,16 @@ concurrency: group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.run_id }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} -# The search-inequality-filters Cargo feature is off by default, so no other -# workflow compiles its code or its tests. These jobs build it, lint it, run -# its unit tests, and run the SearchVectors wire tests against a server built -# with it and the search_inequality_filters setting at `all`. -env: - FEATURES: >- - extenddb-core/search-inequality-filters,extenddb-engine/search-inequality-filters,extenddb-server/search-inequality-filters,extenddb-storage-sqlite/search-inequality-filters,extenddb-storage-postgres/search-inequality-filters - +# The search-inequality-filters Cargo feature is on by default, so the other +# workflows build, lint and test it, and their wire tests run with the +# search_inequality_filters setting absent, which gives every account the +# extended grammar. These jobs cover what they do not: each crate that +# declares the feature built and tested with it compiled out, and the vector +# wire tests with the setting written as `off` and as `all`. jobs: - lint: + compiled-out: runs-on: extenddb_ubuntu-2404_4-core - timeout-minutes: 30 + timeout-minutes: 40 steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master @@ -35,60 +33,21 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo clippy --workspace --all-targets --features "$FEATURES" -- -D warnings - # The SQLite-only binary, whose backend selection differs from the - # workspace build's PostgreSQL default. - - run: cargo clippy -p extenddb --all-targets --no-default-features --features sqlite,search-inequality-filters -- -D warnings - - msrv: - runs-on: extenddb_ubuntu-2404_4-core - timeout-minutes: 30 - steps: - - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master - with: - toolchain: "1.91.1" - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - with: - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo build --locked --workspace --features "$FEATURES" - - unit: - runs-on: extenddb_ubuntu-2404_4-core - timeout-minutes: 40 - services: - postgres: - image: pgvector/pgvector:pg16 - env: - POSTGRES_PASSWORD: devpass - options: >- - --health-cmd "pg_isready -U postgres" - --health-interval 5s - --health-timeout 5s - --health-retries 5 - ports: - - 127.0.0.1:5432:5432 - steps: - - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master - with: - toolchain: stable - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - with: - save-if: ${{ github.ref == 'refs/heads/main' }} - - name: Unit tests of the crates the feature changes - run: >- - cargo test --locked --no-fail-fast - -p extenddb-core -p extenddb-engine -p extenddb-server -p extenddb-storage-sqlite - --features "extenddb-core/search-inequality-filters,extenddb-engine/search-inequality-filters,extenddb-server/search-inequality-filters,extenddb-storage-sqlite/search-inequality-filters" - # Same environment as the PostgreSQL storage-level job in - # integration.yml: the tests create and drop their own databases, and - # EXTENDDB_TEST_PG_REQUIRED turns a missing connection into a failure. - - name: PostgreSQL storage tests - env: - EXTENDDB_TEST_PG_CONNECTION_STRING: postgresql://postgres:devpass@127.0.0.1:5432 - EXTENDDB_TEST_PG_REQUIRED: "1" - run: cargo test --locked --no-fail-fast --release -p extenddb-storage-postgres --features search-inequality-filters --tests + # One crate per run: a crate built with others would get the feature + # back from a dependent that enables its defaults. + - name: Lint each crate with the feature off + run: | + set -e + cargo clippy --locked -p extenddb-core --all-targets --no-default-features --features partiql -- -D warnings + cargo clippy --locked -p extenddb-engine --all-targets --no-default-features --features partiql -- -D warnings + for crate in extenddb-server extenddb-app extenddb-storage-sqlite extenddb-storage-postgres; do + cargo clippy --locked -p "$crate" --all-targets --no-default-features -- -D warnings + done + - name: Unit tests of core and the engine with the feature off + run: | + set -e + cargo test --locked --no-fail-fast -p extenddb-core --no-default-features --features partiql + cargo test --locked --no-fail-fast -p extenddb-engine --no-default-features --features partiql wire: runs-on: extenddb_ubuntu-2404_4-core @@ -97,6 +56,7 @@ jobs: fail-fast: false matrix: backend: [sqlite, postgres] + setting: ["off", all] services: postgres: image: pgvector/pgvector:pg16 @@ -120,7 +80,7 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' }} - name: Build release - run: cargo build --locked --release -p extenddb --no-default-features --features ${{ matrix.backend }},search-inequality-filters + run: cargo build --locked --release -p extenddb --no-default-features --features ${{ matrix.backend }} - name: Initialize ExtendDB id: init @@ -161,14 +121,15 @@ jobs: # file, except the CLI catalog migration file, which builds catalogs of # its own and does not depend on the feature. devtools/run-tests writes # the setting before the suite starts; the modules read it and fail when - # the server serves the other grammar. + # the server serves the other grammar. Under `off` the tests of the + # extended grammar skip. - name: Run the vector wire tests env: EXTENDDB_TEST_ENDPOINT: https://127.0.0.1:18443 EXTENDDB_ADMIN_USER: admin EXTENDDB_ADMIN_PASSWORD: ${{ steps.init.outputs.admin_password }} EXTENDDB_TEST_BACKUP_STORE: ${{ matrix.backend == 'sqlite' && 'filesystem' || 'none' }} - EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS: all + EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS: ${{ matrix.setting }} EXTENDDB_EXPECT_VECTORS: "1" run: devtools/run-tests --extenddb --pytest --parallel --filter "vector and not test_cli" @@ -179,13 +140,11 @@ jobs: search-inequality-filters: runs-on: extenddb_ubuntu-2404_4-core timeout-minutes: 5 - needs: [lint, msrv, unit, wire] + needs: [compiled-out, wire] if: always() steps: - run: | - if [ "${{ needs.lint.result }}" != "success" ] \ - || [ "${{ needs.msrv.result }}" != "success" ] \ - || [ "${{ needs.unit.result }}" != "success" ] \ + if [ "${{ needs.compiled-out.result }}" != "success" ] \ || [ "${{ needs.wire.result }}" != "success" ]; then exit 1 fi diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index cd8cd0b63..2f773dc79 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true homepage.workspace = true [features] +default = ["search-inequality-filters"] # Developer mode: plain HTTP on loopback, open authorization (SigV4 # authentication still enforced), seeded dev credential. A build-time profile # for local development and CI. The thin bin enforces that it is paired with the @@ -21,8 +22,9 @@ backup-test-hooks = ["extenddb-server/backup-test-hooks"] # SearchVectors inequality filters: the extended SearchConditionExpression # grammar (comparators, BETWEEN, IN, OR, NOT, attribute_exists and # attribute_not_exists) for the accounts the `search_inequality_filters` -# runtime setting names. Off by default. Removable: with this off, the -# grammar module is not compiled and SearchVectors behaves as before. +# runtime setting names, every account when it is absent. On by default. +# Removable: with this off, the grammar module is not compiled and +# SearchVectors accepts only an AND of equalities. search-inequality-filters = ["extenddb-server/search-inequality-filters"] [dependencies] diff --git a/crates/bin/Cargo.toml b/crates/bin/Cargo.toml index 1a242aaae..0f544cd84 100755 --- a/crates/bin/Cargo.toml +++ b/crates/bin/Cargo.toml @@ -18,7 +18,7 @@ name = "extenddb" path = "src/main.rs" [features] -default = ["postgres"] +default = ["postgres", "search-inequality-filters"] postgres = ["extenddb-storage-postgres"] cassandra = ["extenddb-storage-cassandra"] sqlite = ["extenddb-storage-sqlite"] @@ -40,7 +40,9 @@ mongodb-test-hooks = [ dev-mode = ["extenddb-app/dev-mode"] # SearchVectors inequality filters: the extended SearchConditionExpression # grammar for the accounts the `search_inequality_filters` runtime setting -# names. Off by default; with it off SearchVectors behaves as before. +# names, every account when it is absent. On by default, here and in every +# crate that declares it; with it off in all of them SearchVectors accepts +# only an AND of equalities. search-inequality-filters = ["extenddb-app/search-inequality-filters"] [dependencies] diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 8bc0451ed..0b465e79b 100755 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -23,13 +23,14 @@ time = { workspace = true } uuid = { workspace = true } [features] -default = ["partiql"] +default = ["partiql", "search-inequality-filters"] # PartiQL grammar, AST and query planning. Removable: with this off, the # `partiql` module is not compiled and nothing else in core references it. partiql = [] # SearchVectors inequality filters: the extended SearchConditionExpression # grammar (comparators, BETWEEN, IN, OR, NOT, attribute_exists and # attribute_not_exists) for the accounts the `search_inequality_filters` -# runtime setting names. Off by default. Removable: with this off, the -# grammar module is not compiled and SearchVectors behaves as before. +# runtime setting names, every account when it is absent. On by default. +# Removable: with this off, the grammar module is not compiled and +# SearchVectors accepts only an AND of equalities. search-inequality-filters = [] diff --git a/crates/core/src/expression/search_filter/gate.rs b/crates/core/src/expression/search_filter/gate.rs index 65c0b71e4..490267889 100644 --- a/crates/core/src/expression/search_filter/gate.rs +++ b/crates/core/src/expression/search_filter/gate.rs @@ -3,19 +3,21 @@ //! Which accounts get the extended grammar. //! -//! The service enables the grammar for a request when the caller or the -//! table owner is enabled. The setting names them: `off`, `all`, or a -//! comma-separated list of 12-digit account IDs. +//! The service serves the grammar to every account. The setting names the +//! accounts ExtendDB serves it to: `all` (the default), `off`, or a +//! comma-separated list of 12-digit account IDs, in which case a request +//! gets the grammar when the caller or the table owner is listed. use std::collections::BTreeSet; /// The parsed value of the setting. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub enum EnabledAccounts { - /// No account. The default, and the value when the setting is absent. - #[default] + /// No account. Off, - /// Every account. + /// Every account. The default, and the value when the setting is absent + /// or empty. + #[default] All, /// The listed accounts. Listed(BTreeSet), @@ -30,7 +32,7 @@ impl EnabledAccounts { pub fn parse(value: &str) -> Result { match value.trim() { "off" => return Ok(Self::Off), - "all" => return Ok(Self::All), + "all" | "" => return Ok(Self::All), _ => {} } let mut accounts = BTreeSet::new(); @@ -64,6 +66,18 @@ impl EnabledAccounts { mod tests { use super::EnabledAccounts; + #[test] + fn every_account_is_the_default() { + assert_eq!(EnabledAccounts::default(), EnabledAccounts::All); + for empty in ["", " ", "\t"] { + assert_eq!( + EnabledAccounts::parse(empty), + Ok(EnabledAccounts::All), + "{empty:?}" + ); + } + } + #[test] fn off_and_all_parse() { assert_eq!(EnabledAccounts::parse("off"), Ok(EnabledAccounts::Off)); @@ -84,7 +98,6 @@ mod tests { #[test] fn a_malformed_value_is_refused() { for bad in [ - "", "on", "true", "12345", diff --git a/crates/core/src/settings_keys.rs b/crates/core/src/settings_keys.rs index 485568cd1..4ba5bc442 100644 --- a/crates/core/src/settings_keys.rs +++ b/crates/core/src/settings_keys.rs @@ -101,9 +101,10 @@ pub const VECTOR_INDEX_MIN_CREATING_MS: &str = "vector_index_min_creating_ms"; pub const VECTOR_ALLOCATION_PHASE_DELAY_MS: &str = "vector_allocation_phase_delay_ms"; /// The accounts whose SearchVectors requests accept the extended -/// `SearchConditionExpression` grammar: `off` (the default when the row is -/// absent), `all`, or a comma-separated list of 12-digit account IDs. Read on -/// every SearchVectors request, so a change applies without a restart. +/// `SearchConditionExpression` grammar: `all` (the default when the row is +/// absent or empty), `off`, or a comma-separated list of 12-digit account +/// IDs. Read on every SearchVectors request, so a change applies without a +/// restart. #[cfg(feature = "search-inequality-filters")] pub const SEARCH_INEQUALITY_FILTERS: &str = "search_inequality_filters"; diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 35a443ac9..752312796 100755 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -11,7 +11,7 @@ repository.workspace = true homepage.workspace = true [features] -default = ["partiql"] +default = ["partiql", "search-inequality-filters"] # Kill-point pauses in the backup job (`EXTENDDB_BACKUP_PAUSE`), for the # binary-level crash tests; never enabled in a release build. backup-test-hooks = [] @@ -23,8 +23,9 @@ partiql = ["extenddb-core/partiql"] # SearchVectors inequality filters: the extended SearchConditionExpression # grammar (comparators, BETWEEN, IN, OR, NOT, attribute_exists and # attribute_not_exists) for the accounts the `search_inequality_filters` -# runtime setting names. Off by default. Removable: with this off, the -# grammar module is not compiled and SearchVectors behaves as before. +# runtime setting names, every account when it is absent. On by default. +# Removable: with this off, the grammar module is not compiled and +# SearchVectors accepts only an AND of equalities. search-inequality-filters = ["extenddb-core/search-inequality-filters"] [dependencies] diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs index 4c63ce615..9339182b9 100644 --- a/crates/engine/src/search_vectors_extended.rs +++ b/crates/engine/src/search_vectors_extended.rs @@ -12,7 +12,7 @@ //! which accounts get the grammar. It is read through the settings store the //! server installs with [`install_search_filter_settings`] (see //! `search_vectors_settings.rs`), so a change applies without a restart. -//! Until a store is installed, no account gets the grammar. +//! Until a store is installed, every account gets the grammar. pub(crate) use imp::{Extended, parse_request, resolve_scope}; diff --git a/crates/engine/src/search_vectors_extended_tests.rs b/crates/engine/src/search_vectors_extended_tests.rs index 26405ca79..8516e2c35 100644 --- a/crates/engine/src/search_vectors_extended_tests.rs +++ b/crates/engine/src/search_vectors_extended_tests.rs @@ -94,14 +94,16 @@ async fn parsed( #[tokio::test] async fn the_setting_selects_the_accounts() { for (value, expected) in [ - (Ok(None), false), + // an absent or empty value is every account + (Ok(None), true), + (Ok(Some("")), true), (Ok(Some("off")), false), (Ok(Some("all")), true), (Ok(Some("111111111111")), true), (Ok(Some("222222222222,111111111111")), true), (Ok(Some("222222222222")), false), - // a value that does not parse reads as off - (Ok(Some("on")), false), + // a value that does not parse is logged and reads as every account + (Ok(Some("on")), true), ] { let storage = install(value).await; assert_eq!( @@ -124,13 +126,13 @@ async fn a_store_that_fails_answers_a_retryable_fault() { } #[tokio::test] -async fn without_an_installed_store_no_account_gets_the_grammar() { +async fn without_an_installed_store_every_account_gets_the_grammar() { let storage: Arc = Arc::new( SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) .await .expect("an in-memory database opens"), ); - assert!(!parsed(&storage, Some(INEQUALITY)).await.unwrap()); + assert!(parsed(&storage, Some(INEQUALITY)).await.unwrap()); } #[tokio::test] diff --git a/crates/engine/src/search_vectors_settings.rs b/crates/engine/src/search_vectors_settings.rs index aad631c9b..ad9eeee16 100644 --- a/crates/engine/src/search_vectors_settings.rs +++ b/crates/engine/src/search_vectors_settings.rs @@ -5,8 +5,9 @@ //! //! The server installs its settings store against its storage engine with //! [`install_search_filter_settings`], so two servers in one process read -//! their own catalogs. A storage engine without an installed store enables no -//! account. +//! their own catalogs. An absent or empty value enables every account, as +//! does a storage engine without an installed store. A malformed value is +//! logged once per change and enables every account. //! //! A read is kept for [`REFRESH`], so a busy server reads the catalog about //! once per interval rather than once per request, and a change made through @@ -69,7 +70,7 @@ pub fn search_filter_settings_changed() { } /// The accounts the setting enables on the server that `storage` belongs -/// to. An absent or malformed value enables none. +/// to. An absent, empty or malformed value enables every account. /// /// # Errors /// @@ -85,7 +86,7 @@ pub(crate) async fn enabled_accounts( .map(|(_, settings)| Arc::clone(settings)); match settings { Some(settings) => settings.enabled_accounts().await, - None => Ok(EnabledAccounts::Off), + None => Ok(EnabledAccounts::All), } } @@ -185,7 +186,10 @@ impl Settings { let previous = kept.take().and_then(|k| k.raw); let (raw, accounts) = match read { Ok(Ok(Ok(raw))) => { - let accounts = Self::parse(raw.as_deref(), previous.as_deref()); + let (accounts, ignored) = Self::parse(raw.as_deref(), previous.as_deref()); + if let Some(ignored) = ignored { + tracing::warn!("{ignored}"); + } (raw, Some(accounts)) } Ok(Ok(Err(e))) => { @@ -214,16 +218,21 @@ impl Settings { answer } - fn parse(raw: Option<&str>, previous: Option<&str>) -> EnabledAccounts { + /// The accounts a stored value enables, and the line to log when the + /// value is malformed and differs from the previous read. An absent + /// value, like a malformed one, enables every account. + fn parse(raw: Option<&str>, previous: Option<&str>) -> (EnabledAccounts, Option) { let Some(value) = raw else { - return EnabledAccounts::Off; + return (EnabledAccounts::All, None); }; - EnabledAccounts::parse(value).unwrap_or_else(|reason| { - if previous != Some(value) { - tracing::warn!("{SEARCH_INEQUALITY_FILTERS} = {value:?} ignored: {reason}"); - } - EnabledAccounts::Off - }) + match EnabledAccounts::parse(value) { + Ok(accounts) => (accounts, None), + Err(reason) => ( + EnabledAccounts::All, + (previous != Some(value)) + .then(|| format!("{SEARCH_INEQUALITY_FILTERS} = {value:?} ignored: {reason}")), + ), + } } } diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index 734f4afa1..143add3bc 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -104,12 +104,55 @@ fn is_unavailable(answer: &Result) -> bool { } #[tokio::test] -async fn a_server_without_a_store_enables_no_account() { +async fn a_server_without_a_store_enables_every_account() { let storage = storage().await; assert_eq!( enabled_accounts(&storage).await.unwrap(), + EnabledAccounts::All + ); +} + +#[tokio::test] +async fn an_absent_or_empty_value_enables_every_account() { + for answer in [Answer::Value(None), Answer::Value(Some(String::new()))] { + let settings = Settings::new(Store::new(answer)); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::All + ); + } +} + +#[tokio::test] +async fn off_and_a_list_still_restrict_the_grammar() { + let settings = Settings::new(Store::value("off")); + assert_eq!( + settings.enabled_accounts().await.unwrap(), EnabledAccounts::Off ); + let settings = Settings::new(Store::value("111111111111")); + let listed = settings.enabled_accounts().await.unwrap(); + assert!(listed.enabled_for("111111111111", None)); + assert!(!listed.enabled_for("222222222222", None)); +} + +/// A malformed value enables every account and is logged once per change. +#[test] +fn a_malformed_value_is_logged_once_and_enables_every_account() { + let (accounts, logged) = Settings::parse(Some("on"), None); + assert_eq!(accounts, EnabledAccounts::All); + assert_eq!( + logged.as_deref(), + Some( + "search_inequality_filters = \"on\" ignored: must be 'off', 'all', or a \ + comma-separated list of 12-digit account IDs" + ) + ); + assert_eq!( + Settings::parse(Some("on"), Some("on")), + (EnabledAccounts::All, None) + ); + assert!(Settings::parse(Some("on"), Some("off")).1.is_some()); } #[tokio::test] @@ -127,7 +170,7 @@ async fn each_server_reads_its_own_store() { ); assert_eq!( enabled_accounts(&third).await.unwrap(), - EnabledAccounts::Off + EnabledAccounts::All ); // installing again replaces the server's store install_search_filter_settings(&first, Store::value("off")); @@ -191,7 +234,7 @@ async fn a_read_is_kept_for_the_refresh_interval() { tokio::time::advance(REFRESH).await; assert_eq!( settings.enabled_accounts().await.unwrap(), - EnabledAccounts::Off + EnabledAccounts::All ); assert_eq!(store.reads(), 4); } @@ -332,3 +375,67 @@ async fn a_poisoned_lock_leaves_the_setting_readable() { ); assert_eq!(store.reads(), 2); } + +/// The warnings this thread's subscriber receives. +#[derive(Clone, Default)] +struct Warnings(Arc>>); + +struct Message<'a>(&'a mut String); + +impl tracing::field::Visit for Message<'_> { + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { + if field.name() == "message" { + *self.0 = format!("{value:?}"); + } + } +} + +impl tracing::Subscriber for Warnings { + fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool { + *metadata.level() == tracing::Level::WARN + } + fn new_span(&self, _span: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + fn record(&self, _span: &tracing::span::Id, _values: &tracing::span::Record<'_>) {} + fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {} + fn event(&self, event: &tracing::Event<'_>) { + let mut message = String::new(); + event.record(&mut Message(&mut message)); + self.0.lock().unwrap().push(message); + } + fn enter(&self, _span: &tracing::span::Id) {} + fn exit(&self, _span: &tracing::span::Id) {} +} + +/// A server that reads a malformed value logs it once, and again after the +/// value changes to another malformed one. +#[tokio::test(start_paused = true)] +async fn a_server_logs_a_malformed_value_once_per_change() { + let warnings = Warnings::default(); + let _guard = tracing::subscriber::set_default(warnings.clone()); + let store = Store::value("on"); + let settings = Settings::new(store.clone()); + for _ in 0..3 { + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::All + ); + tokio::time::advance(REFRESH).await; + } + store.set(Answer::Value(Some("true".to_owned()))); + tokio::time::advance(REFRESH).await; + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::All + ); + assert_eq!(store.reads(), 4); + let reason = "must be 'off', 'all', or a comma-separated list of 12-digit account IDs"; + assert_eq!( + *warnings.0.lock().unwrap(), + [ + format!("search_inequality_filters = \"on\" ignored: {reason}"), + format!("search_inequality_filters = \"true\" ignored: {reason}"), + ] + ); +} diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 1d23b6222..6d85c5c44 100755 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true homepage.workspace = true [features] +default = ["search-inequality-filters"] mongodb-test-hooks = [] # The backup and restore jobs' kill-point pauses (`EXTENDDB_BACKUP_PAUSE`), # for the binary-level crash tests. The engine's points are its own feature; @@ -24,8 +25,9 @@ backup-test-hooks = ["extenddb-engine/backup-test-hooks", "extenddb-storage/test # SearchVectors inequality filters: the extended SearchConditionExpression # grammar (comparators, BETWEEN, IN, OR, NOT, attribute_exists and # attribute_not_exists) for the accounts the `search_inequality_filters` -# runtime setting names. Off by default. Removable: with this off, the -# grammar module is not compiled and SearchVectors behaves as before. +# runtime setting names, every account when it is absent. On by default. +# Removable: with this off, the grammar module is not compiled and +# SearchVectors accepts only an AND of equalities. search-inequality-filters = ["extenddb-core/search-inequality-filters", "extenddb-engine/search-inequality-filters"] [dependencies] diff --git a/crates/storage-postgres/Cargo.toml b/crates/storage-postgres/Cargo.toml index 5544ee9e8..fcabb688a 100755 --- a/crates/storage-postgres/Cargo.toml +++ b/crates/storage-postgres/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true homepage.workspace = true [features] +default = ["search-inequality-filters"] # Compiles the snapshot page-size setter the consistency test uses and the # shared conformance check. Production builds do not compile them. test-hooks = ["extenddb-storage/test-hooks"] @@ -19,8 +20,8 @@ test-hooks = ["extenddb-storage/test-hooks"] # session's settings, and the post-check's definitions. test-util = ["extenddb-storage/test-util"] # The SearchVectors inequality filter tests, which evaluate the extended -# grammar on this backend. Production builds do not need it: the backend -# applies whatever filter the engine hands it. +# grammar on this backend. On by default. The backend applies whatever filter +# the engine hands it, so the feature adds tests only. search-inequality-filters = ["extenddb-core/search-inequality-filters"] [dev-dependencies] diff --git a/crates/storage-sqlite/Cargo.toml b/crates/storage-sqlite/Cargo.toml index d558f719d..fae114aa6 100644 --- a/crates/storage-sqlite/Cargo.toml +++ b/crates/storage-sqlite/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true homepage.workspace = true [features] +default = ["search-inequality-filters"] # Compile the in-memory (`:memory:`) database in as the default storage path, # yielding a zero-config, ephemeral, bootstrap-on-serve deployment (no `init`, # no file on disk). Without this feature the backend is file-backed and the path @@ -20,8 +21,8 @@ memory = [] # shared conformance check. Production builds do not compile them. test-hooks = ["extenddb-storage/test-hooks"] # The SearchVectors inequality filter tests, which evaluate the extended -# grammar on this backend. Production builds do not need it: the backend -# applies whatever filter the engine hands it. +# grammar on this backend. On by default. The backend applies whatever filter +# the engine hands it, so the feature adds tests only. search-inequality-filters = ["extenddb-core/search-inequality-filters"] [dependencies] diff --git a/devtools/run-tests b/devtools/run-tests index f91aff0ca..c08e56605 100755 --- a/devtools/run-tests +++ b/devtools/run-tests @@ -52,7 +52,9 @@ # search_inequality_filters runtime setting # (off, all, or account IDs), written before any # suite starts; a server that refuses it is an -# error. Unset leaves the setting as it is. +# error. Unset leaves the setting as it is; an +# absent setting gives every account the +# extended grammar. # # REQ-TEST-001, D-1, D-2, D-3, D-4, D-5 @@ -131,7 +133,8 @@ Environment (--extenddb with an integration suite): integration suite's backup tests read it too) EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS value for the search_inequality_filters setting, - written before any suite starts (optional) + written before any suite starts (optional; + absent, the setting is every account) Environment (--real-dynamodb): EXTENDDB_TEST_ENDPOINT and EXTENDDB_ADMIN_PASSWORD unset; AWS credentials from the SDK's chain or AWS_ACCESS_KEY_ID. EOF diff --git a/docs/manuals/03-usage-guide.md b/docs/manuals/03-usage-guide.md index 8f04d34aa..fa8fbd988 100755 --- a/docs/manuals/03-usage-guide.md +++ b/docs/manuals/03-usage-guide.md @@ -434,7 +434,12 @@ the declared number of dimensions. An item that omits it is stored and simply do not appear in that index, the same way a GSI ignores an item missing its key. `SearchVectors` returns the nearest items with a `Score` per hit, ordered nearest -first, and takes an optional `TopK` up to 100. +first, and takes an optional `TopK` up to 100. A `SearchConditionExpression` takes +one `=` on the index's HASH attribute and up to 50 conditions on its inline filter +attributes: `=`, `<>`, `<`, `<=`, `>`, `>=`, `BETWEEN`, `IN`, `AND`, `OR`, `NOT`, +parentheses, `attribute_exists` and `attribute_not_exists`. The +`search_inequality_filters` runtime setting can limit the conditions other than +an AND of equalities to a list of accounts, or turn them off. Four things are worth knowing before building on it. diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index 267e1e9e2..da858b76f 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -326,6 +326,7 @@ Managed via `extenddb settings set`. Changes take effect within 30 seconds witho | `log_level` | `info` | Log level: trace, debug, info, warn, error | | `control_plane_delay_seconds` | `0.25` | Delay for table status transitions, in seconds (0 = instant). PostgreSQL and SQLite write 0.25 into the catalog when it is created; MongoDB and Cassandra use 0.25 when the setting is absent. On PostgreSQL and SQLite a value below 1 makes DeleteTable remove the table in the request; on PostgreSQL, if a session holds a lock on the table's data (a reader, an open write transaction, an index build), DeleteTable returns `DELETING` instead (after at most about a second), the drop finishes in the background within about a second of that session's release, and a CreateTable of the same name is refused until then. | | `allow_credential_import` | `false` | Whether `import-access-key` is allowed. Only `true` enables it | +| `search_inequality_filters` | every account | The accounts whose `SearchVectors` requests accept the extended `SearchConditionExpression` grammar, as DynamoDB does for every account: `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. With `off`, or for an account the list does not name, a search condition is an AND of equalities. A server reads the setting at most once a second, so a change applies within about a second without a restart. A build without the `search-inequality-filters` Cargo feature refuses the key and accepts only equalities | | `vector_backfill_batch_delay_ms` | `0` | **Test-oriented.** Milliseconds to pause between batches while a vector index backfills. Zero in production. A test sets it so a write is guaranteed to land while the index is still building. The pause is outside the batch transaction, so writes are still accepted throughout, but it does extend the per-table propagation hold: no index on that table advances while the build runs, GSIs included, and the accepted range goes up to 60 s per batch. | | `vector_allocation_phase_delay_ms` | `0` | **Test-oriented.** Milliseconds to hold a new vector index in the resource-allocation phase (`CREATING` with `Backfilling: false`) before the scan starts. Zero in production. Without it the phase lasts only from the `UpdateTable` transaction, which inserts the row as `CREATING` with `Backfilling: false`, until the detached build task flips the flag, which is a window no client can time reliably rather than one that cannot exist. | diff --git a/tests/search_vectors_wire.py b/tests/search_vectors_wire.py index fd123bd3c..9906d6eaf 100644 --- a/tests/search_vectors_wire.py +++ b/tests/search_vectors_wire.py @@ -168,10 +168,10 @@ def _settings_api() -> tuple[str, tuple[str, str]] | None: def expected_grammar() -> str | None: """``equality`` or ``extended`` from the setting; ``None`` when it cannot be read. - An absent setting is ``off``, which is also what a build without the - feature serves. A list of accounts names the account in - ``EXTENDDB_TEST_ACCOUNT_ID``, which ``devtools/provision-test-credentials`` - exports. + An absent or empty setting is every account, so the extended grammar; + ``off`` is the equality-only grammar. A list of accounts names the + account in ``EXTENDDB_TEST_ACCOUNT_ID``, which + ``devtools/provision-test-credentials`` exports. """ api = _settings_api() if api is None: @@ -179,12 +179,12 @@ def expected_grammar() -> str | None: url, auth = api resp = requests.get(url, auth=auth, timeout=30, verify=False) if resp.status_code == 404: - return "equality" + return "extended" assert resp.status_code == 200, f"GET {url}: {resp.status_code} {resp.text}" value = resp.json()["value"].strip() if value == "off": return "equality" - if value == "all": + if value in ("all", ""): return "extended" account = os.environ.get("EXTENDDB_TEST_ACCOUNT_ID", "").strip() if not account: From b65c23f03fb7589331633070d8dd3a022cc45542 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 05:50:25 +0000 Subject: [PATCH 033/101] docs(search): describe the extended grammar as the service serves it The service serves the extended SearchConditionExpression grammar to every account. The test headers said that their expected answers were measured on an account with the extended grammar, and the condition limit module presented that grammar as one an account can have. The headers now give the region, the dates and the repeat count of each measurement. The condition limit module says that its equality-only answers were measured before the service served the extended grammar to every account, and that ExtendDB serves that grammar when the search_inequality_filters setting is off or does not name the account. The inequality filters module says which accounts ExtendDB serves the extended grammar to. Comment and docstring changes only. --- .../expression/search_filter/tests_grammar.rs | 15 +++++----- .../expression/search_filter/tests_rules.rs | 10 +++---- .../expression/search_filter/tests_schema.rs | 11 ++++--- tests/test_search_vectors_condition_limit.py | 29 ++++++++++--------- tests/test_search_vectors_deep_conditions.py | 10 +++---- tests/test_search_vectors_expression_maps.py | 7 ++--- .../test_search_vectors_inequality_filters.py | 14 +++++---- 7 files changed, 49 insertions(+), 47 deletions(-) diff --git a/crates/core/src/expression/search_filter/tests_grammar.rs b/crates/core/src/expression/search_filter/tests_grammar.rs index 25b97b7a3..e7e7853aa 100644 --- a/crates/core/src/expression/search_filter/tests_grammar.rs +++ b/crates/core/src/expression/search_filter/tests_grammar.rs @@ -4,14 +4,13 @@ //! The grammar and the tree-building checks, before any search schema. //! //! Every expected answer was measured against the live service in -//! eu-north-1, on an account with the extended grammar, each request twice -//! with the same answer. The cases checked through `outcome` were sent on -//! 2026-11-23 to a missing table, with the names and values each case uses; -//! `Ok` stands for a request the service passed to the table lookup. The -//! combined size of substituted names was measured on 2026-11-19 against a -//! vector table, and the unused value message on 2026-11-19 against a vector -//! table and on 2026-11-23 against a missing table, with a parse failure -//! answering ahead of it. +//! eu-north-1, each request twice with the same answer. The cases checked +//! through `outcome` were sent on 2026-11-23 to a missing table, with the +//! names and values each case uses; `Ok` stands for a request the service +//! passed to the table lookup. The combined size of substituted names was +//! measured on 2026-11-19 against a vector table, and the unused value +//! message on 2026-11-19 against a vector table and on 2026-11-23 against a +//! missing table, with a parse failure answering ahead of it. use super::tests_support::{OK, and_chain, assert_outcomes, in_list, n, outcome, p}; diff --git a/crates/core/src/expression/search_filter/tests_rules.rs b/crates/core/src/expression/search_filter/tests_rules.rs index ea2c60f2c..90d10a4d7 100644 --- a/crates/core/src/expression/search_filter/tests_rules.rs +++ b/crates/core/src/expression/search_filter/tests_rules.rs @@ -4,11 +4,11 @@ //! The conditions a search condition records, and the condition limit. //! //! The recorded conditions are internal and have no answer of their own on -//! the wire. Every answer under the limit of 50 was measured against the live -//! service in eu-north-1, on an account with the extended grammar, on -//! 2026-11-23, each request twice with the same answer, against a missing -//! table; `Ok` stands for a request the service passed to the table lookup. -//! A limit of 1 or 3 exists only in these tests. +//! the wire. Every answer under the limit of 50 was measured against the +//! live service in eu-north-1 on 2026-11-23, each request twice with the +//! same answer, against a missing table; `Ok` stands for a request the +//! service passed to the table lookup. A limit of 1 or 3 exists only in +//! these tests. use super::rules::{Condition, Operator}; use super::tests_support::{ diff --git a/crates/core/src/expression/search_filter/tests_schema.rs b/crates/core/src/expression/search_filter/tests_schema.rs index 3f1b928b5..42b6df700 100644 --- a/crates/core/src/expression/search_filter/tests_schema.rs +++ b/crates/core/src/expression/search_filter/tests_schema.rs @@ -4,12 +4,11 @@ //! The search condition against the index search schema. //! //! Every expected answer was measured against the live service in -//! eu-north-1, on an account with the extended grammar, on 2026-11-23, each -//! request twice with the same answer, against a vector table with the -//! search schema of the case; `Ok` stands for a search the service answered -//! with 200, the accepted shapes of the two partition tests included. The -//! partition a condition selects is internal; the wire tests pin that the -//! HASH value scopes the search. +//! eu-north-1 on 2026-11-23, each request twice with the same answer, +//! against a vector table with the search schema of the case; `Ok` stands +//! for a search the service answered with 200, the accepted shapes of the +//! two partition tests included. The partition a condition selects is +//! internal; the wire tests pin that the HASH value scopes the search. use std::collections::HashMap; diff --git a/tests/test_search_vectors_condition_limit.py b/tests/test_search_vectors_condition_limit.py index 8ba6fc6c5..cdd7b3dab 100644 --- a/tests/test_search_vectors_condition_limit.py +++ b/tests/test_search_vectors_condition_limit.py @@ -3,10 +3,13 @@ """SearchVectors condition count limit and the order of the expression checks. -Measured against Amazon DynamoDB on 2026-10-29 and 2026-10-30 in us-east-1, on -a table whose vector index declares a HASH ``h`` and 18 inline filters ``f1`` -to ``f18``. Each request shape was sent twice with the same response both -times. +Under the equality-only grammar, measured against Amazon DynamoDB on +2026-10-29 and 2026-10-30 in us-east-1, before the service served the +extended grammar to every account, on a table whose vector index declares a +HASH ``h`` and 18 inline filters ``f1`` to ``f18``. Each request shape was +sent twice with the same response both times. ExtendDB serves this grammar +when the ``search_inequality_filters`` setting is ``off`` or does not name +the account. The limit is 19 comparisons. The 20th gets ``Invalid SearchConditionExpression: SearchConditionExpression cannot have more than 1 partition key and more than @@ -28,15 +31,15 @@ ExtendDB's wording differs from the service's. Those tests assert that the check, not the count, answers. -An account can have the extended grammar instead (comparators other than -``=``, OR, NOT, IN, BETWEEN, up to 50 conditions). The ``grammar`` fixture -asks the target which grammar it serves, by sending ``h = :v0 AND f1 <> :v1``: -the equality-only grammar refuses it with the comparator message and the -extended grammar answers 200. Against ExtendDB the fixture also reads the -``search_inequality_filters`` setting and fails when the answer is the other -grammar's. Each test then asserts the answer of that grammar. The extended -answers were measured on 2026-11-21 and 2026-11-23 in eu-north-1, on an -account with the extended grammar, each request twice: under it the 20th +The service now serves the extended grammar instead (comparators other than +``=``, OR, NOT, IN, BETWEEN, up to 50 conditions), and so does ExtendDB when +the setting is absent. The ``grammar`` fixture asks the target which grammar +it serves, by sending ``h = :v0 AND f1 <> :v1``: the equality-only grammar +refuses it with the comparator message and the extended grammar answers 200. +Against ExtendDB the fixture also reads the ``search_inequality_filters`` +setting and fails when the answer is the other grammar's. Each test then +asserts the answer of that grammar. The extended answers were measured on +2026-11-21 and 2026-11-23 in eu-north-1, each request twice: under it the 20th comparison is no fault of its own, and the schema, HASH and unused-value checks answer instead. diff --git a/tests/test_search_vectors_deep_conditions.py b/tests/test_search_vectors_deep_conditions.py index 5be644411..22a600286 100644 --- a/tests/test_search_vectors_deep_conditions.py +++ b/tests/test_search_vectors_deep_conditions.py @@ -9,11 +9,11 @@ each request the test sends a valid search, and against ExtendDB it also reads ``/health``. -Measured against the live service in eu-north-1, on an account with the -extended grammar, each request twice with the same answer, on 2026-11-23 on -this table and on a missing table; the 1500 and 4080 open parentheses also on -2026-11-22. Under the equality-only grammar the test asserts only that each -condition is refused and that the server keeps answering. +Measured against the live service in eu-north-1, each request twice with the +same answer, on 2026-11-23 on this table and on a missing table; the 1500 and +4080 open parentheses also on 2026-11-22. Under the equality-only grammar the +test asserts only that each condition is refused and that the server keeps +answering. The module skips when the target backend does not support vector indexes, unless ``EXTENDDB_EXPECT_VECTORS=1``, which makes that a failure. diff --git a/tests/test_search_vectors_expression_maps.py b/tests/test_search_vectors_expression_maps.py index 3b83f7a1d..f0ec111c2 100644 --- a/tests/test_search_vectors_expression_maps.py +++ b/tests/test_search_vectors_expression_maps.py @@ -7,10 +7,9 @@ answers do not depend on the grammar the account has. Every request here uses conditions both grammars accept, and the module runs under either one. -Measured against the live service in eu-north-1, on an account with the -extended grammar, each request twice with the same answer: on 2026-11-21, and -the 254, 255 and 256 byte keys and the empty maps against a missing table on -2026-11-23. +Measured against the live service in eu-north-1, each request twice with +the same answer: on 2026-11-21, and the 254, 255 and 256 byte keys and the +empty maps against a missing table on 2026-11-23. The module skips when the target backend does not support vector indexes, unless ``EXTENDDB_EXPECT_VECTORS=1``, which makes that a failure. diff --git a/tests/test_search_vectors_inequality_filters.py b/tests/test_search_vectors_inequality_filters.py index c07093de2..e15a85df1 100644 --- a/tests/test_search_vectors_inequality_filters.py +++ b/tests/test_search_vectors_inequality_filters.py @@ -3,14 +3,16 @@ """SearchVectors with the extended SearchConditionExpression grammar. -For an account the grammar is enabled for, a search condition takes ``<>``, -``<``, ``<=``, ``>``, ``>=``, BETWEEN, IN, OR, NOT, parentheses, -``attribute_exists`` and ``attribute_not_exists``, and more than one -condition on an attribute, up to 50 conditions. +Under the extended grammar, a search condition takes ``<>``, ``<``, ``<=``, +``>``, ``>=``, BETWEEN, IN, OR, NOT, parentheses, ``attribute_exists`` and +``attribute_not_exists``, and more than one condition on an attribute, up to +50 conditions. The service serves it to every account; ExtendDB serves it to +the accounts the ``search_inequality_filters`` setting names, every account +when the setting is absent. Every expected response was measured against the live service in -eu-north-1, on an account with the extended grammar, each request twice with -the same answer, on 2026-11-19 and 2026-11-21. +eu-north-1, each request twice with the same answer, on 2026-11-19 and +2026-11-21. The module probes one inequality search to learn the grammar the target serves. Against ExtendDB it also reads the ``search_inequality_filters`` From c477e00aea5066ae4ac7a5a78b82a54eb7832eed Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:27:51 +0000 Subject: [PATCH 034/101] test(server): pin SearchVectors dynamodb:Attributes and names map checks 1.0.0 read the SearchVectors ExpressionAttributeNames without the checks that the other operations run. It accepted a key such as n or ##n, and the projection removed every leading # from each key. So a search with ProjectionExpression #n returned the attribute that key named. Authorization finds a placeholder in the map as written. So dynamodb:Attributes did not hold that attribute, and a Deny on it did not refuse the search. DynamoDB refuses such a key on SearchVectors before it evaluates the policy. The message is the GetItem text: ExpressionAttributeNames contains invalid key: Syntax error; key: "n". It also answers an empty map, a key over 255 bytes and an empty attribute name as GetItem does. It answers an IndexName of two characters, an empty SearchVector and a TopK of 0 ahead of a bad key. A value that is not a string, such as 5, gets SerializationException (measured in us-east-1 on 2026-11-21). The handler already runs these checks after the TopK checks and ahead of the table lookup, so this commit adds no engine check. The input struct reads the map as strings, so a value of another JSON type keeps its SerializationException. The service sets no dynamodb:Attributes value on a SearchVectors request. A Deny gated on Null true refused every search. A Deny on an attribute refused none, whether the projection or the SearchConditionExpression named it. So the SearchConditionExpression names stay out of the key, and a unit test checks that. A wire test sends the measured rows under a Deny on ssn and under an Allow of dynamodb:*. The upgrade manual records the change. docs/differences-from-dynamodb.md records the difference in the key. Refs #729 --- crates/server/src/request_attributes.rs | 19 +- crates/server/src/request_attributes/tests.rs | 51 ++++- docs/differences-from-dynamodb.md | 1 + docs/manuals/07-upgrade-manual.md | 6 + tests/test_authz_search_vectors_index.py | 177 +++++++++++++++++- 5 files changed, 231 insertions(+), 23 deletions(-) diff --git a/crates/server/src/request_attributes.rs b/crates/server/src/request_attributes.rs index 3404240e6..37706c6d0 100644 --- a/crates/server/src/request_attributes.rs +++ b/crates/server/src/request_attributes.rs @@ -62,7 +62,11 @@ //! sort key, so the index's sort key is not in the key. The other rules for //! a local secondary index follow from that key content. //! - `SearchVectors`: the paths in `ProjectionExpression`. A `SearchVectors` -//! with no `ProjectionExpression` leaves the key absent. +//! with no `ProjectionExpression` leaves the key absent. The names in +//! `SearchConditionExpression` are not in it. On the service the key is +//! absent on every `SearchVectors` (measured 2026-11-21). A Deny gated on +//! `Null` `true` refused each one. A Deny on an attribute refused none, +//! whether the projection or the condition named it. //! - `BatchGetItem`: per table, the table's key attributes, `AttributesToGet`, //! and the paths in `ProjectionExpression`, as for `GetItem`. The names in //! `Keys` are not read: on a table that does not exist, under a Deny on the @@ -118,12 +122,13 @@ //! key attributes that the key already holds, so the service cannot show //! whether it adds names of its own there. //! -//! An expression is read with the tokenizer and parser the engine uses, under -//! the same size, token and depth limits, so on every operation other than -//! `SearchVectors` an expression the engine accepts gives all its names here. -//! `SearchVectors` matches a `#name` against `ExpressionAttributeNames` keys -//! with their leading `#` removed, so it accepts keys this module does not -//! resolve, and its `SearchConditionExpression` is not read here (both #729). +//! This module reads each expression the list above puts in the key with the +//! engine's tokenizer and parser. The same size, token and depth limits +//! apply, so an expression the engine accepts gives all its names here. This +//! module finds a `#name` in `ExpressionAttributeNames` as written. On every +//! operation the engine refuses a key that is not `#` followed by letters, +//! digits and underscores. So this module and the engine resolve each +//! placeholder to the same name. //! An expression the parser refuses gives none, and the engine refuses the //! same request without reading or writing an item. A key condition also //! goes through the engine's reserved-word check when diff --git a/crates/server/src/request_attributes/tests.rs b/crates/server/src/request_attributes/tests.rs index 7a4ecb2dc..4ac87d33b 100644 --- a/crates/server/src/request_attributes/tests.rs +++ b/crates/server/src/request_attributes/tests.rs @@ -525,18 +525,49 @@ fn scan_holds_its_filter_projection_and_start_key_names() { ); } +/// The paths in `ProjectionExpression` only. A key without `#` resolves no +/// name, and the engine refuses that request. The names in +/// `SearchConditionExpression` are not in the value: the service served a +/// search whose condition named `ssn` under a Deny on `ssn` (measured +/// 2026-11-21). #[test] fn search_vectors_holds_its_projected_paths() { - let input = json!({ - "TableName": "t", - "IndexName": "vi", - "ProjectionExpression": "#v.x, name", - "ExpressionAttributeNames": {"#v": "vec"}, - }); - assert_eq!( - single("SearchVectors", &input, Some(&hash_table())), - names(&["name", "vec"]) - ); + let v = || json!({":v": {"S": "1"}}); + let rows = [ + ( + "projected paths", + json!({ + "ProjectionExpression": "#v.x, name", + "ExpressionAttributeNames": {"#v": "vec"}, + }), + names(&["name", "vec"]), + ), + ( + "a key without #", + json!({"ProjectionExpression": "#n", "ExpressionAttributeNames": {"n": "ssn"}}), + None, + ), + ( + "a condition on ssn", + json!({ + "SearchConditionExpression": "ssn = :v", + "ExpressionAttributeValues": v(), + "ProjectionExpression": "cat", + }), + names(&["cat"]), + ), + ( + "a condition and no projection", + json!({"SearchConditionExpression": "ssn = :v", "ExpressionAttributeValues": v()}), + None, + ), + ]; + for (row, mut input, expected) in rows { + input["TableName"] = json!("t"); + input["IndexName"] = json!("vi"); + let found = single("SearchVectors", &input, Some(&hash_table())); + assert_eq!(found, expected, "{row}"); + } } #[test] diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index a88689353..cc892efeb 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -38,6 +38,7 @@ from a request sent to that service or backend. | Table ARN as `TableName` | Accepted; the request acts on that table | Authorized against that table, then the request fails with `ResourceNotFoundException` | | AccessDenied message for an ARN outside this deployment (caller with no policy) | Names the ARN as supplied. A table ARN in `TableName` with another partition, service or region never reaches the IAM decision: it is `ValidationException` ("Invalid AWS partition", "Invalid vendor code", "Invalid AWS region") for every principal (measured) | Names the ARN as supplied. A table ARN in `TableName` with another partition, service or region is authorized as this deployment's table, and a caller with no policy is denied naming the ARN as supplied | | A resource ARN in another account | Refused with the same answer for a caller allowed `dynamodb:*` on `*` and a caller with no policy. When the account exists: `AccessDeniedException` "User: is not authorized to perform: dynamodb: on resource: because no resource-based policy allows the dynamodb: action", except `CreateTable`, the time-to-live, continuous-backup, backup, export and restore operations, which answer `ValidationException` "This action is only supported by accounts that match the resource owner’s account.". When it does not: `AccessDeniedException` "The caller is not authorized to access the specified resource." on `GetItem`, `PutItem`, `UpdateItem`, `Query`, `Scan` and `BatchGetItem`, the same `ValidationException` on `RestoreTableToPointInTime`, and `AccessDeniedException` "Access is denied" on the rest. A batch or transaction with tables in more than one account is `ValidationException` "Invalid request! All tables in the request must be from a single account." (measured) | The same answers, before the IAM decision and in dev mode too, where an account exists when this deployment's catalog holds it. `RestoreTableToPointInTime` and an `UpdateContinuousBackups` that enables point-in-time recovery get the point-in-time recovery refusal instead (see "Point-in-time recovery" below). `DeleteTable`, `DeleteItem` and `DeleteBackup` take the answers of `UpdateTable`, `UpdateItem` and `DescribeBackup` (not measured). A table ARN in `TableName` that also has another partition, service or region, or that names an index or backup, gets these answers too. The service answers it with a `ValidationException` (the partition, vendor or region text in the row above, or "Valid ARN format is ..." for an index or backup ARN): on `GetItem` whether or not the account exists, and on `DescribeTable` when it exists (measured; the other operations were not sent) | +| `dynamodb:Attributes` on `SearchVectors` | Absent. A `Deny` gated on `Null` `true` refused each `SearchVectors` sent, a projected one included, and a `Deny` on an attribute refused none, whether `ProjectionExpression` or `SearchConditionExpression` named it (measured 2026-11-21) | Holds the attributes in `ProjectionExpression`, and is absent when there is none. A `Deny` on `ssn` refused a `SearchVectors` that projects `ssn`, and served one whose `SearchConditionExpression` alone names `ssn`. A `Deny` gated on `Null` `true` refused a `SearchVectors` with no `ProjectionExpression`, and served one that projects an attribute (measured 2026-11-21) | ## Import and Export diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 30be5d12d..0d79ce895 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -388,6 +388,12 @@ Catalog upgrades change the schema; behavior changes alter how the running serve interprets existing data or configuration. Review these before upgrading a live deployment, even when no catalog migration is required. +### v1.1.0: SearchVectors refuses a malformed `ExpressionAttributeNames` map + +**What changed.** SearchVectors refuses an `ExpressionAttributeNames` key that is not `#` followed by letters, digits and underscores, such as `n` or `##n`, with `ValidationException` `ExpressionAttributeNames contains invalid key: Syntax error; key: "n"`. It also refuses an empty map, a key longer than 255 bytes and an empty attribute name, with the messages GetItem gives. These checks run after the `IndexName`, `SearchVector` and `TopK` checks. DynamoDB answers SearchVectors with the same messages. It answered an `IndexName` of two characters, an empty `SearchVector` and a `TopK` of 0 ahead of a bad key (measured 2026-11-21). Earlier releases served such requests: a search with `ProjectionExpression` `#n` and the key `n` or `##n` returned the attribute the key named. `dynamodb:Attributes` did not hold that attribute, so a `Deny` on it did not refuse the search. + +**Who is affected.** A client that sends SearchVectors with such a map gets `ValidationException`, as it does on the other operations that take the map. No catalog migration is required. + ### v1.0.0: Cassandra reads and writes at `LOCAL_QUORUM` **What changed.** The Cassandra backend runs its reads and writes at `LOCAL_QUORUM`. 0.1.15 ran many of them at `ONE`, the driver's default, in each area: items (the reads of GetItem, Query and Scan among them), transactions, TTL, streams, the catalog, IAM and `init`. A read with `ConsistentRead` `false` also runs at `LOCAL_QUORUM`. A lightweight transaction runs Paxos at `LOCAL_SERIAL` and commits at `LOCAL_QUORUM`. 0.1.15 ran many of its lightweight transactions at those levels already, and others, among them the admin user creation and most IAM writes, at the driver's defaults, `SERIAL` and `ONE`. Batches ran at `LOCAL_QUORUM` before and still do. No setting changes these levels (#945). diff --git a/tests/test_authz_search_vectors_index.py b/tests/test_authz_search_vectors_index.py index a6d036bca..872631fda 100644 --- a/tests/test_authz_search_vectors_index.py +++ b/tests/test_authz_search_vectors_index.py @@ -13,6 +13,16 @@ An IndexName outside ``[a-zA-Z0-9_.-]+`` (``vidx/extra``) gets ValidationException for every caller, before the policy decision, as Query and Scan do. +The ``ROWS`` were measured on DynamoDB in us-east-1 on 2026-11-21, each +request twice with the same answer. The ``deny(ssn)`` rows ran under a session +policy that allows ``dynamodb:*`` and denies ``dynamodb:*`` under +``ForAnyValue:StringEquals {"dynamodb:Attributes": ["ssn"]}``, and the +``allow-all`` rows with no session policy. The service checks the +``ExpressionAttributeNames`` keys before the policy decision, and ExtendDB +decides the policy first. The service sets no ``dynamodb:Attributes`` value +on a SearchVectors request, so it serves a projection of ``ssn`` under +``deny(ssn)``. ExtendDB holds the projected names, so that row is not here. + The principals are builtin-IAM users provisioned through the management API. The module skips when the backend does not support vector indexes, unless ``EXTENDDB_EXPECT_VECTORS=1``, which makes that a failure. @@ -39,9 +49,12 @@ from management_helpers import ManagementClient from search_vectors_wire import expect_vectors as _expect_vectors +from search_vectors_wire import message as _error_message REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") VECTOR = [{"N": "0.1"}, {"N": "0.2"}, {"N": "0.3"}, {"N": "0.4"}] +KEY = {"pk": {"S": "p1"}} +SSN_ITEM = {"ssn": {"S": "123-45-6789"}} ALLOW_ALL = { "Version": "2012-10-17", @@ -138,7 +151,8 @@ def make(policy: dict) -> Principal: @pytest.fixture(scope="module") def vector_table(principal): - """A table with one item and an ACTIVE vector index ``vidx``.""" + """A table with one item and an ACTIVE vector index ``vidx`` whose search + schema holds ``cat`` and ``ssn``, as the measured table's did.""" expected = _expect_vectors() admin = principal(ALLOW_ALL) name = f"sv{uuid.uuid4().hex[:10]}" @@ -146,7 +160,9 @@ def vector_table(principal): "CreateTable", { "TableName": name, - "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "AttributeDefinitions": [ + {"AttributeName": a, "AttributeType": "S"} for a in ("pk", "cat", "ssn") + ], "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], "BillingMode": "PAY_PER_REQUEST", "VectorIndexes": [ @@ -155,6 +171,10 @@ def vector_table(principal): "Dimensions": 4, "DistanceFunction": "COSINE", "VectorAttribute": {"AttributeName": "emb"}, + "SearchSchema": [ + {"AttributeName": a, "SearchSchemaElementType": "INLINE_FILTER"} + for a in ("cat", "ssn") + ], "Projection": {"ProjectionType": "ALL"}, } ], @@ -176,18 +196,18 @@ def vector_table(principal): break assert time.monotonic() < deadline, f"{name} did not become ACTIVE: {table}" time.sleep(0.05) - item = {"pk": {"S": "p1"}, "emb": {"L": VECTOR}} + item = {**KEY, "emb": {"L": VECTOR}, "cat": {"S": "c1"}, **SSN_ITEM} put = admin.post("PutItem", {"TableName": name, "Item": item}) assert put.status_code == 200, put.text - yield {"name": name, "table_arn": table["TableArn"]} + yield {"name": name, "table_arn": table["TableArn"], "admin": admin} finally: admin.post("DeleteTable", {"TableName": name}) -def _search(p: Principal, table: str, index: str = "vidx") -> requests.Response: +def _search(p: Principal, table: str, index: str = "vidx", **members) -> requests.Response: return p.post( "SearchVectors", - {"TableName": table, "IndexName": index, "SearchVector": VECTOR, "TopK": 5}, + {"TableName": table, "IndexName": index, "SearchVector": VECTOR, "TopK": 5, **members}, ) @@ -264,3 +284,148 @@ def test_index_name_outside_the_pattern_is_refused_before_authorization( resp = _search(principal(policy), vector_table["name"], "vidx/extra") assert resp.status_code == 400, resp.text assert _error_type(resp) == "ValidationException", resp.text + + +# -- deny(ssn) --------------------------------------------------------------- + +DENY_SSN = { + "Version": "2012-10-17", + "Statement": [ + {"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}, + { + "Effect": "Deny", + "Action": "dynamodb:*", + "Resource": "*", + "Condition": {"ForAnyValue:StringEquals": {"dynamodb:Attributes": ["ssn"]}}, + }, + ], +} +SSN_VALUE = {":v": SSN_ITEM["ssn"]} +CAT_ONLY = [{"cat": {"S": "c1"}}] + + +LONG_KEY = "#" + "a" * 255 + + +def _invalid_key(key: str) -> str: + return f'ExpressionAttributeNames contains invalid key: Syntax error; key: "{key}"' + + +# The measured rows: the policy, the members added to the search, then the +# error type and message, or None and the items the search returns. +ROWS = { + "projection-key-without-hash": ( + "deny(ssn)", + {"ProjectionExpression": "#n", "ExpressionAttributeNames": {"n": "ssn"}}, + "ValidationException", + _invalid_key("n"), + ), + "projection-key-with-two-hashes": ( + "deny(ssn)", + {"ProjectionExpression": "#n", "ExpressionAttributeNames": {"##n": "ssn"}}, + "ValidationException", + _invalid_key("##n"), + ), + "condition-key-without-hash": ( + "deny(ssn)", + { + "SearchConditionExpression": "#s = :v", + "ExpressionAttributeNames": {"s": "ssn"}, + "ExpressionAttributeValues": SSN_VALUE, + "ProjectionExpression": "cat", + }, + "ValidationException", + _invalid_key("s"), + ), + "condition-on-ssn": ( + "deny(ssn)", + { + "SearchConditionExpression": "ssn = :v", + "ExpressionAttributeValues": SSN_VALUE, + "ProjectionExpression": "cat", + }, + None, + CAT_ONLY, + ), + "condition-on-ssn-by-placeholder": ( + "deny(ssn)", + { + "SearchConditionExpression": "#s = :v", + "ExpressionAttributeNames": {"#s": "ssn"}, + "ExpressionAttributeValues": SSN_VALUE, + "ProjectionExpression": "cat", + }, + None, + CAT_ONLY, + ), + "empty-map": ( + "allow-all", + {"ProjectionExpression": "cat", "ExpressionAttributeNames": {}}, + "ValidationException", + "ExpressionAttributeNames must not be empty", + ), + "key-of-256-bytes": ( + "allow-all", + {"ProjectionExpression": LONG_KEY, "ExpressionAttributeNames": {LONG_KEY: "ssn"}}, + "ValidationException", + "ExpressionAttributeNames contains invalid key: The expression attribute map " + "contains a key that is too long; size of key: 256", + ), + "empty-name": ( + "allow-all", + {"ProjectionExpression": "#n", "ExpressionAttributeNames": {"#n": ""}}, + "ValidationException", + "ExpressionAttributeNames contains invalid value: Empty attribute name for key #n", + ), + "top-k-of-zero-before-the-key-check": ( + "allow-all", + {"TopK": 0, "ProjectionExpression": "#n", "ExpressionAttributeNames": {"n": "ssn"}}, + "ValidationException", + "1 validation error detected: Value at 'TopK' failed to satisfy constraint: " + "Member must have value greater than or equal to 1", + ), + "value-not-a-string-text-tracked-by-1012": ( + "allow-all", + {"ProjectionExpression": "#n", "ExpressionAttributeNames": {"n": 5}}, + "SerializationException", + "invalid type: integer `5`, expected a string", + ), +} + + +@pytest.fixture(scope="module") +def deny_ssn(principal): + return principal(DENY_SSN) + + +def test_the_deny_on_ssn_refuses_a_get_item_of_ssn(deny_ssn, vector_table): + # The control: the policy is in force for this principal. + resp = deny_ssn.post( + "GetItem", + {"TableName": vector_table["name"], "Key": KEY, "ProjectionExpression": "ssn"}, + ) + assert resp.status_code == 400, resp.text + assert _error_type(resp) == "AccessDeniedException", resp.text + message = _error_message(resp) + assert "perform: dynamodb:GetItem on resource:" in message, message + assert "with an explicit deny in an identity-based policy" in message, message + + +@pytest.mark.parametrize("row", list(ROWS)) +def test_search_expression_attribute_names(deny_ssn, vector_table, row): + policy, members, error, expected = ROWS[row] + p = deny_ssn if policy == "deny(ssn)" else vector_table["admin"] + resp = _search(p, vector_table["name"], **members) + if error is None: + assert resp.status_code == 200, f"{row}: {resp.text}" + assert [r["Item"] for r in resp.json()["SearchResults"]] == expected, row + else: + assert resp.status_code == 400, f"{row}: {resp.text}" + assert _error_type(resp) == error, f"{row}: {resp.text}" + message = _error_message(resp) + if error == "SerializationException": + # The service ends this text with the position in the body, and + # ExtendDB puts a sentence of its own before it. + assert expected in message, f"{row}: {message}" + else: + assert message == expected, f"{row}: {message}" From 501ff421df88703cd2a5c00bbe88ee98ba0c3b48 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 16:16:58 +0000 Subject: [PATCH 035/101] docs(upgrade): record the SearchVectors grammar and map checks of 1.1.0 DynamoDB serves the extended SearchConditionExpression grammar to every account, compares a Number in the condition as binary64, and checks both expression maps of SearchVectors ahead of the table lookup. It answers an empty or a too large attribute name ahead of a bad key: {"n": ""} gets the empty-name message, and {"": "cat"} gets "The expression attribute map contains an empty key;" (measured in eu-north-1 and us-east-1 on 2026-11-24, each shape twice). The upgrade manual had a 1.1.0 note for the ExpressionAttributeNames key check only. 1.0.0 is released, and the next release with these changes is 1.1.0. The manual now has a 1.1.0 note for the grammar, the binary64 Number comparison and the search_inequality_filters setting, and the map note lists the other map checks and their order. --- docs/manuals/07-upgrade-manual.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 0d79ce895..e8549db95 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -388,9 +388,17 @@ Catalog upgrades change the schema; behavior changes alter how the running serve interprets existing data or configuration. Review these before upgrading a live deployment, even when no catalog migration is required. +### v1.1.0: SearchVectors serves the extended `SearchConditionExpression` grammar + +**What changed.** A `SearchConditionExpression` takes the comparators `<>`, `<`, `<=`, `>` and `>=`, `BETWEEN`, `IN`, `OR`, `NOT`, parentheses, `attribute_exists` and `attribute_not_exists`, and more than one condition on an attribute, up to 50 conditions. DynamoDB serves this grammar to every account. Earlier releases accepted only an AND of equalities, at most 19, and refused the other forms with `ValidationException`. A Number in the condition now compares as the nearest binary64 value of each side, as on DynamoDB, so `9007199254740992` and `9007199254740993` are equal. Earlier releases compared Numbers in the condition exactly. + +The `search_inequality_filters` runtime setting selects the accounts that get the grammar: `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. With `off`, or for an account the list does not name, a search condition is an AND of equalities, compared as in earlier releases. A server reads the setting at most once a second, so a change applies within about a second without a restart. A read of the setting that fails or does not end within two seconds answers `ServiceUnavailableException`. A malformed value in the catalog is logged once per change and enables every account. The [admin guide](05-admin-guide.md) lists the setting. + +**Who is affected.** A client that sent one of these forms got `ValidationException` and now gets the items the condition selects. A client whose condition compares Numbers that differ only after the 15th significant digit can get other items. To keep the earlier grammar, run `extenddb settings --config extenddb.toml set search_inequality_filters off` after the upgrade. MongoDB and Cassandra refuse SearchVectors, as before. No catalog migration is required. + ### v1.1.0: SearchVectors refuses a malformed `ExpressionAttributeNames` map -**What changed.** SearchVectors refuses an `ExpressionAttributeNames` key that is not `#` followed by letters, digits and underscores, such as `n` or `##n`, with `ValidationException` `ExpressionAttributeNames contains invalid key: Syntax error; key: "n"`. It also refuses an empty map, a key longer than 255 bytes and an empty attribute name, with the messages GetItem gives. These checks run after the `IndexName`, `SearchVector` and `TopK` checks. DynamoDB answers SearchVectors with the same messages. It answered an `IndexName` of two characters, an empty `SearchVector` and a `TopK` of 0 ahead of a bad key (measured 2026-11-21). Earlier releases served such requests: a search with `ProjectionExpression` `#n` and the key `n` or `##n` returned the attribute the key named. `dynamodb:Attributes` did not hold that attribute, so a `Deny` on it did not refuse the search. +**What changed.** SearchVectors refuses an `ExpressionAttributeNames` key that is not `#` followed by letters, digits and underscores, such as `n` or `##n`, with `ValidationException` `ExpressionAttributeNames contains invalid key: Syntax error; key: "n"`. It also refuses an empty map, a key longer than 255 bytes and an empty attribute name, with the messages GetItem gives. SearchVectors also refuses an empty key, an attribute name of 65536 bytes or more, an empty `ExpressionAttributeValues` map or a malformed key in it, either map without an expression that reads it, and a name that no expression uses. An empty attribute name or a name of 65536 bytes or more answers ahead of a bad key. These checks run after the `IndexName`, `SearchVector` and `TopK` checks and ahead of the table lookup. DynamoDB answers SearchVectors with the same messages in the same order. It answered an `IndexName` of two characters, an empty `SearchVector` and a `TopK` of 0 ahead of a bad key (measured 2026-11-21), and an empty or a too large attribute name ahead of a bad key (measured 2026-11-24). Earlier releases served such requests: a search with `ProjectionExpression` `#n` and the key `n` or `##n` returned the attribute the key named. `dynamodb:Attributes` did not hold that attribute, so a `Deny` on it did not refuse the search. **Who is affected.** A client that sends SearchVectors with such a map gets `ValidationException`, as it does on the other operations that take the map. No catalog migration is required. From 120d0b15781519c3061dd60e8ace32b97b7d6b0f Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 16:19:37 +0000 Subject: [PATCH 036/101] test(search): pin a bad name ahead of a bad key in the names map DynamoDB checks every attribute name in ExpressionAttributeNames before any key on SearchVectors. {"n": ""} answers "Empty attribute name for key n" and {"n": 65536 bytes} answers "Attribute name is too large", not the key syntax error (measured in eu-north-1 and us-east-1 on 2026-11-24, each shape twice; two bad keys answered either key, so no test pins that). ExtendDB already answers in this order. A unit test pinned the empty name ahead of a bad key. No test pinned the too-large name ahead of a bad key, and no wire test pinned either order. The deserializer the other operations use checks each key before its name. The expression maps module now sends both shapes. --- tests/test_search_vectors_expression_maps.py | 25 ++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/tests/test_search_vectors_expression_maps.py b/tests/test_search_vectors_expression_maps.py index f0ec111c2..6780f6bdd 100644 --- a/tests/test_search_vectors_expression_maps.py +++ b/tests/test_search_vectors_expression_maps.py @@ -8,8 +8,9 @@ conditions both grammars accept, and the module runs under either one. Measured against the live service in eu-north-1, each request twice with -the same answer: on 2026-11-21, and the 254, 255 and 256 byte keys and the -empty maps against a missing table on 2026-11-23. +the same answer: on 2026-11-21, the 254, 255 and 256 byte keys and the +empty maps against a missing table on 2026-11-23, and a bad name ahead of a +bad key, also in us-east-1, on 2026-11-24. The module skips when the target backend does not support vector indexes, unless ``EXTENDDB_EXPECT_VECTORS=1``, which makes that a failure. @@ -155,6 +156,26 @@ def test_keys_and_names(self, table): fields["ExpressionAttributeNames"] = names refused(_raw(table, **fields), expected) + def test_a_bad_name_answers_ahead_of_a_bad_key(self, table): + """The service checks every name before any key. Measured in + eu-north-1 and us-east-1 on 2026-11-24.""" + cases = [ + ({"n": ""}, + "ExpressionAttributeNames contains invalid value: Empty attribute name for key n"), + ({"n": "C" * 65536}, + "Attribute name is too large, must be less than 65536 bytes for key n"), + ] + for names, expected in cases: + refused( + _raw( + table, + SearchConditionExpression="Country = :us", + ExpressionAttributeNames=names, + ExpressionAttributeValues=US, + ), + expected, + ) + @pytest.mark.parametrize("size", [254, 255, 256]) def test_a_key_is_at_most_255_bytes(self, table, size): name_key = "#" + "a" * (size - 1) From e9f5747b7cfc62ab4da2e3a16b900f2c26a28104 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 19:43:01 +0000 Subject: [PATCH 037/101] refactor(engine): move the SearchVectors request checks to a module The SearchVectors handler file held the request body, the IndexName, SearchVector and TopK bounds, and the SearchVector conversion next to the handler itself. They move unchanged to search_vectors_request.rs, so the checks that run before the table lookup can be shared without growing the handler file. No behaviour changes. The engine's search_vectors unit tests pass. --- crates/engine/src/search_vectors.rs | 85 ++------------------- crates/engine/src/search_vectors_request.rs | 85 +++++++++++++++++++++ 2 files changed, 93 insertions(+), 77 deletions(-) create mode 100644 crates/engine/src/search_vectors_request.rs diff --git a/crates/engine/src/search_vectors.rs b/crates/engine/src/search_vectors.rs index 4c74ecb8a..774b67e12 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -10,51 +10,24 @@ use std::collections::HashMap; -use serde::{Deserialize, Serialize}; +use serde::Serialize; use serde_json::Value; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ExpressionMaps, Projection}; -use extenddb_core::types::{ - AttributeValue, DescribeTableInput, Item, ReturnConsumedCapacity, item_size_bytes, -}; +use extenddb_core::types::{DescribeTableInput, Item, ReturnConsumedCapacity, item_size_bytes}; #[path = "search_vectors_condition.rs"] mod condition; +#[path = "search_vectors_request.rs"] +mod request; + use crate::OperationContext; use crate::create_table::storage_err_to_dynamo; use crate::serialize_output; use crate::{DispatchMetrics, DispatchResult}; - -/// Minimum length of a vector index name. -const MIN_INDEX_NAME_LENGTH: usize = 3; -/// Maximum number of nearest neighbors a single search may request. -const MAX_TOP_K: i64 = 100; -/// Maximum number of elements in a search vector. -const MAX_SEARCH_VECTOR_LENGTH: usize = 4096; -/// `SearchVectors` request body. -#[derive(Debug, Clone, Deserialize)] -struct SearchVectorsInput { - #[serde(rename = "TableName")] - table_name: String, - #[serde(rename = "IndexName")] - index_name: String, - #[serde(rename = "SearchVector")] - search_vector: Vec, - #[serde(rename = "TopK")] - top_k: i64, - #[serde(rename = "SearchConditionExpression")] - search_condition_expression: Option, - #[serde(rename = "ProjectionExpression")] - projection_expression: Option, - #[serde(rename = "ExpressionAttributeNames")] - expression_attribute_names: Option>, - #[serde(rename = "ExpressionAttributeValues")] - expression_attribute_values: Option>, - #[serde(rename = "ReturnConsumedCapacity", default)] - return_consumed_capacity: ReturnConsumedCapacity, -} +use request::{MAX_TOP_K, MIN_INDEX_NAME_LENGTH, SearchVectorsInput, parse_search_vector}; /// A single search result: the item plus its similarity score. #[derive(Debug, Serialize)] @@ -332,50 +305,6 @@ pub async fn handle_search_vectors( }) } -/// Validate a `SearchVector` and convert it into `f32`. -/// -/// Checks the length bounds (1..=`MAX_SEARCH_VECTOR_LENGTH`) and that every -/// element is a finite number before converting. -fn parse_search_vector(values: &[AttributeValue]) -> Result, DynamoDbError> { - if values.is_empty() { - return Err(DynamoDbError::ValidationException( - "1 validation error detected: Value at 'SearchVector' failed to satisfy constraint: \ - Member must have length greater than or equal to 1" - .to_owned(), - )); - } - if values.len() > MAX_SEARCH_VECTOR_LENGTH { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value at 'SearchVector' failed to satisfy constraint: \ - Member must have length less than or equal to {MAX_SEARCH_VECTOR_LENGTH}" - ))); - } - let mut out = Vec::with_capacity(values.len()); - for v in values { - match v { - AttributeValue::N(n) => { - let f = n.parse::().map_err(|_| { - DynamoDbError::ValidationException( - "Search vector contains invalid values. All values in the search vector must be a 32-bit floating-point number attribute".to_owned(), - ) - })?; - if !f.is_finite() { - return Err(DynamoDbError::ValidationException( - "Search vector contains invalid values. All values in the search vector must be a 32-bit floating-point number attribute".to_owned(), - )); - } - out.push(f); - } - _ => { - return Err(DynamoDbError::ValidationException( - "Search vector contains invalid values. All values in the search vector must be a 32-bit floating-point number attribute".to_owned(), - )); - } - } - } - Ok(out) -} - /// Bytes reported as `ConsumedCapacity.VectorSearchRequestBytes` for one search. /// /// `returned_non_vector_bytes` is the summed stored size of the items actually @@ -454,8 +383,10 @@ mod order_tests; #[cfg(test)] mod tests { use super::condition::resolve_search_scope; + use super::request::MAX_SEARCH_VECTOR_LENGTH; use super::*; use extenddb_core::expression::SearchCondition; + use extenddb_core::types::AttributeValue; use extenddb_core::types::{ AttributeDefinition, ScalarAttributeType, SearchSchemaElement, SearchSchemaElementType, }; diff --git a/crates/engine/src/search_vectors_request.rs b/crates/engine/src/search_vectors_request.rs new file mode 100644 index 000000000..d180fdeb4 --- /dev/null +++ b/crates/engine/src/search_vectors_request.rs @@ -0,0 +1,85 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The `SearchVectors` request body and the checks of its `IndexName`, +//! `SearchVector` and `TopK`. + +use std::collections::HashMap; + +use serde::Deserialize; + +use extenddb_core::error::DynamoDbError; +use extenddb_core::types::{AttributeValue, ReturnConsumedCapacity}; + +/// Minimum length of a vector index name. +pub(super) const MIN_INDEX_NAME_LENGTH: usize = 3; +/// Maximum number of nearest neighbors a single search may request. +pub(super) const MAX_TOP_K: i64 = 100; +/// Maximum number of elements in a search vector. +pub(super) const MAX_SEARCH_VECTOR_LENGTH: usize = 4096; +/// `SearchVectors` request body. +#[derive(Debug, Clone, Deserialize)] +pub(super) struct SearchVectorsInput { + #[serde(rename = "TableName")] + pub(super) table_name: String, + #[serde(rename = "IndexName")] + pub(super) index_name: String, + #[serde(rename = "SearchVector")] + pub(super) search_vector: Vec, + #[serde(rename = "TopK")] + pub(super) top_k: i64, + #[serde(rename = "SearchConditionExpression")] + pub(super) search_condition_expression: Option, + #[serde(rename = "ProjectionExpression")] + pub(super) projection_expression: Option, + #[serde(rename = "ExpressionAttributeNames")] + pub(super) expression_attribute_names: Option>, + #[serde(rename = "ExpressionAttributeValues")] + pub(super) expression_attribute_values: Option>, + #[serde(rename = "ReturnConsumedCapacity", default)] + pub(super) return_consumed_capacity: ReturnConsumedCapacity, +} + +/// Validate a `SearchVector` and convert it into `f32`. +/// +/// Checks the length bounds (1..=`MAX_SEARCH_VECTOR_LENGTH`) and that every +/// element is a finite number before converting. +pub(super) fn parse_search_vector(values: &[AttributeValue]) -> Result, DynamoDbError> { + if values.is_empty() { + return Err(DynamoDbError::ValidationException( + "1 validation error detected: Value at 'SearchVector' failed to satisfy constraint: \ + Member must have length greater than or equal to 1" + .to_owned(), + )); + } + if values.len() > MAX_SEARCH_VECTOR_LENGTH { + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value at 'SearchVector' failed to satisfy constraint: \ + Member must have length less than or equal to {MAX_SEARCH_VECTOR_LENGTH}" + ))); + } + let mut out = Vec::with_capacity(values.len()); + for v in values { + match v { + AttributeValue::N(n) => { + let f = n.parse::().map_err(|_| { + DynamoDbError::ValidationException( + "Search vector contains invalid values. All values in the search vector must be a 32-bit floating-point number attribute".to_owned(), + ) + })?; + if !f.is_finite() { + return Err(DynamoDbError::ValidationException( + "Search vector contains invalid values. All values in the search vector must be a 32-bit floating-point number attribute".to_owned(), + )); + } + out.push(f); + } + _ => { + return Err(DynamoDbError::ValidationException( + "Search vector contains invalid values. All values in the search vector must be a 32-bit floating-point number attribute".to_owned(), + )); + } + } + } + Ok(out) +} From fda5e7d68393b90e380775582180fca0a5f1ed09 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 19:46:32 +0000 Subject: [PATCH 038/101] fix(engine): use the last read search filter setting through a fault A read of the search_inequality_filters setting that failed or outlasted READ_TIMEOUT answered ServiceUnavailableException, and the answer was kept for REFRESH. While the PostgreSQL catalog settings table was held under an exclusive lock, every search with a SearchConditionExpression answered 503, an AND of string equalities included, which a build without the setting serves. A server now keeps the value of its last read that answered. A read that fails or outlasts READ_TIMEOUT uses it, and a change through the management API leaves it. A request does not wait on a read another request waits on, or on one that outlasted READ_TIMEOUT, once a read answered after the last change. Before any read has answered, a fault still answers ServiceUnavailableException. Three unit tests pin the fallback after a failed read, after a read that does not end, and while another request waits on a read. On a PostgreSQL release server, with the settings table under LOCK TABLE ... IN ACCESS EXCLUSIVE MODE for 8 s, after one search had read the setting: an inequality, a Number equality and a string equality search answered 200 in each of three rounds, twice, where the earlier build answered 503 to all three from the second round on. On a PostgreSQL release server, with the settings table under LOCK TABLE ... IN ACCESS EXCLUSIVE MODE for 8 s, after one search had read the setting: an inequality, a Number equality and a string equality search answered 200 in each of three rounds, twice, where the earlier build answered 503 to all three from the second round on. --- crates/engine/src/search_vectors_settings.rs | 57 ++++++++-- .../src/search_vectors_settings_tests.rs | 103 +++++++++++++++++- 2 files changed, 149 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/search_vectors_settings.rs b/crates/engine/src/search_vectors_settings.rs index ad9eeee16..ff916678f 100644 --- a/crates/engine/src/search_vectors_settings.rs +++ b/crates/engine/src/search_vectors_settings.rs @@ -12,9 +12,12 @@ //! A read is kept for [`REFRESH`], so a busy server reads the catalog about //! once per interval rather than once per request, and a change made through //! the management API applies at once through -//! [`search_filter_settings_changed`]. A read that fails or outlasts -//! [`READ_TIMEOUT`] answers `ServiceUnavailableException`, as other transient -//! storage faults do; it never changes which grammar an account gets. +//! [`search_filter_settings_changed`]. When a read fails or outlasts +//! [`READ_TIMEOUT`], the server uses the value of its last read that +//! answered, a change through the management API notwithstanding. Before any +//! read has answered, such a read answers `ServiceUnavailableException`, as +//! other transient storage faults do. A fault never changes which grammar an +//! account gets. //! //! A server sends at most one read of the setting at a time. A read that //! outlasts [`READ_TIMEOUT`] keeps running in its own task, and the next @@ -99,7 +102,8 @@ struct Kept { read_at: Instant, /// The stored value, so a malformed value is logged once per change. raw: Option, - /// `None` when the read failed. + /// The value of the last read that answered, this one or an earlier one. + /// `None` when no read has answered yet. accounts: Option, } @@ -113,6 +117,10 @@ struct InFlight { struct Settings { store: Arc, kept: Mutex>, + /// The value of the last read that answered, with the value of + /// [`Settings::changes`] when it was sent. A change through the management + /// API leaves it, so a read that fails after a change uses it. + last: Mutex>, /// How many times the management API changed the setting, so a read /// sent before a change is not used after it. changes: Mutex, @@ -128,6 +136,7 @@ impl Settings { Self { store, kept: Mutex::new(None), + last: Mutex::new(None), changes: Mutex::new(0), reading: tokio::sync::Mutex::new(None), } @@ -139,6 +148,22 @@ impl Settings { *kept = None; } + /// The value of the last read that answered. + fn last(&self) -> Option { + let last = self.last.lock().unwrap_or_else(PoisonError::into_inner); + last.as_ref().map(|(_, accounts)| accounts.clone()) + } + + /// The value of the last read that answered, when no change through the + /// management API came after it was sent. + fn unchanged_last(&self) -> Option { + let last = self.last.lock().unwrap_or_else(PoisonError::into_inner); + let changes = self.changes(); + last.as_ref() + .filter(|(sent, _)| *sent == changes) + .map(|(_, accounts)| accounts.clone()) + } + fn changes(&self) -> u64 { *self.changes.lock().unwrap_or_else(PoisonError::into_inner) } @@ -164,7 +189,16 @@ impl Settings { if let Some(answer) = self.fresh() { return answer; } - let mut reading = self.reading.lock().await; + // A request does not wait on a read that another request waits on, or + // that outlasted READ_TIMEOUT, when an earlier read answered after the + // last change: it uses that read's value. + let mut reading = match self.reading.try_lock() { + Ok(reading) => reading, + Err(_) => match self.unchanged_last() { + Some(accounts) => return Ok(accounts), + None => self.reading.lock().await, + }, + }; if let Some(answer) = self.fresh() { return answer; } @@ -176,6 +210,11 @@ impl Settings { { *reading = None; } + if reading.as_ref().is_some_and(|r| !r.task.is_finished()) + && let Some(accounts) = self.unchanged_last() + { + return Ok(accounts); + } let in_flight = reading.get_or_insert_with(|| self.send_read()); let sent = in_flight.changes; let read = tokio::time::timeout(READ_TIMEOUT, &mut in_flight.task).await; @@ -190,21 +229,23 @@ impl Settings { if let Some(ignored) = ignored { tracing::warn!("{ignored}"); } + *self.last.lock().unwrap_or_else(PoisonError::into_inner) = + Some((sent, accounts.clone())); (raw, Some(accounts)) } Ok(Ok(Err(e))) => { tracing::warn!("{SEARCH_INEQUALITY_FILTERS} could not be read: {e:?}"); - (previous, None) + (previous, self.last()) } Ok(Err(e)) => { tracing::warn!("{SEARCH_INEQUALITY_FILTERS} could not be read: {e}"); - (previous, None) + (previous, self.last()) } Err(_) => { tracing::warn!( "{SEARCH_INEQUALITY_FILTERS} could not be read within {READ_TIMEOUT:?}" ); - (previous, None) + (previous, self.last()) } }; let answer = accounts.clone().ok_or_else(unavailable); diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index 143add3bc..8b6f4880e 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -180,6 +180,7 @@ async fn each_server_reads_its_own_store() { ); } +/// Before any read has answered, a read that fails is a retryable fault. #[tokio::test] async fn a_failed_read_is_a_retryable_fault() { let store = Store::new(Answer::Fail); @@ -225,12 +226,19 @@ async fn a_read_is_kept_for_the_refresh_interval() { ); assert_eq!(store.reads(), 2); - // a fault is kept as briefly, then the next read recovers + // a fault keeps the last value read as briefly, then the next read + // recovers store.set(Answer::Fail); tokio::time::advance(REFRESH).await; - assert!(is_unavailable(&settings.enabled_accounts().await)); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); store.set(Answer::Value(None)); - assert!(is_unavailable(&settings.enabled_accounts().await)); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); tokio::time::advance(REFRESH).await; assert_eq!( settings.enabled_accounts().await.unwrap(), @@ -329,6 +337,95 @@ async fn a_change_applies_while_an_earlier_read_has_not_ended() { assert_eq!(store.reads(), 2); } +/// A read that fails, after an earlier read answered, uses the value of the +/// earlier read, a change through the management API notwithstanding. +#[tokio::test(start_paused = true)] +async fn a_failed_read_uses_the_last_value_read() { + let store = Store::value("off"); + let settings = Settings::new(store.clone()); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + store.set(Answer::Fail); + tokio::time::advance(REFRESH).await; + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + settings.changed(); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + assert_eq!(store.reads(), 3); +} + +/// A read that does not end, after an earlier read answered, is waited on +/// once for READ_TIMEOUT. Later requests use the earlier value at once while +/// it has not ended, and send no read of their own. +#[tokio::test(start_paused = true)] +async fn a_read_that_does_not_end_uses_the_last_value_read() { + let store = Store::value("off"); + let settings = Settings::new(store.clone()); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + store.set(Answer::Hang); + tokio::time::advance(REFRESH).await; + let started = tokio::time::Instant::now(); + // the test's own deadline, so a read without a bound fails here + let answer = tokio::time::timeout(READ_TIMEOUT * 2, settings.enabled_accounts()) + .await + .expect("the read is bounded"); + assert_eq!(answer.unwrap(), EnabledAccounts::Off); + assert_eq!(started.elapsed(), READ_TIMEOUT); + for _ in 0..5 { + tokio::time::advance(REFRESH).await; + let started = tokio::time::Instant::now(); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + assert_eq!(started.elapsed(), std::time::Duration::ZERO); + } + assert_eq!(store.reads(), 2); +} + +/// A request does not wait on a read another request is waiting on when an +/// earlier read answered: it uses the earlier value, and the waiting request +/// gets the new one. +#[tokio::test(start_paused = true)] +async fn a_request_does_not_wait_on_a_read_in_flight_once_a_value_was_read() { + let store = Store::value("off"); + let settings = Arc::new(Settings::new(store.clone())); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + let gate = Arc::new(Notify::new()); + store.set(Answer::Gated(Arc::clone(&gate), "all".to_owned())); + tokio::time::advance(REFRESH).await; + let waiting = { + let settings = Arc::clone(&settings); + tokio::spawn(async move { settings.enabled_accounts().await }) + }; + while store.reads() < 2 { + tokio::task::yield_now().await; + } + let started = tokio::time::Instant::now(); + // the test's own deadline, so a request that waits on the read fails here + let answer = tokio::time::timeout(READ_TIMEOUT / 2, settings.enabled_accounts()) + .await + .expect("the request does not wait on the read"); + assert_eq!(answer.unwrap(), EnabledAccounts::Off); + assert_eq!(started.elapsed(), std::time::Duration::ZERO); + gate.notify_one(); + assert_eq!(waiting.await.unwrap().unwrap(), EnabledAccounts::All); + assert_eq!(store.reads(), 2); +} + /// Poison `lock` with a thread that panics while holding it. fn poison(lock: &Mutex) { std::thread::scope(|s| { From 474a8a198a090ed50beb527fcbbfd63c00fde707 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 19:49:02 +0000 Subject: [PATCH 039/101] fix(engine): enable no account for a malformed search filter setting The CLI and the management API refuse a malformed search_inequality_filters value, so only a direct edit of the catalog stores one. A server that read such a value, `OFF` for example, logged it and gave every account the extended grammar. A value that an operator wrote to restrict the grammar then enabled it everywhere. A malformed value now enables no account and is logged once per change as "enables no account". The refusal text names the empty value, which the validator accepts and which means every account: "must be empty, 'off', 'all', or a comma-separated list of 12-digit account IDs". The settings unit tests pin the parse and the log line. --- .../core/src/expression/search_filter/gate.rs | 5 ++--- crates/engine/src/search_vectors_settings.rs | 13 ++++++----- .../src/search_vectors_settings_tests.rs | 22 +++++++++---------- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/crates/core/src/expression/search_filter/gate.rs b/crates/core/src/expression/search_filter/gate.rs index 490267889..672dfab58 100644 --- a/crates/core/src/expression/search_filter/gate.rs +++ b/crates/core/src/expression/search_filter/gate.rs @@ -39,9 +39,8 @@ impl EnabledAccounts { for entry in value.split(',') { let account = entry.trim(); if account.len() != 12 || !account.bytes().all(|b| b.is_ascii_digit()) { - return Err( - "must be 'off', 'all', or a comma-separated list of 12-digit account IDs", - ); + return Err("must be empty, 'off', 'all', or a comma-separated list of \ + 12-digit account IDs"); } accounts.insert(account.to_owned()); } diff --git a/crates/engine/src/search_vectors_settings.rs b/crates/engine/src/search_vectors_settings.rs index ff916678f..28d0f265d 100644 --- a/crates/engine/src/search_vectors_settings.rs +++ b/crates/engine/src/search_vectors_settings.rs @@ -7,7 +7,7 @@ //! [`install_search_filter_settings`], so two servers in one process read //! their own catalogs. An absent or empty value enables every account, as //! does a storage engine without an installed store. A malformed value is -//! logged once per change and enables every account. +//! logged once per change and enables no account. //! //! A read is kept for [`REFRESH`], so a busy server reads the catalog about //! once per interval rather than once per request, and a change made through @@ -73,7 +73,7 @@ pub fn search_filter_settings_changed() { } /// The accounts the setting enables on the server that `storage` belongs -/// to. An absent, empty or malformed value enables every account. +/// to. An absent or empty value enables every account, a malformed one none. /// /// # Errors /// @@ -261,7 +261,7 @@ impl Settings { /// The accounts a stored value enables, and the line to log when the /// value is malformed and differs from the previous read. An absent - /// value, like a malformed one, enables every account. + /// value enables every account, a malformed one none. fn parse(raw: Option<&str>, previous: Option<&str>) -> (EnabledAccounts, Option) { let Some(value) = raw else { return (EnabledAccounts::All, None); @@ -269,9 +269,10 @@ impl Settings { match EnabledAccounts::parse(value) { Ok(accounts) => (accounts, None), Err(reason) => ( - EnabledAccounts::All, - (previous != Some(value)) - .then(|| format!("{SEARCH_INEQUALITY_FILTERS} = {value:?} ignored: {reason}")), + EnabledAccounts::Off, + (previous != Some(value)).then(|| { + format!("{SEARCH_INEQUALITY_FILTERS} = {value:?} enables no account: {reason}") + }), ), } } diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index 8b6f4880e..cb3f47a80 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -136,21 +136,21 @@ async fn off_and_a_list_still_restrict_the_grammar() { assert!(!listed.enabled_for("222222222222", None)); } -/// A malformed value enables every account and is logged once per change. +/// A malformed value enables no account and is logged once per change. #[test] -fn a_malformed_value_is_logged_once_and_enables_every_account() { +fn a_malformed_value_is_logged_once_and_enables_no_account() { let (accounts, logged) = Settings::parse(Some("on"), None); - assert_eq!(accounts, EnabledAccounts::All); + assert_eq!(accounts, EnabledAccounts::Off); assert_eq!( logged.as_deref(), Some( - "search_inequality_filters = \"on\" ignored: must be 'off', 'all', or a \ - comma-separated list of 12-digit account IDs" + "search_inequality_filters = \"on\" enables no account: must be empty, 'off', \ + 'all', or a comma-separated list of 12-digit account IDs" ) ); assert_eq!( Settings::parse(Some("on"), Some("on")), - (EnabledAccounts::All, None) + (EnabledAccounts::Off, None) ); assert!(Settings::parse(Some("on"), Some("off")).1.is_some()); } @@ -516,7 +516,7 @@ async fn a_server_logs_a_malformed_value_once_per_change() { for _ in 0..3 { assert_eq!( settings.enabled_accounts().await.unwrap(), - EnabledAccounts::All + EnabledAccounts::Off ); tokio::time::advance(REFRESH).await; } @@ -524,15 +524,15 @@ async fn a_server_logs_a_malformed_value_once_per_change() { tokio::time::advance(REFRESH).await; assert_eq!( settings.enabled_accounts().await.unwrap(), - EnabledAccounts::All + EnabledAccounts::Off ); assert_eq!(store.reads(), 4); - let reason = "must be 'off', 'all', or a comma-separated list of 12-digit account IDs"; + let reason = "must be empty, 'off', 'all', or a comma-separated list of 12-digit account IDs"; assert_eq!( *warnings.0.lock().unwrap(), [ - format!("search_inequality_filters = \"on\" ignored: {reason}"), - format!("search_inequality_filters = \"true\" ignored: {reason}"), + format!("search_inequality_filters = \"on\" enables no account: {reason}"), + format!("search_inequality_filters = \"true\" enables no account: {reason}"), ] ); } From aa9d69e3e267480e849e97d32c219775e0a3d6af Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 19:49:02 +0000 Subject: [PATCH 040/101] fix(app): show the default of the search filter setting With no row in the catalog, `extenddb settings get search_inequality_filters` printed "Setting 'search_inequality_filters' not found." and exited 1, `settings list` left the key out, and the console's settings page did not list it. The server uses `all` for an absent row. The server now names the defaults of the keys it reads that no storage engine reads (server_setting_default), and `settings get` and `settings list` fall back to it after the storage engine's default. The console's settings page lists the key with the default `all`. A unit test pins `list` and `get` with and without a row. --- crates/app/src/cmd_settings.rs | 53 ++++++++++++++++--- crates/core/src/settings_keys.rs | 5 ++ .../src/console/pages/settings_pages.rs | 5 ++ crates/server/src/management/ops_settings.rs | 15 ++++++ 4 files changed, 71 insertions(+), 7 deletions(-) diff --git a/crates/app/src/cmd_settings.rs b/crates/app/src/cmd_settings.rs index 42d102289..3fc483dd1 100755 --- a/crates/app/src/cmd_settings.rs +++ b/crates/app/src/cmd_settings.rs @@ -10,9 +10,10 @@ //! masks them: `extenddb_config::should_redact` picks the keys and //! `extenddb_config::MASK` is the text printed; `get --show-secret` prints the //! stored value. A key the catalog has no row for prints the storage -//! engine's default (`extenddb_storage::operations::setting_default`), as the -//! console does, so a fresh install, which seeds no settings rows, lists the -//! values the engine uses. +//! engine's default (`extenddb_storage::operations::setting_default`), or for +//! a key the server reads, the server's (`server_setting_default`), as the +//! console does. So a fresh install, which seeds no settings rows, lists the +//! values the server uses. use clap::{Args, Subcommand}; @@ -21,7 +22,9 @@ use extenddb_storage::management_store::SettingsStore; use extenddb_config::{self as config, MASK}; // Re-use validation constants from the ops layer. -use extenddb_server::management::ops_settings::{KNOWN_KEYS, READONLY_KEYS}; +use extenddb_server::management::ops_settings::{ + KNOWN_KEYS, READONLY_KEYS, server_setting_default, +}; #[derive(Args)] pub struct SettingsArgs { @@ -143,12 +146,18 @@ async fn stored_or_default( Ok(default(current)) } +/// The value the server uses for `key` when the catalog has no row for it: +/// the storage engine's default, else the server's. +fn default_of(key: &str) -> Option { + extenddb_storage::operations::setting_default(key).or_else(|| server_setting_default(key)) +} + async fn list(store: &dyn SettingsStore) -> anyhow::Result<()> { let rows = store .list_settings() .await .map_err(|e| anyhow::anyhow!("Failed to list settings: {e:?}"))?; - let rows = with_defaults(rows, extenddb_storage::operations::setting_default); + let rows = with_defaults(rows, default_of); if rows.is_empty() { println!("No settings found."); @@ -159,8 +168,7 @@ async fn list(store: &dyn SettingsStore) -> anyhow::Result<()> { } async fn get(store: &dyn SettingsStore, key: &str, show_secret: bool) -> anyhow::Result<()> { - let value = - stored_or_default(store, key, extenddb_storage::operations::setting_default).await?; + let value = stored_or_default(store, key, default_of).await?; if let Some(v) = value { println!("{}", display_value(key, &v, show_secret)); @@ -368,6 +376,37 @@ mod tests { } } + /// With no row, `search_inequality_filters` lists and gets the server's + /// default, and a stored row wins over it. + #[cfg(feature = "search-inequality-filters")] + #[tokio::test] + async fn the_search_filter_setting_shows_the_server_default() { + // Another test of this binary may install a storage backend, whose + // defaults `default_of` adds too; no backend reads this key. + let key = "search_inequality_filters"; + let listed = with_defaults(rows(&[("log_level", "debug")]), default_of); + assert!( + listed.contains(&(key.to_owned(), "all".to_owned())), + "{listed:?}" + ); + assert!(listed.contains(&("log_level".to_owned(), "debug".to_owned()))); + let listed = with_defaults(rows(&[(key, "off")]), default_of); + assert!( + listed.contains(&(key.to_owned(), "off".to_owned())), + "{listed:?}" + ); + assert!( + !listed.contains(&(key.to_owned(), "all".to_owned())), + "{listed:?}" + ); + let fresh = Rows(Vec::new()); + let value = stored_or_default(&fresh, key, default_of).await.unwrap(); + assert_eq!(value.as_deref(), Some("all")); + let set = Rows(rows(&[(key, "off")])); + let value = stored_or_default(&set, key, default_of).await.unwrap(); + assert_eq!(value.as_deref(), Some("off")); + } + /// `list` adds a row for each writable key with an engine default and /// no row, in key order, and keeps a stored value over the default. #[test] diff --git a/crates/core/src/settings_keys.rs b/crates/core/src/settings_keys.rs index 4ba5bc442..6cd39106f 100644 --- a/crates/core/src/settings_keys.rs +++ b/crates/core/src/settings_keys.rs @@ -108,6 +108,11 @@ pub const VECTOR_ALLOCATION_PHASE_DELAY_MS: &str = "vector_allocation_phase_dela #[cfg(feature = "search-inequality-filters")] pub const SEARCH_INEQUALITY_FILTERS: &str = "search_inequality_filters"; +/// The value a server uses for [`SEARCH_INEQUALITY_FILTERS`] when the +/// catalog has no row for it. +#[cfg(feature = "search-inequality-filters")] +pub const SEARCH_INEQUALITY_FILTERS_DEFAULT: &str = "all"; + /// Resolve a caller-supplied settings key to its canonical name. /// /// Accepting the old name keeps `extenddb settings set gsi_propagation_delay_ms 0` diff --git a/crates/server/src/console/pages/settings_pages.rs b/crates/server/src/console/pages/settings_pages.rs index 62326e86c..3edab4198 100755 --- a/crates/server/src/console/pages/settings_pages.rs +++ b/crates/server/src/console/pages/settings_pages.rs @@ -34,6 +34,11 @@ const RUNTIME_KEYS: &[(&str, Option<&str>)] = &[ ("data_database_name", None), ("index_propagation_delay_ms", None), ("log_level", Some("info")), + #[cfg(feature = "search-inequality-filters")] + ( + extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS, + Some(extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS_DEFAULT), + ), ("sqlx_log_level", Some("warn")), ("throttling_enabled", Some("false")), ]; diff --git a/crates/server/src/management/ops_settings.rs b/crates/server/src/management/ops_settings.rs index c6d52c401..f73531884 100755 --- a/crates/server/src/management/ops_settings.rs +++ b/crates/server/src/management/ops_settings.rs @@ -58,6 +58,21 @@ fn validate_search_inequality_filters(value: &str) -> Result<(), &'static str> { extenddb_core::expression::search_filter::EnabledAccounts::parse(value).map(|_| ()) } +/// The value the server uses for `key` when the catalog has no row for it, +/// for a key the server reads and no storage engine does. `None` for any +/// other key: a storage engine's default comes from +/// `extenddb_storage::operations::setting_default`. +#[must_use] +pub fn server_setting_default(key: &str) -> Option { + #[cfg(feature = "search-inequality-filters")] + if key == extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS { + return Some(extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS_DEFAULT.to_owned()); + } + #[cfg(not(feature = "search-inequality-filters"))] + let _ = key; + None +} + /// Read-only keys that cannot be changed via the settings API. pub const READONLY_KEYS: &[&str] = &[ "catalog_version", From c3320b226e8143163fbee0bd9584afa3e57aa53b Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 19:56:48 +0000 Subject: [PATCH 041/101] fix(engine): skip the search filter setting when both grammars agree Every SearchVectors with a SearchConditionExpression read the search_inequality_filters setting before its condition was parsed. So a search that both grammars answer alike, an AND of string equalities for example, answered ServiceUnavailableException whenever the setting could not be read, where a build without the setting answers it. The condition is now parsed with both grammars. When both refuse it with the same error, the error answers without a read. When both accept it, the scope is resolved with both once the index schema is known, and when the two scopes are the same search, or the same refusal, the request is served without a read. Only a request whose answer differs between the grammars reads the setting. A Number value compares as binary64 under the extended grammar and exactly under the other, so a condition with a Number reads it. On a PostgreSQL release server started with the settings table under an exclusive lock, so no read had answered, a string equality search and a search without a condition answered 200 in each of three rounds, twice; an inequality and a Number equality answered 503. The earlier build answered 503 to the string equality too. On a PostgreSQL release server started with the settings table under an exclusive lock, so no read had answered, a string equality search and a search without a condition answered 200 in each of three rounds, twice; an inequality and a Number equality answered 503. The earlier build answered 503 to the string equality too. Two unit tests run the parse and the scope against a settings store that fails every read: string and binary equalities, a schema refusal and an unused-names refusal get their answers with no read, and an inequality and a Number equality read the setting once and answer ServiceUnavailableException. --- crates/core/src/settings_keys.rs | 4 +- crates/engine/src/search_vectors.rs | 5 +- crates/engine/src/search_vectors_condition.rs | 183 +++++++++++++----- .../src/search_vectors_condition_tests.rs | 137 ++++++++++++- crates/engine/src/search_vectors_extended.rs | 112 ++++------- .../src/search_vectors_extended_tests.rs | 121 +++--------- 6 files changed, 336 insertions(+), 226 deletions(-) diff --git a/crates/core/src/settings_keys.rs b/crates/core/src/settings_keys.rs index 6cd39106f..45652baf2 100644 --- a/crates/core/src/settings_keys.rs +++ b/crates/core/src/settings_keys.rs @@ -103,8 +103,8 @@ pub const VECTOR_ALLOCATION_PHASE_DELAY_MS: &str = "vector_allocation_phase_dela /// The accounts whose SearchVectors requests accept the extended /// `SearchConditionExpression` grammar: `all` (the default when the row is /// absent or empty), `off`, or a comma-separated list of 12-digit account -/// IDs. Read on every SearchVectors request, so a change applies without a -/// restart. +/// IDs. Read by a SearchVectors request whose answer depends on it, so a +/// change applies without a restart. #[cfg(feature = "search-inequality-filters")] pub const SEARCH_INEQUALITY_FILTERS: &str = "search_inequality_filters"; diff --git a/crates/engine/src/search_vectors.rs b/crates/engine/src/search_vectors.rs index 774b67e12..59fc11a2b 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -170,7 +170,10 @@ pub async fn handle_search_vectors( &parsed, vector_index.search_schema.as_deref(), &table.attribute_definitions, - )?; + &ctx.storage, + &ctx.account_id, + ) + .await?; let search_output = vector_search .search_vectors(extenddb_storage::VectorSearch { diff --git a/crates/engine/src/search_vectors_condition.rs b/crates/engine/src/search_vectors_condition.rs index 954992e90..1b5d9b87f 100644 --- a/crates/engine/src/search_vectors_condition.rs +++ b/crates/engine/src/search_vectors_condition.rs @@ -4,6 +4,12 @@ //! The `SearchConditionExpression` of a `SearchVectors` request: the grammar //! that parses it, and the scope it hands the backend. //! +//! A condition is parsed with both grammars. When both refuse it with the +//! same error, or both accept it and give the backend the same scope, the +//! answer does not depend on the `search_inequality_filters` setting and the +//! setting is not read. Otherwise the setting decides, and is read only +//! then. +//! //! A condition that the extended grammar parses still goes to the backend as //! equality pairs when that gives the same results, so the backend can apply //! it in its own query. The service compares inline-filter strings and binary @@ -16,24 +22,26 @@ use std::collections::HashMap; use std::sync::Arc; use extenddb_core::error::DynamoDbError; -use extenddb_core::expression::{ - SearchCondition, validate_conditions_against_search_schema, - validate_search_condition_expression, -}; +use extenddb_core::expression::{SearchCondition, validate_conditions_against_search_schema}; use extenddb_core::types::{ AttributeDefinition, AttributeValue, SearchSchemaElement, SearchSchemaElementType, }; use extenddb_storage::{StorageEngine, VectorItemFilter, VectorSearchEngine}; +#[cfg(feature = "search-inequality-filters")] use crate::search_vectors_extended::Extended; -/// A search condition parsed by one of the two grammars. -/// -/// With the extended grammar, `conditions` holds the equality pairs of the -/// same condition when the equality-only grammar also accepts it. -pub(crate) struct Parsed { - extended: Option, - conditions: Vec, +/// A search condition parsed by the grammars that accept it. +pub(crate) enum Parsed { + /// The equality-only grammar's conditions; empty without a condition. + Equality(Vec), + /// A condition only the extended grammar serves for the caller. + #[cfg(feature = "search-inequality-filters")] + Extended(Extended), + /// A condition both grammars accept. Which one serves it is decided once + /// the index's schema is known. + #[cfg(feature = "search-inequality-filters")] + Either(Extended, Vec), } /// The HASH equality that selects the partition, the inline-filter @@ -44,80 +52,151 @@ pub(crate) type Scope<'a> = ( Option>, ); -/// Structural validation of the filter expression (schema-independent). -/// An account the extended grammar is enabled for gets that parser instead. +/// Structural validation of the filter expression (schema-independent), +/// with each grammar that may serve the caller. +/// +/// Taking the backend's vector search engine means the grammar is only +/// parsed once the backend has been found to serve vector search: a backend +/// without it refuses the request before this runs. /// /// # Errors /// -/// Returns the `ValidationException` of the first failed check. +/// Returns the `ValidationException` of the first failed check, and +/// `ServiceUnavailableException` when the answer depends on the setting and +/// the setting cannot be read. pub(crate) async fn parse( storage: &Arc, - vector_search: &dyn VectorSearchEngine, + _served_by: &dyn VectorSearchEngine, account_id: &str, expr: Option<&str>, names: Option<&HashMap>, values: Option<&HashMap>, projection: Option<&str>, ) -> Result { - let extended = crate::search_vectors_extended::parse_request( - storage, - vector_search, - account_id, - expr, - names, - values, - projection, - ) - .await?; - let conditions = match expr { - Some(expr) if extended.is_some() => { - validate_search_condition_expression(expr, names, values).unwrap_or_default() - } - Some(expr) => { - crate::search_vectors_params::equality_conditions(expr, names, values, projection)? - } - None => Vec::new(), + let Some(expr) = expr else { + return Ok(Parsed::Equality(Vec::new())); }; - Ok(Parsed { - extended, - conditions, - }) + let equality = + crate::search_vectors_params::equality_conditions(expr, names, values, projection); + #[cfg(feature = "search-inequality-filters")] + { + let extended = crate::search_vectors_extended::parse(expr, names, values, projection); + match (extended, equality) { + (Ok(extended), Ok(conditions)) => Ok(Parsed::Either(extended, conditions)), + (Err(a), Err(b)) if same_error(&a, &b) => Err(a), + (extended, equality) => { + if crate::search_vectors_extended::enabled_for(storage, account_id).await? { + extended.map(Parsed::Extended) + } else { + equality.map(Parsed::Equality) + } + } + } + } + #[cfg(not(feature = "search-inequality-filters"))] + { + let _ = (storage, account_id); + equality.map(Parsed::Equality) + } } /// The scope of the search, once the schema checks pass. /// /// # Errors /// -/// Returns the `ValidationException` of the first failed schema check. -pub(crate) fn resolve<'a>( +/// Returns the `ValidationException` of the first failed schema check, and +/// `ServiceUnavailableException` when the answer depends on the setting and +/// the setting cannot be read. +pub(crate) async fn resolve<'a>( parsed: &'a Parsed, search_schema: Option<&'a [SearchSchemaElement]>, attribute_definitions: &[AttributeDefinition], + storage: &Arc, + account_id: &str, ) -> Result, DynamoDbError> { - Ok(match &parsed.extended { - Some(extended) => { - let (hash_key, item_filter) = crate::search_vectors_extended::resolve_scope( + match parsed { + Parsed::Equality(conditions) => { + let _ = (storage, account_id); + equality_scope(conditions, search_schema, attribute_definitions) + } + #[cfg(feature = "search-inequality-filters")] + Parsed::Extended(extended) => { + extended_scope(extended, None, search_schema, attribute_definitions) + } + #[cfg(feature = "search-inequality-filters")] + Parsed::Either(extended, conditions) => { + let equality = equality_scope(conditions, search_schema, attribute_definitions); + let extended = extended_scope( extended, + Some(conditions), search_schema, attribute_definitions, - )?; - match equality_pairs(&parsed.conditions, search_schema) { - Some(filters) => (hash_key, filters, None), - None => (hash_key, Vec::new(), Some(item_filter)), + ); + if same_scope(&equality, &extended) + || !crate::search_vectors_extended::enabled_for(storage, account_id).await? + { + equality + } else { + extended } } - None => { - let (hash_key, filters) = - resolve_search_scope(&parsed.conditions, search_schema, attribute_definitions)?; - (hash_key, filters, None) - } - }) + } +} + +fn equality_scope<'a>( + conditions: &'a [SearchCondition], + search_schema: Option<&'a [SearchSchemaElement]>, + attribute_definitions: &[AttributeDefinition], +) -> Result, DynamoDbError> { + let (hash_key, filters) = + resolve_search_scope(conditions, search_schema, attribute_definitions)?; + Ok((hash_key, filters, None)) +} + +/// The scope of an extended-grammar condition: the equality pairs of +/// `conditions` when they give the same results, else the item filter. +#[cfg(feature = "search-inequality-filters")] +fn extended_scope<'a>( + extended: &'a Extended, + conditions: Option<&'a [SearchCondition]>, + search_schema: Option<&'a [SearchSchemaElement]>, + attribute_definitions: &[AttributeDefinition], +) -> Result, DynamoDbError> { + let (hash_key, item_filter) = crate::search_vectors_extended::resolve_scope( + extended, + search_schema, + attribute_definitions, + )?; + Ok( + match conditions.and_then(|c| equality_pairs(c, search_schema)) { + Some(filters) => (hash_key, filters, None), + None => (hash_key, Vec::new(), Some(item_filter)), + }, + ) +} + +/// Whether two scopes give the backend the same search, or two refusals +/// the same error. A scope with an item filter is never the same as +/// another. +#[cfg(feature = "search-inequality-filters")] +fn same_scope(a: &Result, DynamoDbError>, b: &Result, DynamoDbError>) -> bool { + match (a, b) { + (Ok((h1, f1, None)), Ok((h2, f2, None))) => h1 == h2 && f1 == f2, + (Err(a), Err(b)) => same_error(a, b), + _ => false, + } +} + +#[cfg(feature = "search-inequality-filters")] +fn same_error(a: &DynamoDbError, b: &DynamoDbError) -> bool { + a.full_error_type() == b.full_error_type() && a.message() == b.message() } /// The inline-filter equalities of an extended-grammar condition that the /// equality pairs express with the same results, or `None` when the backend /// needs the item filter. The HASH equality selects the partition and is not /// among them. +#[cfg(feature = "search-inequality-filters")] fn equality_pairs<'a>( conditions: &'a [SearchCondition], search_schema: Option<&[SearchSchemaElement]>, diff --git a/crates/engine/src/search_vectors_condition_tests.rs b/crates/engine/src/search_vectors_condition_tests.rs index 723842559..d7effefe1 100644 --- a/crates/engine/src/search_vectors_condition_tests.rs +++ b/crates/engine/src/search_vectors_condition_tests.rs @@ -10,6 +10,7 @@ //! a stored 9007199254740992, and `Cat = "A"` does not match a stored "a". use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use extenddb_core::types::{ @@ -17,7 +18,7 @@ use extenddb_core::types::{ SearchSchemaElementType, }; use extenddb_storage::StorageEngine; -use extenddb_storage::management_store::{OpResult, SettingsStore}; +use extenddb_storage::management_store::{OpError, OpResult, SettingsStore}; use extenddb_storage_sqlite::SqliteEngine; use futures::future::BoxFuture; @@ -123,8 +124,15 @@ async fn routed(setting: &str, hash: bool, expr: &str, item: &Item) -> Routed { .await .unwrap(); let schema = schema(hash); - let (hash_key, filters, item_filter): Scope<'_> = - resolve(&parsed, Some(&schema), &definitions()).unwrap(); + let (hash_key, filters, item_filter): Scope<'_> = resolve( + &parsed, + Some(&schema), + &definitions(), + &storage, + "111111111111", + ) + .await + .unwrap(); ( hash_key.map(|(_, v)| v.clone()), filters @@ -234,3 +242,126 @@ async fn an_account_the_setting_leaves_out_keeps_the_equality_grammar() { (us(), pair("Price", ":p"), None) ); } + +/// A settings store whose every read fails, counting the reads. +#[derive(Default)] +struct Failing(AtomicUsize); + +impl SettingsStore for Failing { + fn get_setting(&self, _key: &str) -> BoxFuture<'_, OpResult>> { + self.0.fetch_add(1, Ordering::SeqCst); + Box::pin(async { Err(OpError::Internal("connection reset".to_owned())) }) + } + + fn set_setting(&self, _key: &str, _value: &str) -> BoxFuture<'_, OpResult<()>> { + Box::pin(async { Ok(()) }) + } + + fn list_settings(&self) -> BoxFuture<'_, OpResult>> { + Box::pin(async { Ok(Vec::new()) }) + } +} + +/// The scope, or the error, of `expr` on a server whose settings store +/// fails every read, and the number of reads it got. +async fn without_the_setting( + expr: &str, + names: Option<&HashMap>, +) -> (Result, usize) { + let storage: Arc = Arc::new( + SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) + .await + .expect("an in-memory database opens"), + ); + let store = Arc::new(Failing::default()); + crate::install_search_filter_settings(&storage, store.clone()); + let served = storage + .as_vector_search() + .expect("SQLite serves vector search"); + let values: HashMap = values() + .into_iter() + .filter(|(k, _)| expr.contains(k.as_str())) + .collect(); + let schema = schema(true); + let answer = async { + let parsed = parse( + &storage, + served, + "111111111111", + Some(expr), + names, + Some(&values), + None, + ) + .await?; + let (hash_key, filters, item_filter) = resolve( + &parsed, + Some(&schema), + &definitions(), + &storage, + "111111111111", + ) + .await?; + Ok::(( + hash_key.map(|(_, v)| v.clone()), + filters + .into_iter() + .map(|(n, v)| (n.to_owned(), v.clone())) + .collect(), + item_filter.map(|f| f.matches(&item()).unwrap()), + )) + } + .await + .map_err(|e| e.message().to_owned()); + (answer, store.0.load(Ordering::SeqCst)) +} + +/// A condition that both grammars answer alike is served without a read of +/// the setting, so a setting that cannot be read does not refuse it. +#[tokio::test] +async fn a_condition_both_grammars_answer_alike_does_not_read_the_setting() { + assert_eq!( + without_the_setting("Country = :c AND Cat = :s", None).await, + (Ok((us(), pair("Cat", ":s"), None)), 0) + ); + assert_eq!( + without_the_setting("Country = :c AND Tag = :t", None).await, + (Ok((us(), pair("Tag", ":t"), None)), 0) + ); + // the same schema refusal under both grammars + assert_eq!( + without_the_setting("Cat = :s", None).await, + ( + Err("SearchConditionExpression must have \ + all HASH attributes in configured SearchSchema" + .to_owned()), + 0 + ) + ); + // the same unused-names refusal under both grammars + let names: HashMap = [("#u".to_owned(), "x".to_owned())].into(); + assert_eq!( + without_the_setting("Country = :c", Some(&names)).await, + ( + Err( + "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}" + .to_owned() + ), + 0 + ) + ); +} + +/// A condition whose answer depends on the grammar reads the setting, and a +/// read that fails before any read answered is a retryable fault. +#[tokio::test] +async fn a_condition_the_grammars_answer_differently_reads_the_setting() { + let unavailable = Err("Service is temporarily unavailable".to_owned()); + for expr in ["Country = :c AND Cat <> :s", "Country = :c AND Price = :p"] { + assert_eq!( + without_the_setting(expr, None).await, + (unavailable.clone(), 1), + "{expr}" + ); + } +} diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs index 9339182b9..db4d6de12 100644 --- a/crates/engine/src/search_vectors_extended.rs +++ b/crates/engine/src/search_vectors_extended.rs @@ -3,10 +3,13 @@ //! `SearchVectors` with the extended `SearchConditionExpression` grammar. //! -//! The handler calls [`parse_request`] and, when it returns a filter, -//! [`resolve_scope`] in place of the equality-only validator. With the -//! `search-inequality-filters` feature off, [`parse_request`] always returns -//! `None` and the handler runs exactly as it does without this module. +//! The handler parses a search condition with both grammars. [`parse`] is +//! the extended grammar's parser, and [`resolve_scope`] gives the partition +//! and the filter of a condition it parsed. When the two grammars answer a +//! request alike, the handler does not read the setting; otherwise +//! [`enabled_for`] says which grammar the caller gets. With the +//! `search-inequality-filters` feature off, this module defines no parser +//! and the handler runs the equality-only grammar alone. //! //! With the feature on, the `search_inequality_filters` runtime setting says //! which accounts get the grammar. It is read through the settings store the @@ -14,7 +17,8 @@ //! `search_vectors_settings.rs`), so a change applies without a restart. //! Until a store is installed, every account gets the grammar. -pub(crate) use imp::{Extended, parse_request, resolve_scope}; +#[cfg(feature = "search-inequality-filters")] +pub(crate) use imp::{Extended, enabled_for, parse, resolve_scope}; #[cfg(feature = "search-inequality-filters")] #[path = "search_vectors_settings.rs"] @@ -35,7 +39,7 @@ mod imp { use extenddb_core::expression::search_params::with_unused_names; use extenddb_core::types::{AttributeDefinition, AttributeValue, Item, SearchSchemaElement}; use extenddb_storage::error::StorageError; - use extenddb_storage::{StorageEngine, VectorItemFilter, VectorSearchEngine}; + use extenddb_storage::{StorageEngine, VectorItemFilter}; /// The HASH attribute and the value that selects its partition, and the /// filter the backend applies to each candidate. @@ -47,46 +51,43 @@ mod imp { /// A search condition parsed with the extended grammar. pub(crate) struct Extended(Arc); - /// Parse the request's search condition with the extended grammar when - /// the setting enables it for the caller. `None` when it does not, or when - /// the request has no search condition; the handler then runs its - /// equality-only validator. A name that neither the search condition nor - /// `projection` uses is refused once the condition parses. - /// - /// Taking the backend's vector search engine means the grammar is only - /// parsed once the backend has been found to serve vector search: a - /// backend without it refuses the request before this runs. + /// Parse a search condition with the extended grammar. A name that + /// neither the search condition nor `projection` uses is refused once + /// the condition parses. /// /// # Errors /// - /// Returns the `ValidationException` of the first failed check, and - /// `ServiceUnavailableException` when the setting cannot be read. - pub(crate) async fn parse_request( - storage: &Arc, - _served_by: &dyn VectorSearchEngine, - account_id: &str, - expr: Option<&str>, + /// Returns the `ValidationException` of the first failed check. + pub(crate) fn parse( + expr: &str, names: Option<&HashMap>, values: Option<&HashMap>, projection: Option<&str>, - ) -> Result, DynamoDbError> { - let Some(expr) = expr else { - return Ok(None); - }; - // Cross-account access is refused before dispatch, so the caller is - // the table owner. - if !super::settings::enabled_accounts(storage) - .await? - .enabled_for(account_id, None) - { - return Ok(None); - } + ) -> Result { with_unused_names( parse_search_filter(expr, names, values, DEFAULT_MAX_CONDITIONS), names, &[expr, projection.unwrap_or_default()], ) - .map(|filter| Some(Extended(Arc::new(filter)))) + .map(|filter| Extended(Arc::new(filter))) + } + + /// Whether the setting gives `account_id` the extended grammar on the + /// server `storage` belongs to. + /// + /// # Errors + /// + /// Returns `ServiceUnavailableException` when the setting cannot be read + /// and no earlier read answered. + pub(crate) async fn enabled_for( + storage: &Arc, + account_id: &str, + ) -> Result { + // Cross-account access is refused before dispatch, so the caller is + // the table owner. + Ok(super::settings::enabled_accounts(storage) + .await? + .enabled_for(account_id, None)) } /// The partition the HASH condition selects and the filter the backend @@ -118,44 +119,3 @@ mod imp { #[cfg(all(test, feature = "search-inequality-filters"))] #[path = "search_vectors_extended_tests.rs"] mod tests; - -#[cfg(not(feature = "search-inequality-filters"))] -mod imp { - use std::collections::HashMap; - use std::sync::Arc; - - use extenddb_core::error::DynamoDbError; - use extenddb_core::types::{AttributeDefinition, AttributeValue, SearchSchemaElement}; - use extenddb_storage::{StorageEngine, VectorItemFilter, VectorSearchEngine}; - - /// The HASH attribute and the value that selects its partition, and the - /// filter the backend applies to each candidate. - pub(crate) type Scope<'a> = ( - Option<(&'a str, &'a AttributeValue)>, - Arc, - ); - - /// No value exists: without the feature no request is parsed this way. - pub(crate) enum Extended {} - - #[allow(clippy::unused_async)] - pub(crate) async fn parse_request( - _storage: &Arc, - _served_by: &dyn VectorSearchEngine, - _account_id: &str, - _expr: Option<&str>, - _names: Option<&HashMap>, - _values: Option<&HashMap>, - _projection: Option<&str>, - ) -> Result, DynamoDbError> { - Ok(None) - } - - pub(crate) fn resolve_scope<'a>( - extended: &'a Extended, - _schema: Option<&[SearchSchemaElement]>, - _definitions: &[AttributeDefinition], - ) -> Result, DynamoDbError> { - match *extended {} - } -} diff --git a/crates/engine/src/search_vectors_extended_tests.rs b/crates/engine/src/search_vectors_extended_tests.rs index 8516e2c35..63e41dfb7 100644 --- a/crates/engine/src/search_vectors_extended_tests.rs +++ b/crates/engine/src/search_vectors_extended_tests.rs @@ -14,15 +14,12 @@ use extenddb_core::types::{ AttributeDefinition, AttributeValue, Item, ScalarAttributeType, SearchSchemaElement, SearchSchemaElementType, }; +use extenddb_storage::StorageEngine; use extenddb_storage::management_store::{OpError, OpResult, SettingsStore}; -use extenddb_storage::{ - BoxedFuture, StorageEngine, VectorSearch, VectorSearchEngine, VectorSearchOutput, - VectorSearchResult, -}; use extenddb_storage_sqlite::SqliteEngine; use futures::future::BoxFuture; -use super::imp::{parse_request, resolve_scope}; +use super::imp::{enabled_for, parse, resolve_scope}; use super::install_search_filter_settings; const CALLER: &str = "111111111111"; @@ -58,19 +55,6 @@ async fn install(value: Result, ()>) -> Arc { storage } -struct Served; - -impl VectorSearchEngine for Served { - fn search_vectors(&self, _req: VectorSearch<'_>) -> BoxedFuture<'_, VectorSearchResult> { - Box::pin(async { - Ok(VectorSearchOutput { - hits: Vec::new(), - distance_function: extenddb_core::types::DistanceFunction::Cosine, - }) - }) - } -} - fn values() -> HashMap { [ (":c".to_owned(), AttributeValue::S("US".to_owned())), @@ -81,14 +65,12 @@ fn values() -> HashMap { const INEQUALITY: &str = "Country = :c AND Price > :p"; -async fn parsed( - storage: &Arc, - expr: Option<&str>, -) -> Result { - let values = values(); - parse_request(storage, &Served, CALLER, expr, None, Some(&values), None) - .await - .map(|parsed| parsed.is_some()) +async fn enabled(storage: &Arc) -> Result { + enabled_for(storage, CALLER).await +} + +fn parsed(expr: &str) -> Result { + parse(expr, None, Some(&values()), None) } #[tokio::test] @@ -102,22 +84,18 @@ async fn the_setting_selects_the_accounts() { (Ok(Some("111111111111")), true), (Ok(Some("222222222222,111111111111")), true), (Ok(Some("222222222222")), false), - // a value that does not parse is logged and reads as every account - (Ok(Some("on")), true), + // a value that does not parse is logged and enables no account + (Ok(Some("on")), false), ] { let storage = install(value).await; - assert_eq!( - parsed(&storage, Some(INEQUALITY)).await.unwrap(), - expected, - "{value:?}" - ); + assert_eq!(enabled(&storage).await.unwrap(), expected, "{value:?}"); } } #[tokio::test] async fn a_store_that_fails_answers_a_retryable_fault() { let storage = install(Err(())).await; - let err = parsed(&storage, Some(INEQUALITY)).await.unwrap_err(); + let err = enabled(&storage).await.unwrap_err(); assert!( matches!(&err, DynamoDbError::ServiceUnavailable(m) if m == "Service is temporarily unavailable"), @@ -132,24 +110,14 @@ async fn without_an_installed_store_every_account_gets_the_grammar() { .await .expect("an in-memory database opens"), ); - assert!(parsed(&storage, Some(INEQUALITY)).await.unwrap()); + assert!(enabled(&storage).await.unwrap()); } -#[tokio::test] -async fn no_expression_is_left_to_the_equality_path() { - let storage = install(Ok(Some("all"))).await; - assert!(!parsed(&storage, None).await.unwrap()); -} - -#[tokio::test] -async fn an_enabled_account_gets_the_extended_messages() { - let storage = install(Ok(Some("all"))).await; - let err = parsed( - &storage, - Some("Country = :c AND Price > :p AND begins_with(Category, :c)"), - ) - .await - .unwrap_err(); +#[test] +fn the_extended_grammar_gives_its_own_messages() { + let Err(err) = parsed("Country = :c AND Price > :p AND begins_with(Category, :c)") else { + panic!("refused"); + }; let DynamoDbError::ValidationException(message) = err else { panic!("expected ValidationException, got {err:?}"); }; @@ -160,40 +128,20 @@ async fn an_enabled_account_gets_the_extended_messages() { ); } -#[tokio::test] -async fn a_name_neither_expression_uses_is_refused() { - let storage = install(Ok(Some("all"))).await; +#[test] +fn a_name_neither_expression_uses_is_refused() { let values = values(); let names: HashMap = [("#u".to_owned(), "x".to_owned())].into(); - let err = parse_request( - &storage, - &Served, - CALLER, - Some(INEQUALITY), - Some(&names), - Some(&values), - None, - ) - .await - .err() - .expect("refused"); + let err = parse(INEQUALITY, Some(&names), Some(&values), None) + .err() + .expect("refused"); assert!( matches!(&err, DynamoDbError::ValidationException(m) if m == "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}"), "{err:?}" ); let used: HashMap = [("#u".to_owned(), "Price".to_owned())].into(); - let projected = parse_request( - &storage, - &Served, - CALLER, - Some(INEQUALITY), - Some(&used), - Some(&values), - Some("#u"), - ) - .await; - assert!(projected.is_ok_and(|e| e.is_some())); + assert!(parse(INEQUALITY, Some(&used), Some(&values), Some("#u")).is_ok()); } fn item(country: &str, price: &str) -> Item { @@ -204,22 +152,11 @@ fn item(country: &str, price: &str) -> Item { .into() } -#[tokio::test] -async fn the_scope_selects_the_hash_partition_and_filters_items() { - let storage = install(Ok(Some("all"))).await; - let values = values(); - let extended = parse_request( - &storage, - &Served, - CALLER, - Some(INEQUALITY), - None, - Some(&values), - None, - ) - .await - .unwrap() - .expect("parsed with the extended grammar"); +#[test] +fn the_scope_selects_the_hash_partition_and_filters_items() { + let Ok(extended) = parsed(INEQUALITY) else { + panic!("parsed with the extended grammar"); + }; let schema = [ SearchSchemaElement { attribute_name: "Country".to_owned(), From 95c32f4c6e518a5edb0f72c7262a869199a53f65 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 20:00:47 +0000 Subject: [PATCH 042/101] fix(server): set no dynamodb:Attributes value on SearchVectors DynamoDB sets no dynamodb:Attributes value on a SearchVectors request. Measured in us-east-1 on 2026-11-21, each request twice: under a Deny gated on Null true, every search was refused, a projected one included; under a Deny on ssn, a search that projected ssn and one whose SearchConditionExpression named it were both served. No IAM write was sent for this change; the expectation rests on that measurement. ExtendDB put the paths in ProjectionExpression in the key, so a Deny on ssn refused a search that projected it and a Null true Deny served a projected search. docs/differences-from-dynamodb.md recorded that as a difference. single_table_attributes now gives no value for SearchVectors. The module docs, the security model table and the troubleshooting text say so, and the differences row is removed. The unit test checks five request shapes for no value. The authorization wire module adds a projection of ssn and of cat and ssn under the Deny on ssn, served, and a deny(null) principal whose projected, unprojected and conditioned searches are refused. --- crates/server/src/request_attributes.rs | 10 +-- crates/server/src/request_attributes/tests.rs | 20 +++-- docs/differences-from-dynamodb.md | 1 - docs/manuals/10-security-model.md | 2 +- docs/troubleshooting.md | 2 +- tests/test_authz_search_vectors_index.py | 81 +++++++++++++++---- 6 files changed, 84 insertions(+), 32 deletions(-) diff --git a/crates/server/src/request_attributes.rs b/crates/server/src/request_attributes.rs index 37706c6d0..df8c3d5cf 100644 --- a/crates/server/src/request_attributes.rs +++ b/crates/server/src/request_attributes.rs @@ -61,11 +61,10 @@ //! projected name, and (measured 2026-11-10) under a Deny on the index's //! sort key, so the index's sort key is not in the key. The other rules for //! a local secondary index follow from that key content. -//! - `SearchVectors`: the paths in `ProjectionExpression`. A `SearchVectors` -//! with no `ProjectionExpression` leaves the key absent. The names in -//! `SearchConditionExpression` are not in it. On the service the key is -//! absent on every `SearchVectors` (measured 2026-11-21). A Deny gated on -//! `Null` `true` refused each one. A Deny on an attribute refused none, +//! - `SearchVectors`: the key is absent, whatever `ProjectionExpression` and +//! `SearchConditionExpression` name, as on the service (measured +//! 2026-11-21): a Deny gated on `Null` `true` refused each `SearchVectors` +//! sent, a projected one included, and a Deny on an attribute refused none, //! whether the projection or the condition named it. //! - `BatchGetItem`: per table, the table's key attributes, `AttributesToGet`, //! and the paths in `ProjectionExpression`, as for `GetItem`. The names in @@ -177,7 +176,6 @@ pub(crate) fn single_table_attributes( names.map_keys(input.get("ScanFilter")); names.range_read(input); } - "SearchVectors" => names.projection(input.get("ProjectionExpression")), _ => return None, } names.finish() diff --git a/crates/server/src/request_attributes/tests.rs b/crates/server/src/request_attributes/tests.rs index 4ac87d33b..48e720ac2 100644 --- a/crates/server/src/request_attributes/tests.rs +++ b/crates/server/src/request_attributes/tests.rs @@ -525,13 +525,12 @@ fn scan_holds_its_filter_projection_and_start_key_names() { ); } -/// The paths in `ProjectionExpression` only. A key without `#` resolves no -/// name, and the engine refuses that request. The names in -/// `SearchConditionExpression` are not in the value: the service served a -/// search whose condition named `ssn` under a Deny on `ssn` (measured -/// 2026-11-21). +/// No value, whatever the request names: the service served a search that +/// projected `ssn`, and one whose condition named `ssn`, under a Deny on +/// `ssn`, and refused a projected search under a Deny gated on `Null` `true` +/// (measured 2026-11-21). #[test] -fn search_vectors_holds_its_projected_paths() { +fn search_vectors_holds_no_attributes() { let v = || json!({":v": {"S": "1"}}); let rows = [ ( @@ -540,7 +539,12 @@ fn search_vectors_holds_its_projected_paths() { "ProjectionExpression": "#v.x, name", "ExpressionAttributeNames": {"#v": "vec"}, }), - names(&["name", "vec"]), + None, + ), + ( + "a projection of ssn", + json!({"ProjectionExpression": "ssn"}), + None, ), ( "a key without #", @@ -554,7 +558,7 @@ fn search_vectors_holds_its_projected_paths() { "ExpressionAttributeValues": v(), "ProjectionExpression": "cat", }), - names(&["cat"]), + None, ), ( "a condition and no projection", diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index cc892efeb..a88689353 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -38,7 +38,6 @@ from a request sent to that service or backend. | Table ARN as `TableName` | Accepted; the request acts on that table | Authorized against that table, then the request fails with `ResourceNotFoundException` | | AccessDenied message for an ARN outside this deployment (caller with no policy) | Names the ARN as supplied. A table ARN in `TableName` with another partition, service or region never reaches the IAM decision: it is `ValidationException` ("Invalid AWS partition", "Invalid vendor code", "Invalid AWS region") for every principal (measured) | Names the ARN as supplied. A table ARN in `TableName` with another partition, service or region is authorized as this deployment's table, and a caller with no policy is denied naming the ARN as supplied | | A resource ARN in another account | Refused with the same answer for a caller allowed `dynamodb:*` on `*` and a caller with no policy. When the account exists: `AccessDeniedException` "User: is not authorized to perform: dynamodb: on resource: because no resource-based policy allows the dynamodb: action", except `CreateTable`, the time-to-live, continuous-backup, backup, export and restore operations, which answer `ValidationException` "This action is only supported by accounts that match the resource owner’s account.". When it does not: `AccessDeniedException` "The caller is not authorized to access the specified resource." on `GetItem`, `PutItem`, `UpdateItem`, `Query`, `Scan` and `BatchGetItem`, the same `ValidationException` on `RestoreTableToPointInTime`, and `AccessDeniedException` "Access is denied" on the rest. A batch or transaction with tables in more than one account is `ValidationException` "Invalid request! All tables in the request must be from a single account." (measured) | The same answers, before the IAM decision and in dev mode too, where an account exists when this deployment's catalog holds it. `RestoreTableToPointInTime` and an `UpdateContinuousBackups` that enables point-in-time recovery get the point-in-time recovery refusal instead (see "Point-in-time recovery" below). `DeleteTable`, `DeleteItem` and `DeleteBackup` take the answers of `UpdateTable`, `UpdateItem` and `DescribeBackup` (not measured). A table ARN in `TableName` that also has another partition, service or region, or that names an index or backup, gets these answers too. The service answers it with a `ValidationException` (the partition, vendor or region text in the row above, or "Valid ARN format is ..." for an index or backup ARN): on `GetItem` whether or not the account exists, and on `DescribeTable` when it exists (measured; the other operations were not sent) | -| `dynamodb:Attributes` on `SearchVectors` | Absent. A `Deny` gated on `Null` `true` refused each `SearchVectors` sent, a projected one included, and a `Deny` on an attribute refused none, whether `ProjectionExpression` or `SearchConditionExpression` named it (measured 2026-11-21) | Holds the attributes in `ProjectionExpression`, and is absent when there is none. A `Deny` on `ssn` refused a `SearchVectors` that projects `ssn`, and served one whose `SearchConditionExpression` alone names `ssn`. A `Deny` gated on `Null` `true` refused a `SearchVectors` with no `ProjectionExpression`, and served one that projects an attribute (measured 2026-11-21) | ## Import and Export diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index b3569ef53..fc12f90fa 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -238,7 +238,7 @@ extenddb supports the same access control patterns as real AWS IAM: | `DeleteItem` | The `Key` attributes, the table's key attributes, `Expected`, and the attributes in `ConditionExpression` | | `Query` | The key attributes of the table and of the queried index, the attributes in `KeyConditionExpression` and `KeyConditions`, `AttributesToGet`, `QueryFilter`, `ExclusiveStartKey`, and the attributes in `FilterExpression` and `ProjectionExpression` | | `Scan` | The table's key attributes, `AttributesToGet`, `ScanFilter`, `ExclusiveStartKey`, and the attributes in `FilterExpression` and `ProjectionExpression` | -| `SearchVectors` | The attributes in `ProjectionExpression`; the key is absent when there is none | +| `SearchVectors` | No value, whatever `ProjectionExpression` and `SearchConditionExpression` name, as on DynamoDB (measured 2026-11-21) | | `BatchGetItem` | Per table: the table's key attributes, `AttributesToGet`, and the attributes in `ProjectionExpression`, as for `GetItem`; the names in `Keys` add nothing | | `BatchWriteItem` | Per table: the attributes of every `PutRequest` item and `DeleteRequest` key, and the table's key attributes, evaluated once with the union of the table's items | | `TransactGetItems`, `TransactWriteItems` | Per item, what the single-item operation holds: `Get` as `GetItem`, `Put` as `PutItem`, `Update` as `UpdateItem`, `Delete` as `DeleteItem`; a `ConditionCheck` holds the table's key attributes and the attributes in its `ConditionExpression` | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index e3c462438..22a398a5f 100755 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -455,7 +455,7 @@ These errors occur when `auth.provider = "builtin"` is enabled. To allowlist attributes (allow only when *every* requested attribute is in the set), use `ForAllValues:` on an `Allow` statement. The same rule applies to `dynamodb:LeadingKeys`. -`dynamodb:Attributes` holds the top-level names of the attributes the request names: the attributes of a `PutItem` item and of the items and keys in a `BatchWriteItem` request, the target of each `UpdateExpression` action, `AttributesToGet`, the first name of each projected document path (`secret` for `secret.a`), the attributes a `ConditionExpression` or `FilterExpression` reads, the legacy `Expected`, `AttributeUpdates`, `QueryFilter` and `ScanFilter` names, the attributes in a `Query` key condition, and on every item operation other than `SearchVectors` the key attributes of the table (and of the index a `Query` names). The first page of a `Scan` of an index holds the table's key attributes and not the index's (measured on DynamoDB 2026-11-09), and a later page also holds the index's key attributes, which its `ExclusiveStartKey` carries (measured 2026-11-10). The attributes a `SET` value reads are not in it. Batch requests are evaluated per table and transactions per item. The [security model manual](manuals/10-security-model.md) lists what the key holds for each operation, and how a PartiQL statement is authorized. It follows that: +`dynamodb:Attributes` holds the top-level names of the attributes the request names: the attributes of a `PutItem` item and of the items and keys in a `BatchWriteItem` request, the target of each `UpdateExpression` action, `AttributesToGet`, the first name of each projected document path (`secret` for `secret.a`), the attributes a `ConditionExpression` or `FilterExpression` reads, the legacy `Expected`, `AttributeUpdates`, `QueryFilter` and `ScanFilter` names, the attributes in a `Query` key condition, and on every item operation other than `SearchVectors` the key attributes of the table (and of the index a `Query` names). A `SearchVectors` request holds no value, whatever it projects or its condition names, as on DynamoDB (measured 2026-11-21). The first page of a `Scan` of an index holds the table's key attributes and not the index's (measured on DynamoDB 2026-11-09), and a later page also holds the index's key attributes, which its `ExclusiveStartKey` carries (measured 2026-11-10). The attributes a `SET` value reads are not in it. Batch requests are evaluated per table and transactions per item. The [security model manual](manuals/10-security-model.md) lists what the key holds for each operation, and how a PartiQL statement is authorized. It follows that: - A `Deny` on `ForAnyValue:StringEquals` over `ssn` does not block a `DeleteItem` of an item that holds `ssn`, or a read with no projection, which returns `ssn` with the rest of the item: neither request names `ssn`. DynamoDB answers the same way (measured 2026-10-31). - The same `Deny` does not block an `UpdateItem` that reads `ssn` only in a `SET` value. `SET #n = ssn` copies the value of `ssn` into `name`, and a projection of `name` then returns it. DynamoDB answers the same way (measured 2026-11-01). diff --git a/tests/test_authz_search_vectors_index.py b/tests/test_authz_search_vectors_index.py index 872631fda..cb89af006 100644 --- a/tests/test_authz_search_vectors_index.py +++ b/tests/test_authz_search_vectors_index.py @@ -14,14 +14,15 @@ for every caller, before the policy decision, as Query and Scan do. The ``ROWS`` were measured on DynamoDB in us-east-1 on 2026-11-21, each -request twice with the same answer. The ``deny(ssn)`` rows ran under a session -policy that allows ``dynamodb:*`` and denies ``dynamodb:*`` under -``ForAnyValue:StringEquals {"dynamodb:Attributes": ["ssn"]}``, and the -``allow-all`` rows with no session policy. The service checks the -``ExpressionAttributeNames`` keys before the policy decision, and ExtendDB -decides the policy first. The service sets no ``dynamodb:Attributes`` value -on a SearchVectors request, so it serves a projection of ``ssn`` under -``deny(ssn)``. ExtendDB holds the projected names, so that row is not here. +request twice with the same answer. The ``deny(ssn)`` rows ran +under a session policy that allows ``dynamodb:*`` and denies ``dynamodb:*`` +under ``ForAnyValue:StringEquals {"dynamodb:Attributes": ["ssn"]}``, the +``deny(null)`` rows under one that denies under ``Null +{"dynamodb:Attributes": "true"}``, and the ``allow-all`` rows with no session +policy. The service sets no ``dynamodb:Attributes`` value on a SearchVectors +request: it serves a projection of ``ssn`` under ``deny(ssn)``, and refuses +every search under ``deny(null)``. ExtendDB decides the policy before it +checks the ``ExpressionAttributeNames`` keys. The principals are builtin-IAM users provisioned through the management API. The module skips when the backend does not support vector indexes, unless @@ -300,8 +301,25 @@ def test_index_name_outside_the_pattern_is_refused_before_authorization( }, ], } +DENY_NULL = { + "Version": "2012-10-17", + "Statement": [ + {"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}, + { + "Effect": "Deny", + "Action": "dynamodb:*", + "Resource": "*", + "Condition": {"Null": {"dynamodb:Attributes": "true"}}, + }, + ], +} SSN_VALUE = {":v": SSN_ITEM["ssn"]} CAT_ONLY = [{"cat": {"S": "c1"}}] +DENIED = "perform: dynamodb:SearchVectors on resource:" +TOP_K_OF_ZERO = ( + "1 validation error detected: Value at 'TopK' failed to satisfy constraint: " + "Member must have value greater than or equal to 1" +) LONG_KEY = "#" + "a" * 255 @@ -314,6 +332,34 @@ def _invalid_key(key: str) -> str: # The measured rows: the policy, the members added to the search, then the # error type and message, or None and the items the search returns. ROWS = { + "projection-of-ssn": ( + "deny(ssn)", + {"ProjectionExpression": "ssn"}, + None, + [SSN_ITEM], + ), + "projection-of-cat-and-ssn": ( + "deny(ssn)", + {"ProjectionExpression": "cat, ssn"}, + None, + [{"cat": {"S": "c1"}, **SSN_ITEM}], + ), + "null-projection-of-cat": ( + "deny(null)", + {"ProjectionExpression": "cat"}, + "AccessDeniedException", + DENIED, + ), + "null-no-projection": ("deny(null)", {}, "AccessDeniedException", DENIED), + "null-condition-on-cat": ( + "deny(null)", + { + "SearchConditionExpression": "cat = :v", + "ExpressionAttributeValues": SSN_VALUE, + }, + "AccessDeniedException", + DENIED, + ), "projection-key-without-hash": ( "deny(ssn)", {"ProjectionExpression": "#n", "ExpressionAttributeNames": {"n": "ssn"}}, @@ -381,8 +427,7 @@ def _invalid_key(key: str) -> str: "allow-all", {"TopK": 0, "ProjectionExpression": "#n", "ExpressionAttributeNames": {"n": "ssn"}}, "ValidationException", - "1 validation error detected: Value at 'TopK' failed to satisfy constraint: " - "Member must have value greater than or equal to 1", + TOP_K_OF_ZERO, ), "value-not-a-string-text-tracked-by-1012": ( "allow-all", @@ -398,6 +443,11 @@ def deny_ssn(principal): return principal(DENY_SSN) +@pytest.fixture(scope="module") +def deny_null(principal): + return principal(DENY_NULL) + + def test_the_deny_on_ssn_refuses_a_get_item_of_ssn(deny_ssn, vector_table): # The control: the policy is in force for this principal. resp = deny_ssn.post( @@ -412,9 +462,9 @@ def test_the_deny_on_ssn_refuses_a_get_item_of_ssn(deny_ssn, vector_table): @pytest.mark.parametrize("row", list(ROWS)) -def test_search_expression_attribute_names(deny_ssn, vector_table, row): +def test_search_expression_attribute_names(deny_ssn, deny_null, vector_table, row): policy, members, error, expected = ROWS[row] - p = deny_ssn if policy == "deny(ssn)" else vector_table["admin"] + p = {"deny(ssn)": deny_ssn, "deny(null)": deny_null}.get(policy, vector_table["admin"]) resp = _search(p, vector_table["name"], **members) if error is None: assert resp.status_code == 200, f"{row}: {resp.text}" @@ -423,9 +473,10 @@ def test_search_expression_attribute_names(deny_ssn, vector_table, row): assert resp.status_code == 400, f"{row}: {resp.text}" assert _error_type(resp) == error, f"{row}: {resp.text}" message = _error_message(resp) - if error == "SerializationException": - # The service ends this text with the position in the body, and - # ExtendDB puts a sentence of its own before it. + if error in ("SerializationException", "AccessDeniedException"): + # The service ends the first text with the position in the body, + # and ExtendDB puts a sentence of its own before it. The second + # names the principal and the resource. assert expected in message, f"{row}: {message}" else: assert message == expected, f"{row}: {message}" From a2196c6b1e8b6c36ddfab9d7062f08f9b11172b6 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 20:01:01 +0000 Subject: [PATCH 043/101] fix(server): check a SearchVectors request before the policy decision DynamoDB makes the checks of a SearchVectors request that need no table before it authorizes the request: the body, IndexName, SearchVector, TopK, the expression maps, the projection and the search condition. A table name it refuses answers first. The table, its index and the schema checks come after the decision. ExtendDB made all of them in the engine handler, after authorization. So a caller a policy denies, under a Deny gated on Null true for example, got AccessDeniedException for a TopK of 0 or a names key without #, where the service answers ValidationException. The checks that need no table move from the handler into search_vectors_request.rs. The handler runs them, and the server runs them before the IAM decision through check_search_vectors_request, once the table name passes the table name gate; a failure is recorded in the request metrics as a dispatch error is. The upgrade manual records this and the dynamodb:Attributes change under 1.1.0. The authorization wire module adds four deny(null) rows: a names key without #, an empty names map, a TopK of 0 and an unused name, each answered with its ValidationException. Their expectations follow the service's order of checks and the measured messages; they were not sent to DynamoDB under that policy. --- crates/engine/src/lib.rs | 2 +- crates/engine/src/search_vectors.rs | 83 ++++++------------- crates/engine/src/search_vectors_request.rs | 91 ++++++++++++++++++++- crates/server/src/handler.rs | 27 ++++++ docs/manuals/07-upgrade-manual.md | 6 ++ tests/test_authz_search_vectors_index.py | 37 ++++++++- 6 files changed, 183 insertions(+), 63 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dfa231aca..a12b93338 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -80,7 +80,7 @@ pub use put_item::handle_put_item; pub use query::handle_query; pub use request_limits::check_request_item_counts; pub use scan::handle_scan; -pub use search_vectors::handle_search_vectors; +pub use search_vectors::{check_search_vectors_request, handle_search_vectors}; #[cfg(feature = "search-inequality-filters")] pub use search_vectors_extended::{install_search_filter_settings, search_filter_settings_changed}; pub use streams::{SHARD_ITERATOR_EXPIRED_MESSAGE, ShardIteratorClass, classify_shard_iterator}; diff --git a/crates/engine/src/search_vectors.rs b/crates/engine/src/search_vectors.rs index 59fc11a2b..fc6cd2afe 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -27,7 +27,6 @@ use crate::OperationContext; use crate::create_table::storage_err_to_dynamo; use crate::serialize_output; use crate::{DispatchMetrics, DispatchResult}; -use request::{MAX_TOP_K, MIN_INDEX_NAME_LENGTH, SearchVectorsInput, parse_search_vector}; /// A single search result: the item plus its similarity score. #[derive(Debug, Serialize)] @@ -47,6 +46,26 @@ struct SearchVectorsOutput { consumed_capacity: Option, } +/// The checks of a `SearchVectors` request that need no table: the body, +/// the backend's vector search, `IndexName`, `SearchVector`, `TopK`, the +/// expression maps, the projection and the search condition. The service +/// makes them before it authorizes the request, so the server calls this +/// ahead of the IAM decision. The handler makes them again. +/// +/// # Errors +/// +/// Returns the error of the first failed check. +pub async fn check_search_vectors_request( + body: &Value, + storage: &std::sync::Arc, + account_id: &str, + limits: &extenddb_core::limits::LimitsConfig, +) -> Result<(), DynamoDbError> { + request::check(body, storage, account_id, limits) + .await + .map(|_| ()) +} + /// Handle a `SearchVectors` request. /// /// # Errors @@ -57,62 +76,12 @@ pub async fn handle_search_vectors( body: Value, ctx: &OperationContext, ) -> Result { - let input: SearchVectorsInput = - serde_json::from_value(body).map_err(crate::deserialize_error)?; - - let vector_search = - crate::vector_gate::ensure_search_supported(ctx.storage.as_vector_search())?; - - // Request-shape validation runs before the table lookup, so a malformed - // request against a missing table reports the validation error rather than - // ResourceNotFound. - - // IndexName length. - if input.index_name.len() < MIN_INDEX_NAME_LENGTH { - return Err(DynamoDbError::ValidationException(format!( - "1 validation error detected: Value at 'IndexName' failed to satisfy constraint: \ - Member must have length greater than or equal to {MIN_INDEX_NAME_LENGTH}" - ))); - } - - // SearchVector length and element types. - let query_vector = parse_search_vector(&input.search_vector)?; - - // TopK bounds. The lower bound reports the standard constraint message; the - // upper bound reports the documented range message. - if input.top_k < 1 { - return Err(DynamoDbError::ValidationException( - "1 validation error detected: Value at 'TopK' failed to satisfy constraint: \ - Member must have value greater than or equal to 1" - .to_owned(), - )); - } - if input.top_k > MAX_TOP_K { - return Err(DynamoDbError::ValidationException(format!( - "Provided TopK value '{}' is out of valid range. \ - The value must be between 1 and {MAX_TOP_K} inclusive", - input.top_k - ))); - } - - crate::search_vectors_params::check( - input.expression_attribute_names.as_ref(), - input.expression_attribute_values.as_ref(), - input.search_condition_expression.as_deref(), - input.projection_expression.as_deref(), - &ctx.limits, - )?; - - let parsed = condition::parse( - &ctx.storage, + let request::Checked { + input, + query_vector, + parsed, vector_search, - &ctx.account_id, - input.search_condition_expression.as_deref(), - input.expression_attribute_names.as_ref(), - input.expression_attribute_values.as_ref(), - input.projection_expression.as_deref(), - ) - .await?; + } = request::check(&body, &ctx.storage, &ctx.account_id, &ctx.limits).await?; let key_info = ctx .table_key_info(&input.table_name) @@ -386,7 +355,7 @@ mod order_tests; #[cfg(test)] mod tests { use super::condition::resolve_search_scope; - use super::request::MAX_SEARCH_VECTOR_LENGTH; + use super::request::{MAX_SEARCH_VECTOR_LENGTH, parse_search_vector}; use super::*; use extenddb_core::expression::SearchCondition; use extenddb_core::types::AttributeValue; diff --git a/crates/engine/src/search_vectors_request.rs b/crates/engine/src/search_vectors_request.rs index d180fdeb4..ddeba4e31 100644 --- a/crates/engine/src/search_vectors_request.rs +++ b/crates/engine/src/search_vectors_request.rs @@ -1,15 +1,20 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! The `SearchVectors` request body and the checks of its `IndexName`, -//! `SearchVector` and `TopK`. +//! The `SearchVectors` request body and the checks that need no table. use std::collections::HashMap; +use std::sync::Arc; use serde::Deserialize; +use serde_json::Value; use extenddb_core::error::DynamoDbError; +use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{AttributeValue, ReturnConsumedCapacity}; +use extenddb_storage::{StorageEngine, VectorSearchEngine}; + +use super::condition; /// Minimum length of a vector index name. pub(super) const MIN_INDEX_NAME_LENGTH: usize = 3; @@ -40,6 +45,88 @@ pub(super) struct SearchVectorsInput { pub(super) return_consumed_capacity: ReturnConsumedCapacity, } +/// A `SearchVectors` request whose checks that need no table passed. +pub(super) struct Checked<'s> { + pub(super) input: SearchVectorsInput, + pub(super) query_vector: Vec, + pub(super) parsed: condition::Parsed, + pub(super) vector_search: &'s dyn VectorSearchEngine, +} + +/// Check a `SearchVectors` request as far as the checks need no table. +/// +/// # Errors +/// +/// Returns the error of the first failed check. +pub(super) async fn check<'s>( + body: &Value, + storage: &'s Arc, + account_id: &str, + limits: &LimitsConfig, +) -> Result, DynamoDbError> { + let input = SearchVectorsInput::deserialize(body).map_err(crate::deserialize_error)?; + + let vector_search = crate::vector_gate::ensure_search_supported(storage.as_vector_search())?; + + // Request-shape validation runs before the table lookup, so a malformed + // request against a missing table reports the validation error rather than + // ResourceNotFound. + + // IndexName length. + if input.index_name.len() < MIN_INDEX_NAME_LENGTH { + return Err(DynamoDbError::ValidationException(format!( + "1 validation error detected: Value at 'IndexName' failed to satisfy constraint: \ + Member must have length greater than or equal to {MIN_INDEX_NAME_LENGTH}" + ))); + } + + // SearchVector length and element types. + let query_vector = parse_search_vector(&input.search_vector)?; + + // TopK bounds. The lower bound reports the standard constraint message; the + // upper bound reports the documented range message. + if input.top_k < 1 { + return Err(DynamoDbError::ValidationException( + "1 validation error detected: Value at 'TopK' failed to satisfy constraint: \ + Member must have value greater than or equal to 1" + .to_owned(), + )); + } + if input.top_k > MAX_TOP_K { + return Err(DynamoDbError::ValidationException(format!( + "Provided TopK value '{}' is out of valid range. \ + The value must be between 1 and {MAX_TOP_K} inclusive", + input.top_k + ))); + } + + crate::search_vectors_params::check( + input.expression_attribute_names.as_ref(), + input.expression_attribute_values.as_ref(), + input.search_condition_expression.as_deref(), + input.projection_expression.as_deref(), + limits, + )?; + + let parsed = condition::parse( + storage, + vector_search, + account_id, + input.search_condition_expression.as_deref(), + input.expression_attribute_names.as_ref(), + input.expression_attribute_values.as_ref(), + input.projection_expression.as_deref(), + ) + .await?; + + Ok(Checked { + input, + query_vector, + parsed, + vector_search, + }) +} + /// Validate a `SearchVector` and convert it into `f32`. /// /// Checks the length bounds (1..=`MAX_SEARCH_VECTOR_LENGTH`) and that every diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 6033494d6..7f8fa9372 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -139,6 +139,33 @@ pub(crate) async fn handle_request( return error_response(&e, &request_id); } + // The service checks a SearchVectors request before it authorizes it, as + // far as the checks need no table: the body, IndexName, SearchVector, + // TopK, the expression maps, the projection and the search condition. A + // table name the service refuses still answers first, from + // `authorize_request`. + if operation == "SearchVectors" + && crate::table_name_gate::check_table_name_chars(&operation, &input, &account_id).is_ok() + && let Err(e) = extenddb_engine::check_search_vectors_request( + &input, + &state.storage, + &account_id, + &state.limits, + ) + .await + { + let metric_table = metric_table_name(&operation, &input, &state.limits); + record_error_metrics( + &state.metrics, + &e, + &account_id, + metric_table.as_deref(), + &operation, + ); + state.metrics.record_request_count(&account_id, &operation); + return error_response(&e, &request_id); + } + // --- Authz segment --- let authz_start = std::time::Instant::now(); let authorized_key_info; diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index e8549db95..6ea51a324 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -402,6 +402,12 @@ The `search_inequality_filters` runtime setting selects the accounts that get th **Who is affected.** A client that sends SearchVectors with such a map gets `ValidationException`, as it does on the other operations that take the map. No catalog migration is required. +### v1.1.0: SearchVectors sets no `dynamodb:Attributes` value and checks its request before the policy + +**What changed.** A `SearchVectors` request carries no `dynamodb:Attributes` value, whatever its `ProjectionExpression` and `SearchConditionExpression` name, as on DynamoDB. Earlier releases put the attributes in `ProjectionExpression` in the key. SearchVectors also makes the checks that need no table, of the request body, `IndexName`, `SearchVector`, `TopK`, the expression maps, `ProjectionExpression` and `SearchConditionExpression`, before the IAM decision, as DynamoDB does. A table name the service refuses still answers first. Earlier releases made the IAM decision first. + +**Who is affected.** A deployment with a policy that gates `SearchVectors` on `dynamodb:Attributes`. A `Deny` on an attribute no longer refuses a search that projects it, and a `Deny` gated on `Null` `true` refuses every search, a projected one included. DynamoDB answers both the same way (measured 2026-11-21). An `Allow` gated on `ForAllValues` now grants every search its `Action` covers, because the key is absent. A caller that a policy denies and that sends a request failing one of the checks gets `ValidationException` where it got `AccessDeniedException`. No catalog migration is required. + ### v1.0.0: Cassandra reads and writes at `LOCAL_QUORUM` **What changed.** The Cassandra backend runs its reads and writes at `LOCAL_QUORUM`. 0.1.15 ran many of them at `ONE`, the driver's default, in each area: items (the reads of GetItem, Query and Scan among them), transactions, TTL, streams, the catalog, IAM and `init`. A read with `ConsistentRead` `false` also runs at `LOCAL_QUORUM`. A lightweight transaction runs Paxos at `LOCAL_SERIAL` and commits at `LOCAL_QUORUM`. 0.1.15 ran many of its lightweight transactions at those levels already, and others, among them the admin user creation and most IAM writes, at the driver's defaults, `SERIAL` and `ONE`. Batches ran at `LOCAL_QUORUM` before and still do. No setting changes these levels (#945). diff --git a/tests/test_authz_search_vectors_index.py b/tests/test_authz_search_vectors_index.py index cb89af006..da4807828 100644 --- a/tests/test_authz_search_vectors_index.py +++ b/tests/test_authz_search_vectors_index.py @@ -14,15 +14,18 @@ for every caller, before the policy decision, as Query and Scan do. The ``ROWS`` were measured on DynamoDB in us-east-1 on 2026-11-21, each -request twice with the same answer. The ``deny(ssn)`` rows ran +request twice with the same answer, except the ``deny(null)`` rows that +expect ValidationException, which were not sent. The ``deny(ssn)`` rows ran under a session policy that allows ``dynamodb:*`` and denies ``dynamodb:*`` under ``ForAnyValue:StringEquals {"dynamodb:Attributes": ["ssn"]}``, the ``deny(null)`` rows under one that denies under ``Null {"dynamodb:Attributes": "true"}``, and the ``allow-all`` rows with no session policy. The service sets no ``dynamodb:Attributes`` value on a SearchVectors request: it serves a projection of ``ssn`` under ``deny(ssn)``, and refuses -every search under ``deny(null)``. ExtendDB decides the policy before it -checks the ``ExpressionAttributeNames`` keys. +every search under ``deny(null)``. The service makes the checks of a +SearchVectors request that need no table, ``TopK`` and the +``ExpressionAttributeNames`` keys among them, before the policy decision, so +under ``deny(null)`` a request that fails one gets ValidationException. The principals are builtin-IAM users provisioned through the management API. The module skips when the backend does not support vector indexes, unless @@ -360,6 +363,34 @@ def _invalid_key(key: str) -> str: "AccessDeniedException", DENIED, ), + "null-key-without-hash-before-the-policy": ( + "deny(null)", + {"ProjectionExpression": "#n", "ExpressionAttributeNames": {"n": "cat"}}, + "ValidationException", + _invalid_key("n"), + ), + "null-empty-map-before-the-policy": ( + "deny(null)", + {"ProjectionExpression": "cat", "ExpressionAttributeNames": {}}, + "ValidationException", + "ExpressionAttributeNames must not be empty", + ), + "null-top-k-of-zero-before-the-policy": ( + "deny(null)", + {"TopK": 0, "ProjectionExpression": "cat"}, + "ValidationException", + TOP_K_OF_ZERO, + ), + "null-unused-name-before-the-policy": ( + "deny(null)", + { + "SearchConditionExpression": "cat = :v", + "ExpressionAttributeNames": {"#u": "ssn"}, + "ExpressionAttributeValues": SSN_VALUE, + }, + "ValidationException", + "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}", + ), "projection-key-without-hash": ( "deny(ssn)", {"ProjectionExpression": "#n", "ExpressionAttributeNames": {"n": "ssn"}}, From b3f7f54ea9af527f4e618340504fab675c169100 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 20:01:10 +0000 Subject: [PATCH 044/101] ci: build and wire-test the search grammar compiled out Each crate that declares the search-inequality-filters feature has it in its default list, and the crates take their internal dependencies with default features. So `--no-default-features` on one crate left the feature on in its dependencies: the compiled-out job linted each crate with its own flag off while core and the engine kept the grammar, and no job built or wire-tested a binary without it. The wire helpers took the 404 of an absent setting as the extended grammar, which such a binary does not serve, so 46 vector wire tests failed against it. devtools/compile-out-search-inequality-filters removes the feature from the default list of the seven crates that declare it and checks with cargo tree that nothing in the workspace enables it. The compiled-out job runs it, then clippy on the workspace and the unit tests of core, the engine, the server and the app. The wire job gains a compiled-out cell per backend. expected_grammar tells a server without the setting from one with no row: on a 404 it writes a value every build refuses, and "Unknown setting" means the equality-only grammar. --- .../workflows/search-inequality-filters.yml | 47 ++++++++------- .../compile-out-search-inequality-filters | 59 +++++++++++++++++++ devtools/run-tests | 4 +- tests/search_vectors_wire.py | 22 +++++-- 4 files changed, 105 insertions(+), 27 deletions(-) create mode 100755 devtools/compile-out-search-inequality-filters diff --git a/.github/workflows/search-inequality-filters.yml b/.github/workflows/search-inequality-filters.yml index 63e16d81a..c0ea5d076 100644 --- a/.github/workflows/search-inequality-filters.yml +++ b/.github/workflows/search-inequality-filters.yml @@ -17,9 +17,16 @@ concurrency: # The search-inequality-filters Cargo feature is on by default, so the other # workflows build, lint and test it, and their wire tests run with the # search_inequality_filters setting absent, which gives every account the -# extended grammar. These jobs cover what they do not: each crate that -# declares the feature built and tested with it compiled out, and the vector -# wire tests with the setting written as `off` and as `all`. +# extended grammar. These jobs cover what they do not: the workspace built, +# linted and tested with the feature compiled out, and the vector wire tests +# with the setting written as `off` and as `all`, and against the build with +# the feature compiled out. +# +# The crates take their internal dependencies with default features, so no +# cargo command line compiles the feature out. +# devtools/compile-out-search-inequality-filters removes it from the default +# list of every crate that declares it, which compiles it out of the +# workspace, and checks that nothing enables it. jobs: compiled-out: runs-on: extenddb_ubuntu-2404_4-core @@ -33,21 +40,14 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: save-if: ${{ github.ref == 'refs/heads/main' }} - # One crate per run: a crate built with others would get the feature - # back from a dependent that enables its defaults. - - name: Lint each crate with the feature off + - name: Compile the feature out + run: devtools/compile-out-search-inequality-filters + - name: Lint the workspace with the feature compiled out + run: cargo clippy --locked --workspace --all-targets -- -D warnings + - name: Unit tests with the feature compiled out run: | - set -e - cargo clippy --locked -p extenddb-core --all-targets --no-default-features --features partiql -- -D warnings - cargo clippy --locked -p extenddb-engine --all-targets --no-default-features --features partiql -- -D warnings - for crate in extenddb-server extenddb-app extenddb-storage-sqlite extenddb-storage-postgres; do - cargo clippy --locked -p "$crate" --all-targets --no-default-features -- -D warnings - done - - name: Unit tests of core and the engine with the feature off - run: | - set -e - cargo test --locked --no-fail-fast -p extenddb-core --no-default-features --features partiql - cargo test --locked --no-fail-fast -p extenddb-engine --no-default-features --features partiql + cargo test --locked --no-fail-fast -p extenddb-core -p extenddb-engine \ + -p extenddb-server -p extenddb-app --lib wire: runs-on: extenddb_ubuntu-2404_4-core @@ -56,7 +56,7 @@ jobs: fail-fast: false matrix: backend: [sqlite, postgres] - setting: ["off", all] + setting: ["off", all, compiled-out] services: postgres: image: pgvector/pgvector:pg16 @@ -79,6 +79,10 @@ jobs: cache-on-failure: true save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Compile the feature out + if: matrix.setting == 'compiled-out' + run: devtools/compile-out-search-inequality-filters + - name: Build release run: cargo build --locked --release -p extenddb --no-default-features --features ${{ matrix.backend }} @@ -121,15 +125,16 @@ jobs: # file, except the CLI catalog migration file, which builds catalogs of # its own and does not depend on the feature. devtools/run-tests writes # the setting before the suite starts; the modules read it and fail when - # the server serves the other grammar. Under `off` the tests of the - # extended grammar skip. + # the server serves the other grammar. Under `off`, and against the build + # with the feature compiled out, which has no such setting, the tests of + # the extended grammar skip. - name: Run the vector wire tests env: EXTENDDB_TEST_ENDPOINT: https://127.0.0.1:18443 EXTENDDB_ADMIN_USER: admin EXTENDDB_ADMIN_PASSWORD: ${{ steps.init.outputs.admin_password }} EXTENDDB_TEST_BACKUP_STORE: ${{ matrix.backend == 'sqlite' && 'filesystem' || 'none' }} - EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS: ${{ matrix.setting }} + EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS: ${{ matrix.setting != 'compiled-out' && matrix.setting || '' }} EXTENDDB_EXPECT_VECTORS: "1" run: devtools/run-tests --extenddb --pytest --parallel --filter "vector and not test_cli" diff --git a/devtools/compile-out-search-inequality-filters b/devtools/compile-out-search-inequality-filters new file mode 100755 index 000000000..364af2a38 --- /dev/null +++ b/devtools/compile-out-search-inequality-filters @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 +"""Remove the search-inequality-filters Cargo feature from every default list. + +Each crate that declares the feature has it in its `default` list, and the +crates take their internal dependencies with default features, so no cargo +command line compiles it out. Removing it from every `default` list is how +the feature is compiled out. This script edits the working tree's Cargo.toml +files that way, then checks with `cargo tree` that nothing in the workspace +enables the feature. CI builds, lints and tests the tree it leaves. + +Usage: devtools/compile-out-search-inequality-filters +""" + +from __future__ import annotations + +import re +import subprocess +import sys +from pathlib import Path + +FEATURE = "search-inequality-filters" +CRATES = 7 + + +def main() -> int: + root = Path(__file__).resolve().parent.parent + default = re.compile(r'^default = \[(.*)\]$', re.MULTILINE) + edited = [] + for manifest in sorted(root.glob("crates/*/Cargo.toml")): + text = manifest.read_text() + match = default.search(text) + if match is None or f'"{FEATURE}"' not in match.group(1): + continue + kept = [f for f in (e.strip() for e in match.group(1).split(",")) if f and f != f'"{FEATURE}"'] + text = text[: match.start()] + f"default = [{', '.join(kept)}]" + text[match.end() :] + manifest.write_text(text) + edited.append(manifest.relative_to(root)) + if len(edited) != CRATES: + print(f"error: expected {CRATES} crates with {FEATURE} in default, edited {edited}", file=sys.stderr) + return 1 + tree = subprocess.run( + ["cargo", "tree", "--locked", "--workspace", "-e", "features", "-i", "extenddb-core"], + cwd=root, + check=True, + capture_output=True, + text=True, + ).stdout + if f'feature "{FEATURE}"' in tree: + print(f"error: the workspace still enables {FEATURE}:\n{tree}", file=sys.stderr) + return 1 + for manifest in edited: + print(f"removed {FEATURE} from the default list of {manifest}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/devtools/run-tests b/devtools/run-tests index c08e56605..4a45553a0 100755 --- a/devtools/run-tests +++ b/devtools/run-tests @@ -420,8 +420,8 @@ if $NEEDS_INTEGRATION && [[ "$TARGET" != "real-dynamodb" ]]; then echo " ✓ allow_credential_import set to true" fi fi - # The SearchVectors grammar setting. The suites read it and never write it, - # so parallel workers all see the value written here. + # The SearchVectors grammar setting. The suites read it and never change + # it, so parallel workers all see the value written here. if [[ -n "${EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS:-}" ]]; then if [[ ! -x "$BINARY" || ! -f "$CONFIG_FOR_SETTINGS" ]]; then echo "error: EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS is set and there is no $BINARY or $CONFIG_FOR_SETTINGS to write it with." diff --git a/tests/search_vectors_wire.py b/tests/search_vectors_wire.py index 9906d6eaf..068249a45 100644 --- a/tests/search_vectors_wire.py +++ b/tests/search_vectors_wire.py @@ -11,8 +11,8 @@ extended grammar. Against ExtendDB with admin credentials in the environment, ``expected_grammar`` reads it from the ``search_inequality_filters`` setting, and ``grammar_of`` fails when the target answers with the other grammar. -These helpers only read the setting. ``devtools/run-tests`` writes it, from -``EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS``, before any suite starts. +These helpers never change the setting. ``devtools/run-tests`` writes it, +from ``EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS``, before any suite starts. """ from __future__ import annotations @@ -171,7 +171,9 @@ def expected_grammar() -> str | None: An absent or empty setting is every account, so the extended grammar; ``off`` is the equality-only grammar. A list of accounts names the account in ``EXTENDDB_TEST_ACCOUNT_ID``, which - ``devtools/provision-test-credentials`` exports. + ``devtools/provision-test-credentials`` exports. A build without the + ``search-inequality-filters`` Cargo feature has no such setting and + serves the equality-only grammar. """ api = _settings_api() if api is None: @@ -179,7 +181,7 @@ def expected_grammar() -> str | None: url, auth = api resp = requests.get(url, auth=auth, timeout=30, verify=False) if resp.status_code == 404: - return "extended" + return "extended" if _setting_is_known(url, auth) else "equality" assert resp.status_code == 200, f"GET {url}: {resp.status_code} {resp.text}" value = resp.json()["value"].strip() if value == "off": @@ -195,6 +197,18 @@ def expected_grammar() -> str | None: return "extended" if account in listed else "equality" +def _setting_is_known(url: str, auth: tuple[str, str]) -> bool: + """Whether the server knows the setting, from a write of a value every + build refuses: a build with the feature refuses the value, and one + without it refuses the key. Neither stores anything.""" + resp = requests.put(url, json={"value": "?"}, auth=auth, timeout=30, verify=False) + assert resp.status_code == 400, f"PUT {url}: {resp.status_code} {resp.text}" + if "Unknown setting" in resp.text: + return False + assert "Invalid value" in resp.text, f"PUT {url}: {resp.text}" + return True + + def grammar_of(probe: Callable[[], requests.Response]) -> str: """The grammar the target serves, from ``probe``: an inequality search. From 514105a8b9cb8ae67dd094a14b0e14ac30e8f6dc Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 20:01:19 +0000 Subject: [PATCH 045/101] docs(search): correct the condition count and describe setting reads The usage guide said a SearchConditionExpression takes one `=` on the HASH attribute and up to 50 conditions on the inline filter attributes. DynamoDB counts the HASH condition in the 50: in eu-north-1 on 2026-11-24, each request twice, the HASH equality with 49 inline conditions answers 200 and with 50 answers "The expression contains too many conditions; number of conditions: 51, maximum: 50". The guide also called TopK optional; the service answers a request without it with ValidationException "missing field `TopK`". Both sentences now say what the service does. The admin guide and the upgrade manual now say that a server reads the search_inequality_filters setting only for a search whose answer depends on the grammar, that a failed read uses the last value read, and that a malformed catalog value enables no account. The admin guide no longer describes a build without the Cargo feature. The header of the condition limit wire module dates its measurements without describing how the service served the grammar over time. --- docs/manuals/03-usage-guide.md | 9 +++++---- docs/manuals/05-admin-guide.md | 2 +- docs/manuals/07-upgrade-manual.md | 2 +- tests/test_search_vectors_condition_limit.py | 19 +++++++++---------- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/docs/manuals/03-usage-guide.md b/docs/manuals/03-usage-guide.md index fa8fbd988..983efbbd0 100755 --- a/docs/manuals/03-usage-guide.md +++ b/docs/manuals/03-usage-guide.md @@ -434,10 +434,11 @@ the declared number of dimensions. An item that omits it is stored and simply do not appear in that index, the same way a GSI ignores an item missing its key. `SearchVectors` returns the nearest items with a `Score` per hit, ordered nearest -first, and takes an optional `TopK` up to 100. A `SearchConditionExpression` takes -one `=` on the index's HASH attribute and up to 50 conditions on its inline filter -attributes: `=`, `<>`, `<`, `<=`, `>`, `>=`, `BETWEEN`, `IN`, `AND`, `OR`, `NOT`, -parentheses, `attribute_exists` and `attribute_not_exists`. The +first, and takes a `TopK` from 1 to 100. A `SearchConditionExpression` takes up +to 50 conditions, one `=` on the index's HASH attribute among them. A condition on +an inline filter attribute takes `=`, `<>`, `<`, `<=`, `>`, `>=`, `BETWEEN`, `IN`, +`attribute_exists` or `attribute_not_exists`, and conditions combine with `AND`, +`OR`, `NOT` and parentheses. The `search_inequality_filters` runtime setting can limit the conditions other than an AND of equalities to a list of accounts, or turn them off. diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index da858b76f..b29d9d173 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -326,7 +326,7 @@ Managed via `extenddb settings set`. Changes take effect within 30 seconds witho | `log_level` | `info` | Log level: trace, debug, info, warn, error | | `control_plane_delay_seconds` | `0.25` | Delay for table status transitions, in seconds (0 = instant). PostgreSQL and SQLite write 0.25 into the catalog when it is created; MongoDB and Cassandra use 0.25 when the setting is absent. On PostgreSQL and SQLite a value below 1 makes DeleteTable remove the table in the request; on PostgreSQL, if a session holds a lock on the table's data (a reader, an open write transaction, an index build), DeleteTable returns `DELETING` instead (after at most about a second), the drop finishes in the background within about a second of that session's release, and a CreateTable of the same name is refused until then. | | `allow_credential_import` | `false` | Whether `import-access-key` is allowed. Only `true` enables it | -| `search_inequality_filters` | every account | The accounts whose `SearchVectors` requests accept the extended `SearchConditionExpression` grammar, as DynamoDB does for every account: `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. With `off`, or for an account the list does not name, a search condition is an AND of equalities. A server reads the setting at most once a second, so a change applies within about a second without a restart. A build without the `search-inequality-filters` Cargo feature refuses the key and accepts only equalities | +| `search_inequality_filters` | every account | The accounts whose `SearchVectors` requests accept the extended `SearchConditionExpression` grammar, as DynamoDB does for every account: `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. A malformed value in the catalog, which the CLI and the management API refuse to write, is no account. With `off`, or for an account the list does not name, a search condition is an AND of equalities. A server reads the setting only for a search whose answer depends on the grammar, and at most once a second, so a change applies within about a second without a restart. When a read fails or does not end within two seconds, the server uses the value of its last read that answered; before any read has answered, such a search answers `ServiceUnavailableException` | | `vector_backfill_batch_delay_ms` | `0` | **Test-oriented.** Milliseconds to pause between batches while a vector index backfills. Zero in production. A test sets it so a write is guaranteed to land while the index is still building. The pause is outside the batch transaction, so writes are still accepted throughout, but it does extend the per-table propagation hold: no index on that table advances while the build runs, GSIs included, and the accepted range goes up to 60 s per batch. | | `vector_allocation_phase_delay_ms` | `0` | **Test-oriented.** Milliseconds to hold a new vector index in the resource-allocation phase (`CREATING` with `Backfilling: false`) before the scan starts. Zero in production. Without it the phase lasts only from the `UpdateTable` transaction, which inserts the row as `CREATING` with `Backfilling: false`, until the detached build task flips the flag, which is a window no client can time reliably rather than one that cannot exist. | diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 6ea51a324..437db4200 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -392,7 +392,7 @@ deployment, even when no catalog migration is required. **What changed.** A `SearchConditionExpression` takes the comparators `<>`, `<`, `<=`, `>` and `>=`, `BETWEEN`, `IN`, `OR`, `NOT`, parentheses, `attribute_exists` and `attribute_not_exists`, and more than one condition on an attribute, up to 50 conditions. DynamoDB serves this grammar to every account. Earlier releases accepted only an AND of equalities, at most 19, and refused the other forms with `ValidationException`. A Number in the condition now compares as the nearest binary64 value of each side, as on DynamoDB, so `9007199254740992` and `9007199254740993` are equal. Earlier releases compared Numbers in the condition exactly. -The `search_inequality_filters` runtime setting selects the accounts that get the grammar: `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. With `off`, or for an account the list does not name, a search condition is an AND of equalities, compared as in earlier releases. A server reads the setting at most once a second, so a change applies within about a second without a restart. A read of the setting that fails or does not end within two seconds answers `ServiceUnavailableException`. A malformed value in the catalog is logged once per change and enables every account. The [admin guide](05-admin-guide.md) lists the setting. +The `search_inequality_filters` runtime setting selects the accounts that get the grammar: `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. With `off`, or for an account the list does not name, a search condition is an AND of equalities, compared as in earlier releases. A server reads the setting only for a search whose answer depends on the grammar, such as an inequality or a condition on a Number, and at most once a second, so a change applies within about a second without a restart. A search that both grammars answer alike, such as an AND of string equalities, never reads it. When a read fails or does not end within two seconds, the server uses the value of its last read that answered; before any read has answered, such a search answers `ServiceUnavailableException`. A malformed value in the catalog, which the CLI and the management API refuse to write, is logged once per change and enables no account. The [admin guide](05-admin-guide.md) lists the setting. **Who is affected.** A client that sent one of these forms got `ValidationException` and now gets the items the condition selects. A client whose condition compares Numbers that differ only after the 15th significant digit can get other items. To keep the earlier grammar, run `extenddb settings --config extenddb.toml set search_inequality_filters off` after the upgrade. MongoDB and Cassandra refuse SearchVectors, as before. No catalog migration is required. diff --git a/tests/test_search_vectors_condition_limit.py b/tests/test_search_vectors_condition_limit.py index cdd7b3dab..8aa0c6c73 100644 --- a/tests/test_search_vectors_condition_limit.py +++ b/tests/test_search_vectors_condition_limit.py @@ -3,13 +3,12 @@ """SearchVectors condition count limit and the order of the expression checks. -Under the equality-only grammar, measured against Amazon DynamoDB on -2026-10-29 and 2026-10-30 in us-east-1, before the service served the -extended grammar to every account, on a table whose vector index declares a -HASH ``h`` and 18 inline filters ``f1`` to ``f18``. Each request shape was -sent twice with the same response both times. ExtendDB serves this grammar -when the ``search_inequality_filters`` setting is ``off`` or does not name -the account. +Under the equality-only grammar, which ExtendDB serves when the +``search_inequality_filters`` setting is ``off`` or does not name the +account. The answers were measured against Amazon DynamoDB on 2026-10-29 and +2026-10-30 in us-east-1, on a table whose vector index declares a HASH ``h`` +and 18 inline filters ``f1`` to ``f18``. Each request shape was sent twice +with the same response both times. The limit is 19 comparisons. The 20th gets ``Invalid SearchConditionExpression: SearchConditionExpression cannot have more than 1 partition key and more than @@ -31,9 +30,9 @@ ExtendDB's wording differs from the service's. Those tests assert that the check, not the count, answers. -The service now serves the extended grammar instead (comparators other than -``=``, OR, NOT, IN, BETWEEN, up to 50 conditions), and so does ExtendDB when -the setting is absent. The ``grammar`` fixture asks the target which grammar +The service serves the extended grammar (comparators other than ``=``, OR, +NOT, IN, BETWEEN, up to 50 conditions), and so does ExtendDB when the setting +is absent. The ``grammar`` fixture asks the target which grammar it serves, by sending ``h = :v0 AND f1 <> :v1``: the equality-only grammar refuses it with the comparator message and the extended grammar answers 200. Against ExtendDB the fixture also reads the ``search_inequality_filters`` From f73cad851d2be121b09d4bdecf90cfec4142ac21 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Tue, 24 Nov 2026 20:01:48 +0000 Subject: [PATCH 046/101] test(core): pin a too-large attribute name ahead of a bad names key DynamoDB answers an ExpressionAttributeNames value of 65536 bytes or more ahead of a key that is not # followed by letters, digits and underscores: `{"n": <65536 bytes>}` gets "Attribute name is too large, must be less than 65536 bytes for key n" (eu-north-1 and us-east-1, 2026-11-24, each request twice). The unit tests pinned the empty name ahead of a bad key, and moving the key check between the empty-name and the too-large-name checks passed all of them. A unit test now sends a too-large name with the key `n`, and with `#a-b` beside a values map. --- .../src/expression/search_params_tests.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/core/src/expression/search_params_tests.rs b/crates/core/src/expression/search_params_tests.rs index 241b34875..57725193b 100644 --- a/crates/core/src/expression/search_params_tests.rs +++ b/crates/core/src/expression/search_params_tests.rs @@ -75,6 +75,25 @@ fn an_empty_attribute_name_answers_before_the_keys_and_the_values() { ); } +/// An attribute name of 65536 bytes or more answers ahead of a bad key, as +/// an empty one does (measured on DynamoDB 2026-11-24, `{"n": <65536 bytes>}` +/// twice in each of two regions). +#[test] +fn a_too_large_attribute_name_answers_before_the_keys() { + let large = "C".repeat(65536); + assert_eq!( + maps(Some(&names(&[("n", large.as_str())])), None), + "Attribute name is too large, must be less than 65536 bytes for key n" + ); + assert_eq!( + maps( + Some(&names(&[("#a-b", large.as_str())])), + Some(&values(&[":us"])) + ), + "Attribute name is too large, must be less than 65536 bytes for key #a-b" + ); +} + #[test] fn a_bad_name_key_answers_before_a_bad_value_key() { assert_eq!( From 37ae360340633ddb48e30f82506124b2798f4f1f Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:46:56 +0000 Subject: [PATCH 047/101] refactor(core): check SearchVectors map keys with the shared key check DynamoDB checks the keys of the two expression maps of SearchVectors with the messages the other operations use, and refuses a map that no expression of the request uses with the same two messages. ExtendDB repeated the length and syntax checks of a placeholder key and the two "can only be specified when using expressions" checks in search_params. The map check now calls validate_placeholder_key, made pub(crate), with the key size in the too-long message, after its own empty-key branch, and validate_expression_param_usage for the usage checks. Both maps are refused when empty before that call, so the messages and their order stay the same. The search_params unit tests (9) and the engine map tests pass unchanged. --- crates/core/src/expression/search_params.rs | 45 ++++++++------------- crates/core/src/serde_helpers.rs | 2 +- 2 files changed, 17 insertions(+), 30 deletions(-) diff --git a/crates/core/src/expression/search_params.rs b/crates/core/src/expression/search_params.rs index 5bb3ec056..7e7329510 100644 --- a/crates/core/src/expression/search_params.rs +++ b/crates/core/src/expression/search_params.rs @@ -29,12 +29,10 @@ use std::collections::{BTreeSet, HashMap}; use crate::error::DynamoDbError; -use crate::serde_helpers::is_placeholder_ident; +use crate::expression::validate_expression_param_usage; +use crate::serde_helpers::validate_placeholder_key; use crate::types::AttributeValue; -/// The longest key either map takes, in bytes, prefix included. -const MAX_KEY_BYTES: usize = 255; - /// An attribute name must be shorter than this many bytes. const NAME_LIMIT_BYTES: usize = 65536; @@ -48,7 +46,10 @@ fn invalid(msg: String) -> DynamoDbError { DynamoDbError::ValidationException(msg) } -/// Check one map's size and keys, in the order the service checks them. +/// Check one map's size and keys, in the order the service checks them. An +/// empty key has its own message on this endpoint; every other key goes +/// through the check the other operations use, with the key size in the +/// too-long message of both maps. fn check_keys<'a>( field: &str, prefix: char, @@ -63,19 +64,7 @@ fn check_keys<'a>( "{field} contains invalid key: The expression attribute map contains an empty key;" ))); } - if key.len() > MAX_KEY_BYTES { - return Err(invalid(format!( - "{field} contains invalid key: The expression attribute map contains a key that is \ - too long; size of key: {}", - key.len() - ))); - } - if !key.strip_prefix(prefix).is_some_and(is_placeholder_ident) { - return Err(invalid(format!( - "{field} contains invalid key: Syntax error; key: \"{key}\"" - ))); - } - Ok(()) + validate_placeholder_key(key, prefix, field, true).map_err(invalid) }) } @@ -115,17 +104,15 @@ pub fn check_search_maps( if let Some(values) = values { check_keys(VALUES, ':', values.keys())?; } - if names.is_some() && !has_condition && !has_projection { - return Err(invalid(format!( - "{NAMES} can only be specified when using expressions" - ))); - } - if values.is_some() && !has_condition { - return Err(invalid(format!( - "{VALUES} can only be specified when using expressions" - ))); - } - Ok(()) + // Both maps are known not to be empty here, so the shared check refuses + // exactly a map that no expression of the request can use. + validate_expression_param_usage( + names, + has_condition || has_projection, + values, + has_condition, + &[], + ) } /// Every `#name` written in `exprs`. diff --git a/crates/core/src/serde_helpers.rs b/crates/core/src/serde_helpers.rs index 3f3dae411..a9036c809 100644 --- a/crates/core/src/serde_helpers.rs +++ b/crates/core/src/serde_helpers.rs @@ -28,7 +28,7 @@ pub(crate) fn is_placeholder_ident(rest: &str) -> bool { /// /// `include_size_in_too_long`: the Names too-long message appends /// `; size of key: N`, the Values one does not (Amazon `DynamoDB` quirk). -fn validate_placeholder_key( +pub(crate) fn validate_placeholder_key( key: &str, prefix: char, field_name: &str, From 054ae772597488bdc8998ede8a92acd8c8821a2f Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:47:06 +0000 Subject: [PATCH 048/101] fix(core): share the BETWEEN bound check and show Binary bounds in base64 DynamoDB refuses two BETWEEN value bounds of different types, then a lower bound above the upper bound, with the same text for ConditionExpression, FilterExpression and SearchConditionExpression, and shows a Binary bound as B: and the base64 of its bytes: `{B:Ag==}` for the bytes 0x02 (measured in eu-north-1 on 2026-11-25, each request twice, for bounds B/B out of order, B/S, S/B and N/B). ExtendDB had two copies of the check: the evaluator showed a Binary bound as `B:`, and the search grammar repeated the check with its own display. The evaluator now has one check, between_bounds_fault, and one operand display, which shows a Binary bound in base64. The evaluator and the search grammar call both, so a ConditionExpression with Binary bounds now names them as the service does. The Number bound comparison stays exact for both. A new evaluator test pins the two measured ConditionExpression texts with Binary bounds, and a new search grammar row the B/S text; both fail with the display set back to `B:`. --- crates/core/src/expression/evaluator.rs | 69 ++++++++++++++----- crates/core/src/expression/evaluator_tests.rs | 35 ++++++++++ .../expression/search_filter/tests_grammar.rs | 8 +++ .../core/src/expression/search_filter/walk.rs | 50 ++------------ 4 files changed, 97 insertions(+), 65 deletions(-) diff --git a/crates/core/src/expression/evaluator.rs b/crates/core/src/expression/evaluator.rs index 56b226d03..e2f50b189 100755 --- a/crates/core/src/expression/evaluator.rs +++ b/crates/core/src/expression/evaluator.rs @@ -84,25 +84,16 @@ pub fn evaluate_condition_at( if matches!(low.as_ref(), Expr::Placeholder(_)) && matches!(high.as_ref(), Expr::Placeholder(_)) && let (Some(l), Some(h)) = (lo.as_deref(), hi.as_deref()) + && let Some(fault) = between_bounds_fault( + l, + h, + placeholder_numeric(low, maps), + placeholder_numeric(high, maps), + ) { - let l_type = attribute_type_code(l); - let h_type = attribute_type_code(h); - if l_type != h_type { - return Err(DynamoDbError::ValidationException(format!( - "Invalid ConditionExpression: The BETWEEN operator requires same data type for lower and upper bounds; lower bound operand: AttributeValue: {{{}}}, upper bound operand: AttributeValue: {{{}}}", - format_attribute_value(l), - format_attribute_value(h) - ))); - } - let lpn = placeholder_numeric(low, maps); - let hpn = placeholder_numeric(high, maps); - if compare_values(l, h, CompareOp::Gt, lpn, hpn, NumberPrecision::Exact) { - return Err(DynamoDbError::ValidationException(format!( - "Invalid ConditionExpression: The BETWEEN operator requires upper bound to be greater than or equal to lower bound; lower bound operand: AttributeValue: {{{}}}, upper bound operand: AttributeValue: {{{}}}", - format_attribute_value(l), - format_attribute_value(h) - ))); - } + return Err(DynamoDbError::ValidationException(format!( + "Invalid ConditionExpression: {fault}" + ))); } match (&val, &lo, &hi) { (Some(v), Some(l), Some(h)) => { @@ -413,11 +404,51 @@ fn evaluate_size<'a>( } /// Format an `AttributeValue` for error messages (e.g. `N:5`, `S:hello`). +/// The fault of two BETWEEN bounds that are both values, without the +/// expression prefix: bounds of different types, then a lower bound above the +/// upper bound. Numbers compare exactly, whatever the precision of the +/// expression. `low_parsed` and `high_parsed` are the pre-parsed numbers of +/// placeholder bounds, when the caller has them. +pub(crate) fn between_bounds_fault( + low: &AttributeValue, + high: &AttributeValue, + low_parsed: Option>, + high_parsed: Option>, +) -> Option { + let fault = if attribute_type_code(low) != attribute_type_code(high) { + "The BETWEEN operator requires same data type for lower and upper bounds" + } else if compare_values( + low, + high, + CompareOp::Gt, + low_parsed, + high_parsed, + NumberPrecision::Exact, + ) { + "The BETWEEN operator requires upper bound to be greater than or equal to lower bound" + } else { + return None; + }; + Some(format!( + "{fault}; lower bound operand: AttributeValue: {{{}}}, upper bound operand: \ + AttributeValue: {{{}}}", + format_attribute_value(low), + format_attribute_value(high) + )) +} + +/// A value as the service shows an operand in a message: `S:US`, `N:5`, or +/// `B:` and the base64 of the bytes (measured 2026-11-25 in eu-north-1 on the +/// BETWEEN bounds of ConditionExpression, FilterExpression and +/// SearchConditionExpression). fn format_attribute_value(val: &AttributeValue) -> String { + use base64::Engine as _; match val { AttributeValue::S(s) => format!("S:{s}"), AttributeValue::N(n) => format!("N:{n}"), - AttributeValue::B(_) => "B:".to_owned(), + AttributeValue::B(b) => { + format!("B:{}", base64::engine::general_purpose::STANDARD.encode(b)) + } _ => format!("{}:", attribute_type_code(val)), } } diff --git a/crates/core/src/expression/evaluator_tests.rs b/crates/core/src/expression/evaluator_tests.rs index 3fbf228d8..1520a2778 100755 --- a/crates/core/src/expression/evaluator_tests.rs +++ b/crates/core/src/expression/evaluator_tests.rs @@ -251,6 +251,41 @@ fn between_out_of_range() { assert!(!eval("age BETWEEN :lo AND :hi", &item, HashMap::new(), values).unwrap()); } +/// A Binary bound shows as `B:` and the base64 of its bytes, as DynamoDB +/// shows it for ConditionExpression, FilterExpression and +/// SearchConditionExpression (eu-north-1, 2026-11-25, each request twice: +/// `Tag BETWEEN :a AND :b` with `:a` `{"B": "Ag=="}` and `:b` `{"B": "AQ=="}`, +/// and with `:a` `{"B": "AQ=="}` and `:b` `{"S": "x"}`). +#[test] +fn between_bound_faults_show_binary_bounds_in_base64() { + let item = simple_item(); + let bin = |b: &[u8]| AttributeValue::B(b.to_vec()); + let cases = [ + ( + bin(&[2]), + bin(&[1]), + "Invalid ConditionExpression: The BETWEEN operator requires upper bound to be \ + greater than or equal to lower bound; lower bound operand: AttributeValue: \ + {B:Ag==}, upper bound operand: AttributeValue: {B:AQ==}", + ), + ( + bin(&[1]), + AttributeValue::S("x".into()), + "Invalid ConditionExpression: The BETWEEN operator requires same data type for \ + lower and upper bounds; lower bound operand: AttributeValue: {B:AQ==}, upper \ + bound operand: AttributeValue: {S:x}", + ), + ]; + for (lo, hi, want) in cases { + let values = HashMap::from([("a".to_owned(), lo), ("b".to_owned(), hi)]); + let err = eval("Tag BETWEEN :a AND :b", &item, HashMap::new(), values).unwrap_err(); + assert!( + matches!(&err, DynamoDbError::ValidationException(m) if m == want), + "{err:?}" + ); + } +} + #[test] fn in_expression_match() { let item = simple_item(); diff --git a/crates/core/src/expression/search_filter/tests_grammar.rs b/crates/core/src/expression/search_filter/tests_grammar.rs index e7e7853aa..5b0c656d7 100644 --- a/crates/core/src/expression/search_filter/tests_grammar.rs +++ b/crates/core/src/expression/search_filter/tests_grammar.rs @@ -139,6 +139,14 @@ fn between_bounds_are_checked_while_the_tree_is_built() { AttributeValue: {S:US}", ), ), + ( + "a BETWEEN :b AND :s", + p( + "The BETWEEN operator requires same data type for lower and upper bounds; \ + lower bound operand: AttributeValue: {B:aGk=}, upper bound operand: \ + AttributeValue: {S:US}", + ), + ), ("a BETWEEN :t AND :t", ordering("BETWEEN", "BOOL")), ( "a BETWEEN a AND :n", diff --git a/crates/core/src/expression/search_filter/walk.rs b/crates/core/src/expression/search_filter/walk.rs index e5ccf0154..b5e910045 100644 --- a/crates/core/src/expression/search_filter/walk.rs +++ b/crates/core/src/expression/search_filter/walk.rs @@ -13,7 +13,7 @@ use std::collections::HashMap; use super::grammar::{Call, Element, Node, Operand}; use crate::expression::CompareOp; -use crate::expression::resolver::{attribute_type_code, number_value}; +use crate::expression::resolver::attribute_type_code; use crate::types::AttributeValue; /// The most values an IN list takes. @@ -365,55 +365,13 @@ pub(super) fn resolved_path(elements: &[Element], maps: &Maps<'_>) -> String { } /// When both bounds are values: the same type, then the lower bound not -/// above the upper bound. +/// above the upper bound, with the check and the operand display that +/// ConditionExpression uses. fn between_bounds(low: &Operand, high: &Operand, maps: &Maps<'_>) -> Result<(), String> { let (Some(lo), Some(hi)) = (literal(low, maps), literal(high, maps)) else { return Ok(()); }; - let bounds = || { - format!( - "lower bound operand: AttributeValue: {{{}}}, upper bound operand: \ - AttributeValue: {{{}}}", - shown(lo), - shown(hi) - ) - }; - let above = match (lo, hi) { - (AttributeValue::S(l), AttributeValue::S(h)) => l > h, - (AttributeValue::B(l), AttributeValue::B(h)) => l > h, - (AttributeValue::N(l), AttributeValue::N(h)) => match (number_value(l), number_value(h)) { - (Some(l), Some(h)) => l > h, - _ => false, - }, - _ => { - return Err(format!( - "The BETWEEN operator requires same data type for lower and upper bounds; {}", - bounds() - )); - } - }; - if above { - return Err(format!( - "The BETWEEN operator requires upper bound to be greater than or equal to lower \ - bound; {}", - bounds() - )); - } - Ok(()) -} - -/// A bound as the BETWEEN messages show it: `N:5`, `S:US`, or `B:` and the -/// base64 of the bytes. -fn shown(value: &AttributeValue) -> String { - use base64::Engine as _; - match value { - AttributeValue::S(s) => format!("S:{s}"), - AttributeValue::N(n) => format!("N:{n}"), - AttributeValue::B(b) => { - format!("B:{}", base64::engine::general_purpose::STANDARD.encode(b)) - } - other => attribute_type_code(other).to_owned(), - } + crate::expression::evaluator::between_bounds_fault(lo, hi, None, None).map_or(Ok(()), Err) } /// The number of operators in `node`: each AND, OR, NOT, comparison, BETWEEN, From 81af51b96d9f1c6c9bd1304f3567198031186652 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:50:43 +0000 Subject: [PATCH 049/101] refactor(core): list unused SearchVectors map keys with one function DynamoDB refuses a SearchVectors name that neither the search condition nor the projection uses, and a value the search condition does not use, listing every unused key in sorted order. ExtendDB had two functions that each collected the unused keys into a sorted set and joined them, and found the names in use by scanning the raw text of both expressions for `#`. check_unused_keys in search_params now lists the unused keys of either map against a set of used keys, and both the unused-names check and the extended grammar's unused-values check call it. The names in use come from tokens: the projection's NameRef tokens, the extended grammar's NameRef tokens (search_filter::name_refs), and the keys the equality-only grammar resolves (search_condition_name_refs), which for `##c` include `#c` as before. The core search_params tests and the 52 engine search_vectors tests pass; new tests cover the sorted listing and the equality-only keys. --- crates/core/src/expression/mod.rs | 2 +- .../core/src/expression/search_condition.rs | 7 ++ .../src/expression/search_condition_phases.rs | 17 ++++ .../core/src/expression/search_filter/mod.rs | 35 ++++---- crates/core/src/expression/search_params.rs | 85 ++++++++++--------- .../src/expression/search_params_tests.rs | 63 ++++++++++++-- crates/engine/src/search_vectors_extended.rs | 5 +- crates/engine/src/search_vectors_params.rs | 10 ++- 8 files changed, 150 insertions(+), 74 deletions(-) diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 39bc966a0..38c3db4a6 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -46,7 +46,7 @@ pub use resolver::{ }; pub use search_condition::{ MAX_INLINE_FILTER_CONDITIONS, MAX_PARTITION_KEY_CONDITIONS, MAX_SEARCH_CONDITIONS, - SearchCondition, validate_conditions_against_search_schema, + SearchCondition, search_condition_name_refs, validate_conditions_against_search_schema, validate_search_condition_expression, }; pub use tokenizer::{Token, tokenize, tokenize_for, tokenize_with_limit}; diff --git a/crates/core/src/expression/search_condition.rs b/crates/core/src/expression/search_condition.rs index df53697be..e5d8c8548 100644 --- a/crates/core/src/expression/search_condition.rs +++ b/crates/core/src/expression/search_condition.rs @@ -109,6 +109,13 @@ pub fn validate_search_condition_expression( Ok(conditions) } +/// The `ExpressionAttributeNames` keys the equality-only grammar can resolve +/// in `expr`, for the unused-names check. +#[must_use] +pub fn search_condition_name_refs(expr: &str) -> std::collections::BTreeSet<&str> { + phases::name_refs(expr) +} + /// Validate resolved filter conditions against a vector index search schema. /// /// Enforces that every referenced attribute belongs to the search schema, that diff --git a/crates/core/src/expression/search_condition_phases.rs b/crates/core/src/expression/search_condition_phases.rs index 9c6e1ebdf..349e25581 100644 --- a/crates/core/src/expression/search_condition_phases.rs +++ b/crates/core/src/expression/search_condition_phases.rs @@ -147,6 +147,23 @@ pub(super) fn each_comparison( Ok(conditions) } +/// The `ExpressionAttributeNames` keys a search condition can resolve: for +/// each `#alias` element of an operand, the key `#alias` and the key `alias`, +/// the two keys [`resolve_name`] looks up. +pub(super) fn name_refs(expr: &str) -> std::collections::BTreeSet<&str> { + let mut used = std::collections::BTreeSet::new(); + for token in tokenize(expr) { + for element in token.split('.') { + let name = element.split('[').next().unwrap_or_default(); + if let Some(alias) = name.strip_prefix('#') { + used.insert(name); + used.insert(alias); + } + } + } + used +} + /// Split an expression into operands, comparators and `AND`. /// /// Whitespace separates tokens. `=`, `<`, `>`, `<=`, `>=` and `<>` are tokens diff --git a/crates/core/src/expression/search_filter/mod.rs b/crates/core/src/expression/search_filter/mod.rs index a8e0d9101..87d0d9646 100644 --- a/crates/core/src/expression/search_filter/mod.rs +++ b/crates/core/src/expression/search_filter/mod.rs @@ -43,6 +43,7 @@ pub use gate::EnabledAccounts; pub use rules::{Condition, Operator}; use crate::error::DynamoDbError; +use crate::expression::search_params::check_unused_keys; use crate::expression::{Expr, ExpressionMaps}; use crate::types::{AttributeDefinition, AttributeValue, Item, SearchSchemaElement}; @@ -117,26 +118,22 @@ fn unused_values( src: &str, values: Option<&HashMap>, ) -> Result<(), DynamoDbError> { - let Some(values) = values else { - return Ok(()); - }; - let used: BTreeSet<&str> = toks - .iter() - .filter(|t| t.kind == lexer::Kind::ValueRef) + let used = refs(toks, src, lexer::Kind::ValueRef); + check_unused_keys("ExpressionAttributeValues", values, &used) +} + +/// The text of every token of `kind`. +fn refs<'a>(toks: &[lexer::Tok], src: &'a str, kind: lexer::Kind) -> BTreeSet<&'a str> { + toks.iter() + .filter(|t| t.kind == kind) .map(|t| &src[t.start..t.end]) - .collect(); - let unused: BTreeSet<&str> = values - .keys() - .map(String::as_str) - .filter(|k| !used.contains(k)) - .collect(); - if unused.is_empty() { - return Ok(()); - } - Err(DynamoDbError::ValidationException(format!( - "Value provided in ExpressionAttributeValues unused in expressions: keys: {{{}}}", - unused.into_iter().collect::>().join(", ") - ))) + .collect() +} + +/// The `#name` tokens of `expr`, for the unused-names check. +#[must_use] +pub fn name_refs(expr: &str) -> BTreeSet<&str> { + refs(&lexer::lex(expr), expr, lexer::Kind::NameRef) } /// The maps the evaluator reads: names keyed without `#`, values without `:`. diff --git a/crates/core/src/expression/search_params.rs b/crates/core/src/expression/search_params.rs index 7e7329510..875d6e009 100644 --- a/crates/core/src/expression/search_params.rs +++ b/crates/core/src/expression/search_params.rs @@ -115,56 +115,62 @@ pub fn check_search_maps( ) } -/// Every `#name` written in `exprs`. -fn written_names<'a>(exprs: &[&'a str]) -> BTreeSet<&'a str> { - let mut found = BTreeSet::new(); - for expr in exprs { - let bytes = expr.as_bytes(); - let mut i = 0; - while i < bytes.len() { - if bytes[i] == b'#' { - let end = bytes[i + 1..] - .iter() - .position(|b| !(b.is_ascii_alphanumeric() || *b == b'_')) - .map_or(bytes.len(), |n| i + 1 + n); - found.insert(&expr[i..end]); - i = end.max(i + 1); - } else { - i += 1; - } - } - } - found -} - -/// Every name in `names` must be written in one of `exprs` (the search -/// condition and the projection). The unused keys are listed in sorted order. +/// Refuse the keys of `map` that `used` does not hold, listed in sorted +/// order. `field` names the map in the message. Both grammars of the search +/// condition and the projection check use it. /// /// # Errors /// -/// Returns the unused-names `ValidationException`. -pub fn check_unused_names( - names: Option<&HashMap>, - exprs: &[&str], +/// Returns the unused-keys `ValidationException`. +pub fn check_unused_keys( + field: &str, + map: Option<&HashMap>, + used: &BTreeSet<&str>, ) -> Result<(), DynamoDbError> { - let Some(names) = names else { - return Ok(()); - }; - let written = written_names(exprs); - let unused: BTreeSet<&str> = names - .keys() + let unused: BTreeSet<&str> = map + .into_iter() + .flat_map(HashMap::keys) .map(String::as_str) - .filter(|k| !written.contains(k)) + .filter(|k| !used.contains(k)) .collect(); if unused.is_empty() { return Ok(()); } Err(invalid(format!( - "Value provided in {NAMES} unused in expressions: keys: {{{}}}", + "Value provided in {field} unused in expressions: keys: {{{}}}", unused.into_iter().collect::>().join(", ") ))) } +/// Every name in `names` must be used by the search condition, whose +/// `#name` tokens are `condition_names`, or by `projection`, a projection +/// that has already parsed. +/// +/// # Errors +/// +/// Returns the unused-names `ValidationException`, or the projection's +/// tokenizer error, which the earlier parse of the projection has answered. +pub fn check_unused_names( + names: Option<&HashMap>, + condition_names: &BTreeSet<&str>, + projection: &str, +) -> Result<(), DynamoDbError> { + if names.is_none() { + return Ok(()); + } + let projection_names: Vec = + crate::expression::tokenize_with_limit(projection, usize::MAX)? + .into_iter() + .filter_map(|t| match t { + crate::expression::Token::NameRef(name) => Some(format!("#{name}")), + _ => None, + }) + .collect(); + let mut used = condition_names.clone(); + used.extend(projection_names.iter().map(String::as_str)); + check_unused_keys(NAMES, names, &used) +} + /// Apply the unused-names check to the result of parsing a search condition. /// /// A parse failure answers first, except the unused-values failure, which @@ -176,12 +182,13 @@ pub fn check_unused_names( pub fn with_unused_names( parsed: Result, names: Option<&HashMap>, - exprs: &[&str], + condition_names: &BTreeSet<&str>, + projection: &str, ) -> Result { match parsed { - Ok(parsed) => check_unused_names(names, exprs).map(|()| parsed), + Ok(parsed) => check_unused_names(names, condition_names, projection).map(|()| parsed), Err(DynamoDbError::ValidationException(msg)) if msg.starts_with(UNUSED_VALUES) => { - check_unused_names(names, exprs)?; + check_unused_names(names, condition_names, projection)?; Err(DynamoDbError::ValidationException(msg)) } Err(other) => Err(other), diff --git a/crates/core/src/expression/search_params_tests.rs b/crates/core/src/expression/search_params_tests.rs index 57725193b..ae59486fe 100644 --- a/crates/core/src/expression/search_params_tests.rs +++ b/crates/core/src/expression/search_params_tests.rs @@ -6,7 +6,9 @@ use std::collections::HashMap; -use super::{check_search_maps, check_unused_names, with_unused_names}; +use std::collections::BTreeSet; + +use super::{check_search_maps, check_unused_keys, check_unused_names, with_unused_names}; use crate::error::DynamoDbError; use crate::types::AttributeValue; @@ -194,18 +196,45 @@ fn a_map_needs_the_expression_that_reads_it() { #[test] fn a_name_is_used_by_the_condition_or_the_projection() { let n = names(&[("#p", "Price"), ("#c", "Country")]); - assert!(check_unused_names(Some(&n), &["#c = :us", "#p"]).is_ok()); - assert!(check_unused_names(None, &["a = :s"]).is_ok()); + let cond = |keys: &[&'static str]| keys.iter().copied().collect::>(); + assert!(check_unused_names(Some(&n), &cond(&["#c"]), "#p").is_ok()); + assert!(check_unused_names(Some(&n), &cond(&[]), "#c, a.#p[0]").is_ok()); + assert!(check_unused_names(None, &cond(&[]), "").is_ok()); assert_eq!( - refused(check_unused_names(Some(&n), &["Country = :us", "Price"])), + refused(check_unused_names(Some(&n), &cond(&[]), "Price")), "Value provided in ExpressionAttributeNames unused in expressions: keys: {#c, #p}" ); assert_eq!( - refused(check_unused_names(Some(&n), &["#c = :us", ""])), + refused(check_unused_names(Some(&n), &cond(&["#c"]), "")), "Value provided in ExpressionAttributeNames unused in expressions: keys: {#p}" ); } +#[test] +fn unused_keys_are_listed_in_sorted_order() { + let v: HashMap = [(":b", 1), (":a", 2), (":c", 3)] + .into_iter() + .map(|(k, x)| (k.to_owned(), x)) + .collect(); + let used: BTreeSet<&str> = [":c"].into_iter().collect(); + assert_eq!( + refused(check_unused_keys( + "ExpressionAttributeValues", + Some(&v), + &used + )), + "Value provided in ExpressionAttributeValues unused in expressions: keys: {:a, :b}" + ); + assert!( + check_unused_keys( + "ExpressionAttributeValues", + None::<&HashMap>, + &used + ) + .is_ok() + ); +} + #[test] fn unused_names_answer_after_a_parse_error_and_before_unused_values() { let n = names(&[("#u", "x")]); @@ -218,12 +247,13 @@ fn unused_names_answer_after_a_parse_error_and_before_unused_values() { Err(DynamoDbError::ValidationException(m.to_owned())) }; let names_msg = "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}"; + let none = BTreeSet::new(); assert_eq!( - refused(with_unused_names(syntax(), Some(&n), &["Country = = :us"])), + refused(with_unused_names(syntax(), Some(&n), &none, "")), "Invalid SearchConditionExpression: Syntax error" ); assert_eq!( - refused(with_unused_names(Ok(()), Some(&n), &["Country = :us"])), + refused(with_unused_names(Ok(()), Some(&n), &none, "")), names_msg ); for values_msg in [ @@ -234,7 +264,8 @@ fn unused_names_answer_after_a_parse_error_and_before_unused_values() { refused(with_unused_names( unused_values(values_msg), Some(&n), - &["Country = :us"] + &none, + "" )), names_msg ); @@ -242,9 +273,23 @@ fn unused_names_answer_after_a_parse_error_and_before_unused_values() { refused(with_unused_names( unused_values(values_msg), None, - &["Country = :us"] + &none, + "" )), values_msg ); } } + +/// The equality-only grammar resolves `#alias` through the key `#alias` and +/// then the key `alias`, so `##c` uses the key `#c`, and its names check +/// counts the key the resolution reads. +#[test] +fn equality_grammar_names_are_the_keys_it_resolves() { + let refs = crate::expression::search_condition_name_refs("##c = :v AND #p = :w"); + for key in ["#c", "#p"] { + assert!(refs.contains(key), "{key} is used: {refs:?}"); + } + let n = names(&[("#c", "cat")]); + assert!(check_unused_names(Some(&n), &refs, "").is_ok()); +} diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs index db4d6de12..aea4a503b 100644 --- a/crates/engine/src/search_vectors_extended.rs +++ b/crates/engine/src/search_vectors_extended.rs @@ -34,7 +34,7 @@ mod imp { use extenddb_core::error::DynamoDbError; use extenddb_core::expression::search_filter::{ - DEFAULT_MAX_CONDITIONS, SearchFilter, parse_search_filter, + DEFAULT_MAX_CONDITIONS, SearchFilter, name_refs, parse_search_filter, }; use extenddb_core::expression::search_params::with_unused_names; use extenddb_core::types::{AttributeDefinition, AttributeValue, Item, SearchSchemaElement}; @@ -67,7 +67,8 @@ mod imp { with_unused_names( parse_search_filter(expr, names, values, DEFAULT_MAX_CONDITIONS), names, - &[expr, projection.unwrap_or_default()], + &name_refs(expr), + projection.unwrap_or_default(), ) .map(|filter| Extended(Arc::new(filter))) } diff --git a/crates/engine/src/search_vectors_params.rs b/crates/engine/src/search_vectors_params.rs index f6b3b80db..1a3d35bb3 100644 --- a/crates/engine/src/search_vectors_params.rs +++ b/crates/engine/src/search_vectors_params.rs @@ -11,14 +11,15 @@ //! unused-names check here; a request with one gets it after its condition //! parses, through [`equality_conditions`] or the extended parser. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::search_params::{ check_search_maps, check_unused_names, with_unused_names, }; use extenddb_core::expression::{ - ExpressionMaps, Projection, SearchCondition, validate_search_condition_expression, + ExpressionMaps, Projection, SearchCondition, search_condition_name_refs, + validate_search_condition_expression, }; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::AttributeValue; @@ -47,7 +48,7 @@ pub(crate) fn check( Projection::compile(&paths, &ExpressionMaps::new(names, HashMap::new()), true)?; } if condition.is_none() { - check_unused_names(names, &[projection.unwrap_or_default()])?; + check_unused_names(names, &BTreeSet::new(), projection.unwrap_or_default())?; } Ok(()) } @@ -66,7 +67,8 @@ pub(crate) fn equality_conditions( with_unused_names( validate_search_condition_expression(expr, names, values), names, - &[expr, projection.unwrap_or_default()], + &search_condition_name_refs(expr), + projection.unwrap_or_default(), ) } From 4ea1ca3b5061eb9bb25c1f297c153851a2da1d31 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:56:58 +0000 Subject: [PATCH 050/101] fix(core): read the SearchVectors size limits from the limits keys DynamoDB refuses a SearchConditionExpression over 4096 bytes and an attribute name of 65536 bytes or more with the same limits as the other expressions and operations. ExtendDB checked both on SearchVectors against fixed numbers, while a Scan, a GetItem and the other operations read max_expression_length_bytes and max_attribute_name_bytes from [limits]. With those keys at 8192 and 100000, a Scan with a 5,008-byte FilterExpression was served while SearchVectors with the same expression got the size refusal. check_expression_size moves from the engine to core unchanged, and gains the SearchConditionExpression kind, whose size refusal carries no length. The extended grammar calls it with the request's limits after its empty-expression check. The names map check calls validate_expression_attribute_name_sizes with a new SearchRequest form, whose message has no "1 validation error detected: " prefix and names the key, as measured on the service. Both answers stay the same under the default limits. New core tests send a 5,008-byte condition and a 70,000-byte name under raised limits (served) and the default limits (refused with the measured messages). The core and engine unit tests pass. --- crates/core/src/expression/kind.rs | 30 ++++++++ crates/core/src/expression/mod.rs | 2 +- .../core/src/expression/search_filter/mod.rs | 16 ++-- .../expression/search_filter/tests_depth.rs | 18 ++++- .../expression/search_filter/tests_eval.rs | 20 ++++- .../expression/search_filter/tests_grammar.rs | 77 ++++++++++++++++--- .../search_filter/tests_operands.rs | 8 +- .../expression/search_filter/tests_schema.rs | 27 ++++++- .../expression/search_filter/tests_support.rs | 8 +- crates/core/src/expression/search_params.rs | 32 ++++---- .../src/expression/search_params_tests.rs | 65 ++++++++++++++-- crates/core/src/validation/mod.rs | 20 +++-- crates/engine/src/expression_helpers.rs | 29 +------ crates/engine/src/search_vectors_condition.rs | 7 +- .../src/search_vectors_condition_tests.rs | 3 + crates/engine/src/search_vectors_extended.rs | 4 +- .../src/search_vectors_extended_tests.rs | 15 +++- crates/engine/src/search_vectors_params.rs | 8 +- crates/engine/src/search_vectors_request.rs | 1 + .../tests/common/vector_filter_fixture.rs | 9 ++- .../tests/vector_search_filter.rs | 9 ++- .../storage-sqlite/src/vector_filter_tests.rs | 9 ++- 22 files changed, 322 insertions(+), 95 deletions(-) diff --git a/crates/core/src/expression/kind.rs b/crates/core/src/expression/kind.rs index 7614c9e48..7809b7163 100644 --- a/crates/core/src/expression/kind.rs +++ b/crates/core/src/expression/kind.rs @@ -5,6 +5,9 @@ use std::fmt; +use crate::error::DynamoDbError; +use crate::limits::LimitsConfig; + /// A `DynamoDB` expression parameter. /// /// The string form is the exact wire-format parameter name `DynamoDB` uses in @@ -17,6 +20,8 @@ pub enum ExpressionKind { Filter, KeyCondition, Update, + /// The `SearchConditionExpression` of a `SearchVectors` request. + SearchCondition, } impl ExpressionKind { @@ -29,6 +34,7 @@ impl ExpressionKind { Self::Filter => "FilterExpression", Self::KeyCondition => "KeyConditionExpression", Self::Update => "UpdateExpression", + Self::SearchCondition => "SearchConditionExpression", } } @@ -49,3 +55,27 @@ impl fmt::Display for ExpressionKind { f.write_str(self.as_str()) } } + +/// Reject an expression over the byte-size limit, measured on the raw text +/// before `#name` / `:value` substitution (Amazon `DynamoDB`: 4096). The error +/// carries the per-parameter prefix and, for Filter/Condition, the byte length. +/// +/// # Errors +/// +/// Returns `DynamoDbError::ValidationException` when `expr` is over the limit. +pub fn check_expression_size( + expr: &str, + kind: ExpressionKind, + limits: &LimitsConfig, +) -> Result<(), DynamoDbError> { + if expr.len() > limits.max_expression_length_bytes { + let mut msg = + format!("Invalid {kind}: Expression size has exceeded the maximum allowed size;"); + if kind.size_error_includes_length() { + use std::fmt::Write as _; + let _ = write!(msg, " expression size: {}", expr.len()); + } + return Err(DynamoDbError::ValidationException(msg)); + } + Ok(()) +} diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 38c3db4a6..27a8950cb 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -35,7 +35,7 @@ pub use key_condition::{ KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands, parse_key_condition, }; -pub use kind::ExpressionKind; +pub use kind::{ExpressionKind, check_expression_size}; pub use parser::{parse_condition, parse_condition_with_depth_limit}; pub use projection::{Projection, parse_projection}; pub use reserved_words::validate_no_reserved_words; diff --git a/crates/core/src/expression/search_filter/mod.rs b/crates/core/src/expression/search_filter/mod.rs index 87d0d9646..5b82710c1 100644 --- a/crates/core/src/expression/search_filter/mod.rs +++ b/crates/core/src/expression/search_filter/mod.rs @@ -9,7 +9,8 @@ //! one condition on one attribute. The checks run in this order, and the //! first failure is the answer: //! -//! 1. the expression is not empty and is at most 4096 bytes; +//! 1. the expression is not empty and is at most `max_expression_length_bytes` +//! of `[limits]` (4096 by default); //! 2. the syntax, then redundant parentheses; //! 3. the checks of the condition grammar, post-order (see [`walk`]); //! 4. at most 300 operators, then the combined size; @@ -44,15 +45,13 @@ pub use rules::{Condition, Operator}; use crate::error::DynamoDbError; use crate::expression::search_params::check_unused_keys; -use crate::expression::{Expr, ExpressionMaps}; +use crate::expression::{Expr, ExpressionKind, ExpressionMaps, check_expression_size}; +use crate::limits::LimitsConfig; use crate::types::{AttributeDefinition, AttributeValue, Item, SearchSchemaElement}; /// The condition limit the service applies by default. pub const DEFAULT_MAX_CONDITIONS: usize = 50; -/// The most bytes an expression takes, counted before substitution. -const MAX_EXPRESSION_BYTES: usize = 4096; - const PREFIX: &str = "Invalid SearchConditionExpression: "; fn invalid(body: &str) -> DynamoDbError { @@ -78,15 +77,12 @@ pub fn parse_search_filter( names: Option<&HashMap>, values: Option<&HashMap>, max_conditions: usize, + limits: &LimitsConfig, ) -> Result { if expr.is_empty() { return Err(invalid("The expression can not be empty;")); } - if expr.len() > MAX_EXPRESSION_BYTES { - return Err(invalid( - "Expression size has exceeded the maximum allowed size;", - )); - } + check_expression_size(expr, ExpressionKind::SearchCondition, limits)?; let toks = lexer::lex(expr); let tree = grammar::parse(expr, &toks).map_err(|body| invalid(&body))?; let maps = walk::Maps { names, values }; diff --git a/crates/core/src/expression/search_filter/tests_depth.rs b/crates/core/src/expression/search_filter/tests_depth.rs index 4a5d326ae..7bbefc31c 100644 --- a/crates/core/src/expression/search_filter/tests_depth.rs +++ b/crates/core/src/expression/search_filter/tests_depth.rs @@ -51,7 +51,13 @@ fn outcome_on(stack: usize, expr: &str) -> String { let expr = expr.to_owned(); on_stack(stack, move || { let values = values_for(&expr); - match parse_search_filter(&expr, None, Some(&values), DEFAULT_MAX_CONDITIONS) { + match parse_search_filter( + &expr, + None, + Some(&values), + DEFAULT_MAX_CONDITIONS, + &crate::limits::LimitsConfig::default(), + ) { Ok(_) => OK.to_owned(), Err(DynamoDbError::ValidationException(m)) => m, Err(other) => format!("{other:?}"), @@ -214,8 +220,14 @@ fn the_deepest_accepted_condition_parses_and_evaluates() { assert_eq!(outcome_on(WORKER_STACK, &accepted), OK); let matched = on_stack(WORKER_STACK, move || { let values = values_for(&accepted); - let filter = parse_search_filter(&accepted, None, Some(&values), DEFAULT_MAX_CONDITIONS) - .unwrap_or_else(|e| panic!("{e:?}")); + let filter = parse_search_filter( + &accepted, + None, + Some(&values), + DEFAULT_MAX_CONDITIONS, + &crate::limits::LimitsConfig::default(), + ) + .unwrap_or_else(|e| panic!("{e:?}")); let item: Item = Item::from([("a".to_owned(), AttributeValue::S("x".to_owned()))]); let matched = filter.matches(&item).unwrap_or_else(|e| panic!("{e:?}")); drop(filter); diff --git a/crates/core/src/expression/search_filter/tests_eval.rs b/crates/core/src/expression/search_filter/tests_eval.rs index 29c5134fd..5c006f9a1 100644 --- a/crates/core/src/expression/search_filter/tests_eval.rs +++ b/crates/core/src/expression/search_filter/tests_eval.rs @@ -90,8 +90,14 @@ fn values() -> HashMap { /// The ids of the items `expr` matches, in item order. fn matching(expr: &str) -> Vec { let used = used_values(expr, &values()); - let filter = parse_search_filter(expr, None, Some(&used), 50) - .unwrap_or_else(|e| panic!("{expr}: {e:?}")); + let filter = parse_search_filter( + expr, + None, + Some(&used), + 50, + &crate::limits::LimitsConfig::default(), + ) + .unwrap_or_else(|e| panic!("{expr}: {e:?}")); items() .iter() .filter(|item| { @@ -262,8 +268,14 @@ fn a_last_digit_difference_counts_only_beyond_binary64() { for (rest, expected) in cases { let expr = h(rest); let used = used_values(&expr, &values); - let filter = parse_search_filter(&expr, None, Some(&used), 50) - .unwrap_or_else(|e| panic!("{expr}: {e:?}")); + let filter = parse_search_filter( + &expr, + None, + Some(&used), + 50, + &crate::limits::LimitsConfig::default(), + ) + .unwrap_or_else(|e| panic!("{expr}: {e:?}")); let actual: Vec<&str> = rows .iter() .filter(|(_, price)| { diff --git a/crates/core/src/expression/search_filter/tests_grammar.rs b/crates/core/src/expression/search_filter/tests_grammar.rs index 5b0c656d7..8d3ad3476 100644 --- a/crates/core/src/expression/search_filter/tests_grammar.rs +++ b/crates/core/src/expression/search_filter/tests_grammar.rs @@ -222,12 +222,17 @@ fn between_bounds_compare_numbers_exactly() { .iter() .filter_map(|(lo, hi, expected)| { let values = HashMap::from([(":lo".to_owned(), n(lo)), (":hi".to_owned(), n(hi))]); - let actual = - match parse_search_filter("Price BETWEEN :lo AND :hi", None, Some(&values), 50) { - Ok(_) => OK.to_owned(), - Err(DynamoDbError::ValidationException(m)) => m, - Err(other) => format!("{other:?}"), - }; + let actual = match parse_search_filter( + "Price BETWEEN :lo AND :hi", + None, + Some(&values), + 50, + &crate::limits::LimitsConfig::default(), + ) { + Ok(_) => OK.to_owned(), + Err(DynamoDbError::ValidationException(m)) => m, + Err(other) => format!("{other:?}"), + }; (&actual != expected) .then(|| format!("{lo} / {hi}: expected {expected:?}, got {actual:?}")) }) @@ -397,7 +402,14 @@ fn the_combined_size_counts_each_substituted_name() { .collect::>() .join(" AND "); let values: HashMap<_, _> = [(":s".to_owned(), super::tests_support::s("US"))].into(); - let err = super::parse_search_filter(&expr, Some(&long), Some(&values), 50).unwrap_err(); + let err = super::parse_search_filter( + &expr, + Some(&long), + Some(&values), + 50, + &crate::limits::LimitsConfig::default(), + ) + .unwrap_err(); assert_eq!( super::tests_support::message(err), p("Expression size has exceeded the maximum allowed size;") @@ -413,13 +425,27 @@ fn an_unused_value_is_named_without_the_prefix() { (":w".to_owned(), super::tests_support::s("unused")), ] .into(); - let err = super::parse_search_filter("a > :s", None, Some(&values), 50).unwrap_err(); + let err = super::parse_search_filter( + "a > :s", + None, + Some(&values), + 50, + &crate::limits::LimitsConfig::default(), + ) + .unwrap_err(); assert_eq!( super::tests_support::message(err), "Value provided in ExpressionAttributeValues unused in expressions: keys: {:w, :x}" ); // a parse failure answers before the unused value - let err = super::parse_search_filter("a > :s OR", None, Some(&values), 50).unwrap_err(); + let err = super::parse_search_filter( + "a > :s OR", + None, + Some(&values), + 50, + &crate::limits::LimitsConfig::default(), + ) + .unwrap_err(); assert_eq!( super::tests_support::message(err), p("Syntax error; token: \"\", near: \"OR\"") @@ -479,7 +505,13 @@ fn a_name_cannot_start_with_an_underscore() { .iter() .filter_map(|(expr, expected)| { let values = used_values(expr, &all); - let actual = match parse_search_filter(expr, Some(&names), Some(&values), 50) { + let actual = match parse_search_filter( + expr, + Some(&names), + Some(&values), + 50, + &crate::limits::LimitsConfig::default(), + ) { Ok(_) => OK.to_owned(), Err(DynamoDbError::ValidationException(m)) => m, Err(other) => format!("{other:?}"), @@ -490,3 +522,28 @@ fn a_name_cannot_start_with_an_underscore() { .collect(); assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); } + +/// The expression size limit is `max_expression_length_bytes` of `[limits]`, +/// the key the other expressions read. +#[test] +fn the_expression_size_limit_follows_the_limits_key() { + use super::parse_search_filter; + use crate::limits::LimitsConfig; + + let values = super::tests_support::all_values(); + let expr = format!("{} = :s", "a".repeat(5_008 - " = :s".len())); + let raised = LimitsConfig { + max_expression_length_bytes: 8192, + ..LimitsConfig::default() + }; + let used: std::collections::HashMap<_, _> = + values.into_iter().filter(|(k, _)| k == ":s").collect(); + assert!(parse_search_filter(&expr, None, Some(&used), 50, &raised).is_ok()); + let err = parse_search_filter(&expr, None, Some(&used), 50, &LimitsConfig::default()) + .err() + .map(super::tests_support::message); + assert_eq!( + err.as_deref(), + Some(p("Expression size has exceeded the maximum allowed size;").as_str()) + ); +} diff --git a/crates/core/src/expression/search_filter/tests_operands.rs b/crates/core/src/expression/search_filter/tests_operands.rs index 32799eb93..56bb3f92c 100644 --- a/crates/core/src/expression/search_filter/tests_operands.rs +++ b/crates/core/src/expression/search_filter/tests_operands.rs @@ -28,7 +28,13 @@ fn assert_measured_with(values: &[(&str, AttributeValue)], cases: &[(&str, Strin .iter() .filter_map(|(expr, expected)| { let values = used_values(expr, &all); - let actual = match parse_search_filter(expr, None, Some(&values), 50) { + let actual = match parse_search_filter( + expr, + None, + Some(&values), + 50, + &crate::limits::LimitsConfig::default(), + ) { Ok(_) => OK.to_owned(), Err(DynamoDbError::ValidationException(m)) => m, Err(other) => format!("{other:?}"), diff --git a/crates/core/src/expression/search_filter/tests_schema.rs b/crates/core/src/expression/search_filter/tests_schema.rs index 42b6df700..192e7671d 100644 --- a/crates/core/src/expression/search_filter/tests_schema.rs +++ b/crates/core/src/expression/search_filter/tests_schema.rs @@ -118,7 +118,14 @@ fn outcome(index: &Index, expr: &str, all: &HashMap) -> .map(|(k, v)| (k.to_owned(), v.to_owned())) .collect(); let used = used_values(expr, all); - match parse_search_filter(expr, Some(&names), Some(&used), 50).and_then(|filter| { + match parse_search_filter( + expr, + Some(&names), + Some(&used), + 50, + &crate::limits::LimitsConfig::default(), + ) + .and_then(|filter| { filter .validate_against_schema(Some(&index.schema), &index.definitions) .map(|_| ()) @@ -342,7 +349,14 @@ fn accepted_shapes_select_the_hash_partition() { "Category = :s AND ((Country = :s AND ProductCount > :n) OR (Country = :other AND ProductCount < :hi))", ] { let used = used_values(expr, &values()); - let filter = parse_search_filter(expr, None, Some(&used), 50).unwrap(); + let filter = parse_search_filter( + expr, + None, + Some(&used), + 50, + &crate::limits::LimitsConfig::default(), + ) + .unwrap(); let selected = filter .validate_against_schema(Some(&index.schema), &index.definitions) .unwrap_or_else(|e| panic!("{expr}: {e:?}")); @@ -363,7 +377,14 @@ fn an_index_without_hash_searches_the_whole_index() { "NOT Country IN (:s, :other) AND attribute_exists(ProductCount)", ] { let used = used_values(expr, &values()); - let filter = parse_search_filter(expr, None, Some(&used), 50).unwrap(); + let filter = parse_search_filter( + expr, + None, + Some(&used), + 50, + &crate::limits::LimitsConfig::default(), + ) + .unwrap(); let selected = filter .validate_against_schema(Some(&index.schema), &index.definitions) .unwrap_or_else(|e| panic!("{expr}: {e:?}")); diff --git a/crates/core/src/expression/search_filter/tests_support.rs b/crates/core/src/expression/search_filter/tests_support.rs index 315fb440c..e472fa0bd 100644 --- a/crates/core/src/expression/search_filter/tests_support.rs +++ b/crates/core/src/expression/search_filter/tests_support.rs @@ -64,7 +64,13 @@ pub(super) fn used_values( pub(super) fn parse_with(expr: &str, max: usize) -> Result { let values = used_values(expr, &all_values()); - parse_search_filter(expr, Some(&names()), Some(&values), max) + parse_search_filter( + expr, + Some(&names()), + Some(&values), + max, + &crate::limits::LimitsConfig::default(), + ) } /// `Ok`, or the message of the error. diff --git a/crates/core/src/expression/search_params.rs b/crates/core/src/expression/search_params.rs index 875d6e009..e41ae2fbf 100644 --- a/crates/core/src/expression/search_params.rs +++ b/crates/core/src/expression/search_params.rs @@ -9,8 +9,9 @@ //! answers ahead of a dimension mismatch, a missing table and any expression //! error. In order: //! -//! 1. the names: an empty attribute name anywhere in the map, then a name of -//! 65536 bytes or more, then an empty map, then each key (empty, longer than +//! 1. the names: an empty attribute name anywhere in the map, then a name +//! longer than `max_attribute_name_bytes` of `[limits]` (65535 by +//! default), then an empty map, then each key (empty, longer than //! 255 bytes, not `#` followed by letters, digits or `_`); //! 2. the values: an empty map, then each key, as for the names with `:`; //! 3. names with neither a search condition nor a projection, then values @@ -30,11 +31,10 @@ use std::collections::{BTreeSet, HashMap}; use crate::error::DynamoDbError; use crate::expression::validate_expression_param_usage; +use crate::limits::LimitsConfig; use crate::serde_helpers::validate_placeholder_key; use crate::types::AttributeValue; - -/// An attribute name must be shorter than this many bytes. -const NAME_LIMIT_BYTES: usize = 65536; +use crate::validation::{AttributeNameRequestForm, validate_expression_attribute_name_sizes}; const NAMES: &str = "ExpressionAttributeNames"; const VALUES: &str = "ExpressionAttributeValues"; @@ -68,20 +68,21 @@ fn check_keys<'a>( }) } -fn check_names(names: &HashMap) -> Result<(), DynamoDbError> { +fn check_names( + names: &HashMap, + limits: &LimitsConfig, +) -> Result<(), DynamoDbError> { if let Some((key, _)) = names.iter().find(|(_, name)| name.is_empty()) { return Err(invalid(format!( "{NAMES} contains invalid value: Empty attribute name for key {key}" ))); } - if let Some((key, _)) = names - .iter() - .find(|(_, name)| name.len() >= NAME_LIMIT_BYTES) - { - return Err(invalid(format!( - "Attribute name is too large, must be less than {NAME_LIMIT_BYTES} bytes for key {key}" - ))); - } + validate_expression_attribute_name_sizes( + Some(names), + None, + limits, + AttributeNameRequestForm::SearchRequest, + )?; check_keys(NAMES, '#', names.keys()) } @@ -97,9 +98,10 @@ pub fn check_search_maps( values: Option<&HashMap>, has_condition: bool, has_projection: bool, + limits: &LimitsConfig, ) -> Result<(), DynamoDbError> { if let Some(names) = names { - check_names(names)?; + check_names(names, limits)?; } if let Some(values) = values { check_keys(VALUES, ':', values.keys())?; diff --git a/crates/core/src/expression/search_params_tests.rs b/crates/core/src/expression/search_params_tests.rs index ae59486fe..983720cb6 100644 --- a/crates/core/src/expression/search_params_tests.rs +++ b/crates/core/src/expression/search_params_tests.rs @@ -8,6 +8,8 @@ use std::collections::HashMap; use std::collections::BTreeSet; +use crate::limits::LimitsConfig; + use super::{check_search_maps, check_unused_keys, check_unused_names, with_unused_names}; use crate::error::DynamoDbError; use crate::types::AttributeValue; @@ -43,7 +45,13 @@ fn maps( n: Option<&HashMap>, v: Option<&HashMap>, ) -> String { - refused(check_search_maps(n, v, true, false)) + refused(check_search_maps( + n, + v, + true, + false, + &LimitsConfig::default(), + )) } #[test] @@ -59,7 +67,13 @@ fn an_empty_map_is_refused_names_first() { "ExpressionAttributeNames must not be empty" ); assert_eq!( - refused(check_search_maps(None, Some(&empty_v), false, false)), + refused(check_search_maps( + None, + Some(&empty_v), + false, + false, + &LimitsConfig::default() + )), "ExpressionAttributeValues must not be empty" ); } @@ -165,14 +179,31 @@ fn an_attribute_name_must_be_shorter_than_65536_bytes() { "Attribute name is too large, must be less than 65536 bytes for key #c" ); let below = "C".repeat(65535); - assert!(check_search_maps(Some(&names(&[("#c", &below)])), None, true, false).is_ok()); + assert!( + check_search_maps( + Some(&names(&[("#c", &below)])), + None, + true, + false, + &LimitsConfig::default() + ) + .is_ok() + ); } #[test] fn a_map_needs_the_expression_that_reads_it() { let n = names(&[("#p", "Price")]); let v = values(&[":us"]); - let without = |n, v, cond, proj| refused(check_search_maps(n, v, cond, proj)); + let without = |n, v, cond, proj| { + refused(check_search_maps( + n, + v, + cond, + proj, + &LimitsConfig::default(), + )) + }; assert_eq!( without(Some(&n), None, false, false), "ExpressionAttributeNames can only be specified when using expressions" @@ -189,8 +220,8 @@ fn a_map_needs_the_expression_that_reads_it() { without(Some(&n), Some(&v), false, true), "ExpressionAttributeValues can only be specified when using expressions" ); - assert!(check_search_maps(Some(&n), None, false, true).is_ok()); - assert!(check_search_maps(Some(&n), Some(&v), true, false).is_ok()); + assert!(check_search_maps(Some(&n), None, false, true, &LimitsConfig::default()).is_ok()); + assert!(check_search_maps(Some(&n), Some(&v), true, false, &LimitsConfig::default()).is_ok()); } #[test] @@ -293,3 +324,25 @@ fn equality_grammar_names_are_the_keys_it_resolves() { let n = names(&[("#c", "cat")]); assert!(check_unused_names(Some(&n), &refs, "").is_ok()); } + +/// The name size limit is `max_attribute_name_bytes` of `[limits]`, the key +/// the other operations read, with the message of this endpoint. +#[test] +fn the_name_size_limit_follows_the_limits_key() { + let n = names(&[("#c", &"C".repeat(70_000))]); + let raised = LimitsConfig { + max_attribute_name_bytes: 100_000, + ..LimitsConfig::default() + }; + assert!(check_search_maps(Some(&n), None, true, false, &raised).is_ok()); + assert_eq!( + refused(check_search_maps( + Some(&n), + None, + true, + false, + &LimitsConfig::default() + )), + "Attribute name is too large, must be less than 65536 bytes for key #c" + ); +} diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index 9c1bcbb21..f491c4b46 100755 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -1234,6 +1234,11 @@ pub enum AttributeNameRequestForm { /// A `PutRequest` of a `BatchWriteItem` request. It carries no /// expression maps. BatchRequest, + /// A `SearchVectors` request: `Attribute name is too large, must be less + /// than 65536 bytes for key #n`, without the `1 validation error + /// detected: ` prefix (measured on DynamoDB 2026-11-24). Its callers pass + /// no `ExpressionAttributeValues`. + SearchRequest, } /// Validate that no attribute name exceeds the maximum allowed size (REQ-LIM-004). @@ -1283,7 +1288,10 @@ pub fn validate_expression_attribute_name_sizes( limits: &LimitsConfig, form: AttributeNameRequestForm, ) -> Result<(), DynamoDbError> { - if form == AttributeNameRequestForm::SingleItem { + if matches!( + form, + AttributeNameRequestForm::SingleItem | AttributeNameRequestForm::SearchRequest + ) { check_expression_attribute_names(names, limits, form)?; check_expression_attribute_values(values, limits, form) } else { @@ -1379,9 +1387,9 @@ fn attribute_name_too_large(limits: &LimitsConfig, form: AttributeNameRequestFor ); match form { AttributeNameRequestForm::SingleItem => format!("1 validation error detected: {sentence}"), - AttributeNameRequestForm::TransactionMember | AttributeNameRequestForm::BatchRequest => { - sentence - } + AttributeNameRequestForm::TransactionMember + | AttributeNameRequestForm::BatchRequest + | AttributeNameRequestForm::SearchRequest => sentence, } } @@ -1396,7 +1404,9 @@ fn expression_attribute_name_too_large( ) -> String { let refusal = attribute_name_too_large(limits, form); match form { - AttributeNameRequestForm::SingleItem => format!("{refusal} for key {placeholder}"), + AttributeNameRequestForm::SingleItem | AttributeNameRequestForm::SearchRequest => { + format!("{refusal} for key {placeholder}") + } AttributeNameRequestForm::TransactionMember | AttributeNameRequestForm::BatchRequest => { format!("{map} contains invalid value: {refusal} for key {placeholder}") } diff --git a/crates/engine/src/expression_helpers.rs b/crates/engine/src/expression_helpers.rs index 22f51019c..32c0a2067 100755 --- a/crates/engine/src/expression_helpers.rs +++ b/crates/engine/src/expression_helpers.rs @@ -8,8 +8,9 @@ use std::collections::HashMap; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{ Expr, ExpressionKind, ExpressionMaps, KeyCondition, PathElement, Token, UpdateAction, - parse_condition_with_depth_limit, parse_key_condition, parse_projection, parse_update_from, - tokenize_for, tokenize_with_limit, validate_no_reserved_words, validate_ordering_operand_types, + check_expression_size, parse_condition_with_depth_limit, parse_key_condition, parse_projection, + parse_update_from, tokenize_for, tokenize_with_limit, validate_no_reserved_words, + validate_ordering_operand_types, }; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{AttributeValue, ConditionalOperator, ExpectedAttributeValue}; @@ -55,30 +56,6 @@ pub fn build_expression_maps( ) } -/// Reject an expression over the byte-size limit, measured on the raw text -/// before `#name` / `:value` substitution (Amazon `DynamoDB`: 4096). The error -/// carries the per-parameter prefix and, for Filter/Condition, the byte length. -/// -/// # Errors -/// -/// Returns `DynamoDbError::ValidationException` when `expr` is over the limit. -pub fn check_expression_size( - expr: &str, - kind: ExpressionKind, - limits: &LimitsConfig, -) -> Result<(), DynamoDbError> { - if expr.len() > limits.max_expression_length_bytes { - let mut msg = - format!("Invalid {kind}: Expression size has exceeded the maximum allowed size;"); - if kind.size_error_includes_length() { - use std::fmt::Write as _; - let _ = write!(msg, " expression size: {}", expr.len()); - } - return Err(DynamoDbError::ValidationException(msg)); - } - Ok(()) -} - /// Tokenize, reserved-word check, and parse a required `ConditionExpression`. /// /// Errors carry the `ConditionExpression` prefix, matching Amazon DynamoDB. diff --git a/crates/engine/src/search_vectors_condition.rs b/crates/engine/src/search_vectors_condition.rs index 1b5d9b87f..77762766f 100644 --- a/crates/engine/src/search_vectors_condition.rs +++ b/crates/engine/src/search_vectors_condition.rs @@ -23,6 +23,7 @@ use std::sync::Arc; use extenddb_core::error::DynamoDbError; use extenddb_core::expression::{SearchCondition, validate_conditions_against_search_schema}; +use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{ AttributeDefinition, AttributeValue, SearchSchemaElement, SearchSchemaElementType, }; @@ -72,6 +73,7 @@ pub(crate) async fn parse( names: Option<&HashMap>, values: Option<&HashMap>, projection: Option<&str>, + limits: &LimitsConfig, ) -> Result { let Some(expr) = expr else { return Ok(Parsed::Equality(Vec::new())); @@ -80,7 +82,8 @@ pub(crate) async fn parse( crate::search_vectors_params::equality_conditions(expr, names, values, projection); #[cfg(feature = "search-inequality-filters")] { - let extended = crate::search_vectors_extended::parse(expr, names, values, projection); + let extended = + crate::search_vectors_extended::parse(expr, names, values, projection, limits); match (extended, equality) { (Ok(extended), Ok(conditions)) => Ok(Parsed::Either(extended, conditions)), (Err(a), Err(b)) if same_error(&a, &b) => Err(a), @@ -95,7 +98,7 @@ pub(crate) async fn parse( } #[cfg(not(feature = "search-inequality-filters"))] { - let _ = (storage, account_id); + let _ = (storage, account_id, limits); equality.map(Parsed::Equality) } } diff --git a/crates/engine/src/search_vectors_condition_tests.rs b/crates/engine/src/search_vectors_condition_tests.rs index d7effefe1..b2b9f158e 100644 --- a/crates/engine/src/search_vectors_condition_tests.rs +++ b/crates/engine/src/search_vectors_condition_tests.rs @@ -13,6 +13,7 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; +use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{ AttributeDefinition, AttributeValue, Item, ScalarAttributeType, SearchSchemaElement, SearchSchemaElementType, @@ -120,6 +121,7 @@ async fn routed(setting: &str, hash: bool, expr: &str, item: &Item) -> Routed { None, Some(&values), None, + &LimitsConfig::default(), ) .await .unwrap(); @@ -292,6 +294,7 @@ async fn without_the_setting( names, Some(&values), None, + &LimitsConfig::default(), ) .await?; let (hash_key, filters, item_filter) = resolve( diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs index aea4a503b..93fa081ac 100644 --- a/crates/engine/src/search_vectors_extended.rs +++ b/crates/engine/src/search_vectors_extended.rs @@ -37,6 +37,7 @@ mod imp { DEFAULT_MAX_CONDITIONS, SearchFilter, name_refs, parse_search_filter, }; use extenddb_core::expression::search_params::with_unused_names; + use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{AttributeDefinition, AttributeValue, Item, SearchSchemaElement}; use extenddb_storage::error::StorageError; use extenddb_storage::{StorageEngine, VectorItemFilter}; @@ -63,9 +64,10 @@ mod imp { names: Option<&HashMap>, values: Option<&HashMap>, projection: Option<&str>, + limits: &LimitsConfig, ) -> Result { with_unused_names( - parse_search_filter(expr, names, values, DEFAULT_MAX_CONDITIONS), + parse_search_filter(expr, names, values, DEFAULT_MAX_CONDITIONS, limits), names, &name_refs(expr), projection.unwrap_or_default(), diff --git a/crates/engine/src/search_vectors_extended_tests.rs b/crates/engine/src/search_vectors_extended_tests.rs index 63e41dfb7..3533a00e5 100644 --- a/crates/engine/src/search_vectors_extended_tests.rs +++ b/crates/engine/src/search_vectors_extended_tests.rs @@ -69,8 +69,17 @@ async fn enabled(storage: &Arc) -> Result = + std::sync::LazyLock::new(extenddb_core::limits::LimitsConfig::default); + fn parsed(expr: &str) -> Result { - parse(expr, None, Some(&values()), None) + parse( + expr, + None, + Some(&values()), + None, + &extenddb_core::limits::LimitsConfig::default(), + ) } #[tokio::test] @@ -132,7 +141,7 @@ fn the_extended_grammar_gives_its_own_messages() { fn a_name_neither_expression_uses_is_refused() { let values = values(); let names: HashMap = [("#u".to_owned(), "x".to_owned())].into(); - let err = parse(INEQUALITY, Some(&names), Some(&values), None) + let err = parse(INEQUALITY, Some(&names), Some(&values), None, &LIMITS) .err() .expect("refused"); assert!( @@ -141,7 +150,7 @@ fn a_name_neither_expression_uses_is_refused() { "{err:?}" ); let used: HashMap = [("#u".to_owned(), "Price".to_owned())].into(); - assert!(parse(INEQUALITY, Some(&used), Some(&values), Some("#u")).is_ok()); + assert!(parse(INEQUALITY, Some(&used), Some(&values), Some("#u"), &LIMITS).is_ok()); } fn item(country: &str, price: &str) -> Item { diff --git a/crates/engine/src/search_vectors_params.rs b/crates/engine/src/search_vectors_params.rs index 1a3d35bb3..c2d9759a3 100644 --- a/crates/engine/src/search_vectors_params.rs +++ b/crates/engine/src/search_vectors_params.rs @@ -37,7 +37,13 @@ pub(crate) fn check( projection: Option<&str>, limits: &LimitsConfig, ) -> Result<(), DynamoDbError> { - check_search_maps(names, values, condition.is_some(), projection.is_some())?; + check_search_maps( + names, + values, + condition.is_some(), + projection.is_some(), + limits, + )?; if let Some(projection) = projection { let paths = crate::expression_helpers::parse_projection_expr(projection, limits)?; let names = names diff --git a/crates/engine/src/search_vectors_request.rs b/crates/engine/src/search_vectors_request.rs index ddeba4e31..fcb1c5d5f 100644 --- a/crates/engine/src/search_vectors_request.rs +++ b/crates/engine/src/search_vectors_request.rs @@ -116,6 +116,7 @@ pub(super) async fn check<'s>( input.expression_attribute_names.as_ref(), input.expression_attribute_values.as_ref(), input.projection_expression.as_deref(), + limits, ) .await?; diff --git a/crates/storage-postgres/tests/common/vector_filter_fixture.rs b/crates/storage-postgres/tests/common/vector_filter_fixture.rs index 2834e8a6b..351038789 100644 --- a/crates/storage-postgres/tests/common/vector_filter_fixture.rs +++ b/crates/storage-postgres/tests/common/vector_filter_fixture.rs @@ -271,7 +271,14 @@ pub fn parse( }) .map(|(k, v)| (k.clone(), v.clone())) .collect(); - let filter = parse_search_filter(expr, None, Some(&used), 50).expect("parse"); + let filter = parse_search_filter( + expr, + None, + Some(&used), + 50, + &extenddb_core::limits::LimitsConfig::default(), + ) + .expect("parse"); let hash = filter .validate_against_schema( Some(fixture.key_info.vector_indexes[0].search_schema.as_slice()), diff --git a/crates/storage-postgres/tests/vector_search_filter.rs b/crates/storage-postgres/tests/vector_search_filter.rs index 9819fc15e..2dc6dab70 100644 --- a/crates/storage-postgres/tests/vector_search_filter.rs +++ b/crates/storage-postgres/tests/vector_search_filter.rs @@ -128,7 +128,14 @@ async fn the_partition_scopes_the_search_without_the_condition() { run("COSINE", ROWS, async |f: &Fixture| { // A condition with no HASH term, so only the partition keeps c2 out. let v = values(&[("p100", "100")]); - let filter = parse_search_filter("Price = :p100", None, Some(&v), 50).expect("parse"); + let filter = parse_search_filter( + "Price = :p100", + None, + Some(&v), + 50, + &extenddb_core::limits::LimitsConfig::default(), + ) + .expect("parse"); let us = AttributeValue::S("US".to_owned()); let hits = search_with( f, diff --git a/crates/storage-sqlite/src/vector_filter_tests.rs b/crates/storage-sqlite/src/vector_filter_tests.rs index f6c24a01e..6f67fe794 100644 --- a/crates/storage-sqlite/src/vector_filter_tests.rs +++ b/crates/storage-sqlite/src/vector_filter_tests.rs @@ -156,7 +156,14 @@ async fn search( }) .map(|(k, v)| (k.clone(), v.clone())) .collect(); - let filter = parse_search_filter(expr, None, Some(&used), 50).expect("parse"); + let filter = parse_search_filter( + expr, + None, + Some(&used), + 50, + &extenddb_core::limits::LimitsConfig::default(), + ) + .expect("parse"); let schema = &key_info.vector_indexes[0].search_schema; let definitions = &key_info.attribute_definitions; let hash = filter From 2c1a9d00d601a70f3987129925ea8552c1b3539f Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:57:58 +0000 Subject: [PATCH 051/101] test(core): pin the combined size of a search condition at one mebibyte DynamoDB refuses a SearchConditionExpression whose bytes and substitutions, counted at each use, exceed 1,048,576 bytes: with `:v` used 100 times, 1,048,576 bytes answer 200 and 1,048,577 answer "Expression size has exceeded the maximum allowed size;", with and without a name substitution (measured in eu-north-1 on 2026-11-25, each request twice). ExtendDB applied that limit, and no test pinned it: the one test of the combined size was about 65 KB over it. A core test sends the measured requests at 1,048,576 and 1,048,577 bytes. It fails with the limit raised by one byte. --- .../search_filter/tests_operands.rs | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/crates/core/src/expression/search_filter/tests_operands.rs b/crates/core/src/expression/search_filter/tests_operands.rs index 56bb3f92c..08abc3547 100644 --- a/crates/core/src/expression/search_filter/tests_operands.rs +++ b/crates/core/src/expression/search_filter/tests_operands.rs @@ -236,3 +236,57 @@ fn function_operands_are_checked_by_type() { ], ); } + +/// The expression, a name for each use of its key and a value for each use +/// of its key take at most 1,048,576 bytes. The condition below uses `:v` +/// 100 times, sized to each total. Measured on the live service in +/// eu-north-1 on 2026-11-25, each request twice with the same answer: +/// 1,048,576 bytes answer 200 and 1,048,577 the size refusal, with and +/// without the name. +#[test] +fn the_combined_size_is_at_most_one_mebibyte() { + use std::collections::HashMap; + + use super::parse_search_filter; + use super::tests_support::{message, p, s}; + use crate::limits::LimitsConfig; + + let uses = 100; + for (attribute, names) in [ + ("Category", None), + ( + "#c", + Some(HashMap::from([("#c".to_owned(), "Category".to_owned())])), + ), + ] { + let expr = format!( + "Country = :h AND {attribute} IN ({})", + vec![":v"; uses].join(", ") + ); + let fixed = expr.len() + if names.is_some() { "Category".len() } else { 0 }; + for (total, served) in [(1_048_576, true), (1_048_577, false)] { + let each = (total - fixed) / uses; + let head = total - fixed - uses * each; + let values = HashMap::from([ + (":h".to_owned(), s(&"U".repeat(head))), + (":v".to_owned(), s(&"x".repeat(each))), + ]); + let got = parse_search_filter( + &expr, + names.as_ref(), + Some(&values), + 50, + &LimitsConfig::default(), + ); + if served { + assert!(got.is_ok(), "{total} {attribute}: {:?}", got.err()); + } else { + assert_eq!( + got.err().map(message), + Some(p("Expression size has exceeded the maximum allowed size;")), + "{total} {attribute}" + ); + } + } + } +} From 5be9fca6bcffb3886a88c454d15534945ad140bf Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:58:06 +0000 Subject: [PATCH 052/101] test(search): pin the doubled name marker and the combined size limit DynamoDB answers a SearchConditionExpression `##c = :v` with `{"#c": "cat"}` with ValidationException "Invalid SearchConditionExpression: Syntax error; token: \"#\", near: \"##c\"", and `near: "AND ##c"` when the HASH equality comes first. It serves a condition of 1,048,576 combined bytes and refuses one of 1,048,577 with the size message (eu-north-1, 2026-11-25, each request twice). The extended grammar answered both as the service does, and no wire test sent the `##c` request or a request at the combined limit. TestExpressionMapsUnderTheExtendedGrammar gains the three `##c` requests and the four requests at 1,048,576 and 1,048,577 bytes, with and without a name. --- .../test_search_vectors_inequality_filters.py | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/tests/test_search_vectors_inequality_filters.py b/tests/test_search_vectors_inequality_filters.py index e15a85df1..8062c57e6 100644 --- a/tests/test_search_vectors_inequality_filters.py +++ b/tests/test_search_vectors_inequality_filters.py @@ -454,6 +454,55 @@ def test_unused_names(self, grammar_table): ExpressionAttributeNames=u, ExpressionAttributeValues=us), P + 'Syntax error; token: "=", near: "= = :us"') + def test_a_doubled_name_marker_is_a_syntax_error(self, grammar_table): + """``##c`` is a syntax error at its first ``#``, whatever ``#c`` names. + + Measured on the live service in eu-north-1 on 2026-11-25, each request + twice with the same answer. + """ + for names, values, expr, near in [ + ({"#c": "cat"}, {":v": {"S": "c1"}}, "##c = :v", "##c"), + ({"#c": "Category"}, {":v": {"S": "a"}}, "##c = :v", "##c"), + ({"#c": "Category"}, {":us": {"S": "US"}, ":v": {"S": "a"}}, + "Country = :us AND ##c = :v", "AND ##c"), + ]: + _refused( + _raw(grammar_table, SearchConditionExpression=expr, + ExpressionAttributeNames=names, ExpressionAttributeValues=values), + P + f'Syntax error; token: "#", near: "{near}"', + ) + + def test_the_combined_size_limit(self, grammar_table): + """The expression and every substitution, counted at each use, take at + most 1,048,576 bytes. + + The condition is ``Country = :h AND IN (:v, ...)`` with + ``:v`` used 100 times, sized so that the bytes of the expression, of + the name ``Category`` when it is written ``#c``, of ``:h`` and of each + use of ``:v`` add up to the total. Measured on the live service in + eu-north-1 on 2026-11-25, each request twice with the same answer: + 1,048,574 to 1,048,576 bytes answer 200 and 1,048,577, 1,048,578 and + 1,048,600 answer the size refusal. + """ + uses = 100 + for attribute, names in [("Category", None), ("#c", {"#c": "Category"})]: + expr = f"Country = :h AND {attribute} IN ({', '.join([':v'] * uses)})" + fixed = len(expr) + (len("Category") if names else 0) + for total, served in [(1_048_576, True), (1_048_577, False)]: + each = (total - fixed) // uses + head = total - fixed - uses * each + fields = { + "SearchConditionExpression": expr, + "ExpressionAttributeValues": {":h": {"S": "U" * head}, ":v": {"S": "x" * each}}, + } + if names: + fields["ExpressionAttributeNames"] = names + resp = _raw(grammar_table, **fields) + if served: + assert resp.status_code == 200, (total, attribute, resp.text) + else: + _refused(resp, P + "Expression size has exceeded the maximum allowed size;") + def test_the_projection_is_read_before_the_condition(self, grammar_table): _refused( _raw(grammar_table, ProjectionExpression="#p", SearchConditionExpression="Country = = :us", From fa19720c0a50bca6e6abf81a76c53f44cfffe3d5 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:58:46 +0000 Subject: [PATCH 053/101] perf(core): size each search condition substitution once The combined size of a search condition counts each substitution at every use, so a list or map value referenced by the 100 operands of an IN list counts 100 times. ExtendDB computed that by walking the value once per use, before the IAM decision: a large list value used 100 times was walked 100 times. combined_bytes now counts the uses of each distinct name and value, sizes each once and multiplies by its uses. The total is the same. The core search_filter tests pass, the combined size rows at 1,048,576 and 1,048,577 bytes among them. --- .../core/src/expression/search_filter/walk.rs | 42 +++++++++++-------- 1 file changed, 25 insertions(+), 17 deletions(-) diff --git a/crates/core/src/expression/search_filter/walk.rs b/crates/core/src/expression/search_filter/walk.rs index b5e910045..c80c1b1b3 100644 --- a/crates/core/src/expression/search_filter/walk.rs +++ b/crates/core/src/expression/search_filter/walk.rs @@ -423,27 +423,35 @@ fn each_operand<'a>( } /// The expression's bytes plus the bytes each substitution adds, counted at -/// every use. +/// every use. Each distinct name and value is sized once and multiplied by +/// its uses, so a list or map value used many times is walked once. pub(super) fn combined_bytes(src: &str, node: &Node, maps: &Maps<'_>) -> usize { - let mut total = src.len(); + let mut names: HashMap<&str, usize> = HashMap::new(); + let mut values: HashMap<&str, usize> = HashMap::new(); each_operand( node, - |o| { - total += match o { - Operand::Path(elements) => elements - .iter() - .map(|e| match e { - Element::Name(n) if n.starts_with('#') => maps.name(n).map_or(0, str::len), - Element::Name(_) | Element::Index(_) => 0, - }) - .sum(), - Operand::Value(reference) => maps - .value(reference) - .map_or(0, crate::types::attribute_value_size), - Operand::Call(_) => 0, - }; + |o| match o { + Operand::Path(elements) => { + for e in elements { + if let Element::Name(n) = e + && n.starts_with('#') + { + *names.entry(n.as_str()).or_default() += 1; + } + } + } + Operand::Value(reference) => *values.entry(reference.as_str()).or_default() += 1, + Operand::Call(_) => {} }, |_| {}, ); - total + let names: usize = names + .into_iter() + .map(|(n, uses)| maps.name(n).map_or(0, str::len) * uses) + .sum(); + let values: usize = values + .into_iter() + .map(|(v, uses)| maps.value(v).map_or(0, crate::types::attribute_value_size) * uses) + .sum(); + src.len() + names + values } From 3d8339fbd5575c2f10b150d1a4a80075b047e3a8 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 06:01:04 +0000 Subject: [PATCH 054/101] refactor(core): drop the table owner from the search filter setting A request on a table of another account is refused before the search grammar is chosen, so the caller of every request that reaches the choice owns the table. EnabledAccounts::enabled_for took an owner for that case, and only its unit test passed one; the engine passed None. enabled_for now takes the caller alone, and a list enables the accounts it names. The module comment says why no owner is needed. The gate and engine settings tests pass. --- .../core/src/expression/search_filter/gate.rs | 26 +++++++++---------- crates/engine/src/search_vectors_extended.rs | 2 +- .../src/search_vectors_settings_tests.rs | 4 +-- 3 files changed, 15 insertions(+), 17 deletions(-) diff --git a/crates/core/src/expression/search_filter/gate.rs b/crates/core/src/expression/search_filter/gate.rs index 672dfab58..a501e08f3 100644 --- a/crates/core/src/expression/search_filter/gate.rs +++ b/crates/core/src/expression/search_filter/gate.rs @@ -6,7 +6,9 @@ //! The service serves the grammar to every account. The setting names the //! accounts ExtendDB serves it to: `all` (the default), `off`, or a //! comma-separated list of 12-digit account IDs, in which case a request -//! gets the grammar when the caller or the table owner is listed. +//! gets the grammar when the caller is listed. A request on a table of +//! another account is refused before the grammar is chosen, so the caller +//! owns the table. use std::collections::BTreeSet; @@ -47,16 +49,13 @@ impl EnabledAccounts { Ok(Self::Listed(accounts)) } - /// Whether a request by `caller` on a table owned by `owner` gets the - /// grammar. `owner` is `None` when the caller owns the table. + /// Whether a request by `caller` gets the grammar. #[must_use] - pub fn enabled_for(&self, caller: &str, owner: Option<&str>) -> bool { + pub fn enabled_for(&self, caller: &str) -> bool { match self { Self::Off => false, Self::All => true, - Self::Listed(accounts) => std::iter::once(caller) - .chain(owner) - .any(|account| accounts.contains(account)), + Self::Listed(accounts) => accounts.contains(caller), } } } @@ -81,17 +80,16 @@ mod tests { fn off_and_all_parse() { assert_eq!(EnabledAccounts::parse("off"), Ok(EnabledAccounts::Off)); assert_eq!(EnabledAccounts::parse("all"), Ok(EnabledAccounts::All)); - assert!(!EnabledAccounts::Off.enabled_for("123456789012", None)); - assert!(EnabledAccounts::All.enabled_for("123456789012", None)); + assert!(!EnabledAccounts::Off.enabled_for("123456789012")); + assert!(EnabledAccounts::All.enabled_for("123456789012")); } #[test] - fn a_list_enables_the_caller_or_the_owner() { + fn a_list_enables_the_accounts_it_names() { let listed = EnabledAccounts::parse("111111111111, 222222222222").unwrap(); - assert!(listed.enabled_for("111111111111", None)); - assert!(listed.enabled_for("333333333333", Some("222222222222"))); - assert!(!listed.enabled_for("333333333333", None)); - assert!(!listed.enabled_for("333333333333", Some("444444444444"))); + assert!(listed.enabled_for("111111111111")); + assert!(listed.enabled_for("222222222222")); + assert!(!listed.enabled_for("333333333333")); } #[test] diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs index 93fa081ac..b6b6855c6 100644 --- a/crates/engine/src/search_vectors_extended.rs +++ b/crates/engine/src/search_vectors_extended.rs @@ -90,7 +90,7 @@ mod imp { // the table owner. Ok(super::settings::enabled_accounts(storage) .await? - .enabled_for(account_id, None)) + .enabled_for(account_id)) } /// The partition the HASH condition selects and the filter the backend diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index cb3f47a80..f12fb011d 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -132,8 +132,8 @@ async fn off_and_a_list_still_restrict_the_grammar() { ); let settings = Settings::new(Store::value("111111111111")); let listed = settings.enabled_accounts().await.unwrap(); - assert!(listed.enabled_for("111111111111", None)); - assert!(!listed.enabled_for("222222222222", None)); + assert!(listed.enabled_for("111111111111")); + assert!(!listed.enabled_for("222222222222")); } /// A malformed value enables no account and is logged once per change. From 646579d776a9d2e463590482231d6f3cb5507047 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 06:01:04 +0000 Subject: [PATCH 055/101] refactor(core): keep the parsed search conditions inside the grammar Only the grammar's own rule tests read SearchFilter::conditions, and no code outside the module names Condition or Operator. conditions() is now test-only and module-private, and the re-export of Condition and Operator is gone. --- crates/core/src/expression/search_filter/mod.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/core/src/expression/search_filter/mod.rs b/crates/core/src/expression/search_filter/mod.rs index 5b82710c1..c62d6042c 100644 --- a/crates/core/src/expression/search_filter/mod.rs +++ b/crates/core/src/expression/search_filter/mod.rs @@ -41,7 +41,7 @@ mod walk; use std::collections::{BTreeSet, HashMap}; pub use gate::EnabledAccounts; -pub use rules::{Condition, Operator}; +use rules::Condition; use crate::error::DynamoDbError; use crate::expression::search_params::check_unused_keys; @@ -152,8 +152,8 @@ fn evaluation_maps( impl SearchFilter { /// The conditions in written order. - #[must_use] - pub fn conditions(&self) -> &[Condition] { + #[cfg(test)] + pub(super) fn conditions(&self) -> &[Condition] { &self.conditions } From 0f9943e32a4c942d4d3db943ff637676be5f789d Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 06:01:04 +0000 Subject: [PATCH 056/101] refactor(core): define each search schema message once for both grammars The equality-only grammar and the extended grammar refuse a missing HASH attribute and an attribute outside the search schema with the same measured text. Each grammar had its own copy of both messages. search_condition now defines HASH_ATTRIBUTES_MISSING and not_in_search_schema, and both grammars use them. The text is unchanged. --- .../core/src/expression/search_condition.rs | 29 ++++++++++++------- .../src/expression/search_filter/schema.rs | 11 +++---- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/crates/core/src/expression/search_condition.rs b/crates/core/src/expression/search_condition.rs index e5d8c8548..b0a0523db 100644 --- a/crates/core/src/expression/search_condition.rs +++ b/crates/core/src/expression/search_condition.rs @@ -116,6 +116,22 @@ pub fn search_condition_name_refs(expr: &str) -> std::collections::BTreeSet<&str phases::name_refs(expr) } +/// The refusal of a search condition that omits a declared HASH attribute, +/// in both grammars. Measured against the service 2026-08-19 (us-east-1). +pub(crate) const HASH_ATTRIBUTES_MISSING: &str = + "SearchConditionExpression must have all HASH attributes in configured SearchSchema"; + +/// The refusal of a condition on an attribute outside the search schema, in +/// both grammars. Wording measured against the service on 2026-08-11; the +/// service's own grammar slip ("attributes that is not") is reproduced +/// because clients receive it. +pub(crate) fn not_in_search_schema(attribute: &str) -> String { + format!( + "SearchConditionExpression must not contain any attributes that is not in \ + SearchSchema. Invalid attribute: {attribute}" + ) +} + /// Validate resolved filter conditions against a vector index search schema. /// /// Enforces that every referenced attribute belongs to the search schema, that @@ -148,12 +164,7 @@ pub fn validate_conditions_against_search_schema( .iter() .any(|condition| condition.attribute_name == element.attribute_name); if !present { - return Err(invalid( - // Measured against the service 2026-08-19 (us-east-1): an - // expression that omits a declared HASH attribute is refused - // with exactly this text. - "SearchConditionExpression must have all HASH attributes in configured SearchSchema", - )); + return Err(invalid(HASH_ATTRIBUTES_MISSING)); } } @@ -169,11 +180,7 @@ pub fn validate_conditions_against_search_schema( .iter() .any(|element| element.attribute_name == condition.attribute_name); if !in_schema { - return Err(invalid(format!( - "SearchConditionExpression must not contain any attributes that is not in \ - SearchSchema. Invalid attribute: {}", - condition.attribute_name - ))); + return Err(invalid(not_in_search_schema(&condition.attribute_name))); } } diff --git a/crates/core/src/expression/search_filter/schema.rs b/crates/core/src/expression/search_filter/schema.rs index a7320a872..1ac994408 100644 --- a/crates/core/src/expression/search_filter/schema.rs +++ b/crates/core/src/expression/search_filter/schema.rs @@ -9,13 +9,14 @@ //! messages carry no expression prefix. use super::rules::{Condition, Operator}; +use crate::expression::search_condition::{ + HASH_ATTRIBUTES_MISSING as HASH_MISSING, not_in_search_schema, +}; use crate::types::{ AttributeDefinition, AttributeValue, ScalarAttributeType, SearchSchemaElement, SearchSchemaElementType, }; -const HASH_MISSING: &str = - "SearchConditionExpression must have all HASH attributes in configured SearchSchema"; const HASH_MORE_THAN_ONCE: &str = "SearchConditionExpression must contain only one condition \ on the HASH attribute; to search more than one HASH value, \ make one SearchVectors call for each value"; @@ -84,11 +85,7 @@ pub(super) fn validate<'a>( .iter() .find(|e| e.attribute_name == condition.attribute) else { - return Err(format!( - "SearchConditionExpression must not contain any attributes that is not in \ - SearchSchema. Invalid attribute: {}", - condition.attribute - )); + return Err(not_in_search_schema(&condition.attribute)); }; let Some(declared) = definitions .iter() From 32fa11201cdad46dbf282f1e0c7aff2ff5ecb9e8 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 06:01:18 +0000 Subject: [PATCH 057/101] docs(core): state what reaches a vector search backend and what recurses VectorSearch::filters said that range and function conditions are refused before a backend and that the type must widen if the service admits them. Range, IN, OR, NOT and function conditions, and Number equalities, now reach the backend as item_filter, and filters holds the String and Binary equalities the backend applies in its own query. The comment now says so. The comment on the drop of the search condition tree said that dropping never recurses. That holds for the parsed tree. The lowering, the evaluator and the drop of the lowered Expr recurse once per level, and the 300-operator limit bounds them; the comment now says that too. --- .../core/src/expression/search_filter/grammar.rs | 6 +++++- crates/storage/src/lib.rs | 14 ++++++-------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/crates/core/src/expression/search_filter/grammar.rs b/crates/core/src/expression/search_filter/grammar.rs index 6a723dc61..9c8c62fa0 100644 --- a/crates/core/src/expression/search_filter/grammar.rs +++ b/crates/core/src/expression/search_filter/grammar.rs @@ -79,7 +79,11 @@ pub(super) enum Node { // A tree can be as deep as the expression is long, and the drop glue of a // `Box` chain recurses once per level. These drops move the children onto a -// heap stack instead, so dropping never recurses. +// heap stack instead, so dropping a `Node` never recurses. The steps after +// the checks still recurse: `rules::lower`, the evaluator that +// `SearchFilter::matches` calls and the drop of the lowered `Expr` take one +// frame per level. The operator limit bounds that depth: an accepted +// condition has at most 300 operators, so at most 300 levels. impl Drop for Node { fn drop(&mut self) { diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index c3a18bdef..7241b90ff 100755 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -187,14 +187,12 @@ pub struct VectorSearch<'a> { /// on every search against such an index. Backends may therefore treat /// `Some` as a mandatory predicate rather than a hint. pub hash_key: Option<(&'a str, &'a AttributeValue)>, - /// Equality filters over the index's inline-filter attributes, combined - /// with logical AND. Empty means no additional filtering. - /// - /// Equality only, deliberately. The wire surface accepts a filter - /// expression, which the engine parses and lowers to these pairs; that is - /// lossless today because only exact-match conditions are supported, and - /// range or function conditions are rejected before reaching a backend. If - /// the service ever admits range conditions this type must widen. + /// Equalities on String and Binary values over the index's inline-filter + /// attributes, combined with logical AND, which the backend applies in + /// its own query. Empty means no additional filtering. + /// + /// Every other condition of a search condition, a range, `IN`, `OR`, + /// `NOT`, a function or a Number equality, arrives as `item_filter`. pub filters: &'a [(&'a str, &'a AttributeValue)], /// A condition each candidate must satisfy before it is ranked, for a /// search condition that `filters` cannot express. `None` means no From 888f75d5fb6e813db33a89eb0ac6418b53e160e1 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:44:18 +0000 Subject: [PATCH 058/101] fix(auth): match a bare negated operator on SearchVectors attributes DynamoDB sets no dynamodb:Attributes value on a SearchVectors request, whatever its projection and condition name: a Deny gated on Null true refused every search, a projected one included (measured 2026-11-21 in us-east-1). IAM matches a bare negated operator on an absent multivalued key, measured on IAM for dynamodb:Attributes. A Deny gated on a bare StringNotEquals over the key therefore refuses every search. ExtendDB also sets no value on a SearchVectors, but kept the no-match rule for an absent dynamodb:Attributes on every operation, so that Deny refused no search and an Allow gated on it granted none. The request context now carries whether the service leaves the key absent on the request, which the server sets for SearchVectors, and a bare negated operator over the absent key matches there. The other operations, and dynamodb:LeadingKeys, keep the no-match rule. The comments in the condition evaluator, the request context and the multivalued key test, the security model and the upgrade manual now say so. Verified with evaluator tests over the request context the server builds (Deny and Allow under StringNotEquals, StringNotLike and StringNotEqualsIgnoreCase on a SearchVectors, Scan and GetItem), and three wire rows: a Deny gated on the operator refuses a search with and without a projection, and an Allow gated on it grants a search. No request under such a policy was sent to DynamoDB. --- crates/auth/src/policy/condition.rs | 6 +- .../src/policy/condition/tests/multivalued.rs | 24 ++-- crates/auth/src/policy/context.rs | 43 +++--- crates/auth/src/policy/evaluator/tests.rs | 1 + .../evaluator/tests/absent_attributes.rs | 124 ++++++++++++++++++ crates/server/src/request_helpers.rs | 4 + docs/manuals/07-upgrade-manual.md | 2 +- docs/manuals/10-security-model.md | 2 +- tests/test_authz_search_vectors_index.py | 52 +++++++- 9 files changed, 226 insertions(+), 32 deletions(-) create mode 100644 crates/auth/src/policy/evaluator/tests/absent_attributes.rs diff --git a/crates/auth/src/policy/condition.rs b/crates/auth/src/policy/condition.rs index 036a1d120..fb48f31a8 100644 --- a/crates/auth/src/policy/condition.rs +++ b/crates/auth/src/policy/condition.rs @@ -157,8 +157,10 @@ pub fn evaluate_condition_with( // requests the service does. ExtendDB leaves `dynamodb:LeadingKeys` // absent on query shapes it cannot pin to a partition value, where // the service populates it. It leaves `dynamodb:Attributes` absent - // only on a `SearchVectors` with no `ProjectionExpression` (#729) - // and, on a table that does not exist, on a `GetItem`, + // on every `SearchVectors`, as the service does (measured + // 2026-11-21), so there the absent-key answer is IAM's and a bare + // negated operator matches. It also leaves `dynamodb:Attributes` + // absent, on a table that does not exist, on a `GetItem`, // transaction `Get` or `BatchGetItem` that names no attribute // outside its keys, a `Query` whose key condition the key // condition parser refuses and that names none elsewhere, and a diff --git a/crates/auth/src/policy/condition/tests/multivalued.rs b/crates/auth/src/policy/condition/tests/multivalued.rs index 763192567..bc064e323 100644 --- a/crates/auth/src/policy/condition/tests/multivalued.rs +++ b/crates/auth/src/policy/condition/tests/multivalued.rs @@ -494,17 +494,19 @@ fn bare_negated_op_absent_dynamodb_keys_do_not_match() { // IAM matches a bare negated operator on absent dynamodb:Attributes and // dynamodb:LeadingKeys too. ExtendDB leaves dynamodb:LeadingKeys absent on // query shapes it cannot pin to a partition value, where the service - // populates it. It leaves dynamodb:Attributes absent only on a - // SearchVectors with no ProjectionExpression (#729) and, on a table that - // does not exist, on a GetItem, transaction Get or BatchGetItem that names - // no attribute outside its keys, a Query whose key condition the key - // condition parser refuses and that names none elsewhere, and a Scan that - // names none. On the service the key holds the table's key attributes on - // every item request measured, a Scan that names no attribute included, - // and an Allow gated on a bare StringNotEquals over it grants no Scan - // (measured 2026-11-01). Matching on those absent keys could grant an - // Allow the service refuses, so for these two keys an absent key keeps the - // no-match rule (BR-7085). + // populates it. Outside SearchVectors it leaves dynamodb:Attributes absent + // only on a table that does not exist, on a GetItem, transaction Get or + // BatchGetItem that names no attribute outside its keys, a Query whose key + // condition the key condition parser refuses and that names none + // elsewhere, and a Scan that names none. On the service the key holds the + // table's key attributes on every item request measured, a Scan that + // names no attribute included, and an Allow gated on a bare + // StringNotEquals over it grants no Scan (measured 2026-11-01). Matching + // on those absent keys could grant an Allow the service refuses, so a + // context that does not report the service's absence keeps the no-match + // rule for these two keys. On a SearchVectors, where the service sets no + // dynamodb:Attributes value, the request context reports it and the + // operator matches (see evaluator/tests/absent_attributes.rs). let ctx = TestContext::new(); for key in ["dynamodb:Attributes", "dynamodb:LeadingKeys"] { for op in [ diff --git a/crates/auth/src/policy/context.rs b/crates/auth/src/policy/context.rs index 8f13aa580..1b0858c1f 100755 --- a/crates/auth/src/policy/context.rs +++ b/crates/auth/src/policy/context.rs @@ -177,6 +177,11 @@ pub struct RequestParams { /// Attribute names being read/written (for `dynamodb:Attributes`). /// `None` when not applicable. pub attributes: Option>, + /// Whether the service leaves `dynamodb:Attributes` absent on this request + /// as ExtendDB does, so that a bare negated operator over the absent key + /// matches as it does in IAM. `true` for `SearchVectors`, which sets no + /// value for the key on the service. + pub attributes_absent_on_service: bool, /// The Select parameter value (for `dynamodb:Select`). pub select: Option, /// The `ReturnValues` parameter value (for `dynamodb:ReturnValues`). @@ -249,6 +254,9 @@ pub struct RequestContext { pub leading_keys: Option>, /// Attribute names being read/written. pub attributes: Option>, + /// Whether the service leaves `dynamodb:Attributes` absent on this + /// request (see [`RequestParams::attributes_absent_on_service`]). + pub attributes_absent_on_service: bool, /// The Select parameter value. pub select: Option, /// The `ReturnValues` parameter value. @@ -321,6 +329,7 @@ impl RequestContext { resource_tags, leading_keys: params.leading_keys, attributes: params.attributes, + attributes_absent_on_service: params.attributes_absent_on_service, select: params.select, return_values: params.return_values, return_consumed_capacity: params.return_consumed_capacity, @@ -474,23 +483,27 @@ impl ConditionContext for RequestContext { fn bare_negated_matches_absent_multivalued_key(&self, key: &str) -> bool { // IAM matches a bare negated operator on any absent multivalued key. - // ExtendDB applies that only to `aws:TagKeys`, which it populates on + // ExtendDB applies that to `aws:TagKeys`, which it populates on // exactly the three operations the AWS service authorization reference // lists it for (TagResource, UntagResource, CreateTable with Tags), so - // its absence here is the service's absence. `dynamodb:LeadingKeys` is - // left absent on query shapes the extractor cannot pin to a partition - // value, where the service populates it. `dynamodb:Attributes` is - // absent only on a `SearchVectors` with no `ProjectionExpression` - // (#729) and, on a table that does not exist, on a `GetItem`, - // transaction `Get` or `BatchGetItem` that names no attribute outside - // its keys, a `Query` whose key condition the key condition parser - // refuses and that names none elsewhere, and a `Scan` that names none. - // On the service the key is present on a `Scan` that names no - // attribute, and an Allow gated on a bare `StringNotEquals` over it - // grants no `Scan` (measured 2026-11-01). - // For those two keys an absent key keeps the no-match rule, so an - // Allow gated on a bare negated operator over them grants nothing. - super::casefold::case_fold(key) == "aws:tagkeys" + // its absence here is the service's absence. It applies it to + // `dynamodb:Attributes` on a `SearchVectors`, where the service sets + // no value for the key whatever the projection and the condition name + // (measured 2026-11-21: a Deny gated on `Null` `true` refused every + // search, a projected one included), and ExtendDB sets none either. + // `dynamodb:LeadingKeys` is left absent on query shapes the extractor + // cannot pin to a partition value, where the service populates it. + // `dynamodb:Attributes` is otherwise absent only on a table that does + // not exist, on a `GetItem`, transaction `Get` or `BatchGetItem` that + // names no attribute outside its keys, a `Query` whose key condition + // the key condition parser refuses and that names none elsewhere, and + // a `Scan` that names none. On the service the key is present on a + // `Scan` that names no attribute, and an Allow gated on a bare + // `StringNotEquals` over it grants no `Scan` (measured 2026-11-01). + // For those cases an absent key keeps the no-match rule, so an Allow + // gated on a bare negated operator over them grants nothing. + let key = super::casefold::case_fold(key); + key == "aws:tagkeys" || (key == "dynamodb:attributes" && self.attributes_absent_on_service) } } diff --git a/crates/auth/src/policy/evaluator/tests.rs b/crates/auth/src/policy/evaluator/tests.rs index e48b6089b..38c504630 100644 --- a/crates/auth/src/policy/evaluator/tests.rs +++ b/crates/auth/src/policy/evaluator/tests.rs @@ -57,6 +57,7 @@ fn parse(json: &str) -> PolicyDocument { PolicyDocument::from_json(json).unwrap() } +mod absent_attributes; mod arn_value_tokens; mod case_three; mod combined; diff --git a/crates/auth/src/policy/evaluator/tests/absent_attributes.rs b/crates/auth/src/policy/evaluator/tests/absent_attributes.rs new file mode 100644 index 000000000..2b276c926 --- /dev/null +++ b/crates/auth/src/policy/evaluator/tests/absent_attributes.rs @@ -0,0 +1,124 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! A bare negated operator over an absent `dynamodb:Attributes`, evaluated +//! against the request context the server builds. +//! +//! IAM matches a bare negated operator on an absent multivalued key, measured +//! on IAM for `dynamodb:Attributes`. The service sets no `dynamodb:Attributes` +//! value on a `SearchVectors` (measured 2026-11-21 in us-east-1: a Deny gated +//! on `Null` `true` refused every search, a projected one included), and +//! ExtendDB sets none either. On a `SearchVectors` the operator therefore +//! matches: a Deny gated on it refuses the search and an Allow gated on it +//! grants it. On the other operations ExtendDB leaves the key absent on +//! requests where the service populates it, so there the operator keeps the +//! no-match rule. + +use super::*; +use crate::policy::context::{RequestContext, RequestParams}; + +const INDEX: &str = "arn:aws:dynamodb:us-east-1:123456789012:table/t/index/v"; +const TABLE: &str = "arn:aws:dynamodb:us-east-1:123456789012:table/t"; +const NEGATED: [&str; 3] = [ + "StringNotEquals", + "StringNotLike", + "StringNotEqualsIgnoreCase", +]; + +fn policy(effect: &str, action: &str, operator: &str) -> Vec { + let mut statements = vec![serde_json::json!({ + "Effect": effect, "Action": action, "Resource": "*", + "Condition": {operator: {"dynamodb:Attributes": "x"}}, + })]; + if effect == "Deny" { + statements.push(serde_json::json!({ + "Effect": "Allow", "Action": "dynamodb:*", "Resource": "*", + })); + } + vec![parse( + &serde_json::json!({"Version": "2012-10-17", "Statement": statements}).to_string(), + )] +} + +fn context(search: bool, attributes: Option>) -> RequestContext { + RequestContext::build( + HashMap::new(), + HashMap::new(), + false, + RequestParams { + attributes, + attributes_absent_on_service: search, + ..Default::default() + }, + ) +} + +#[test] +fn a_bare_negated_deny_refuses_every_search() { + for operator in NEGATED { + let policies = policy("Deny", "dynamodb:SearchVectors", operator); + let decision = evaluate_policies( + &policies, + None, + None, + "dynamodb:SearchVectors", + INDEX, + &context(true, None), + ); + assert_eq!(decision, AuthzDecision::Deny, "{operator} Deny on a search"); + } +} + +#[test] +fn a_bare_negated_allow_grants_a_search() { + for operator in NEGATED { + let policies = policy("Allow", "dynamodb:SearchVectors", operator); + let decision = evaluate_policies( + &policies, + None, + None, + "dynamodb:SearchVectors", + INDEX, + &context(true, None), + ); + assert_eq!( + decision, + AuthzDecision::Allow, + "{operator} Allow on a search" + ); + } +} + +#[test] +fn other_operations_keep_the_no_match_rule() { + for (action, resource) in [("dynamodb:Scan", TABLE), ("dynamodb:GetItem", TABLE)] { + for operator in NEGATED { + let deny = policy("Deny", action, operator); + let decision = + evaluate_policies(&deny, None, None, action, resource, &context(false, None)); + assert_eq!( + decision, + AuthzDecision::Allow, + "{operator} Deny on {action}" + ); + let allow = policy("Allow", action, operator); + let decision = + evaluate_policies(&allow, None, None, action, resource, &context(false, None)); + assert_eq!( + decision, + AuthzDecision::Deny, + "{operator} Allow on {action}" + ); + } + } +} + +#[test] +fn leading_keys_keep_the_no_match_rule_on_a_search() { + let ctx = context(true, None); + assert!(ctx.bare_negated_matches_absent_multivalued_key("dynamodb:Attributes")); + assert!(!ctx.bare_negated_matches_absent_multivalued_key("dynamodb:LeadingKeys")); + assert!( + !context(false, None).bare_negated_matches_absent_multivalued_key("dynamodb:Attributes") + ); +} diff --git a/crates/server/src/request_helpers.rs b/crates/server/src/request_helpers.rs index 485ce725f..84177f5ee 100755 --- a/crates/server/src/request_helpers.rs +++ b/crates/server/src/request_helpers.rs @@ -491,6 +491,10 @@ pub(crate) async fn authorize_request( key_info.as_ref(), &state.limits, ), + // The service sets no `dynamodb:Attributes` value on a + // SearchVectors, so a bare negated operator over the key matches + // as it does in IAM (see `request_attributes`). + attributes_absent_on_service: operation == "SearchVectors", select: input .get("Select") .and_then(|v| v.as_str()) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 437db4200..75a864bbb 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -406,7 +406,7 @@ The `search_inequality_filters` runtime setting selects the accounts that get th **What changed.** A `SearchVectors` request carries no `dynamodb:Attributes` value, whatever its `ProjectionExpression` and `SearchConditionExpression` name, as on DynamoDB. Earlier releases put the attributes in `ProjectionExpression` in the key. SearchVectors also makes the checks that need no table, of the request body, `IndexName`, `SearchVector`, `TopK`, the expression maps, `ProjectionExpression` and `SearchConditionExpression`, before the IAM decision, as DynamoDB does. A table name the service refuses still answers first. Earlier releases made the IAM decision first. -**Who is affected.** A deployment with a policy that gates `SearchVectors` on `dynamodb:Attributes`. A `Deny` on an attribute no longer refuses a search that projects it, and a `Deny` gated on `Null` `true` refuses every search, a projected one included. DynamoDB answers both the same way (measured 2026-11-21). An `Allow` gated on `ForAllValues` now grants every search its `Action` covers, because the key is absent. A caller that a policy denies and that sends a request failing one of the checks gets `ValidationException` where it got `AccessDeniedException`. No catalog migration is required. +**Who is affected.** A deployment with a policy that gates `SearchVectors` on `dynamodb:Attributes`. A `Deny` on an attribute no longer refuses a search that projects it, and a `Deny` gated on `Null` `true` refuses every search, a projected one included. DynamoDB answers both the same way (measured 2026-11-21). An `Allow` gated on `ForAllValues` now grants every search its `Action` covers, because the key is absent. A bare negated operator over the key, such as `StringNotEquals` `{"dynamodb:Attributes": "x"}`, now matches every search, as IAM matches one on an absent key: a `Deny` gated on it refuses every search, a projected one included, and an `Allow` gated on it grants every search its `Action` covers. Earlier releases matched it on no search. This answer follows from the two measurements above and was not sent to DynamoDB under such a policy. A caller that a policy denies and that sends a request failing one of the checks gets `ValidationException` where it got `AccessDeniedException`. No catalog migration is required. ### v1.0.0: Cassandra reads and writes at `LOCAL_QUORUM` diff --git a/docs/manuals/10-security-model.md b/docs/manuals/10-security-model.md index fc12f90fa..099ef5af5 100755 --- a/docs/manuals/10-security-model.md +++ b/docs/manuals/10-security-model.md @@ -243,7 +243,7 @@ extenddb supports the same access control patterns as real AWS IAM: | `BatchWriteItem` | Per table: the attributes of every `PutRequest` item and `DeleteRequest` key, and the table's key attributes, evaluated once with the union of the table's items | | `TransactGetItems`, `TransactWriteItems` | Per item, what the single-item operation holds: `Get` as `GetItem`, `Put` as `PutItem`, `Update` as `UpdateItem`, `Delete` as `DeleteItem`; a `ConditionCheck` holds the table's key attributes and the attributes in its `ConditionExpression` | -The names come from the request alone. A `DeleteItem` holds the key attributes of the item it deletes, not the item's other attributes, and a read with no projection holds the key attributes while it returns every attribute of the item, so a `Deny` on `ForAnyValue:StringEquals` over an attribute blocks neither (measured on DynamoDB 2026-10-31). As in DynamoDB, a policy on `dynamodb:Attributes` does not stop an `UpdateItem` from copying a denied attribute's value into another attribute through a `SET` value: under a `Deny` on `ssn`, `SET #n = ssn` with `#n` for `name` is allowed, and a projection of `name` then returns the value (measured on DynamoDB 2026-11-01). A `Scan` holds the table's key attributes when it names no attribute, a `Select COUNT` `Scan` included, so a `Null` condition on the key does not match it: a `Deny` of `Scan` gated on `Null` with value `true` refuses neither a `Scan` with no projection nor a projected one, and an `Allow` of `Scan` gated on it grants neither a `Scan` with no projection nor a `Select COUNT` `Scan` (measured on DynamoDB 2026-11-01). A bare `StringNotEquals` on the key does not match whether the key is present or absent, so an `Allow` gated on it grants nothing; on DynamoDB it granted no `Scan`, whether the `Scan` named an attribute or not (measured 2026-11-01). An allowlist written as an `Allow` on `ForAllValues:StringEquals` must list the table's key attributes, because every item request other than `SearchVectors` holds them. For a `Query` of an index, and for a later page of a `Scan` of an index, it must also list the index's key attributes. A `Query` of an index holds the index's full key schema, its sort key included, when the key condition names only the index's partition key (measured on DynamoDB 2026-11-09 on a global secondary index). The first page of a `Scan` of an index, which carries no `ExclusiveStartKey`, holds the table's key attributes and not the index's. On DynamoDB an `Allow` of `Scan` whose list holds the table's keys and not the index's grants that `Scan` of a global secondary index, and a `Deny` on the global secondary index's partition key does not refuse it. An `Allow` whose list holds the table's keys and the projected name grants that `Scan` of a local secondary index (measured 2026-11-09), and a `Deny` on the local secondary index's sort key does not refuse it (measured 2026-11-10). The other rules for a local secondary index follow from that key content. A later page carries the previous page's `LastEvaluatedKey` as its `ExclusiveStartKey`, which holds the table's and the index's key attributes, and the key holds them. So an allowlist that omits the index's key attributes refuses a later page, and a `Deny` on one of them refuses it. DynamoDB answers the same (measured 2026-11-10). Under an `Allow` whose list holds the table's keys, alone or with the projected name, it refused a later page of a `Scan` of the global and of the local secondary index, and allowed a later page of a `Scan` of the table. A `Deny` on the global secondary index's partition key, or on the local secondary index's sort key, refused a later page of a `Scan` of that index. On a table that does not exist, a `Query` holds the names in its key condition, a non-key name included, so a `Deny` on one of them answers `AccessDeniedException` rather than `ResourceNotFoundException`; a `GetItem` or `BatchGetItem` holds nothing from its key, so under a `Deny` on the key attribute both answer `ResourceNotFoundException` (measured on DynamoDB 2026-11-09). The key is absent on a `SearchVectors` with no `ProjectionExpression` and, on a table that does not exist, on a `GetItem`, transaction `Get` or `BatchGetItem` that names no attribute outside its keys, a `Query` whose key condition the key condition parser refuses and that names none elsewhere, and a `Scan` that names none. The table above covers the item, batch and transaction operations. A PartiQL statement (`ExecuteStatement`, `BatchExecuteStatement` and `ExecuteTransaction`) is authorized by the engine, one statement at a time, with the `dynamodb:PartiQL*` action of its type. The engine fills `dynamodb:Attributes` with the table's key attributes and the top-level names the statement uses (measured 2026-11-03). For a read of an index, it holds the index's key attributes only when the statement names them (not measured). +The names come from the request alone. A `DeleteItem` holds the key attributes of the item it deletes, not the item's other attributes, and a read with no projection holds the key attributes while it returns every attribute of the item, so a `Deny` on `ForAnyValue:StringEquals` over an attribute blocks neither (measured on DynamoDB 2026-10-31). As in DynamoDB, a policy on `dynamodb:Attributes` does not stop an `UpdateItem` from copying a denied attribute's value into another attribute through a `SET` value: under a `Deny` on `ssn`, `SET #n = ssn` with `#n` for `name` is allowed, and a projection of `name` then returns the value (measured on DynamoDB 2026-11-01). A `Scan` holds the table's key attributes when it names no attribute, a `Select COUNT` `Scan` included, so a `Null` condition on the key does not match it: a `Deny` of `Scan` gated on `Null` with value `true` refuses neither a `Scan` with no projection nor a projected one, and an `Allow` of `Scan` gated on it grants neither a `Scan` with no projection nor a `Select COUNT` `Scan` (measured on DynamoDB 2026-11-01). Outside `SearchVectors`, a bare `StringNotEquals` on the key does not match whether the key is present or absent, so an `Allow` gated on it grants nothing; on DynamoDB it granted no `Scan`, whether the `Scan` named an attribute or not (measured 2026-11-01). On a `SearchVectors`, where the key has no value, a bare negated operator on it matches, as IAM matches one on an absent key: a `Deny` gated on `StringNotEquals` over the key refuses every search, a projected one included, and an `Allow` gated on it grants the search. An allowlist written as an `Allow` on `ForAllValues:StringEquals` must list the table's key attributes, because every item request other than `SearchVectors` holds them. For a `Query` of an index, and for a later page of a `Scan` of an index, it must also list the index's key attributes. A `Query` of an index holds the index's full key schema, its sort key included, when the key condition names only the index's partition key (measured on DynamoDB 2026-11-09 on a global secondary index). The first page of a `Scan` of an index, which carries no `ExclusiveStartKey`, holds the table's key attributes and not the index's. On DynamoDB an `Allow` of `Scan` whose list holds the table's keys and not the index's grants that `Scan` of a global secondary index, and a `Deny` on the global secondary index's partition key does not refuse it. An `Allow` whose list holds the table's keys and the projected name grants that `Scan` of a local secondary index (measured 2026-11-09), and a `Deny` on the local secondary index's sort key does not refuse it (measured 2026-11-10). The other rules for a local secondary index follow from that key content. A later page carries the previous page's `LastEvaluatedKey` as its `ExclusiveStartKey`, which holds the table's and the index's key attributes, and the key holds them. So an allowlist that omits the index's key attributes refuses a later page, and a `Deny` on one of them refuses it. DynamoDB answers the same (measured 2026-11-10). Under an `Allow` whose list holds the table's keys, alone or with the projected name, it refused a later page of a `Scan` of the global and of the local secondary index, and allowed a later page of a `Scan` of the table. A `Deny` on the global secondary index's partition key, or on the local secondary index's sort key, refused a later page of a `Scan` of that index. On a table that does not exist, a `Query` holds the names in its key condition, a non-key name included, so a `Deny` on one of them answers `AccessDeniedException` rather than `ResourceNotFoundException`; a `GetItem` or `BatchGetItem` holds nothing from its key, so under a `Deny` on the key attribute both answer `ResourceNotFoundException` (measured on DynamoDB 2026-11-09). The key is absent on every `SearchVectors` and, on a table that does not exist, on a `GetItem`, transaction `Get` or `BatchGetItem` that names no attribute outside its keys, a `Query` whose key condition the key condition parser refuses and that names none elsewhere, and a `Scan` that names none. The table above covers the item, batch and transaction operations. A PartiQL statement (`ExecuteStatement`, `BatchExecuteStatement` and `ExecuteTransaction`) is authorized by the engine, one statement at a time, with the `dynamodb:PartiQL*` action of its type. The engine fills `dynamodb:Attributes` with the table's key attributes and the top-level names the statement uses (measured 2026-11-03). For a read of an index, it holds the index's key attributes only when the statement names them (not measured). A `Deny` on `dynamodb:Attributes` does not stop `ReturnValues` `ALL_OLD` or `ReturnValuesOnConditionCheckFailure` `ALL_OLD` from returning the whole stored item, the denied attribute included. Under a `Deny` on `ssn`, an `UpdateItem` of `name` with `ReturnValues` `ALL_OLD` returns the old item with `ssn` in it, and a `PutItem` whose condition fails and a `TransactWriteItems` `ConditionCheck` that fails, each with `ReturnValuesOnConditionCheckFailure` `ALL_OLD`, return the stored item with `ssn` in the error. DynamoDB does the same (measured 2026-11-01). ExtendDB returns the whole stored item in each of these cases, and on a `PutItem` with `ReturnValues` `ALL_OLD`, whose answer on DynamoDB was not measured. The IAM guide's guard against `ReturnValues` returning attributes is a condition on `dynamodb:ReturnValues`. ExtendDB sets that key only when the request carries `ReturnValues`; DynamoDB sets it to `NONE` on a `PutItem` that carries none (measured 2026-11-01, tracked in #717). diff --git a/tests/test_authz_search_vectors_index.py b/tests/test_authz_search_vectors_index.py index da4807828..802dcd808 100644 --- a/tests/test_authz_search_vectors_index.py +++ b/tests/test_authz_search_vectors_index.py @@ -27,6 +27,14 @@ ``ExpressionAttributeNames`` keys among them, before the policy decision, so under ``deny(null)`` a request that fails one gets ValidationException. +The ``deny(not-x)`` and ``allow(not-x)`` rows were not sent to DynamoDB +either. They gate the statement on a bare ``StringNotEquals +{"dynamodb:Attributes": "x"}``. IAM matches a bare negated operator on an +absent multivalued key, measured on IAM for ``dynamodb:Attributes``, and the +service leaves the key absent on every SearchVectors, as the ``deny(null)`` +rows show. So the Deny refuses every search, a projected one included, and +the Allow grants a search. + The principals are builtin-IAM users provisioned through the management API. The module skips when the backend does not support vector indexes, unless ``EXTENDDB_EXPECT_VECTORS=1``, which makes that a failure. @@ -304,6 +312,22 @@ def test_index_name_outside_the_pattern_is_refused_before_authorization( }, ], } + + +def _bare_not_equals(effect: str) -> dict: + statement = { + "Effect": effect, + "Action": "dynamodb:*" if effect == "Deny" else "dynamodb:SearchVectors", + "Resource": "*", + "Condition": {"StringNotEquals": {"dynamodb:Attributes": "x"}}, + } + allow = [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}] + return { + "Version": "2012-10-17", + "Statement": (allow if effect == "Deny" else []) + [statement], + } + + DENY_NULL = { "Version": "2012-10-17", "Statement": [ @@ -391,6 +415,19 @@ def _invalid_key(key: str) -> str: "ValidationException", "Value provided in ExpressionAttributeNames unused in expressions: keys: {#u}", ), + "not-x-no-projection": ("deny(not-x)", {}, "AccessDeniedException", DENIED), + "not-x-projection-of-cat": ( + "deny(not-x)", + {"ProjectionExpression": "cat"}, + "AccessDeniedException", + DENIED, + ), + "not-x-allow-grants-a-projection": ( + "allow(not-x)", + {"ProjectionExpression": "cat"}, + None, + CAT_ONLY, + ), "projection-key-without-hash": ( "deny(ssn)", {"ProjectionExpression": "#n", "ExpressionAttributeNames": {"n": "ssn"}}, @@ -479,6 +516,14 @@ def deny_null(principal): return principal(DENY_NULL) +@pytest.fixture(scope="module") +def bare_not_equals(principal): + return { + "deny(not-x)": principal(_bare_not_equals("Deny")), + "allow(not-x)": principal(_bare_not_equals("Allow")), + } + + def test_the_deny_on_ssn_refuses_a_get_item_of_ssn(deny_ssn, vector_table): # The control: the policy is in force for this principal. resp = deny_ssn.post( @@ -493,9 +538,12 @@ def test_the_deny_on_ssn_refuses_a_get_item_of_ssn(deny_ssn, vector_table): @pytest.mark.parametrize("row", list(ROWS)) -def test_search_expression_attribute_names(deny_ssn, deny_null, vector_table, row): +def test_search_expression_attribute_names( + deny_ssn, deny_null, bare_not_equals, vector_table, row +): policy, members, error, expected = ROWS[row] - p = {"deny(ssn)": deny_ssn, "deny(null)": deny_null}.get(policy, vector_table["admin"]) + principals = {"deny(ssn)": deny_ssn, "deny(null)": deny_null, **bare_not_equals} + p = principals.get(policy, vector_table["admin"]) resp = _search(p, vector_table["name"], **members) if error is None: assert resp.status_code == 200, f"{row}: {resp.text}" From 144b338b2a923992182101613d38d6c30d9e5016 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:44:24 +0000 Subject: [PATCH 059/101] test(server): name what the deny(null) order rows rest on The four deny(null) rows of the SearchVectors authorization module that expect ValidationException were not sent to DynamoDB under the Null session policy, and the header said only that. The header now names the three measurements they rest on: on 2026-11-21 in us-east-1 a Deny gated on Null true refused every SearchVectors; on 2026-11-24 in us-east-1 the same four requests on a table ARN in another account, which the service refuses at its authorization decision, each answered ValidationException; and each row's message is the service's answer to the request without a policy. Comment only; the module passes unchanged on SQLite. --- tests/test_authz_search_vectors_index.py | 32 ++++++++++++++---------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/tests/test_authz_search_vectors_index.py b/tests/test_authz_search_vectors_index.py index 802dcd808..d348ce931 100644 --- a/tests/test_authz_search_vectors_index.py +++ b/tests/test_authz_search_vectors_index.py @@ -13,19 +13,25 @@ An IndexName outside ``[a-zA-Z0-9_.-]+`` (``vidx/extra``) gets ValidationException for every caller, before the policy decision, as Query and Scan do. -The ``ROWS`` were measured on DynamoDB in us-east-1 on 2026-11-21, each -request twice with the same answer, except the ``deny(null)`` rows that -expect ValidationException, which were not sent. The ``deny(ssn)`` rows ran -under a session policy that allows ``dynamodb:*`` and denies ``dynamodb:*`` -under ``ForAnyValue:StringEquals {"dynamodb:Attributes": ["ssn"]}``, the -``deny(null)`` rows under one that denies under ``Null -{"dynamodb:Attributes": "true"}``, and the ``allow-all`` rows with no session -policy. The service sets no ``dynamodb:Attributes`` value on a SearchVectors -request: it serves a projection of ``ssn`` under ``deny(ssn)``, and refuses -every search under ``deny(null)``. The service makes the checks of a -SearchVectors request that need no table, ``TopK`` and the -``ExpressionAttributeNames`` keys among them, before the policy decision, so -under ``deny(null)`` a request that fails one gets ValidationException. +The ``ROWS`` that run under ``deny(ssn)``, ``allow-all`` and the +``deny(null)`` rows that expect AccessDeniedException were measured on +DynamoDB in us-east-1 on 2026-11-21, each request twice with the same answer. +The ``deny(ssn)`` rows ran under a session policy that allows ``dynamodb:*`` +and denies ``dynamodb:*`` under ``ForAnyValue:StringEquals +{"dynamodb:Attributes": ["ssn"]}``, the ``deny(null)`` rows under one that +denies under ``Null {"dynamodb:Attributes": "true"}``, and the ``allow-all`` +rows with no session policy. The service sets no ``dynamodb:Attributes`` +value on a SearchVectors request: it serves a projection of ``ssn`` under +``deny(ssn)``, and refuses every search under ``deny(null)``. + +The four ``deny(null)`` rows that expect ValidationException were not sent to +DynamoDB under the ``Null`` session policy. They rest on three measurements. +On 2026-11-21 in us-east-1 a Deny gated on ``Null`` ``true`` refused every +SearchVectors sent. On 2026-11-24 in us-east-1 the same four requests, sent on +a table ARN in another account, which the service refuses at its +authorization decision, each answered ValidationException, so the service +makes these checks ahead of that decision. Each row's message is the one the +service answers for the same request without a policy. The ``deny(not-x)`` and ``allow(not-x)`` rows were not sent to DynamoDB either. They gate the statement on a bare ``StringNotEquals From e017fbaf9f1cdecfd58f0ad1ad2a766a7ff7fc7b Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 06:02:04 +0000 Subject: [PATCH 060/101] docs(search): state the check order served and where the grammar was measured The handler comment and the upgrade manual said that a table name the service refuses answers first on SearchVectors. On the service, TopK 0 and a two-character IndexName answer ahead of a refused table name, and the service checks the table name's length, which ExtendDB does not on SearchVectors. The handler comment and the upgrade note now state the order this release serves: a table name outside the pattern answers first, and no length check applies. The upgrade manual, the admin guide, the gate module and the wire test header said that DynamoDB serves the grammar to every account. They now say that it accepts it on the accounts and regions measured, us-east-1, eu-north-1 and ap-southeast-2, and the upgrade note adds that the API reference documents only `=`. --- crates/core/src/expression/search_filter/gate.rs | 3 ++- crates/server/src/handler.rs | 11 ++++++----- docs/manuals/05-admin-guide.md | 2 +- docs/manuals/07-upgrade-manual.md | 4 ++-- tests/test_search_vectors_inequality_filters.py | 3 ++- 5 files changed, 13 insertions(+), 10 deletions(-) diff --git a/crates/core/src/expression/search_filter/gate.rs b/crates/core/src/expression/search_filter/gate.rs index a501e08f3..fbe0ee756 100644 --- a/crates/core/src/expression/search_filter/gate.rs +++ b/crates/core/src/expression/search_filter/gate.rs @@ -3,7 +3,8 @@ //! Which accounts get the extended grammar. //! -//! The service serves the grammar to every account. The setting names the +//! DynamoDB accepts the grammar on the accounts and regions measured +//! (us-east-1, eu-north-1, ap-southeast-2). The setting names the //! accounts ExtendDB serves it to: `all` (the default), `off`, or a //! comma-separated list of 12-digit account IDs, in which case a request //! gets the grammar when the caller is listed. A request on a table of diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index b37835e4c..0fe017bd3 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -131,11 +131,12 @@ pub(crate) async fn handle_request( } }; - // The service checks a SearchVectors request before it authorizes it, as - // far as the checks need no table: the body, IndexName, SearchVector, - // TopK, the expression maps, the projection and the search condition. A - // table name the service refuses still answers first, from - // `authorize_request`. + // A SearchVectors request is checked before it is authorized, as far as + // the checks need no table: the body, IndexName, SearchVector, TopK, the + // expression maps, the projection and the search condition. They run once + // the table name passes `check_table_name_chars`; a table name outside + // its pattern answers first, from `authorize_request`, and no length + // check applies to the table name here (#1462). if operation == "SearchVectors" && crate::table_name_gate::check_table_name_chars(&operation, &input, &account_id).is_ok() && let Err(e) = extenddb_engine::check_search_vectors_request( diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index b29d9d173..af5d30d11 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -326,7 +326,7 @@ Managed via `extenddb settings set`. Changes take effect within 30 seconds witho | `log_level` | `info` | Log level: trace, debug, info, warn, error | | `control_plane_delay_seconds` | `0.25` | Delay for table status transitions, in seconds (0 = instant). PostgreSQL and SQLite write 0.25 into the catalog when it is created; MongoDB and Cassandra use 0.25 when the setting is absent. On PostgreSQL and SQLite a value below 1 makes DeleteTable remove the table in the request; on PostgreSQL, if a session holds a lock on the table's data (a reader, an open write transaction, an index build), DeleteTable returns `DELETING` instead (after at most about a second), the drop finishes in the background within about a second of that session's release, and a CreateTable of the same name is refused until then. | | `allow_credential_import` | `false` | Whether `import-access-key` is allowed. Only `true` enables it | -| `search_inequality_filters` | every account | The accounts whose `SearchVectors` requests accept the extended `SearchConditionExpression` grammar, as DynamoDB does for every account: `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. A malformed value in the catalog, which the CLI and the management API refuse to write, is no account. With `off`, or for an account the list does not name, a search condition is an AND of equalities. A server reads the setting only for a search whose answer depends on the grammar, and at most once a second, so a change applies within about a second without a restart. When a read fails or does not end within two seconds, the server uses the value of its last read that answered; before any read has answered, such a search answers `ServiceUnavailableException` | +| `search_inequality_filters` | every account | The accounts whose `SearchVectors` requests accept the extended `SearchConditionExpression` grammar, which DynamoDB accepts on the accounts and regions measured (us-east-1, eu-north-1, ap-southeast-2): `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. A malformed value in the catalog, which the CLI and the management API refuse to write, is no account. With `off`, or for an account the list does not name, a search condition is an AND of equalities. A server reads the setting only for a search whose answer depends on the grammar, and at most once a second, so a change applies within about a second without a restart. When a read fails or does not end within two seconds, the server uses the value of its last read that answered; before any read has answered, such a search answers `ServiceUnavailableException` | | `vector_backfill_batch_delay_ms` | `0` | **Test-oriented.** Milliseconds to pause between batches while a vector index backfills. Zero in production. A test sets it so a write is guaranteed to land while the index is still building. The pause is outside the batch transaction, so writes are still accepted throughout, but it does extend the per-table propagation hold: no index on that table advances while the build runs, GSIs included, and the accepted range goes up to 60 s per batch. | | `vector_allocation_phase_delay_ms` | `0` | **Test-oriented.** Milliseconds to hold a new vector index in the resource-allocation phase (`CREATING` with `Backfilling: false`) before the scan starts. Zero in production. Without it the phase lasts only from the `UpdateTable` transaction, which inserts the row as `CREATING` with `Backfilling: false`, until the detached build task flips the flag, which is a window no client can time reliably rather than one that cannot exist. | diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 75a864bbb..9eec107bf 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -390,7 +390,7 @@ deployment, even when no catalog migration is required. ### v1.1.0: SearchVectors serves the extended `SearchConditionExpression` grammar -**What changed.** A `SearchConditionExpression` takes the comparators `<>`, `<`, `<=`, `>` and `>=`, `BETWEEN`, `IN`, `OR`, `NOT`, parentheses, `attribute_exists` and `attribute_not_exists`, and more than one condition on an attribute, up to 50 conditions. DynamoDB serves this grammar to every account. Earlier releases accepted only an AND of equalities, at most 19, and refused the other forms with `ValidationException`. A Number in the condition now compares as the nearest binary64 value of each side, as on DynamoDB, so `9007199254740992` and `9007199254740993` are equal. Earlier releases compared Numbers in the condition exactly. +**What changed.** A `SearchConditionExpression` takes the comparators `<>`, `<`, `<=`, `>` and `>=`, `BETWEEN`, `IN`, `OR`, `NOT`, parentheses, `attribute_exists` and `attribute_not_exists`, and more than one condition on an attribute, up to 50 conditions. DynamoDB accepts this grammar on the accounts and regions measured (us-east-1, eu-north-1, ap-southeast-2), although its API reference documents only `=`. Earlier releases accepted only an AND of equalities, at most 19, and refused the other forms with `ValidationException`. A Number in the condition now compares as the nearest binary64 value of each side, as on DynamoDB, so `9007199254740992` and `9007199254740993` are equal. Earlier releases compared Numbers in the condition exactly. The `search_inequality_filters` runtime setting selects the accounts that get the grammar: `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. With `off`, or for an account the list does not name, a search condition is an AND of equalities, compared as in earlier releases. A server reads the setting only for a search whose answer depends on the grammar, such as an inequality or a condition on a Number, and at most once a second, so a change applies within about a second without a restart. A search that both grammars answer alike, such as an AND of string equalities, never reads it. When a read fails or does not end within two seconds, the server uses the value of its last read that answered; before any read has answered, such a search answers `ServiceUnavailableException`. A malformed value in the catalog, which the CLI and the management API refuse to write, is logged once per change and enables no account. The [admin guide](05-admin-guide.md) lists the setting. @@ -404,7 +404,7 @@ The `search_inequality_filters` runtime setting selects the accounts that get th ### v1.1.0: SearchVectors sets no `dynamodb:Attributes` value and checks its request before the policy -**What changed.** A `SearchVectors` request carries no `dynamodb:Attributes` value, whatever its `ProjectionExpression` and `SearchConditionExpression` name, as on DynamoDB. Earlier releases put the attributes in `ProjectionExpression` in the key. SearchVectors also makes the checks that need no table, of the request body, `IndexName`, `SearchVector`, `TopK`, the expression maps, `ProjectionExpression` and `SearchConditionExpression`, before the IAM decision, as DynamoDB does. A table name the service refuses still answers first. Earlier releases made the IAM decision first. +**What changed.** A `SearchVectors` request carries no `dynamodb:Attributes` value, whatever its `ProjectionExpression` and `SearchConditionExpression` name, as on DynamoDB. Earlier releases put the attributes in `ProjectionExpression` in the key. SearchVectors also makes the checks that need no table, of the request body, `IndexName`, `SearchVector`, `TopK`, the expression maps, `ProjectionExpression` and `SearchConditionExpression`, before the IAM decision, as DynamoDB does. A table name outside the pattern `[a-zA-Z0-9_.-]+` answers first, and no length check applies to the table name. Earlier releases made the IAM decision first. **Who is affected.** A deployment with a policy that gates `SearchVectors` on `dynamodb:Attributes`. A `Deny` on an attribute no longer refuses a search that projects it, and a `Deny` gated on `Null` `true` refuses every search, a projected one included. DynamoDB answers both the same way (measured 2026-11-21). An `Allow` gated on `ForAllValues` now grants every search its `Action` covers, because the key is absent. A bare negated operator over the key, such as `StringNotEquals` `{"dynamodb:Attributes": "x"}`, now matches every search, as IAM matches one on an absent key: a `Deny` gated on it refuses every search, a projected one included, and an `Allow` gated on it grants every search its `Action` covers. Earlier releases matched it on no search. This answer follows from the two measurements above and was not sent to DynamoDB under such a policy. A caller that a policy denies and that sends a request failing one of the checks gets `ValidationException` where it got `AccessDeniedException`. No catalog migration is required. diff --git a/tests/test_search_vectors_inequality_filters.py b/tests/test_search_vectors_inequality_filters.py index 8062c57e6..1510c18c5 100644 --- a/tests/test_search_vectors_inequality_filters.py +++ b/tests/test_search_vectors_inequality_filters.py @@ -6,7 +6,8 @@ Under the extended grammar, a search condition takes ``<>``, ``<``, ``<=``, ``>``, ``>=``, BETWEEN, IN, OR, NOT, parentheses, ``attribute_exists`` and ``attribute_not_exists``, and more than one condition on an attribute, up to -50 conditions. The service serves it to every account; ExtendDB serves it to +50 conditions. The service accepts it on the accounts and regions measured +(us-east-1, eu-north-1, ap-southeast-2); ExtendDB serves it to the accounts the ``search_inequality_filters`` setting names, every account when the setting is absent. From 06dcace96399bc118df96f74fa143b9edbf23b98 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:51:31 +0000 Subject: [PATCH 061/101] fix(wasm): serve the extended search grammar in the browser build The workspace takes extenddb-engine with its default features off, and extenddb-wasm-adapter asked for none of its features, so in a build of the adapter the engine had no search-inequality-filters feature while extenddb-core and extenddb-storage-sqlite had it from their defaults. `cargo tree -p extenddb-wasm-adapter -e features -i extenddb-engine` showed the engine with no feature. The browser build therefore served SearchVectors with the equality-only grammar: a range condition answered "Invalid comparator used in SearchConditionExpression". The adapter now declares a search-inequality-filters feature in its default list that enables the feature on the engine, core and the SQLite backend, so the compile-out script removes it there as from the seven other crates. The engine's reads of the search_inequality_filters setting use a tokio task and the clock, which wasm32-unknown-unknown does not have, so on wasm32 the engine compiles them out and gives every account the grammar, as on a server that has installed no settings store; the browser build has no catalog to install one from. The parity corpus gains a table with a HASH and a Number INLINE_FILTER search schema and a SearchVectors with `Country = :c AND Price > :p` that returns only the item it selects, run natively and on wasm32. Verified: the corpus case fails on the native build of the adapter without the feature (the error above) and passes with it. The wasm build, clippy, guard and pedantic steps of devtools/run-wasm-step pass on 1.97.0 with the feature on and compiled out; enabling the feature on the engine without the wasm32 gate fails the clippy step on four disallowed calls in search_vectors_settings.rs. --- crates/engine/src/lib.rs | 2 +- crates/engine/src/search_vectors_extended.rs | 27 ++- crates/wasm-adapter/Cargo.toml | 15 ++ crates/wasm-adapter/parity/corpus.json | 188 ++++++++++++++++++ .../compile-out-search-inequality-filters | 2 +- 5 files changed, 229 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 92186e8a1..e295f917b 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -98,7 +98,7 @@ pub use query::handle_query; pub use request_limits::check_request_item_counts; pub use scan::handle_scan; pub use search_vectors::{check_search_vectors_request, handle_search_vectors}; -#[cfg(feature = "search-inequality-filters")] +#[cfg(all(feature = "search-inequality-filters", not(target_arch = "wasm32")))] pub use search_vectors_extended::{install_search_filter_settings, search_filter_settings_changed}; pub use streams::{SHARD_ITERATOR_EXPIRED_MESSAGE, ShardIteratorClass, classify_shard_iterator}; pub use streams::{ShardIterator, decode_shard_iterator, encode_shard_iterator}; diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs index b6b6855c6..7a91ba4be 100644 --- a/crates/engine/src/search_vectors_extended.rs +++ b/crates/engine/src/search_vectors_extended.rs @@ -15,18 +15,39 @@ //! which accounts get the grammar. It is read through the settings store the //! server installs with [`install_search_filter_settings`] (see //! `search_vectors_settings.rs`), so a change applies without a restart. -//! Until a store is installed, every account gets the grammar. +//! Until a store is installed, every account gets the grammar. The browser +//! build (wasm32) has no catalog and installs no store, so it compiles the +//! store reads out and gives every account the grammar. #[cfg(feature = "search-inequality-filters")] pub(crate) use imp::{Extended, enabled_for, parse, resolve_scope}; -#[cfg(feature = "search-inequality-filters")] +#[cfg(all(feature = "search-inequality-filters", not(target_arch = "wasm32")))] #[path = "search_vectors_settings.rs"] mod settings; -#[cfg(feature = "search-inequality-filters")] +#[cfg(all(feature = "search-inequality-filters", not(target_arch = "wasm32")))] pub use settings::{install_search_filter_settings, search_filter_settings_changed}; +/// The setting in the browser build, which installs no settings store: every +/// account, as on a server that has not installed one. The store reads use a +/// tokio task and the clock, which wasm32-unknown-unknown does not have. +#[cfg(all(feature = "search-inequality-filters", target_arch = "wasm32"))] +mod settings { + use std::future::{Future, ready}; + use std::sync::Arc; + + use extenddb_core::error::DynamoDbError; + use extenddb_core::expression::search_filter::EnabledAccounts; + use extenddb_storage::StorageEngine; + + pub(crate) fn enabled_accounts( + _storage: &Arc, + ) -> impl Future> { + ready(Ok(EnabledAccounts::All)) + } +} + #[cfg(feature = "search-inequality-filters")] mod imp { use std::collections::HashMap; diff --git a/crates/wasm-adapter/Cargo.toml b/crates/wasm-adapter/Cargo.toml index 8f7380f76..1cf2b9dd9 100644 --- a/crates/wasm-adapter/Cargo.toml +++ b/crates/wasm-adapter/Cargo.toml @@ -20,6 +20,21 @@ publish = false # `cargo build -p extenddb-wasm-adapter` (the wasm build-check) work. crate-type = ["cdylib", "rlib"] +[features] +# The engine is taken with its default features off (the workspace entry), so +# this crate names the search-inequality-filters feature for the engine, core +# and the SQLite backend together. Without it the engine would compile the +# extended search grammar out while core and the backend compile it in, and +# the browser build would serve the equality-only grammar. +# devtools/compile-out-search-inequality-filters removes it from this default +# list as from the others. +default = ["search-inequality-filters"] +search-inequality-filters = [ + "extenddb-core/search-inequality-filters", + "extenddb-engine/search-inequality-filters", + "extenddb-storage-sqlite/search-inequality-filters", +] + [dependencies] extenddb-auth = { workspace = true } extenddb-core = { workspace = true } diff --git a/crates/wasm-adapter/parity/corpus.json b/crates/wasm-adapter/parity/corpus.json index bb8840a7a..435c2b576 100644 --- a/crates/wasm-adapter/parity/corpus.json +++ b/crates/wasm-adapter/parity/corpus.json @@ -3450,6 +3450,194 @@ } ] }, + { + "name": "search grammar: CreateTable with a HASH and a Number INLINE_FILTER search schema succeeds", + "op": "CreateTable", + "body": { + "TableName": "SvFilter", + "KeySchema": [ + { + "AttributeName": "pk", + "KeyType": "HASH" + } + ], + "AttributeDefinitions": [ + { + "AttributeName": "pk", + "AttributeType": "S" + }, + { + "AttributeName": "Country", + "AttributeType": "S" + }, + { + "AttributeName": "Price", + "AttributeType": "N" + } + ], + "BillingMode": "PAY_PER_REQUEST", + "VectorIndexes": [ + { + "IndexName": "vidx", + "Dimensions": 3, + "DistanceFunction": "COSINE", + "VectorAttribute": { + "AttributeName": "emb" + }, + "SearchSchema": [ + { + "AttributeName": "Country", + "SearchSchemaElementType": "HASH" + }, + { + "AttributeName": "Price", + "SearchSchemaElementType": "INLINE_FILTER" + } + ], + "Projection": { + "ProjectionType": "ALL" + } + } + ] + }, + "error": null, + "checks": [ + { + "path": "/TableDescription/VectorIndexes/0/IndexStatus", + "equals": "ACTIVE" + } + ] + }, + { + "name": "search grammar: PutItem cheap with Price 5 writes the item", + "op": "PutItem", + "body": { + "TableName": "SvFilter", + "Item": { + "pk": { + "S": "cheap" + }, + "Country": { + "S": "US" + }, + "Price": { + "N": "5" + }, + "emb": { + "L": [ + { + "N": "1" + }, + { + "N": "0" + }, + { + "N": "0" + } + ] + } + } + }, + "error": null, + "checks": [ + { + "path": "", + "equals": {} + } + ] + }, + { + "name": "search grammar: PutItem dear with Price 20 writes the item", + "op": "PutItem", + "body": { + "TableName": "SvFilter", + "Item": { + "pk": { + "S": "dear" + }, + "Country": { + "S": "US" + }, + "Price": { + "N": "20" + }, + "emb": { + "L": [ + { + "N": "1" + }, + { + "N": "1" + }, + { + "N": "0" + } + ] + } + } + }, + "error": null, + "checks": [ + { + "path": "", + "equals": {} + } + ] + }, + { + "name": "search grammar: SearchVectors with a range condition returns only the item it selects", + "op": "SearchVectors", + "body": { + "TableName": "SvFilter", + "IndexName": "vidx", + "SearchVector": [ + { + "N": "1" + }, + { + "N": "0" + }, + { + "N": "0" + } + ], + "TopK": 2, + "SearchConditionExpression": "Country = :c AND Price > :p", + "ExpressionAttributeValues": { + ":c": { + "S": "US" + }, + ":p": { + "N": "10" + } + } + }, + "error": null, + "checks": [ + { + "path": "/SearchResults/0/Item/pk/S", + "equals": "dear" + }, + { + "path": "/SearchResults/1", + "absent": true + } + ] + }, + { + "name": "search grammar: DeleteTable deletes the search schema table", + "op": "DeleteTable", + "body": { + "TableName": "SvFilter" + }, + "error": null, + "checks": [ + { + "path": "/TableDescription/TableName", + "equals": "SvFilter" + } + ] + }, { "name": "table names: Query with a TableName outside the pattern answers ResourceNotFoundException", "op": "Query", diff --git a/devtools/compile-out-search-inequality-filters b/devtools/compile-out-search-inequality-filters index 364af2a38..4371ddf2d 100755 --- a/devtools/compile-out-search-inequality-filters +++ b/devtools/compile-out-search-inequality-filters @@ -21,7 +21,7 @@ import sys from pathlib import Path FEATURE = "search-inequality-filters" -CRATES = 7 +CRATES = 8 def main() -> int: From 26042451d6da7be46785f25cca8ec7f65d6b08ca Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:51:48 +0000 Subject: [PATCH 062/101] fix(devtools): edit no manifest when the compile-out count is wrong devtools/compile-out-search-inequality-filters wrote each Cargo.toml inside its loop and compared the number of edited crates with the expected count afterwards, so a wrong count exited 1 with the tree already edited and named the files only as Path reprs. The script now collects the edits, checks the count, and writes only when it matches. The refusal names every crate it found and says that no file was edited. The docstring describes the browser build's crate, which names the feature for the engine, core and the SQLite backend. Verified: with the expected count set to 7 on a clean tree the script exits 1 with the refusal and `git status --short` is empty; with 8 it removes the feature from the eight default lists and its cargo tree check passes. --- .../compile-out-search-inequality-filters | 59 ++++++++++++------- 1 file changed, 38 insertions(+), 21 deletions(-) diff --git a/devtools/compile-out-search-inequality-filters b/devtools/compile-out-search-inequality-filters index 4371ddf2d..6ed5c8ef0 100755 --- a/devtools/compile-out-search-inequality-filters +++ b/devtools/compile-out-search-inequality-filters @@ -3,11 +3,16 @@ # SPDX-License-Identifier: Apache-2.0 """Remove the search-inequality-filters Cargo feature from every default list. -Each crate that declares the feature has it in its `default` list, and the +Each crate that declares the feature has it in its `default` list. Most crates take their internal dependencies with default features, so no cargo -command line compiles it out. Removing it from every `default` list is how -the feature is compiled out. This script edits the working tree's Cargo.toml -files that way, then checks with `cargo tree` that nothing in the workspace +command line compiles it out. The workspace takes extenddb-engine with its +default features off, so the browser build's crate, extenddb-wasm-adapter, +names the feature for the engine, core and the SQLite backend itself. +Removing the feature from every `default` list is how it is compiled out. + +This script reads every crates/*/Cargo.toml, refuses to edit any of them +unless exactly the expected number list the feature in `default`, then +writes the edits and checks with `cargo tree` that nothing in the workspace enables the feature. CI builds, lints and tests the tree it leaves. Usage: devtools/compile-out-search-inequality-filters @@ -24,36 +29,48 @@ FEATURE = "search-inequality-filters" CRATES = 8 -def main() -> int: - root = Path(__file__).resolve().parent.parent +def feature_tree(root: Path, *args: str) -> str: + return subprocess.run( + ["cargo", "tree", "--locked", "-e", "features", *args], + cwd=root, + check=True, + capture_output=True, + text=True, + ).stdout + + +def compile_out(root: Path) -> int: default = re.compile(r'^default = \[(.*)\]$', re.MULTILINE) - edited = [] + edits = [] for manifest in sorted(root.glob("crates/*/Cargo.toml")): text = manifest.read_text() match = default.search(text) if match is None or f'"{FEATURE}"' not in match.group(1): continue kept = [f for f in (e.strip() for e in match.group(1).split(",")) if f and f != f'"{FEATURE}"'] - text = text[: match.start()] + f"default = [{', '.join(kept)}]" + text[match.end() :] - manifest.write_text(text) - edited.append(manifest.relative_to(root)) - if len(edited) != CRATES: - print(f"error: expected {CRATES} crates with {FEATURE} in default, edited {edited}", file=sys.stderr) + edits.append((manifest, text[: match.start()] + f"default = [{', '.join(kept)}]" + text[match.end() :])) + names = [str(m.relative_to(root)) for m, _ in edits] + if len(edits) != CRATES: + print( + f"error: expected {CRATES} crates with {FEATURE} in default, found {len(edits)}: {names}; " + "no file was edited", + file=sys.stderr, + ) return 1 - tree = subprocess.run( - ["cargo", "tree", "--locked", "--workspace", "-e", "features", "-i", "extenddb-core"], - cwd=root, - check=True, - capture_output=True, - text=True, - ).stdout + for manifest, text in edits: + manifest.write_text(text) + tree = feature_tree(root, "--workspace", "-i", "extenddb-core") if f'feature "{FEATURE}"' in tree: print(f"error: the workspace still enables {FEATURE}:\n{tree}", file=sys.stderr) return 1 - for manifest in edited: - print(f"removed {FEATURE} from the default list of {manifest}") + for name in names: + print(f"removed {FEATURE} from the default list of {name}") return 0 +def main() -> int: + return compile_out(Path(__file__).resolve().parent.parent) + + if __name__ == "__main__": sys.exit(main()) From fc8dbf8bc55c8c49cd86773ed37e9940294123ca Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:52:05 +0000 Subject: [PATCH 063/101] ci: check the search grammar feature state of the browser build The feature workflow checked that nothing in the workspace enables search-inequality-filters once it is compiled out, and nothing checked the default tree. A browser build whose engine lacked the feature while core had it passed every check. devtools/compile-out-search-inequality-filters takes `--check on|off`: it edits nothing and checks with `cargo tree -p extenddb-wasm-adapter` that extenddb-core, extenddb-engine and extenddb-storage-sqlite all carry the feature, or all lack it. The compile-out run makes the `off` check after its edits. The compiled-out job runs `--check on` on the default tree before it compiles the feature out. The workflow comment describes the adapter's feature. Verified: `--check on` passes on this tree and `--check off` refuses it; on a copy compiled out, `--check off` passes. With the adapter's default list emptied, `--check on` exits 1 naming the three crates. --- .../workflows/search-inequality-filters.yml | 21 +++++---- .../compile-out-search-inequality-filters | 43 ++++++++++++++++++- 2 files changed, 54 insertions(+), 10 deletions(-) diff --git a/.github/workflows/search-inequality-filters.yml b/.github/workflows/search-inequality-filters.yml index c0ea5d076..6bbe0e4ec 100644 --- a/.github/workflows/search-inequality-filters.yml +++ b/.github/workflows/search-inequality-filters.yml @@ -18,15 +18,18 @@ concurrency: # workflows build, lint and test it, and their wire tests run with the # search_inequality_filters setting absent, which gives every account the # extended grammar. These jobs cover what they do not: the workspace built, -# linted and tested with the feature compiled out, and the vector wire tests -# with the setting written as `off` and as `all`, and against the build with -# the feature compiled out. +# linted and tested with the feature compiled out, the feature state of the +# browser build, and the vector wire tests with the setting written as `off` +# and as `all`, and against the build with the feature compiled out. # -# The crates take their internal dependencies with default features, so no -# cargo command line compiles the feature out. -# devtools/compile-out-search-inequality-filters removes it from the default -# list of every crate that declares it, which compiles it out of the -# workspace, and checks that nothing enables it. +# Most crates take their internal dependencies with default features, so no +# cargo command line compiles the feature out. The workspace takes +# extenddb-engine with its default features off, so extenddb-wasm-adapter, +# the browser build, names the feature for the engine, core and the SQLite +# backend itself. devtools/compile-out-search-inequality-filters removes the +# feature from the default list of every crate that declares it, which +# compiles it out of the workspace, and checks that nothing enables it; with +# `--check on` it checks that the browser build enables it on all three. jobs: compiled-out: runs-on: extenddb_ubuntu-2404_4-core @@ -40,6 +43,8 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Check that the browser build enables the feature on the engine, core and SQLite + run: devtools/compile-out-search-inequality-filters --check on - name: Compile the feature out run: devtools/compile-out-search-inequality-filters - name: Lint the workspace with the feature compiled out diff --git a/devtools/compile-out-search-inequality-filters b/devtools/compile-out-search-inequality-filters index 6ed5c8ef0..99a7b574e 100755 --- a/devtools/compile-out-search-inequality-filters +++ b/devtools/compile-out-search-inequality-filters @@ -15,11 +15,18 @@ unless exactly the expected number list the feature in `default`, then writes the edits and checks with `cargo tree` that nothing in the workspace enables the feature. CI builds, lints and tests the tree it leaves. -Usage: devtools/compile-out-search-inequality-filters +With `--check on` it edits nothing and checks the tree as it is: in the +browser build (`-p extenddb-wasm-adapter`), extenddb-core, extenddb-engine +and extenddb-storage-sqlite must all carry the feature (`on`) or all lack +it (`off`). Without `--check`, the script runs that check with `off` after +its edits. + +Usage: devtools/compile-out-search-inequality-filters [--check on|off] """ from __future__ import annotations +import argparse import re import subprocess import sys @@ -27,6 +34,8 @@ from pathlib import Path FEATURE = "search-inequality-filters" CRATES = 8 +BROWSER = "extenddb-wasm-adapter" +BROWSER_CRATES = ("extenddb-core", "extenddb-engine", "extenddb-storage-sqlite") def feature_tree(root: Path, *args: str) -> str: @@ -39,6 +48,16 @@ def feature_tree(root: Path, *args: str) -> str: ).stdout +def check_browser(root: Path, want: bool) -> list[str]: + """The crates of the browser build whose feature state is not `want`.""" + wrong = [] + for crate in BROWSER_CRATES: + tree = feature_tree(root, "-p", BROWSER, "-i", crate) + if (f'{crate} feature "{FEATURE}"' in tree) != want: + wrong.append(crate) + return wrong + + def compile_out(root: Path) -> int: default = re.compile(r'^default = \[(.*)\]$', re.MULTILINE) edits = [] @@ -63,13 +82,33 @@ def compile_out(root: Path) -> int: if f'feature "{FEATURE}"' in tree: print(f"error: the workspace still enables {FEATURE}:\n{tree}", file=sys.stderr) return 1 + wrong = check_browser(root, False) + if wrong: + print(f"error: the browser build still enables {FEATURE} on {wrong}", file=sys.stderr) + return 1 for name in names: print(f"removed {FEATURE} from the default list of {name}") return 0 def main() -> int: - return compile_out(Path(__file__).resolve().parent.parent) + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--check", choices=["on", "off"]) + args = parser.parse_args() + root = Path(__file__).resolve().parent.parent + if args.check is None: + return compile_out(root) + wrong = check_browser(root, args.check == "on") + if wrong: + state = "lack" if args.check == "on" else "carry" + print( + f"error: in the browser build ({BROWSER}), {', '.join(wrong)} {state} {FEATURE}, " + f"and {', '.join(BROWSER_CRATES)} must all be {args.check}", + file=sys.stderr, + ) + return 1 + print(f"{BROWSER}: {', '.join(BROWSER_CRATES)} all have {FEATURE} {args.check}") + return 0 if __name__ == "__main__": From 896f02cce95925187efb4e533e66ce1d30c9dcc4 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:56:49 +0000 Subject: [PATCH 064/101] ci: run the vector wire tests with the search setting as an account list The `all` leg of the feature workflow's wire job ran the same grammar as the absent setting, which integration.yml already runs on SQLite and PostgreSQL: both give every account the extended grammar. Nothing ran the setting as a list of accounts. The leg is now `listed`: devtools/run-tests writes the setting as `123456789012,210987654321`, the test account that devtools/provision-test-credentials creates and an account the tests do not use. The wire modules read the setting and, from the list, expect the extended grammar for the test account. Verified on a SQLite release server, the four SearchVectors modules and test_authz_search_vectors_index.py: with the setting at `123456789012,210987654321`, 106 passed and 1 skipped, the counts of the absent setting; at `210987654321` alone, 87 passed and 20 skipped, the counts of `off`. --- .../workflows/search-inequality-filters.yml | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/.github/workflows/search-inequality-filters.yml b/.github/workflows/search-inequality-filters.yml index 6bbe0e4ec..6d7a65a72 100644 --- a/.github/workflows/search-inequality-filters.yml +++ b/.github/workflows/search-inequality-filters.yml @@ -20,7 +20,8 @@ concurrency: # extended grammar. These jobs cover what they do not: the workspace built, # linted and tested with the feature compiled out, the feature state of the # browser build, and the vector wire tests with the setting written as `off` -# and as `all`, and against the build with the feature compiled out. +# and as a list of accounts, and against the build with the feature compiled +# out. # # Most crates take their internal dependencies with default features, so no # cargo command line compiles the feature out. The workspace takes @@ -61,7 +62,12 @@ jobs: fail-fast: false matrix: backend: [sqlite, postgres] - setting: ["off", all, compiled-out] + # `listed` writes the setting as the test account, which + # devtools/provision-test-credentials creates, and an account the + # tests do not use, so the tests expect the extended grammar from the + # list. The absent setting, which gives every account the grammar, is + # what integration.yml runs. + setting: ["off", listed, compiled-out] services: postgres: image: pgvector/pgvector:pg16 @@ -130,16 +136,17 @@ jobs: # file, except the CLI catalog migration file, which builds catalogs of # its own and does not depend on the feature. devtools/run-tests writes # the setting before the suite starts; the modules read it and fail when - # the server serves the other grammar. Under `off`, and against the build - # with the feature compiled out, which has no such setting, the tests of - # the extended grammar skip. + # the server serves the other grammar. Under `listed` they expect the + # extended grammar, because the list names the test account. Under + # `off`, and against the build with the feature compiled out, which has + # no such setting, the tests of the extended grammar skip. - name: Run the vector wire tests env: EXTENDDB_TEST_ENDPOINT: https://127.0.0.1:18443 EXTENDDB_ADMIN_USER: admin EXTENDDB_ADMIN_PASSWORD: ${{ steps.init.outputs.admin_password }} EXTENDDB_TEST_BACKUP_STORE: ${{ matrix.backend == 'sqlite' && 'filesystem' || 'none' }} - EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS: ${{ matrix.setting != 'compiled-out' && matrix.setting || '' }} + EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS: ${{ matrix.setting == 'listed' && '123456789012,210987654321' || matrix.setting != 'compiled-out' && matrix.setting || '' }} EXTENDDB_EXPECT_VECTORS: "1" run: devtools/run-tests --extenddb --pytest --parallel --filter "vector and not test_cli" From 8d5d7c2896a29693b2cd71292c9faef3e1baee2c Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 06:06:23 +0000 Subject: [PATCH 065/101] test(wasm): run the search grammar corpus cases only with the grammar The five corpus cases named "search grammar: " send a range condition, which only a build with the search-inequality-filters feature serves. In the compiled-out tree the adapter's parity test failed on them, so the unit tests of the adapter did not pass with the feature off. The parity test now skips those cases when the adapter is built without the feature. With the feature on it runs them as before. `cargo test -p extenddb-wasm-adapter --test parity` passes with the default features and with --no-default-features. --- crates/wasm-adapter/tests/parity.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/wasm-adapter/tests/parity.rs b/crates/wasm-adapter/tests/parity.rs index d505c43a1..909b6cf00 100644 --- a/crates/wasm-adapter/tests/parity.rs +++ b/crates/wasm-adapter/tests/parity.rs @@ -42,6 +42,11 @@ const CORPUS: &str = include_str!("../parity/corpus.json"); /// has one. const ON_WASM: bool = cfg!(target_arch = "wasm32"); +/// Whether the build serves the extended search grammar, and the name prefix +/// of the corpus cases that need it. +const SEARCH_GRAMMAR: bool = cfg!(feature = "search-inequality-filters"); +const SEARCH_GRAMMAR_CASES: &str = "search grammar: "; + /// The members a case may have. const CASE_MEMBERS: [&str; 8] = [ "name", "op", "body", "rawBody", "error", "checks", "save", "onWasm", @@ -618,6 +623,11 @@ async fn every_case_gives_its_expected_answer() { let mut saved = HashMap::new(); let mut checks = 0; for case in &cases { + // The extended search grammar's cases need the grammar, which a build + // with the feature compiled out does not have. + if !SEARCH_GRAMMAR && case.name.starts_with(SEARCH_GRAMMAR_CASES) { + continue; + } let expect = match &case.on_wasm { Some(on_wasm) if ON_WASM => on_wasm, _ => &case.expect, From 55da96de817551015bee49fbed8a2d25660a5c20 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 06:08:15 +0000 Subject: [PATCH 066/101] docs(adr): record the search condition grammar, its seam and its gate The change adds a public field to VectorSearch, the input of the storage trait, changes the dynamodb:Attributes content of SearchVectors and adds a runtime setting, and no decision record described why the search condition has its own parser. ADR-0030 records the options (extend the existing parser, a separate parser, backend SQL for every condition), the decision and its consequences, with the measurements that decide it: the service answers ConditionExpression and FilterExpression syntax errors and depth as it answers SearchConditionExpression (eu-north-1, 2026-11-25, 13 shapes each twice), so extending the existing parser would change those operations' answers. --- docs/adr/0030-search-condition-grammar.md | 100 ++++++++++++++++++++++ docs/adr/README.md | 1 + 2 files changed, 101 insertions(+) create mode 100644 docs/adr/0030-search-condition-grammar.md diff --git a/docs/adr/0030-search-condition-grammar.md b/docs/adr/0030-search-condition-grammar.md new file mode 100644 index 000000000..22014f0de --- /dev/null +++ b/docs/adr/0030-search-condition-grammar.md @@ -0,0 +1,100 @@ +# ADR-0030: SearchVectors serves the extended search condition grammar from its own parser, behind a feature and a setting + +- Status: Proposed +- Date: 2026-11-25 +- Deciders: @demohan + +## Context + +DynamoDB accepts a `SearchConditionExpression` with `<>`, `<`, `<=`, `>`, `>=`, +`BETWEEN`, `IN`, `OR`, `NOT`, parentheses, `attribute_exists` and +`attribute_not_exists`, up to 50 conditions with one `=` on the index's HASH +attribute among them, on the accounts and regions measured (us-east-1, +eu-north-1, ap-southeast-2). Its API reference documents only `=`. ExtendDB +accepted only an AND of equalities. + +Three parts of ExtendDB meet this grammar: + +- **The parser.** Core already parses the condition grammar for + ConditionExpression, FilterExpression, KeyConditionExpression and + UpdateExpression (`tokenizer.rs`, `parser.rs`, `parser_common.rs`). It + recurses, refuses past `max_expression_depth` (150 by default) with + `expression nesting depth exceeded`, and words its syntax errors in its own + terms. For a SearchConditionExpression the service answers a syntax error + with `Syntax error; token: "", near: ""` and parses a condition + nested as deep as the 4096-byte limit allows. Measured in eu-north-1 on + 2026-11-25, each request twice, the service answers ConditionExpression and + FilterExpression the same way: `a == :s`, `a = 10` and `_Cat = :v` are + syntax errors that name the token, 4089 unclosed `(` answer at ``, and + 151 and 160 nested `NOT (` and `(a) = :v` are accepted. The existing parser + answers each of those differently. +- **The storage seam.** `VectorSearch` carried the HASH equality and a list of + equalities, which every backend applies in its own query. A range, `IN`, + `OR`, `NOT` or a function cannot be written as an equality pair. +- **Authorization.** The service sets no `dynamodb:Attributes` value on a + SearchVectors, whatever the projection and the condition name (measured + 2026-11-21: a Deny gated on `Null` `true` refused every search). + +## Options Considered + +1. **Extend the existing parser** to carry the token and near text and to + parse without recursion, and parse the search condition with it. Every + other expression would then answer its syntax errors and its depth as the + service does, which changes their answers on the shapes above; keeping + their earlier answers needs a mode at the tokenizer, at each error site, at + the depth rule and at the reserved-word check. +2. **A separate parser for the search condition**, written to the service's + answers for SearchConditionExpression, that lowers to the `Expr` the + evaluator already runs. +3. **Lower every condition to backend SQL**, widening the equality pairs into + a predicate type each backend translates. + +## Decision + +Option 2: the grammar has its own lexer, grammar and checks in +`crates/core/src/expression/search_filter`, behind the +`search-inequality-filters` Cargo feature and the `search_inequality_filters` +runtime setting (default `all`); a condition the equality pairs cannot express +reaches the backend as `VectorSearch::item_filter`, which the backend calls on +each candidate; SearchVectors sets no `dynamodb:Attributes` value. + +## Rationale + +- Option 1 changes the answers of ConditionExpression and the other + expressions, which is a change to those operations with its own measurements + and its own review. Option 2 changes no answer outside SearchVectors. +- The evaluator that FilterExpression uses already decides a missing attribute + and a type mismatch as the service does, so the lowered `Expr` reuses it. The + BETWEEN bound check, the operand display, the map key checks, the usage + checks and the size checks are shared with the other expressions. +- Option 3 needs a translation per backend for every operator and function, + and two backends serve vector search. `item_filter` is one call per + candidate; PostgreSQL reads a filtered search in bounded pages of its score + ordering, and an equality-only condition keeps the SQL equality filter. +- The feature keeps the grammar removable: with it compiled out, SearchVectors + serves the equality-only grammar. The setting lets an operator keep the + earlier grammar for some or all accounts without a rebuild. + +## Consequences + +- Two parsers of the condition grammar exist in core. A change to the shared + grammar is made in both, until the other expressions move to the second + parser in a change of their own. +- `VectorSearch` has a public field, `item_filter`, that every caller sets and + every backend that serves vector search honours. +- A deployment that gates SearchVectors on `dynamodb:Attributes` gets the + service's answer for an absent key: a Deny gated on `Null` `true` refuses + every search, and a bare negated operator over the key matches. +- Removing the feature is deleting the module, the dispatch arms and the + setting. + +--- + +## License + +Copyright 2026 ExtendDB contributors. Licensed under the Apache License, Version 2.0. +See [LICENSE](../../LICENSE) for the full text. + +This software is provided "as is" without warranty of any kind. ExtendDB is an open +source project maintained by AWS. It is not Amazon DynamoDB or an AWS service. +"DynamoDB" is a trademark of Amazon.com, Inc. or its affiliates. diff --git a/docs/adr/README.md b/docs/adr/README.md index 7febe92df..76cb8a42e 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -55,6 +55,7 @@ decision, write a new ADR. | [0026](0026-credential-crypto-on-aws-lc.md) | Credential cryptography uses AWS-LC through aws-lc-rs | Accepted | | [0027](0027-cassandra-index-row-version-stamps.md) | Cassandra: index rows carry the base-row version as their write timestamp | Accepted | | [0029](0029-crates-io-packaging.md) | The workspace crates go to crates.io together, at one version with exact pins | Accepted | +| [0030](0030-search-condition-grammar.md) | SearchVectors serves the extended search condition grammar from its own parser, behind a feature and a setting | Proposed | --- From 096ba91cfa58f7ca6f90812c29f8c24f9107c93c Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:45:10 +0000 Subject: [PATCH 067/101] test(engine): build the unit test engine and context in one place The SearchVectors unit tests built an in-memory SQLite engine with the same call in five places, and the order tests wrote out an OperationContext next to the one the PartiQL tests use. `test_context` now holds both: `memory_engine` opens an empty in-memory SQLite engine and `context_on` builds a context on a given engine. The SearchVectors tests and the PartiQL test context call them. Verified: the engine unit tests pass, 926 of 926, as before. --- crates/engine/src/lib.rs | 2 + crates/engine/src/partiql/test_context.rs | 30 +++----------- .../src/search_vectors_condition_tests.rs | 13 +----- .../src/search_vectors_extended_tests.rs | 13 +----- .../engine/src/search_vectors_order_tests.rs | 18 +------- .../src/search_vectors_settings_tests.rs | 7 +--- crates/engine/src/test_context.rs | 41 +++++++++++++++++++ 7 files changed, 56 insertions(+), 68 deletions(-) create mode 100644 crates/engine/src/test_context.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e295f917b..238933cd4 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -50,6 +50,8 @@ mod list_tables; #[cfg(feature = "partiql")] mod partiql; mod pre_dispatch; +#[cfg(test)] +mod test_context; pub use pre_dispatch::{ParsedRequest, parse_request}; // `private_fs` creates the private directories the filesystem-backed // import/export use; it has no wasm32 consumer and uses unix/windows file diff --git a/crates/engine/src/partiql/test_context.rs b/crates/engine/src/partiql/test_context.rs index 443514af0..e14b530ae 100644 --- a/crates/engine/src/partiql/test_context.rs +++ b/crates/engine/src/partiql/test_context.rs @@ -12,13 +12,8 @@ use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use extenddb_core::error::DynamoDbError; -use extenddb_core::limits::LimitsConfig; -use extenddb_storage_sqlite::SqliteEngine; -use crate::{ - AuthorizedKeyInfo, BackupRuntime, ItemAccess, ItemAuthorization, ItemAuthorizer, - OperationContext, -}; +use crate::{ItemAccess, ItemAuthorization, ItemAuthorizer, OperationContext}; /// Run `future` to completion on a runtime of its own. pub(super) fn block_on(future: F) -> F::Output { @@ -31,24 +26,11 @@ pub(super) fn block_on(future: F) -> F::Output { /// A context whose item authorizer is `authorizer`. pub(super) async fn context(authorizer: Option>) -> OperationContext { - let storage = SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) - .await - .expect("an in-memory database opens"); - let mut authorized_key_info = AuthorizedKeyInfo::new(); - authorized_key_info.insert("t".to_owned(), None); - 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, - auth_cache: extenddb_auth::AuthCacheRegistry::default(), - table_key_info_lookup: None, - item_authorizer: authorizer, - } + let mut ctx = + crate::test_context::context_on(crate::test_context::memory_engine().await, "000000000000"); + ctx.authorized_key_info.insert("t".to_owned(), None); + ctx.item_authorizer = authorizer; + ctx } /// Gives every access the same answer, and counts the accesses it is asked diff --git a/crates/engine/src/search_vectors_condition_tests.rs b/crates/engine/src/search_vectors_condition_tests.rs index b2b9f158e..fcf90910b 100644 --- a/crates/engine/src/search_vectors_condition_tests.rs +++ b/crates/engine/src/search_vectors_condition_tests.rs @@ -20,7 +20,6 @@ use extenddb_core::types::{ }; use extenddb_storage::StorageEngine; use extenddb_storage::management_store::{OpError, OpResult, SettingsStore}; -use extenddb_storage_sqlite::SqliteEngine; use futures::future::BoxFuture; use super::{Scope, parse, resolve}; @@ -43,11 +42,7 @@ impl SettingsStore for Store { } async fn server(setting: &str) -> Arc { - let storage: Arc = Arc::new( - SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) - .await - .expect("an in-memory database opens"), - ); + let storage = crate::test_context::memory_engine().await; crate::install_search_filter_settings(&storage, Arc::new(Store(Mutex::new(setting.into())))); storage } @@ -270,11 +265,7 @@ async fn without_the_setting( expr: &str, names: Option<&HashMap>, ) -> (Result, usize) { - let storage: Arc = Arc::new( - SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) - .await - .expect("an in-memory database opens"), - ); + let storage = crate::test_context::memory_engine().await; let store = Arc::new(Failing::default()); crate::install_search_filter_settings(&storage, store.clone()); let served = storage diff --git a/crates/engine/src/search_vectors_extended_tests.rs b/crates/engine/src/search_vectors_extended_tests.rs index 3533a00e5..6ff3825bf 100644 --- a/crates/engine/src/search_vectors_extended_tests.rs +++ b/crates/engine/src/search_vectors_extended_tests.rs @@ -16,7 +16,6 @@ use extenddb_core::types::{ }; use extenddb_storage::StorageEngine; use extenddb_storage::management_store::{OpError, OpResult, SettingsStore}; -use extenddb_storage_sqlite::SqliteEngine; use futures::future::BoxFuture; use super::imp::{enabled_for, parse, resolve_scope}; @@ -45,11 +44,7 @@ impl SettingsStore for Store { /// A storage engine whose server reads `value` for the setting. async fn install(value: Result, ()>) -> Arc { - let storage: Arc = Arc::new( - SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) - .await - .expect("an in-memory database opens"), - ); + let storage = crate::test_context::memory_engine().await; let value = value.map(|v| v.map(str::to_owned)); install_search_filter_settings(&storage, Arc::new(Store(Mutex::new(value)))); storage @@ -114,11 +109,7 @@ async fn a_store_that_fails_answers_a_retryable_fault() { #[tokio::test] async fn without_an_installed_store_every_account_gets_the_grammar() { - let storage: Arc = Arc::new( - SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) - .await - .expect("an in-memory database opens"), - ); + let storage = crate::test_context::memory_engine().await; assert!(enabled(&storage).await.unwrap()); } diff --git a/crates/engine/src/search_vectors_order_tests.rs b/crates/engine/src/search_vectors_order_tests.rs index a5c1a9e05..e36b754a6 100644 --- a/crates/engine/src/search_vectors_order_tests.rs +++ b/crates/engine/src/search_vectors_order_tests.rs @@ -10,18 +10,16 @@ //! `SearchVector` on a four-dimension index; with valid maps the same //! requests answer ResourceNotFoundException and the dimension message. -use std::sync::Arc; use std::time::Duration; use serde_json::{Value, json}; use extenddb_core::error::DynamoDbError; -use extenddb_core::limits::LimitsConfig; use extenddb_storage::server_components::ServerComponentsOptions; use extenddb_storage_sqlite::SqliteConfig; use tempfile::TempDir; -use crate::{AuthorizedKeyInfo, BackupRuntime, OperationContext}; +use crate::OperationContext; /// A context on a bootstrapped SQLite catalog in `dir`, where a table is /// created ACTIVE. @@ -48,19 +46,7 @@ async fn context(dir: &TempDir) -> OperationContext { .set_setting("control_plane_delay_seconds", "0") .await .unwrap(); - OperationContext { - storage: components.engine, - backup: Arc::new(BackupRuntime::new(1)), - limits: Arc::new(LimitsConfig::default()), - region: Arc::from("us-east-1"), - account_id: Arc::from(account_id), - 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, - } + crate::test_context::context_on(components.engine, &account_id) } /// A table "tbl" with a four-dimension vector index "vix" whose HASH element diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index f12fb011d..700ec2683 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -12,7 +12,6 @@ use extenddb_core::error::DynamoDbError; use extenddb_core::expression::search_filter::EnabledAccounts; use extenddb_storage::StorageEngine; use extenddb_storage::management_store::{OpError, OpResult, SettingsStore}; -use extenddb_storage_sqlite::SqliteEngine; use futures::future::BoxFuture; use tokio::sync::Notify; @@ -91,11 +90,7 @@ impl SettingsStore for Store { } async fn storage() -> Arc { - Arc::new( - SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) - .await - .expect("an in-memory database opens"), - ) + crate::test_context::memory_engine().await } fn is_unavailable(answer: &Result) -> bool { diff --git a/crates/engine/src/test_context.rs b/crates/engine/src/test_context.rs new file mode 100644 index 000000000..6999fd528 --- /dev/null +++ b/crates/engine/src/test_context.rs @@ -0,0 +1,41 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The storage engine and the [`OperationContext`] that the engine's unit +//! tests build: an empty in-memory SQLite database, and a context on a given +//! engine with no item authorizer and no authorized keys. + +use std::sync::Arc; + +use extenddb_core::limits::LimitsConfig; +use extenddb_storage::StorageEngine; +use extenddb_storage_sqlite::SqliteEngine; + +use crate::{AuthorizedKeyInfo, BackupRuntime, OperationContext}; + +/// A storage engine on an empty in-memory SQLite database. +pub(crate) async fn memory_engine() -> Arc { + Arc::new( + SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) + .await + .expect("an in-memory database opens"), + ) +} + +/// A context on `storage` for `account_id` in us-east-1, with the default +/// limits, no item authorizer and no authorized keys. +pub(crate) fn context_on(storage: Arc, account_id: &str) -> OperationContext { + OperationContext { + storage, + backup: Arc::new(BackupRuntime::new(1)), + limits: Arc::new(LimitsConfig::default()), + region: Arc::from("us-east-1"), + account_id: Arc::from(account_id), + 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, + } +} From 462aa71f265eea40668f9f0bfb930e8f5e853a9e Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:47:18 +0000 Subject: [PATCH 068/101] refactor(engine): drop the unused vector search argument of the parse The search condition parse took the backend's vector search engine and never read it. The request check finds that the backend serves vector search before it parses the condition, so the order does not depend on the argument. The parameter is gone from `search_vectors_condition::parse` and from its callers, and the doc comment says the caller has made that check. Verified: the engine unit tests pass, 926 of 926; the engine builds with the search-inequality-filters feature off. --- crates/engine/src/search_vectors_condition.rs | 10 +++------- crates/engine/src/search_vectors_condition_tests.rs | 8 -------- crates/engine/src/search_vectors_request.rs | 1 - 3 files changed, 3 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/search_vectors_condition.rs b/crates/engine/src/search_vectors_condition.rs index 77762766f..2b98a29c9 100644 --- a/crates/engine/src/search_vectors_condition.rs +++ b/crates/engine/src/search_vectors_condition.rs @@ -27,7 +27,7 @@ use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{ AttributeDefinition, AttributeValue, SearchSchemaElement, SearchSchemaElementType, }; -use extenddb_storage::{StorageEngine, VectorItemFilter, VectorSearchEngine}; +use extenddb_storage::{StorageEngine, VectorItemFilter}; #[cfg(feature = "search-inequality-filters")] use crate::search_vectors_extended::Extended; @@ -54,11 +54,8 @@ pub(crate) type Scope<'a> = ( ); /// Structural validation of the filter expression (schema-independent), -/// with each grammar that may serve the caller. -/// -/// Taking the backend's vector search engine means the grammar is only -/// parsed once the backend has been found to serve vector search: a backend -/// without it refuses the request before this runs. +/// with each grammar that may serve the caller. The caller has already +/// found that the backend serves vector search. /// /// # Errors /// @@ -67,7 +64,6 @@ pub(crate) type Scope<'a> = ( /// the setting cannot be read. pub(crate) async fn parse( storage: &Arc, - _served_by: &dyn VectorSearchEngine, account_id: &str, expr: Option<&str>, names: Option<&HashMap>, diff --git a/crates/engine/src/search_vectors_condition_tests.rs b/crates/engine/src/search_vectors_condition_tests.rs index fcf90910b..723a5360f 100644 --- a/crates/engine/src/search_vectors_condition_tests.rs +++ b/crates/engine/src/search_vectors_condition_tests.rs @@ -101,16 +101,12 @@ type Routed = ( async fn routed(setting: &str, hash: bool, expr: &str, item: &Item) -> Routed { let storage = server(setting).await; - let served = storage - .as_vector_search() - .expect("SQLite serves vector search"); let values: HashMap = values() .into_iter() .filter(|(k, _)| expr.contains(k.as_str())) .collect(); let parsed = parse( &storage, - served, "111111111111", Some(expr), None, @@ -268,9 +264,6 @@ async fn without_the_setting( let storage = crate::test_context::memory_engine().await; let store = Arc::new(Failing::default()); crate::install_search_filter_settings(&storage, store.clone()); - let served = storage - .as_vector_search() - .expect("SQLite serves vector search"); let values: HashMap = values() .into_iter() .filter(|(k, _)| expr.contains(k.as_str())) @@ -279,7 +272,6 @@ async fn without_the_setting( let answer = async { let parsed = parse( &storage, - served, "111111111111", Some(expr), names, diff --git a/crates/engine/src/search_vectors_request.rs b/crates/engine/src/search_vectors_request.rs index fcb1c5d5f..5c50d4a99 100644 --- a/crates/engine/src/search_vectors_request.rs +++ b/crates/engine/src/search_vectors_request.rs @@ -110,7 +110,6 @@ pub(super) async fn check<'s>( let parsed = condition::parse( storage, - vector_search, account_id, input.search_condition_expression.as_deref(), input.expression_attribute_names.as_ref(), From 8d6938072fd313acdc479e77b1e782423c96effa Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:49:04 +0000 Subject: [PATCH 069/101] test(engine): move the poisoned lock and log tests of the setting The tests of the search_inequality_filters setting share one file. The poisoned lock test and the log test of a malformed value move to `search_vectors_settings_fault_tests.rs`, a child of the settings tests, unchanged, so the file of read tests has room for more rows. Verified: the engine unit tests pass, 926 of 926, with the two moved tests listed under the new module. --- .../search_vectors_settings_fault_tests.rs | 118 ++++++++++++++++++ .../src/search_vectors_settings_tests.rs | 112 +---------------- 2 files changed, 120 insertions(+), 110 deletions(-) create mode 100644 crates/engine/src/search_vectors_settings_fault_tests.rs diff --git a/crates/engine/src/search_vectors_settings_fault_tests.rs b/crates/engine/src/search_vectors_settings_fault_tests.rs new file mode 100644 index 000000000..88d3e3b3b --- /dev/null +++ b/crates/engine/src/search_vectors_settings_fault_tests.rs @@ -0,0 +1,118 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The setting through a poisoned lock, and the log line of a malformed +//! value. + +use super::*; + +/// Poison `lock` with a thread that panics while holding it. +fn poison(lock: &Mutex) { + std::thread::scope(|s| { + let held = s.spawn(|| { + let _held = lock.lock(); + panic!("poison the lock"); + }); + assert!(held.join().is_err()); + }); + assert!(lock.is_poisoned()); +} + +/// A thread that panicked while holding the server list or a server's kept +/// read leaves the setting readable. +#[tokio::test] +async fn a_poisoned_lock_leaves_the_setting_readable() { + let storage = storage().await; + let store = Store::value("all"); + install_search_filter_settings(&storage, store.clone()); + let settings = SERVERS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .find(|(engine, _)| same(engine, &storage)) + .map(|(_, settings)| Arc::clone(settings)) + .expect("the server is installed"); + poison(&SERVERS); + poison(&settings.kept); + poison(&settings.changes); + assert_eq!( + enabled_accounts(&storage).await.unwrap(), + EnabledAccounts::All + ); + assert_eq!( + enabled_accounts(&storage).await.unwrap(), + EnabledAccounts::All + ); + assert_eq!(store.reads(), 1, "the kept read is used"); + store.set(Answer::Value(Some("off".to_owned()))); + search_filter_settings_changed(); + assert_eq!( + enabled_accounts(&storage).await.unwrap(), + EnabledAccounts::Off + ); + assert_eq!(store.reads(), 2); +} + +/// The warnings this thread's subscriber receives. +#[derive(Clone, Default)] +struct Warnings(Arc>>); + +struct Message<'a>(&'a mut String); + +impl tracing::field::Visit for Message<'_> { + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { + if field.name() == "message" { + *self.0 = format!("{value:?}"); + } + } +} + +impl tracing::Subscriber for Warnings { + fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool { + *metadata.level() == tracing::Level::WARN + } + fn new_span(&self, _span: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + fn record(&self, _span: &tracing::span::Id, _values: &tracing::span::Record<'_>) {} + fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {} + fn event(&self, event: &tracing::Event<'_>) { + let mut message = String::new(); + event.record(&mut Message(&mut message)); + self.0.lock().unwrap().push(message); + } + fn enter(&self, _span: &tracing::span::Id) {} + fn exit(&self, _span: &tracing::span::Id) {} +} + +/// A server that reads a malformed value logs it once, and again after the +/// value changes to another malformed one. +#[tokio::test(start_paused = true)] +async fn a_server_logs_a_malformed_value_once_per_change() { + let warnings = Warnings::default(); + let _guard = tracing::subscriber::set_default(warnings.clone()); + let store = Store::value("on"); + let settings = Settings::new(store.clone()); + for _ in 0..3 { + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + tokio::time::advance(REFRESH).await; + } + store.set(Answer::Value(Some("true".to_owned()))); + tokio::time::advance(REFRESH).await; + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + assert_eq!(store.reads(), 4); + let reason = "must be empty, 'off', 'all', or a comma-separated list of 12-digit account IDs"; + assert_eq!( + *warnings.0.lock().unwrap(), + [ + format!("search_inequality_filters = \"on\" enables no account: {reason}"), + format!("search_inequality_filters = \"true\" enables no account: {reason}"), + ] + ); +} diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index 700ec2683..e85a60a45 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -421,113 +421,5 @@ async fn a_request_does_not_wait_on_a_read_in_flight_once_a_value_was_read() { assert_eq!(store.reads(), 2); } -/// Poison `lock` with a thread that panics while holding it. -fn poison(lock: &Mutex) { - std::thread::scope(|s| { - let held = s.spawn(|| { - let _held = lock.lock(); - panic!("poison the lock"); - }); - assert!(held.join().is_err()); - }); - assert!(lock.is_poisoned()); -} - -/// A thread that panicked while holding the server list or a server's kept -/// read leaves the setting readable. -#[tokio::test] -async fn a_poisoned_lock_leaves_the_setting_readable() { - let storage = storage().await; - let store = Store::value("all"); - install_search_filter_settings(&storage, store.clone()); - let settings = SERVERS - .lock() - .unwrap_or_else(PoisonError::into_inner) - .iter() - .find(|(engine, _)| same(engine, &storage)) - .map(|(_, settings)| Arc::clone(settings)) - .expect("the server is installed"); - poison(&SERVERS); - poison(&settings.kept); - poison(&settings.changes); - assert_eq!( - enabled_accounts(&storage).await.unwrap(), - EnabledAccounts::All - ); - assert_eq!( - enabled_accounts(&storage).await.unwrap(), - EnabledAccounts::All - ); - assert_eq!(store.reads(), 1, "the kept read is used"); - store.set(Answer::Value(Some("off".to_owned()))); - search_filter_settings_changed(); - assert_eq!( - enabled_accounts(&storage).await.unwrap(), - EnabledAccounts::Off - ); - assert_eq!(store.reads(), 2); -} - -/// The warnings this thread's subscriber receives. -#[derive(Clone, Default)] -struct Warnings(Arc>>); - -struct Message<'a>(&'a mut String); - -impl tracing::field::Visit for Message<'_> { - fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { - if field.name() == "message" { - *self.0 = format!("{value:?}"); - } - } -} - -impl tracing::Subscriber for Warnings { - fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool { - *metadata.level() == tracing::Level::WARN - } - fn new_span(&self, _span: &tracing::span::Attributes<'_>) -> tracing::span::Id { - tracing::span::Id::from_u64(1) - } - fn record(&self, _span: &tracing::span::Id, _values: &tracing::span::Record<'_>) {} - fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {} - fn event(&self, event: &tracing::Event<'_>) { - let mut message = String::new(); - event.record(&mut Message(&mut message)); - self.0.lock().unwrap().push(message); - } - fn enter(&self, _span: &tracing::span::Id) {} - fn exit(&self, _span: &tracing::span::Id) {} -} - -/// A server that reads a malformed value logs it once, and again after the -/// value changes to another malformed one. -#[tokio::test(start_paused = true)] -async fn a_server_logs_a_malformed_value_once_per_change() { - let warnings = Warnings::default(); - let _guard = tracing::subscriber::set_default(warnings.clone()); - let store = Store::value("on"); - let settings = Settings::new(store.clone()); - for _ in 0..3 { - assert_eq!( - settings.enabled_accounts().await.unwrap(), - EnabledAccounts::Off - ); - tokio::time::advance(REFRESH).await; - } - store.set(Answer::Value(Some("true".to_owned()))); - tokio::time::advance(REFRESH).await; - assert_eq!( - settings.enabled_accounts().await.unwrap(), - EnabledAccounts::Off - ); - assert_eq!(store.reads(), 4); - let reason = "must be empty, 'off', 'all', or a comma-separated list of 12-digit account IDs"; - assert_eq!( - *warnings.0.lock().unwrap(), - [ - format!("search_inequality_filters = \"on\" enables no account: {reason}"), - format!("search_inequality_filters = \"true\" enables no account: {reason}"), - ] - ); -} +#[path = "search_vectors_settings_fault_tests.rs"] +mod fault; From f88a7d6b0df0977e21a429b6200050f7558f271c Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:52:23 +0000 Subject: [PATCH 070/101] fix(engine): send one read of the search filter setting through a change The search_inequality_filters setting is read by one request at a time, and a read that outlasts its two second timeout keeps running. Once a value had been read, a request that found the read taken used that value only while no change through the management API had come after it. After a change, every request waited on the one read in flight, for up to two seconds. A read sent before a change was left running while a second one was sent, so two reads were in flight until the first ended. Once a value has been read, a request that finds a read in flight now uses the last value read, after a change too. A read sent before a change stays the one read in flight until it ends; the first request after it ends sends a read of the changed value. Before any value has been read, a request still waits on the read in flight for at most two seconds and answers ServiceUnavailableException when it does not end. The module comment states this rule. Verified: three unit tests with their own deadlines. A request does not wait on a read sent after a change; while a read sent before a change has not ended, three requests use the last value read at once and no second read is sent, and the next request after it ends reads the new value; before any value has been read, no second read is sent after a change. Each test fails with the earlier rule restored. The engine unit tests pass, 928 of 928. --- crates/engine/src/search_vectors_settings.rs | 80 ++++++------ .../src/search_vectors_settings_tests.rs | 114 +++++++++++++++++- 2 files changed, 148 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/search_vectors_settings.rs b/crates/engine/src/search_vectors_settings.rs index 28d0f265d..c6e780573 100644 --- a/crates/engine/src/search_vectors_settings.rs +++ b/crates/engine/src/search_vectors_settings.rs @@ -19,11 +19,17 @@ //! other transient storage faults do. A fault never changes which grammar an //! account gets. //! -//! A server sends at most one read of the setting at a time. A read that -//! outlasts [`READ_TIMEOUT`] keeps running in its own task, and the next -//! request waits on that read rather than sending another, so a catalog -//! that does not answer holds at most one of its connections for the -//! setting while requests that do not read it keep the rest. +//! A server sends at most one read of the setting at a time, a read sent +//! before a change through the management API included. A read that +//! outlasts [`READ_TIMEOUT`] keeps running in its own task until it ends, +//! and no other read is sent meanwhile, so a catalog that does not answer +//! holds at most one of its connections for the setting while requests that +//! do not read it keep the rest. Once a read has answered, a request never +//! waits on a read another request sent: while a read is in flight, it uses +//! the value of the last read that answered. Before any read has answered, +//! a request waits on the read in flight for at most [`READ_TIMEOUT`]. A +//! change through the management API applies at the first read sent after +//! it, which is the next one once no read is in flight. use std::sync::{Arc, Mutex, PoisonError, Weak}; use std::time::Duration; @@ -117,17 +123,16 @@ struct InFlight { struct Settings { store: Arc, kept: Mutex>, - /// The value of the last read that answered, with the value of - /// [`Settings::changes`] when it was sent. A change through the management - /// API leaves it, so a read that fails after a change uses it. - last: Mutex>, + /// The value of the last read that answered. A change through the + /// management API leaves it, so a read that fails after a change uses it. + last: Mutex>, /// How many times the management API changed the setting, so a read /// sent before a change is not used after it. changes: Mutex, /// Held by the one request that reads the store when the kept read is - /// stale, so concurrent requests wait for that read instead of sending - /// their own. It holds a read that outlasted [`READ_TIMEOUT`] until the - /// read ends, so the next request waits on it instead of sending another. + /// stale, so concurrent requests do not send reads of their own. It + /// holds a read that outlasted [`READ_TIMEOUT`] until the read ends, so + /// no other read is sent while it runs. reading: tokio::sync::Mutex>, } @@ -150,18 +155,10 @@ impl Settings { /// The value of the last read that answered. fn last(&self) -> Option { - let last = self.last.lock().unwrap_or_else(PoisonError::into_inner); - last.as_ref().map(|(_, accounts)| accounts.clone()) - } - - /// The value of the last read that answered, when no change through the - /// management API came after it was sent. - fn unchanged_last(&self) -> Option { - let last = self.last.lock().unwrap_or_else(PoisonError::into_inner); - let changes = self.changes(); - last.as_ref() - .filter(|(sent, _)| *sent == changes) - .map(|(_, accounts)| accounts.clone()) + self.last + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() } fn changes(&self) -> u64 { @@ -189,12 +186,12 @@ impl Settings { if let Some(answer) = self.fresh() { return answer; } - // A request does not wait on a read that another request waits on, or - // that outlasted READ_TIMEOUT, when an earlier read answered after the - // last change: it uses that read's value. + // Once a read has answered, a request does not wait on a read that + // another request waits on, or that outlasted READ_TIMEOUT: it uses + // the value of the last read that answered. let mut reading = match self.reading.try_lock() { Ok(reading) => reading, - Err(_) => match self.unchanged_last() { + Err(_) => match self.last() { Some(accounts) => return Ok(accounts), None => self.reading.lock().await, }, @@ -202,18 +199,18 @@ impl Settings { if let Some(answer) = self.fresh() { return answer; } - // A read sent before a change through the management API may answer - // the old value: it is left to end on its own and a new one is sent. - if reading - .as_ref() - .is_some_and(|r| r.changes != self.changes()) - { - *reading = None; - } - if reading.as_ref().is_some_and(|r| !r.task.is_finished()) - && let Some(accounts) = self.unchanged_last() - { - return Ok(accounts); + if let Some(in_flight) = reading.as_ref() { + if !in_flight.task.is_finished() { + // The read has not ended, whenever it was sent: no other is + // sent while it runs. + if let Some(accounts) = self.last() { + return Ok(accounts); + } + } else if in_flight.changes != self.changes() { + // A read that ended but was sent before a change through the + // management API may hold the old value: a new one is sent. + *reading = None; + } } let in_flight = reading.get_or_insert_with(|| self.send_read()); let sent = in_flight.changes; @@ -229,8 +226,7 @@ impl Settings { if let Some(ignored) = ignored { tracing::warn!("{ignored}"); } - *self.last.lock().unwrap_or_else(PoisonError::into_inner) = - Some((sent, accounts.clone())); + *self.last.lock().unwrap_or_else(PoisonError::into_inner) = Some(accounts.clone()); (raw, Some(accounts)) } Ok(Ok(Err(e))) => { diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index e85a60a45..b3e157307 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -316,15 +316,43 @@ async fn a_read_that_ends_late_answers_the_next_request() { assert_eq!(store.reads(), 1); } -/// A read sent before a change through the management API is not waited on -/// after it: the next request sends a read of the changed value. +/// Wait until no read of the store is in flight. +async fn until_the_read_ends(settings: &Settings) { + loop { + if let Ok(reading) = settings.reading.try_lock() + && reading.as_ref().is_none_or(|r| r.task.is_finished()) + { + return; + } + tokio::task::yield_now().await; + } +} + +/// A read sent before a change through the management API stays the one +/// read in flight until it ends. Before any value has been read, the next +/// request waits on it; once it has ended, the next request sends a read of +/// the changed value. #[tokio::test(start_paused = true)] -async fn a_change_applies_while_an_earlier_read_has_not_ended() { - let store = Store::new(Answer::Hang); +async fn a_read_sent_before_a_change_is_the_only_read_until_it_ends() { + let gate = Arc::new(Notify::new()); + let store = Store::new(Answer::Gated(Arc::clone(&gate), "off".to_owned())); let settings = Settings::new(store.clone()); assert!(is_unavailable(&settings.enabled_accounts().await)); store.set(Answer::Value(Some("all".to_owned()))); settings.changed(); + // the test's own deadline, so a request that waits without a bound + // fails here + let answer = tokio::time::timeout(READ_TIMEOUT * 2, settings.enabled_accounts()) + .await + .expect("the wait is bounded"); + assert!(is_unavailable(&answer), "{answer:?}"); + assert_eq!( + store.reads(), + 1, + "a read was sent while another was in flight" + ); + gate.notify_one(); + until_the_read_ends(&settings).await; assert_eq!( settings.enabled_accounts().await.unwrap(), EnabledAccounts::All @@ -332,6 +360,51 @@ async fn a_change_applies_while_an_earlier_read_has_not_ended() { assert_eq!(store.reads(), 2); } +/// Once a value has been read, a read that outlasted READ_TIMEOUT and was +/// sent before a change through the management API stays the one read in +/// flight: requests use the last value read at once until it ends, and the +/// next request then reads the changed value. +#[tokio::test(start_paused = true)] +async fn a_change_sends_no_second_read_while_one_is_in_flight() { + let store = Store::value("off"); + let settings = Settings::new(store.clone()); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + let gate = Arc::new(Notify::new()); + store.set(Answer::Gated(Arc::clone(&gate), "off".to_owned())); + tokio::time::advance(REFRESH).await; + // the test's own deadline, so a read without a bound fails here + let answer = tokio::time::timeout(READ_TIMEOUT * 2, settings.enabled_accounts()) + .await + .expect("the read is bounded"); + assert_eq!(answer.unwrap(), EnabledAccounts::Off); + store.set(Answer::Value(Some("all".to_owned()))); + settings.changed(); + for _ in 0..3 { + let started = tokio::time::Instant::now(); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + assert_eq!(started.elapsed(), std::time::Duration::ZERO); + tokio::time::advance(REFRESH).await; + } + assert_eq!( + store.reads(), + 2, + "a read was sent while another was in flight" + ); + gate.notify_one(); + until_the_read_ends(&settings).await; + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::All + ); + assert_eq!(store.reads(), 3); +} + /// A read that fails, after an earlier read answered, uses the value of the /// earlier read, a change through the management API notwithstanding. #[tokio::test(start_paused = true)] @@ -421,5 +494,38 @@ async fn a_request_does_not_wait_on_a_read_in_flight_once_a_value_was_read() { assert_eq!(store.reads(), 2); } +/// Once a value has been read, a request does not wait on a read another +/// request is waiting on, also when that read was sent after a change +/// through the management API. +#[tokio::test(start_paused = true)] +async fn a_request_does_not_wait_on_a_read_in_flight_after_a_change() { + let store = Store::value("off"); + let settings = Arc::new(Settings::new(store.clone())); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); + let gate = Arc::new(Notify::new()); + store.set(Answer::Gated(Arc::clone(&gate), "all".to_owned())); + settings.changed(); + let waiting = { + let settings = Arc::clone(&settings); + tokio::spawn(async move { settings.enabled_accounts().await }) + }; + while store.reads() < 2 { + tokio::task::yield_now().await; + } + let started = tokio::time::Instant::now(); + // the test's own deadline, so a request that waits on the read fails here + let answer = tokio::time::timeout(READ_TIMEOUT / 2, settings.enabled_accounts()) + .await + .expect("the request does not wait on the read"); + assert_eq!(answer.unwrap(), EnabledAccounts::Off); + assert_eq!(started.elapsed(), std::time::Duration::ZERO); + gate.notify_one(); + assert_eq!(waiting.await.unwrap().unwrap(), EnabledAccounts::All); + assert_eq!(store.reads(), 2); +} + #[path = "search_vectors_settings_fault_tests.rs"] mod fault; From 39c58e1de998e304d67c8afb58532f95ee7183a5 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 05:54:26 +0000 Subject: [PATCH 071/101] test(engine): poison the last value lock of the search filter setting The setting recovers from a poisoned lock on the server list, the kept read, the change count and the last value read. The test poisoned the first three only, so replacing the recoveries on the last value with `unwrap()` passed every SearchVectors test. The test now poisons the last value lock too and, after the change it already makes, fails the next read and asserts that the last value read is answered. Verified: the test passes, and fails when the three recoveries on the last value lock are replaced with `unwrap()`. The engine unit tests pass, 928 of 928. --- .../src/search_vectors_settings_fault_tests.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/search_vectors_settings_fault_tests.rs b/crates/engine/src/search_vectors_settings_fault_tests.rs index 88d3e3b3b..64a625156 100644 --- a/crates/engine/src/search_vectors_settings_fault_tests.rs +++ b/crates/engine/src/search_vectors_settings_fault_tests.rs @@ -18,8 +18,9 @@ fn poison(lock: &Mutex) { assert!(lock.is_poisoned()); } -/// A thread that panicked while holding the server list or a server's kept -/// read leaves the setting readable. +/// A thread that panicked while holding the server list, a server's kept +/// read, its change count or its last value read leaves the setting +/// readable, and a failed read still answers the last value read. #[tokio::test] async fn a_poisoned_lock_leaves_the_setting_readable() { let storage = storage().await; @@ -35,6 +36,7 @@ async fn a_poisoned_lock_leaves_the_setting_readable() { poison(&SERVERS); poison(&settings.kept); poison(&settings.changes); + poison(&settings.last); assert_eq!( enabled_accounts(&storage).await.unwrap(), EnabledAccounts::All @@ -51,6 +53,13 @@ async fn a_poisoned_lock_leaves_the_setting_readable() { EnabledAccounts::Off ); assert_eq!(store.reads(), 2); + store.set(Answer::Fail); + search_filter_settings_changed(); + assert_eq!( + enabled_accounts(&storage).await.unwrap(), + EnabledAccounts::Off, + "a failed read answers the last value read" + ); } /// The warnings this thread's subscriber receives. From 350a0afbb1bad64dfe1b9aa420d603d312b453f4 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 06:00:13 +0000 Subject: [PATCH 072/101] fix(storage): bound only the SearchVectors read of a setting A SearchVectors request reads the search_inequality_filters setting, and on PostgreSQL that read must not wait on a held lock on the `settings` table without end. ExtendDB bounded `get_setting` itself with `lock_timeout` 1 s and `statement_timeout` 1.5 s, so every settings read on PostgreSQL got the bound: the management API's GET, `extenddb settings get` and `list`, and the server's startup reads answered "Database error" behind a held lock where they waited before. `SettingsStore` gains `get_setting_bounded`, whose default calls `get_setting`. The PostgreSQL store overrides it with the bounded read, and its `get_setting` is the plain read it was before. The setting's reader sends `get_setting_bounded`. Verified: on PostgreSQL 16 with the `settings` table locked, a bounded read fails within 3 s and leaves no statement waiting on the lock 3 s after four dropped reads; a plain read is still waiting after 3 s and answers once the lock is released. An engine unit test with a store whose plain read never ends answers from the bounded read, and fails when the reader sends `get_setting`. The engine unit tests pass, 929 of 929; clippy 1.97.0 is clean on the engine and the three storage crates. --- crates/engine/src/search_vectors_settings.rs | 4 +- .../src/search_vectors_settings_tests.rs | 31 +++++++++++ crates/storage-postgres/src/catalog_store.rs | 26 +++++++-- .../tests/settings_read_bound.rs | 54 ++++++++++++++----- crates/storage/src/management_store/mod.rs | 8 +++ 5 files changed, 106 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/search_vectors_settings.rs b/crates/engine/src/search_vectors_settings.rs index c6e780573..a570231fe 100644 --- a/crates/engine/src/search_vectors_settings.rs +++ b/crates/engine/src/search_vectors_settings.rs @@ -171,7 +171,9 @@ impl Settings { let store = Arc::clone(&self.store); InFlight { changes: self.changes(), - task: tokio::spawn(async move { store.get_setting(SEARCH_INEQUALITY_FILTERS).await }), + task: tokio::spawn(async move { + store.get_setting_bounded(SEARCH_INEQUALITY_FILTERS).await + }), } } diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index b3e157307..97cf79747 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -527,5 +527,36 @@ async fn a_request_does_not_wait_on_a_read_in_flight_after_a_change() { assert_eq!(store.reads(), 2); } +/// A store whose plain read never ends and whose bounded read answers `off`. +struct BoundedOnly; + +impl SettingsStore for BoundedOnly { + fn get_setting(&self, _key: &str) -> BoxFuture<'_, OpResult>> { + Box::pin(std::future::pending()) + } + + fn get_setting_bounded(&self, _key: &str) -> BoxFuture<'_, OpResult>> { + Box::pin(async { Ok(Some("off".to_owned())) }) + } + + fn set_setting(&self, _key: &str, _value: &str) -> BoxFuture<'_, OpResult<()>> { + Box::pin(async { Ok(()) }) + } + + fn list_settings(&self) -> BoxFuture<'_, OpResult>> { + Box::pin(async { Ok(Vec::new()) }) + } +} + +/// A request reads the setting with the store's bounded read. +#[tokio::test(start_paused = true)] +async fn a_request_reads_the_setting_with_the_bounded_read() { + let settings = Settings::new(Arc::new(BoundedOnly)); + assert_eq!( + settings.enabled_accounts().await.unwrap(), + EnabledAccounts::Off + ); +} + #[path = "search_vectors_settings_fault_tests.rs"] mod fault; diff --git a/crates/storage-postgres/src/catalog_store.rs b/crates/storage-postgres/src/catalog_store.rs index 0c51903b3..474eb8f74 100755 --- a/crates/storage-postgres/src/catalog_store.rs +++ b/crates/storage-postgres/src/catalog_store.rs @@ -76,18 +76,38 @@ impl PostgresCatalogStore { // ── SettingsStore ────────────────────────────────────────────────────── -/// The server-side bound on a settings read: how long it waits for a lock -/// on the `settings` table, and how long it runs in all. +/// The server-side bound on a bounded settings read: how long it waits for +/// a lock on the `settings` table, and how long it runs in all. const SETTING_READ_BOUND: &str = "SELECT set_config('lock_timeout', '1s', true), \ set_config('statement_timeout', '1500ms', true)"; impl extenddb_storage::management_store::SettingsStore for PostgresCatalogStore { fn get_setting(&self, key: &str) -> futures::future::BoxFuture<'_, OpResult>> { + let key = key.to_string(); + let pool = self.pool.clone(); + Box::pin(async move { + let row: Option<(String,)> = + sqlx::query_as("SELECT value FROM settings WHERE key = $1") + .bind(&key) + .fetch_optional(&pool) + .await + .map_err(|e| { + tracing::error!("get_setting: {e}"); + OpError::Internal("Database error".to_owned()) + })?; + Ok(row.map(|(v,)| v)) + }) + } + + fn get_setting_bounded( + &self, + key: &str, + ) -> futures::future::BoxFuture<'_, OpResult>> { let key = key.to_string(); let pool = self.pool.clone(); Box::pin(async move { let failed = |e: sqlx::Error| { - tracing::error!("get_setting: {e}"); + tracing::error!("get_setting_bounded: {e}"); OpError::Internal("Database error".to_owned()) }; // The bound is set on the server, so a read that waits on a lock diff --git a/crates/storage-postgres/tests/settings_read_bound.rs b/crates/storage-postgres/tests/settings_read_bound.rs index da9d9d91a..5d43e4f95 100644 --- a/crates/storage-postgres/tests/settings_read_bound.rs +++ b/crates/storage-postgres/tests/settings_read_bound.rs @@ -1,12 +1,15 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! A settings read on a catalog whose `settings` table another session -//! holds locked: the read fails within its server-side bound and leaves no +//! Settings reads on a catalog whose `settings` table another session holds +//! locked. A bounded read fails within its server-side bound and leaves no //! statement waiting on the lock, including when the caller stops waiting -//! for it first. See `migrations_support` for the database these tests need. +//! for it first. A plain read waits on the lock as before and answers once +//! it is released. See `migrations_support` for the database these tests +//! need. mod migrations_support; +use std::sync::Arc; use std::time::{Duration, Instant}; use extenddb_storage::management_store::SettingsStore; @@ -30,7 +33,7 @@ async fn waiting(admin: &PgPool, catalog: &str) -> i64 { } #[tokio::test] -async fn a_read_behind_a_held_lock_fails_within_its_bound_and_leaves_nothing_waiting() { +async fn a_bounded_read_behind_a_held_lock_fails_within_its_bound_and_leaves_nothing_waiting() { let Some(base) = base_conn() else { return skip("settings read bound"); }; @@ -38,7 +41,7 @@ async fn a_read_behind_a_held_lock_fails_within_its_bound_and_leaves_nothing_wai s.migrate_through(MigrationId::LATEST).await; let catalog = pool(&s.catalog_url(), 4).await; let admin = pool(&format!("{base}/postgres"), 1).await; - let store = PostgresCatalogStore::new(catalog.clone()); + let store = Arc::new(PostgresCatalogStore::new(catalog.clone())); store .set_setting("search_inequality_filters", "all") .await @@ -51,11 +54,15 @@ async fn a_read_behind_a_held_lock_fails_within_its_bound_and_leaves_nothing_wai .await .expect("lock the settings table"); - // A read the caller waits for ends with an error within the bound. + // A bounded read the caller waits for ends with an error within the + // bound. let started = Instant::now(); - let read = tokio::time::timeout(DEADLINE, store.get_setting("search_inequality_filters")) - .await - .expect("a read behind the lock ends before the test's deadline"); + let read = tokio::time::timeout( + DEADLINE, + store.get_setting_bounded("search_inequality_filters"), + ) + .await + .expect("a read behind the lock ends before the test's deadline"); assert!(read.is_err(), "a read behind the lock fails: {read:?}"); assert!( started.elapsed() < Duration::from_secs(3), @@ -63,11 +70,11 @@ async fn a_read_behind_a_held_lock_fails_within_its_bound_and_leaves_nothing_wai started.elapsed() ); - // Reads the caller stops waiting for still end in the server. + // Bounded reads the caller stops waiting for still end in the server. for _ in 0..4 { let _ = tokio::time::timeout( Duration::from_millis(100), - store.get_setting("search_inequality_filters"), + store.get_setting_bounded("search_inequality_filters"), ) .await; } @@ -79,10 +86,31 @@ async fn a_read_behind_a_held_lock_fails_within_its_bound_and_leaves_nothing_wai "a statement still waits on the lock 3 s after its read was dropped" ); + // A plain read is not bounded: it still waits on the lock after the + // bounded read's bound, and answers once the lock is released. + let plain = { + let store = Arc::clone(&store); + tokio::spawn(async move { store.get_setting("search_inequality_filters").await }) + }; + tokio::time::sleep(Duration::from_secs(3)).await; + assert!( + !plain.is_finished(), + "a plain read behind the lock ended within 3 s" + ); + assert!(waiting(&admin, &s.catalog_name).await > 0); + lock.rollback().await.expect("release the lock"); - let read = tokio::time::timeout(DEADLINE, store.get_setting("search_inequality_filters")) + let read = tokio::time::timeout(DEADLINE, plain) .await - .expect("a read after the lock ends"); + .expect("the plain read ends once the lock is released") + .expect("the read task runs"); + assert_eq!(read.expect("the read succeeds"), Some("all".to_owned())); + let read = tokio::time::timeout( + DEADLINE, + store.get_setting_bounded("search_inequality_filters"), + ) + .await + .expect("a bounded read after the lock ends"); assert_eq!(read.expect("the read succeeds"), Some("all".to_owned())); locker.close().await; diff --git a/crates/storage/src/management_store/mod.rs b/crates/storage/src/management_store/mod.rs index a043f015c..5ec15991c 100755 --- a/crates/storage/src/management_store/mod.rs +++ b/crates/storage/src/management_store/mod.rs @@ -57,6 +57,14 @@ pub trait SettingsStore: Send + Sync { /// Get a single setting value. Returns `None` if the key does not exist. fn get_setting(&self, key: &str) -> BoxFuture<'_, OpResult>>; + /// Get a single setting value for a data-plane request, which must not + /// wait on the store without bound. The default is + /// [`SettingsStore::get_setting`]; a store whose read can wait on a lock + /// overrides it with a read bounded in the store. + fn get_setting_bounded(&self, key: &str) -> BoxFuture<'_, OpResult>> { + self.get_setting(key) + } + /// Set a setting value (upsert). fn set_setting(&self, key: &str, value: &str) -> BoxFuture<'_, OpResult<()>>; From 117f63cb0021c6792e8c4b98eeefa450539e6bad Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:21:22 +0000 Subject: [PATCH 073/101] fix(engine): send the attribute a parenthesised equality names The service reads a parenthesised attribute in a SearchConditionExpression equality as the attribute. Measured in eu-north-1, each request twice: `Country = :c AND (Cat) = :s`, `(Country) = :c AND Cat = :s`, `Country = :c AND (#k) = :s` with `#k` for `Cat`, `(Price) = :p` and `(Bin) = :b` with a Binary value each return the matching item, and `((Cat)) = :s` answers "The expression has redundant parentheses;". When both grammars parsed a condition, ExtendDB gave the backend the equality pairs of the equality-only grammar, which reads `(Cat)` as an attribute named `(Cat)`. The extended parse passed the schema check, so under the default setting the backend got the pair `("(Cat)", S:x)` and the search returned no item, for a String or Binary operand and for a parenthesised HASH attribute. The equality pairs now come from the extended parse: `SearchFilter::equalities` gives the attribute and value of each condition when the condition is an AND of `=` comparisons and nothing else, with names resolved and parentheses read as grouping. The equality-only grammar still decides the answer of an account the setting leaves out. Engine tests route each parenthesised shape to the pair of the attribute it names, and keep the equality-only refusals under `off`; wire rows search with a parenthesised String, Binary and Number operand and with doubled parentheses. --- .../core/src/expression/search_filter/mod.rs | 17 +++ crates/engine/src/search_vectors_condition.rs | 34 +++--- .../src/search_vectors_condition_tests.rs | 101 ++++++++++++++++++ crates/engine/src/search_vectors_extended.rs | 8 ++ .../test_search_vectors_inequality_filters.py | 24 +++++ 5 files changed, 168 insertions(+), 16 deletions(-) diff --git a/crates/core/src/expression/search_filter/mod.rs b/crates/core/src/expression/search_filter/mod.rs index c62d6042c..565d63873 100644 --- a/crates/core/src/expression/search_filter/mod.rs +++ b/crates/core/src/expression/search_filter/mod.rs @@ -157,6 +157,23 @@ impl SearchFilter { &self.conditions } + /// The attribute and value of each condition, in written order, when the + /// condition is an AND of `=` comparisons and nothing else; `None` + /// otherwise. Each attribute is the one the condition names, with a + /// `#name` resolved and the parentheses around it read as grouping. + #[must_use] + pub fn equalities(&self) -> Option> { + self.conditions + .iter() + .map(|c| match c.values.as_slice() { + [value] if c.operator == rules::Operator::Eq && c.must_match => { + Some((c.attribute.as_str(), value)) + } + _ => None, + }) + .collect() + } + /// Check the conditions against the index search schema, and return the /// HASH attribute and the value that selects its partition when the /// schema declares a HASH element. diff --git a/crates/engine/src/search_vectors_condition.rs b/crates/engine/src/search_vectors_condition.rs index 2b98a29c9..c6b4006ef 100644 --- a/crates/engine/src/search_vectors_condition.rs +++ b/crates/engine/src/search_vectors_condition.rs @@ -120,17 +120,12 @@ pub(crate) async fn resolve<'a>( } #[cfg(feature = "search-inequality-filters")] Parsed::Extended(extended) => { - extended_scope(extended, None, search_schema, attribute_definitions) + extended_scope(extended, false, search_schema, attribute_definitions) } #[cfg(feature = "search-inequality-filters")] Parsed::Either(extended, conditions) => { let equality = equality_scope(conditions, search_schema, attribute_definitions); - let extended = extended_scope( - extended, - Some(conditions), - search_schema, - attribute_definitions, - ); + let extended = extended_scope(extended, true, search_schema, attribute_definitions); if same_scope(&equality, &extended) || !crate::search_vectors_extended::enabled_for(storage, account_id).await? { @@ -152,12 +147,15 @@ fn equality_scope<'a>( Ok((hash_key, filters, None)) } -/// The scope of an extended-grammar condition: the equality pairs of -/// `conditions` when they give the same results, else the item filter. +/// The scope of an extended-grammar condition: when the equality-only +/// grammar also parsed it (`as_pairs`), the equality pairs of the attributes +/// the extended grammar names if they give the same results, else the item +/// filter. The equality-only grammar reads a parenthesised attribute such as +/// `(Cat)` as an attribute named `(Cat)`, so its conditions are not used. #[cfg(feature = "search-inequality-filters")] fn extended_scope<'a>( extended: &'a Extended, - conditions: Option<&'a [SearchCondition]>, + as_pairs: bool, search_schema: Option<&'a [SearchSchemaElement]>, attribute_definitions: &[AttributeDefinition], ) -> Result, DynamoDbError> { @@ -167,7 +165,10 @@ fn extended_scope<'a>( attribute_definitions, )?; Ok( - match conditions.and_then(|c| equality_pairs(c, search_schema)) { + match as_pairs + .then(|| equality_pairs(extended, search_schema)) + .flatten() + { Some(filters) => (hash_key, filters, None), None => (hash_key, Vec::new(), Some(item_filter)), }, @@ -197,23 +198,24 @@ fn same_error(a: &DynamoDbError, b: &DynamoDbError) -> bool { /// among them. #[cfg(feature = "search-inequality-filters")] fn equality_pairs<'a>( - conditions: &'a [SearchCondition], + extended: &'a Extended, search_schema: Option<&[SearchSchemaElement]>, ) -> Option> { + let conditions = extended.equalities()?; let hash_attr = search_schema .unwrap_or_default() .iter() .find(|e| e.element_type == SearchSchemaElementType::Hash) .map(|e| e.attribute_name.as_str()); let mut filters: Vec<(&str, &AttributeValue)> = Vec::with_capacity(conditions.len()); - for c in conditions { - if Some(c.attribute_name.as_str()) == hash_attr { + for &(name, value) in &conditions { + if Some(name) == hash_attr { continue; } - if !matches!(c.value, AttributeValue::S(_) | AttributeValue::B(_)) { + if !matches!(value, AttributeValue::S(_) | AttributeValue::B(_)) { return None; } - filters.push((c.attribute_name.as_str(), &c.value)); + filters.push((name, value)); } (!conditions.is_empty()).then_some(filters) } diff --git a/crates/engine/src/search_vectors_condition_tests.rs b/crates/engine/src/search_vectors_condition_tests.rs index 723a5360f..fabc7a38d 100644 --- a/crates/engine/src/search_vectors_condition_tests.rs +++ b/crates/engine/src/search_vectors_condition_tests.rs @@ -351,3 +351,104 @@ async fn a_condition_the_grammars_answer_differently_reads_the_setting() { ); } } + +/// The scope, or the error message, of `expr` with `names` under `setting`, +/// on a table with a HASH element. +async fn searched( + setting: &str, + expr: &str, + names: Option<&HashMap>, +) -> Result { + let storage = server(setting).await; + let values: HashMap = values() + .into_iter() + .filter(|(k, _)| expr.contains(k.as_str())) + .collect(); + let schema = schema(true); + async { + let parsed = parse( + &storage, + "111111111111", + Some(expr), + names, + Some(&values), + None, + &LimitsConfig::default(), + ) + .await?; + let (hash_key, filters, item_filter) = resolve( + &parsed, + Some(&schema), + &definitions(), + &storage, + "111111111111", + ) + .await?; + Ok::(( + hash_key.map(|(_, v)| v.clone()), + filters + .into_iter() + .map(|(n, v)| (n.to_owned(), v.clone())) + .collect(), + item_filter.map(|f| f.matches(&item()).unwrap()), + )) + } + .await + .map_err(|e| e.message().to_owned()) +} + +/// The equality-only grammar reads `(Cat)` as an attribute named `(Cat)`. +/// With the extended grammar the backend gets the pair of the attribute in +/// the parentheses, as for the condition without them. +#[tokio::test] +async fn a_parenthesised_string_or_binary_operand_reaches_the_backend_by_its_name() { + let k: HashMap = [("#k".to_owned(), "Cat".to_owned())].into(); + let h: HashMap = [("#h".to_owned(), "Country".to_owned())].into(); + for (expr, names, filters) in [ + ("Country = :c AND (Cat) = :s", None, pair("Cat", ":s")), + ("(Country) = :c AND Cat = :s", None, pair("Cat", ":s")), + ("Country = :c AND (Tag) = :t", None, pair("Tag", ":t")), + ("(Country) = :c AND (Tag) = :t", None, pair("Tag", ":t")), + ] { + assert_eq!( + searched("all", expr, names).await, + Ok((us(), filters, None)), + "{expr}" + ); + } + // The equality-only grammar refuses these, so the item filter serves + // them; a Number equality always goes to the item filter. + for (expr, names) in [ + ("Country = :c AND (#k) = :s", Some(&k)), + ("(#h) = :c AND (Cat) = :s", Some(&h)), + ("Country = :c AND :s = (Cat)", None), + ("Country = :c AND (Price) = :p", None), + ] { + assert_eq!( + searched("all", expr, names).await, + Ok((us(), Vec::new(), Some(true))), + "{expr}" + ); + } +} + +/// An account the setting leaves out keeps the equality-only grammar's +/// answer to a parenthesised operand. +#[tokio::test] +async fn a_parenthesised_operand_keeps_the_equality_answer_under_off() { + assert_eq!( + searched("off", "Country = :c AND (Cat) = :s", None).await, + Err( + "SearchConditionExpression must not contain any attributes that is not in \ + SearchSchema. Invalid attribute: (Cat)" + .to_owned() + ) + ); + assert_eq!( + searched("off", "(Country) = :c AND Cat = :s", None).await, + Err( + "SearchConditionExpression must have all HASH attributes in configured SearchSchema" + .to_owned() + ) + ); +} diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs index 7a91ba4be..6be1e7a1b 100644 --- a/crates/engine/src/search_vectors_extended.rs +++ b/crates/engine/src/search_vectors_extended.rs @@ -73,6 +73,14 @@ mod imp { /// A search condition parsed with the extended grammar. pub(crate) struct Extended(Arc); + impl Extended { + /// The attribute and value of each condition when the condition is + /// an AND of `=` comparisons and nothing else. + pub(crate) fn equalities(&self) -> Option> { + self.0.equalities() + } + } + /// Parse a search condition with the extended grammar. A name that /// neither the search condition nor `projection` uses is refused once /// the condition parses. diff --git a/tests/test_search_vectors_inequality_filters.py b/tests/test_search_vectors_inequality_filters.py index 1510c18c5..4e6c0f6ca 100644 --- a/tests/test_search_vectors_inequality_filters.py +++ b/tests/test_search_vectors_inequality_filters.py @@ -310,6 +310,30 @@ def test_in_and_between(self, grammar_table): assert "i1" not in _ids(_search(grammar_table, H + "NOT Price BETWEEN :p5 AND :p10")) +class TestParenthesisedOperands: + """A parenthesised attribute in an equality is the attribute, for a String, + Binary or Number operand and for the HASH attribute. Measured in + eu-north-1 on 2026-11-25, each request twice.""" + + def test_a_parenthesised_string_or_binary_operand(self, grammar_table): + category = {"i1", "i4", "i6"} + assert _ids(_search(grammar_table, H + "(Category) = :a")) == category + assert _ids(_search(grammar_table, "(Country) = :us AND Category = :a")) == category + names = {"#k": "Category"} + assert _ids(_search(grammar_table, H + "(#k) = :a", names=names)) == category + assert _ids(_search(grammar_table, H + "(Tag) = :t1")) == {"i1"} + assert _ids(_search(grammar_table, "(Country) = :us AND (Tag) = :t1")) == {"i1"} + + def test_a_parenthesised_number_operand(self, grammar_table): + assert _ids(_search(grammar_table, H + "(Price) = :p5")) == {"i1"} + + def test_doubled_parentheses_are_redundant(self, grammar_table): + _refused( + _search(grammar_table, H + "((Category)) = :a"), + P + "The expression has redundant parentheses;", + ) + + class TestRefusals: def test_hash_rules(self, grammar_table): _refused(_search(grammar_table, "Category = :a"), HASH_MISSING) From e8504611fb698eb47bee0c7bedf09b3d6267ef8a Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:21:30 +0000 Subject: [PATCH 074/101] test(core): pin the function and bound messages of a search condition The service answers a SearchConditionExpression whose function has the wrong number of operands with "Incorrect number of operands for operator or function; operator or function: attribute_exists, number of operands: 2", `if_not_exists` and `list_append` with "The function is not allowed in a condition expression", an unknown function with "Invalid function name", and String BETWEEN bounds out of order with the upper bound message showing `{S:z}` and `{S:a}`. A SearchVectors with `ProjectionExpression` `#a_b` and the name `#a_b` answers 200. Measured in eu-north-1, each request twice; FilterExpression gets the same bodies. ExtendDB answered each of these as the service does, and no test failed when the arity check, the update-function branch or the String bound comparison was changed, or when a name ended at its first `_`. A core test sends the six conditions and an in-order String range, and a search parameters test uses `#a_b` from the projection and from the condition. --- .../search_filter/tests_operands.rs | 61 +++++++++++++++++++ .../src/expression/search_params_tests.rs | 14 +++++ 2 files changed, 75 insertions(+) diff --git a/crates/core/src/expression/search_filter/tests_operands.rs b/crates/core/src/expression/search_filter/tests_operands.rs index 08abc3547..56227db32 100644 --- a/crates/core/src/expression/search_filter/tests_operands.rs +++ b/crates/core/src/expression/search_filter/tests_operands.rs @@ -290,3 +290,64 @@ fn the_combined_size_is_at_most_one_mebibyte() { } } } + +/// A function given the wrong number of operands, a function an update +/// takes, and String bounds out of order. Measured on the service in +/// eu-north-1 on 2026-11-25, each request twice, with the HASH equality +/// before each condition; the service answers FilterExpression with the +/// same bodies. +#[test] +fn function_arity_update_functions_and_string_bounds() { + use super::tests_support::message; + use crate::limits::LimitsConfig; + + let values = HashMap::from([ + (":hi".to_owned(), s("z")), + (":lo".to_owned(), s("a")), + (":v".to_owned(), s("x")), + ]); + let arity = |name: &str| { + p(&format!( + "Incorrect number of operands for operator or function; operator or function: \ + {name}, number of operands: 2" + )) + }; + let not_allowed = |name: &str| { + p(&format!( + "The function is not allowed in a condition expression; function: {name}" + )) + }; + for (expr, expected) in [ + ("attribute_exists(a, :v)", arity("attribute_exists")), + ("attribute_not_exists(a, :v)", arity("attribute_not_exists")), + ("if_not_exists(a, :v) = :v", not_allowed("if_not_exists")), + ("list_append(a, :v) = :v", not_allowed("list_append")), + ( + "bogus_fn(a) = :v", + p("Invalid function name; function: bogus_fn"), + ), + ( + "a BETWEEN :hi AND :lo", + p( + "The BETWEEN operator requires upper bound to be greater than or equal to \ + lower bound; lower bound operand: AttributeValue: {S:z}, upper bound operand: \ + AttributeValue: {S:a}", + ), + ), + ] { + let used = used_values(expr, &values); + let got = parse_search_filter(expr, None, Some(&used), 50, &LimitsConfig::default()); + assert_eq!(got.err().map(message), Some(expected), "{expr}"); + } + let used = used_values("a BETWEEN :lo AND :hi", &values); + assert!( + parse_search_filter( + "a BETWEEN :lo AND :hi", + None, + Some(&used), + 50, + &LimitsConfig::default() + ) + .is_ok() + ); +} diff --git a/crates/core/src/expression/search_params_tests.rs b/crates/core/src/expression/search_params_tests.rs index 983720cb6..c37f21233 100644 --- a/crates/core/src/expression/search_params_tests.rs +++ b/crates/core/src/expression/search_params_tests.rs @@ -241,6 +241,20 @@ fn a_name_is_used_by_the_condition_or_the_projection() { ); } +/// A name with `_` is one name in the projection and in the condition. +/// Measured on the service in eu-north-1 on 2026-11-25, twice: a +/// SearchVectors with `ProjectionExpression` `#a_b` and the name `#a_b` +/// answers 200. +#[test] +fn a_name_with_an_underscore_is_used_whole() { + let n = names(&[("#a_b", "Category")]); + assert!(check_unused_names(Some(&n), &BTreeSet::new(), "#a_b").is_ok()); + #[cfg(feature = "search-inequality-filters")] + let condition = crate::expression::search_filter::name_refs("Country = :c AND #a_b = :s"); + #[cfg(feature = "search-inequality-filters")] + assert!(check_unused_names(Some(&n), &condition, "").is_ok()); +} + #[test] fn unused_keys_are_listed_in_sorted_order() { let v: HashMap = [(":b", 1), (":a", 2), (":c", 3)] From 464f7c4228617bb5b33b568a7c00ed3c2319d96d Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:21:30 +0000 Subject: [PATCH 075/101] refactor(core): keep the number precision of the evaluator in the crate `NumberPrecision` and `evaluate_condition_at` were public items of `extenddb-core` that no other crate uses; the search filter calls them inside the crate. Both are now `pub(crate)` and the re-export is gone. `Binary64` is unused with the `search-inequality-filters` feature off and is allowed dead there. Core clippy passes with the feature on and off. --- crates/core/src/expression/evaluator.rs | 5 +++-- crates/core/src/expression/mod.rs | 2 +- crates/core/src/expression/search_filter/mod.rs | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/core/src/expression/evaluator.rs b/crates/core/src/expression/evaluator.rs index e2f50b189..ef41ae1b3 100755 --- a/crates/core/src/expression/evaluator.rs +++ b/crates/core/src/expression/evaluator.rs @@ -20,12 +20,13 @@ use super::resolver::{ /// How two `N` values compare. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum NumberPrecision { +pub(crate) enum NumberPrecision { /// As decimals, exactly: condition, filter and key condition expressions. Exact, /// As the nearest IEEE 754 binary64 value of each side: the inline /// filters of a `SearchVectors` search condition. The validity of each /// number, and the BETWEEN bound check, stay exact. + #[cfg_attr(not(feature = "search-inequality-filters"), allow(dead_code))] Binary64, } @@ -51,7 +52,7 @@ pub fn evaluate_condition( /// # Errors /// /// Returns `ValidationException` for unresolvable placeholders or type errors. -pub fn evaluate_condition_at( +pub(crate) fn evaluate_condition_at( expr: &Expr, item: &BTreeMap, maps: &ExpressionMaps, diff --git a/crates/core/src/expression/mod.rs b/crates/core/src/expression/mod.rs index 27a8950cb..4e68df885 100755 --- a/crates/core/src/expression/mod.rs +++ b/crates/core/src/expression/mod.rs @@ -30,7 +30,7 @@ mod update_evaluator; mod update_parser; pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only}; -pub use evaluator::{NumberPrecision, evaluate_condition, evaluate_condition_at}; +pub use evaluator::evaluate_condition; pub use key_condition::{ KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands, parse_key_condition, diff --git a/crates/core/src/expression/search_filter/mod.rs b/crates/core/src/expression/search_filter/mod.rs index 565d63873..60f5f100f 100644 --- a/crates/core/src/expression/search_filter/mod.rs +++ b/crates/core/src/expression/search_filter/mod.rs @@ -199,11 +199,11 @@ impl SearchFilter { /// condition the evaluator would refuse, so this does not happen for a /// parsed filter. pub fn matches(&self, item: &Item) -> Result { - crate::expression::evaluate_condition_at( + crate::expression::evaluator::evaluate_condition_at( &self.expr, item, &self.maps, - crate::expression::NumberPrecision::Binary64, + crate::expression::evaluator::NumberPrecision::Binary64, ) } } From 23bceb94dfdd97f5a89bc954b41e9958933c35b3 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:21:49 +0000 Subject: [PATCH 076/101] docs(core): state how the service and the FilterExpression parser read the search grammar The module comment said a search condition shares its grammar with ConditionExpression. On the service, a SearchConditionExpression and a Scan FilterExpression of the same text answer alike: measured in eu-north-1, each text twice, `(Cat) = :s`, `attribute_exists((Cat))` and `Price IN ((:p))` pass both, and `_x = :s` is a syntax error at `_` in both. ExtendDB's FilterExpression parser refuses the first three and accepts the fourth. The comment now says that. --- crates/core/src/expression/search_filter/grammar.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/core/src/expression/search_filter/grammar.rs b/crates/core/src/expression/search_filter/grammar.rs index 9c8c62fa0..ba6ac3271 100644 --- a/crates/core/src/expression/search_filter/grammar.rs +++ b/crates/core/src/expression/search_filter/grammar.rs @@ -1,8 +1,17 @@ // Copyright 2026 ExtendDB contributors // SPDX-License-Identifier: Apache-2.0 -//! The condition grammar a search condition shares with ConditionExpression, -//! parsed into a tree that keeps the operands as written. +//! The condition grammar of a search condition, parsed into a tree that +//! keeps the operands as written. +//! +//! The service answers a SearchConditionExpression and a Scan +//! FilterExpression of the same text alike, apart from the expression name +//! in the message prefix: measured in eu-north-1 on 2026-11-25, each text +//! twice, `(Cat) = :s`, `attribute_exists((Cat))` and `Price IN ((:p))` +//! pass both, and `_x = :s` is a syntax error at `_` in both. The +//! FilterExpression and ConditionExpression parser of this crate +//! (`parser.rs`) is a separate parser and refuses the first three and +//! accepts the fourth. //! //! ```text //! condition := and ( OR and )* From d9f8aa2dea05b41b338a0b2aa8f3a7e4cd19975a Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:13:45 +0000 Subject: [PATCH 077/101] docs(engine): name the ServiceUnavailable wire type in the setting comments The error a SearchVectors request gets when the search_inequality_filters setting cannot be read is sent with the wire type ServiceUnavailable (com.amazonaws.dynamodb.v20120810#ServiceUnavailable, HTTP 503). The comments of the setting module, the condition check and the extended grammar named it ServiceUnavailableException. The comments now name ServiceUnavailable. No code changes. --- crates/engine/src/search_vectors_condition.rs | 4 ++-- crates/engine/src/search_vectors_extended.rs | 2 +- crates/engine/src/search_vectors_settings.rs | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/search_vectors_condition.rs b/crates/engine/src/search_vectors_condition.rs index c6b4006ef..d3f057220 100644 --- a/crates/engine/src/search_vectors_condition.rs +++ b/crates/engine/src/search_vectors_condition.rs @@ -60,7 +60,7 @@ pub(crate) type Scope<'a> = ( /// # Errors /// /// Returns the `ValidationException` of the first failed check, and -/// `ServiceUnavailableException` when the answer depends on the setting and +/// `ServiceUnavailable` when the answer depends on the setting and /// the setting cannot be read. pub(crate) async fn parse( storage: &Arc, @@ -104,7 +104,7 @@ pub(crate) async fn parse( /// # Errors /// /// Returns the `ValidationException` of the first failed schema check, and -/// `ServiceUnavailableException` when the answer depends on the setting and +/// `ServiceUnavailable` when the answer depends on the setting and /// the setting cannot be read. pub(crate) async fn resolve<'a>( parsed: &'a Parsed, diff --git a/crates/engine/src/search_vectors_extended.rs b/crates/engine/src/search_vectors_extended.rs index 6be1e7a1b..69c01417e 100644 --- a/crates/engine/src/search_vectors_extended.rs +++ b/crates/engine/src/search_vectors_extended.rs @@ -109,7 +109,7 @@ mod imp { /// /// # Errors /// - /// Returns `ServiceUnavailableException` when the setting cannot be read + /// Returns `ServiceUnavailable` when the setting cannot be read /// and no earlier read answered. pub(crate) async fn enabled_for( storage: &Arc, diff --git a/crates/engine/src/search_vectors_settings.rs b/crates/engine/src/search_vectors_settings.rs index a570231fe..9e1db5d39 100644 --- a/crates/engine/src/search_vectors_settings.rs +++ b/crates/engine/src/search_vectors_settings.rs @@ -15,7 +15,7 @@ //! [`search_filter_settings_changed`]. When a read fails or outlasts //! [`READ_TIMEOUT`], the server uses the value of its last read that //! answered, a change through the management API notwithstanding. Before any -//! read has answered, such a read answers `ServiceUnavailableException`, as +//! read has answered, such a read answers `ServiceUnavailable`, as //! other transient storage faults do. A fault never changes which grammar an //! account gets. //! @@ -48,7 +48,7 @@ use extenddb_storage::management_store::{OpResult, SettingsStore}; pub(crate) const REFRESH: Duration = Duration::from_secs(1); /// How long a read of the setting may take before the request is answered -/// with `ServiceUnavailableException`. +/// with `ServiceUnavailable`. pub(crate) const READ_TIMEOUT: Duration = Duration::from_secs(2); /// Each storage engine of this process with the settings of its server. @@ -83,7 +83,7 @@ pub fn search_filter_settings_changed() { /// /// # Errors /// -/// Returns `ServiceUnavailableException` when the setting cannot be read. +/// Returns `ServiceUnavailable` when the setting cannot be read. pub(crate) async fn enabled_accounts( storage: &Arc, ) -> Result { From fd1c06b1690bb7af5ce319e448f149de8790663a Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:21:08 +0000 Subject: [PATCH 078/101] fix(engine): wait on a read of the search filter setting only once A server reads the search_inequality_filters setting for a SearchVectors request whose answer depends on the grammar. Before any read has answered, a request waits on the read in flight for at most two seconds and then answers ServiceUnavailable. When that read did not end, each request after the kept answer expired waited the two seconds again on the same read: with a catalog that holds the read, the requests at the change and at 3, 6, 9 and 12 seconds each took two seconds. A request that arrived while another was waiting waited a full two seconds of its own after that one gave up. The read now records when it was sent. A request waits on it only until two seconds after that, and once they have passed it answers at once, with the last value read or ServiceUnavailable. A read that does not end is still the only read in flight, across changes through the management API too, so a catalog that does not answer holds one connection for the setting. The module comment states the rule. Unit tests with a paused clock and their own deadlines: three changes while a read does not end send no second read; after the first request waits two seconds, requests over the next 12 seconds, a change among them, answer at once; a request that arrives one second into the first wait waits one second; a request that finds the read after the request that sent it was cancelled half a second in waits the remaining 1.5 seconds. The test of a read that ends late now waits for the read to end before the next request. --- crates/engine/src/search_vectors_settings.rs | 16 ++- .../src/search_vectors_settings_tests.rs | 4 + .../src/search_vectors_settings_wait_tests.rs | 104 ++++++++++++++++++ 3 files changed, 120 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/search_vectors_settings_wait_tests.rs diff --git a/crates/engine/src/search_vectors_settings.rs b/crates/engine/src/search_vectors_settings.rs index 9e1db5d39..09071865c 100644 --- a/crates/engine/src/search_vectors_settings.rs +++ b/crates/engine/src/search_vectors_settings.rs @@ -27,9 +27,10 @@ //! do not read it keep the rest. Once a read has answered, a request never //! waits on a read another request sent: while a read is in flight, it uses //! the value of the last read that answered. Before any read has answered, -//! a request waits on the read in flight for at most [`READ_TIMEOUT`]. A -//! change through the management API applies at the first read sent after -//! it, which is the next one once no read is in flight. +//! a request waits on the read in flight until [`READ_TIMEOUT`] after it +//! was sent, and once that has passed, it answers at once. A change through +//! the management API applies at the first read sent after it, which is the +//! next one once no read is in flight. use std::sync::{Arc, Mutex, PoisonError, Weak}; use std::time::Duration; @@ -117,6 +118,8 @@ struct Kept { struct InFlight { /// The value of [`Settings::changes`] when the read was sent. changes: u64, + /// When the read was sent. + sent_at: Instant, task: JoinHandle>>, } @@ -171,6 +174,7 @@ impl Settings { let store = Arc::clone(&self.store); InFlight { changes: self.changes(), + sent_at: Instant::now(), task: tokio::spawn(async move { store.get_setting_bounded(SEARCH_INEQUALITY_FILTERS).await }), @@ -216,7 +220,11 @@ impl Settings { } let in_flight = reading.get_or_insert_with(|| self.send_read()); let sent = in_flight.changes; - let read = tokio::time::timeout(READ_TIMEOUT, &mut in_flight.task).await; + // A request waits on a read only until READ_TIMEOUT after it was + // sent, so a read that does not end delays the first requests + // rather than one request after each refresh. + let wait = READ_TIMEOUT.saturating_sub(in_flight.sent_at.elapsed()); + let read = tokio::time::timeout(wait, &mut in_flight.task).await; if read.is_ok() { *reading = None; } diff --git a/crates/engine/src/search_vectors_settings_tests.rs b/crates/engine/src/search_vectors_settings_tests.rs index 97cf79747..b238de22d 100644 --- a/crates/engine/src/search_vectors_settings_tests.rs +++ b/crates/engine/src/search_vectors_settings_tests.rs @@ -307,6 +307,7 @@ async fn a_read_that_ends_late_answers_the_next_request() { assert!(is_unavailable(&settings.enabled_accounts().await)); tokio::time::advance(REFRESH).await; gate.notify_one(); + until_the_read_ends(&settings).await; let started = tokio::time::Instant::now(); assert_eq!( settings.enabled_accounts().await.unwrap(), @@ -560,3 +561,6 @@ async fn a_request_reads_the_setting_with_the_bounded_read() { #[path = "search_vectors_settings_fault_tests.rs"] mod fault; + +#[path = "search_vectors_settings_wait_tests.rs"] +mod wait; diff --git a/crates/engine/src/search_vectors_settings_wait_tests.rs b/crates/engine/src/search_vectors_settings_wait_tests.rs new file mode 100644 index 000000000..e74335283 --- /dev/null +++ b/crates/engine/src/search_vectors_settings_wait_tests.rs @@ -0,0 +1,104 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! How long requests wait on a read of the setting that does not end, and +//! how many reads such a read lets the server send. + +use std::time::Duration; + +use tokio::time::Instant; + +use super::*; + +/// A read that does not end is the only read sent, also across changes +/// through the management API, so it holds one catalog connection. +#[tokio::test(start_paused = true)] +async fn changes_while_a_read_does_not_end_send_no_more_reads() { + let store = Store::new(Answer::Hang); + let settings = Settings::new(store.clone()); + assert!(is_unavailable(&settings.enabled_accounts().await)); + for _ in 0..3 { + settings.changed(); + assert!(is_unavailable(&settings.enabled_accounts().await)); + } + assert_eq!(store.reads(), 1, "reads sent while the first had not ended"); +} + +/// Before any read has answered, only the first request waits on a read +/// that does not end. Requests sent later, after each refresh interval and +/// after a change, answer at once. +#[tokio::test(start_paused = true)] +async fn a_read_that_does_not_end_delays_only_the_first_request() { + let store = Store::new(Answer::Hang); + let settings = Settings::new(store.clone()); + let started = Instant::now(); + assert!(is_unavailable(&settings.enabled_accounts().await)); + assert_eq!(started.elapsed(), READ_TIMEOUT); + for round in 0..12 { + if round == 3 { + settings.changed(); + } + tokio::time::advance(REFRESH).await; + let started = Instant::now(); + // the test's own deadline, so a request that waits again fails here + let answer = tokio::time::timeout(READ_TIMEOUT / 2, settings.enabled_accounts()) + .await + .expect("the request does not wait on the read again"); + assert!(is_unavailable(&answer)); + assert_eq!(started.elapsed(), Duration::ZERO, "round {round}"); + } + assert_eq!(store.reads(), 1); +} + +/// A request that arrives while another waits on the first read waits only +/// until READ_TIMEOUT after that read was sent. +#[tokio::test(start_paused = true)] +async fn a_second_request_waits_only_for_the_rest_of_the_read_timeout() { + let store = Store::new(Answer::Hang); + let settings = Arc::new(Settings::new(store.clone())); + let first = { + let settings = Arc::clone(&settings); + tokio::spawn(async move { settings.enabled_accounts().await }) + }; + while store.reads() < 1 { + tokio::task::yield_now().await; + } + tokio::time::advance(READ_TIMEOUT / 2).await; + let started = Instant::now(); + // the test's own deadline, so a request that waits a full READ_TIMEOUT + // of its own fails here + let answer = tokio::time::timeout(READ_TIMEOUT, settings.enabled_accounts()) + .await + .expect("the wait ends with the first read's timeout"); + assert!(is_unavailable(&answer)); + assert_eq!(started.elapsed(), READ_TIMEOUT / 2); + assert!(is_unavailable(&first.await.unwrap())); + assert_eq!(store.reads(), 1); +} + +/// A request that finds a read in flight that the request which sent it +/// stopped waiting on waits only for the rest of READ_TIMEOUT. +#[tokio::test(start_paused = true)] +async fn a_request_after_a_dropped_wait_waits_only_for_the_rest() { + let store = Store::new(Answer::Hang); + let settings = Arc::new(Settings::new(store.clone())); + let first = { + let settings = Arc::clone(&settings); + tokio::spawn(async move { settings.enabled_accounts().await }) + }; + while store.reads() < 1 { + tokio::task::yield_now().await; + } + tokio::time::advance(READ_TIMEOUT / 4).await; + first.abort(); + assert!(first.await.unwrap_err().is_cancelled()); + let started = Instant::now(); + // the test's own deadline, so a request that waits a full READ_TIMEOUT + // of its own fails here + let answer = tokio::time::timeout(READ_TIMEOUT, settings.enabled_accounts()) + .await + .expect("the wait ends with the read's timeout"); + assert!(is_unavailable(&answer)); + assert_eq!(started.elapsed(), READ_TIMEOUT * 3 / 4); + assert_eq!(store.reads(), 1); +} From 62627a858515b0a8b93a2c8ad153944de0523fdf Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:21:08 +0000 Subject: [PATCH 079/101] test(engine): pin the one and two seconds of the search filter setting The admin guide and the upgrade note state that a read of the search_inequality_filters setting is kept for about a second and that a read is waited on for at most two seconds. The unit tests compared against the REFRESH and READ_TIMEOUT constants, so they passed with the constants at 10 and 20 seconds. A unit test with a paused clock now sends a second read at 1 second and none at 999 milliseconds, and answers ServiceUnavailable after exactly 2 seconds for a read that does not end. --- .../src/search_vectors_settings_wait_tests.rs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/engine/src/search_vectors_settings_wait_tests.rs b/crates/engine/src/search_vectors_settings_wait_tests.rs index e74335283..729ec33a5 100644 --- a/crates/engine/src/search_vectors_settings_wait_tests.rs +++ b/crates/engine/src/search_vectors_settings_wait_tests.rs @@ -102,3 +102,27 @@ async fn a_request_after_a_dropped_wait_waits_only_for_the_rest() { assert_eq!(started.elapsed(), READ_TIMEOUT * 3 / 4); assert_eq!(store.reads(), 1); } + +/// The admin guide and the upgrade note state the two intervals: a read is +/// kept for one second, and a read is waited on for at most two. +#[tokio::test(start_paused = true)] +async fn a_read_is_kept_for_one_second_and_waited_on_for_two() { + let store = Store::value("all"); + let settings = Settings::new(store.clone()); + settings.enabled_accounts().await.unwrap(); + tokio::time::advance(Duration::from_millis(999)).await; + settings.enabled_accounts().await.unwrap(); + assert_eq!(store.reads(), 1, "the read was not kept for one second"); + tokio::time::advance(Duration::from_millis(1)).await; + settings.enabled_accounts().await.unwrap(); + assert_eq!(store.reads(), 2, "the read was kept past one second"); + + let settings = Settings::new(Store::new(Answer::Hang)); + let started = Instant::now(); + // the test's own deadline, past the documented two seconds + let answer = tokio::time::timeout(Duration::from_secs(3), settings.enabled_accounts()) + .await + .expect("the read is waited on for at most two seconds"); + assert!(is_unavailable(&answer)); + assert_eq!(started.elapsed(), Duration::from_secs(2)); +} From e4068ef499c260c2f095d80f8ecc5a469bc8b012 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:21:08 +0000 Subject: [PATCH 080/101] test(server): pin that a change of the search filter setting applies at once The management API calls search_filter_settings_changed after it writes search_inequality_filters, so the next SearchVectors reads the new value rather than the read kept for a second. No test failed without that call: the engine tests call it themselves, and the wire tests write the setting before the suites start. A server unit test installs a settings store on an in-memory SQLite engine, writes the setting through set_setting, and checks that the request check takes `Price > :p` under all and refuses it under off, three changes in a row with no wait between them. --- crates/server/src/management/ops_settings.rs | 4 + .../management/ops_settings_search_tests.rs | 83 +++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 crates/server/src/management/ops_settings_search_tests.rs diff --git a/crates/server/src/management/ops_settings.rs b/crates/server/src/management/ops_settings.rs index f73531884..f5f0940dd 100755 --- a/crates/server/src/management/ops_settings.rs +++ b/crates/server/src/management/ops_settings.rs @@ -224,3 +224,7 @@ pub async fn set_setting( ); Ok(()) } + +#[cfg(all(test, feature = "search-inequality-filters"))] +#[path = "ops_settings_search_tests.rs"] +mod search_tests; diff --git a/crates/server/src/management/ops_settings_search_tests.rs b/crates/server/src/management/ops_settings_search_tests.rs new file mode 100644 index 000000000..8c3582b76 --- /dev/null +++ b/crates/server/src/management/ops_settings_search_tests.rs @@ -0,0 +1,83 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! A change of `search_inequality_filters` through the management API +//! reaches the next search at once, without waiting for the kept read of +//! the setting to expire. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use extenddb_core::limits::LimitsConfig; +use extenddb_storage::StorageEngine; +use extenddb_storage::management_store::{OpResult, SettingsStore}; +use extenddb_storage_sqlite::SqliteEngine; +use futures::future::BoxFuture; +use serde_json::json; + +use super::set_setting; + +/// A settings store that keeps what is written to it. +#[derive(Default)] +struct Store(Mutex>); + +impl SettingsStore for Store { + fn get_setting(&self, key: &str) -> BoxFuture<'_, OpResult>> { + let value = self.0.lock().unwrap().get(key).cloned(); + Box::pin(async move { Ok(value) }) + } + + fn set_setting(&self, key: &str, value: &str) -> BoxFuture<'_, OpResult<()>> { + self.0 + .lock() + .unwrap() + .insert(key.to_owned(), value.to_owned()); + Box::pin(async { Ok(()) }) + } + + fn list_settings(&self) -> BoxFuture<'_, OpResult>> { + Box::pin(async { Ok(Vec::new()) }) + } +} + +/// Whether the server takes `Price > :p` as a search condition, which only +/// the extended grammar accepts. +async fn takes_an_inequality(storage: &Arc) -> bool { + let body = json!({ + "TableName": "tbl", + "IndexName": "vidx", + "SearchVector": [{"N": "1"}, {"N": "0"}], + "TopK": 1, + "SearchConditionExpression": "Price > :p", + "ExpressionAttributeValues": {":p": {"N": "5"}}, + }); + extenddb_engine::check_search_vectors_request( + &body, + storage, + "123456789012", + &LimitsConfig::default(), + ) + .await + .is_ok() +} + +#[tokio::test] +async fn a_change_through_the_management_api_reaches_the_next_search() { + let storage: Arc = Arc::new( + SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) + .await + .expect("an in-memory database opens"), + ); + let store = Arc::new(Store::default()); + extenddb_engine::install_search_filter_settings(&storage, store.clone()); + let key = extenddb_core::settings_keys::SEARCH_INEQUALITY_FILTERS; + + set_setting(&*store, key, "off").await.unwrap(); + assert!(!takes_an_inequality(&storage).await); + // Well within the one second a read of the setting is kept: only the + // change through the management API can make the next search read it. + set_setting(&*store, key, "all").await.unwrap(); + assert!(takes_an_inequality(&storage).await); + set_setting(&*store, key, "off").await.unwrap(); + assert!(!takes_an_inequality(&storage).await); +} From 35f89c8ad44a4afbda492377affad42143f2fd35 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:39:43 +0000 Subject: [PATCH 081/101] refactor(storage-postgres): move the bounded setting read to its own file The bounded read of a setting moves from catalog_store.rs to catalog_settings_read.rs as it was, so the change that follows keeps catalog_store.rs under 600 lines. No statement changes. --- .../src/catalog_settings_read.rs | 36 +++++++++++++++++++ crates/storage-postgres/src/catalog_store.rs | 36 ++++--------------- 2 files changed, 43 insertions(+), 29 deletions(-) create mode 100644 crates/storage-postgres/src/catalog_settings_read.rs diff --git a/crates/storage-postgres/src/catalog_settings_read.rs b/crates/storage-postgres/src/catalog_settings_read.rs new file mode 100644 index 000000000..c8e13156d --- /dev/null +++ b/crates/storage-postgres/src/catalog_settings_read.rs @@ -0,0 +1,36 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The bounded read of a setting, which the SearchVectors reader of the +//! `search_inequality_filters` setting sends. + +use extenddb_storage::management_store::{OpError, OpResult}; +use sqlx::PgPool; + +/// The server-side bound on a bounded settings read: how long it waits for +/// a lock on the `settings` table, and how long it runs in all. +const SETTING_READ_BOUND: &str = "SELECT set_config('lock_timeout', '1s', true), \ + set_config('statement_timeout', '1500ms', true)"; + +/// Read `key` from the `settings` table under [`SETTING_READ_BOUND`]. +pub(super) async fn get_setting_bounded(pool: PgPool, key: String) -> OpResult> { + let failed = |e: sqlx::Error| { + tracing::error!("get_setting_bounded: {e}"); + OpError::Internal("Database error".to_owned()) + }; + // The bound is set on the server, so a read that waits on a lock + // ends there and gives its connection back even when the caller + // has stopped waiting for it. + let mut tx = pool.begin().await.map_err(failed)?; + sqlx::query(SETTING_READ_BOUND) + .execute(&mut *tx) + .await + .map_err(failed)?; + let row: Option<(String,)> = sqlx::query_as("SELECT value FROM settings WHERE key = $1") + .bind(&key) + .fetch_optional(&mut *tx) + .await + .map_err(failed)?; + tx.commit().await.map_err(failed)?; + Ok(row.map(|(v,)| v)) +} diff --git a/crates/storage-postgres/src/catalog_store.rs b/crates/storage-postgres/src/catalog_store.rs index 474eb8f74..ffcfb2c84 100755 --- a/crates/storage-postgres/src/catalog_store.rs +++ b/crates/storage-postgres/src/catalog_store.rs @@ -19,6 +19,9 @@ use sqlx::PgPool; use crate::data::catalog_check::CheckFailure; +#[path = "catalog_settings_read.rs"] +mod settings_read; + /// PostgreSQL-backed catalog store for settings, metrics, and rate limiting. /// /// Holds a connection pool to the catalog database. Created once at startup @@ -76,11 +79,6 @@ impl PostgresCatalogStore { // ── SettingsStore ────────────────────────────────────────────────────── -/// The server-side bound on a bounded settings read: how long it waits for -/// a lock on the `settings` table, and how long it runs in all. -const SETTING_READ_BOUND: &str = "SELECT set_config('lock_timeout', '1s', true), \ - set_config('statement_timeout', '1500ms', true)"; - impl extenddb_storage::management_store::SettingsStore for PostgresCatalogStore { fn get_setting(&self, key: &str) -> futures::future::BoxFuture<'_, OpResult>> { let key = key.to_string(); @@ -103,30 +101,10 @@ impl extenddb_storage::management_store::SettingsStore for PostgresCatalogStore &self, key: &str, ) -> futures::future::BoxFuture<'_, OpResult>> { - let key = key.to_string(); - let pool = self.pool.clone(); - Box::pin(async move { - let failed = |e: sqlx::Error| { - tracing::error!("get_setting_bounded: {e}"); - OpError::Internal("Database error".to_owned()) - }; - // The bound is set on the server, so a read that waits on a lock - // ends there and gives its connection back even when the caller - // has stopped waiting for it. - let mut tx = pool.begin().await.map_err(failed)?; - sqlx::query(SETTING_READ_BOUND) - .execute(&mut *tx) - .await - .map_err(failed)?; - let row: Option<(String,)> = - sqlx::query_as("SELECT value FROM settings WHERE key = $1") - .bind(&key) - .fetch_optional(&mut *tx) - .await - .map_err(failed)?; - tx.commit().await.map_err(failed)?; - Ok(row.map(|(v,)| v)) - }) + Box::pin(settings_read::get_setting_bounded( + self.pool.clone(), + key.to_string(), + )) } fn set_setting(&self, key: &str, value: &str) -> futures::future::BoxFuture<'_, OpResult<()>> { From ee5c63a7727b31dea6c1731cd48b448d8b094472 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:43:28 +0000 Subject: [PATCH 082/101] fix(storage-postgres): leave a caller's transaction open in a bounded setting read The bounded read of a setting sets lock_timeout and statement_timeout with set_config(.., true), which lasts until the end of the transaction, so it opened a transaction with BEGIN and ended it with COMMIT. On a connection already inside a transaction block, such as the READ ONLY session that serve loads its keys on, that BEGIN only warns and the COMMIT ends the owner's transaction, after which the session can write. The read now asks the server, in one simple query, whether the connection is inside a transaction block. Inside one, it runs under a savepoint and rolls back to it, which restores the two settings and an aborted read; otherwise it opens and commits its own transaction as before. The check uses the simple protocol because the extended protocol sets a statement's start again at Execute, so outside a block the two timestamps differ there. Verified on PostgreSQL 16: on a one-connection pool in BEGIN READ ONLY, after get_setting and after get_setting_bounded the transaction is still open with the same start time, read-only, with statement_timeout and lock_timeout unchanged, and an UPDATE fails; a bounded read behind a held lock fails within its bound and leaves that transaction unaborted and unchanged. The bound tests of settings_read_bound pass. --- .../src/catalog_settings_read.rs | 58 +++++++- .../tests/settings_read_in_transaction.rs | 131 ++++++++++++++++++ 2 files changed, 185 insertions(+), 4 deletions(-) create mode 100644 crates/storage-postgres/tests/settings_read_in_transaction.rs diff --git a/crates/storage-postgres/src/catalog_settings_read.rs b/crates/storage-postgres/src/catalog_settings_read.rs index c8e13156d..8aaf4a9e3 100644 --- a/crates/storage-postgres/src/catalog_settings_read.rs +++ b/crates/storage-postgres/src/catalog_settings_read.rs @@ -5,14 +5,29 @@ //! `search_inequality_filters` setting sends. use extenddb_storage::management_store::{OpError, OpResult}; -use sqlx::PgPool; +use sqlx::{Executor, PgPool, Row}; /// The server-side bound on a bounded settings read: how long it waits for /// a lock on the `settings` table, and how long it runs in all. const SETTING_READ_BOUND: &str = "SELECT set_config('lock_timeout', '1s', true), \ set_config('statement_timeout', '1500ms', true)"; +/// The read itself. +const READ: &str = "SELECT value FROM settings WHERE key = $1"; + +/// Whether the connection is inside a transaction block, sent as a simple +/// query. Outside one, the statement is its own transaction and starts +/// when it does; inside one, it starts after the `BEGIN` that opened the +/// block. +const IN_TRANSACTION_BLOCK: &str = "SELECT statement_timestamp() <> transaction_timestamp()"; + /// Read `key` from the `settings` table under [`SETTING_READ_BOUND`]. +/// +/// `set_config(.., true)` lasts until the end of the transaction, so the +/// read runs in one. On a connection already inside a transaction block, +/// which only its owner may end, the read runs under a savepoint and rolls +/// back to it, which also restores the two settings; otherwise it opens and +/// commits its own transaction. pub(super) async fn get_setting_bounded(pool: PgPool, key: String) -> OpResult> { let failed = |e: sqlx::Error| { tracing::error!("get_setting_bounded: {e}"); @@ -21,16 +36,51 @@ pub(super) async fn get_setting_bounded(pool: PgPool, key: String) -> OpResult { + sqlx::query_scalar::<_, String>(READ) + .bind(&key) + .fetch_optional(&mut *conn) + .await + } + Err(e) => Err(e), + }; + let rolled_back = sqlx::query("ROLLBACK TO SAVEPOINT extenddb_bounded_setting_read") + .execute(&mut *conn) + .await; + let released = sqlx::query("RELEASE SAVEPOINT extenddb_bounded_setting_read") + .execute(&mut *conn) + .await; + let row = row.map_err(failed)?; + rolled_back.map_err(failed)?; + released.map_err(failed)?; + return Ok(row); + } + let mut tx = sqlx::Connection::begin(&mut *conn).await.map_err(failed)?; sqlx::query(SETTING_READ_BOUND) .execute(&mut *tx) .await .map_err(failed)?; - let row: Option<(String,)> = sqlx::query_as("SELECT value FROM settings WHERE key = $1") + let row = sqlx::query_scalar::<_, String>(READ) .bind(&key) .fetch_optional(&mut *tx) .await .map_err(failed)?; tx.commit().await.map_err(failed)?; - Ok(row.map(|(v,)| v)) + Ok(row) } diff --git a/crates/storage-postgres/tests/settings_read_in_transaction.rs b/crates/storage-postgres/tests/settings_read_in_transaction.rs new file mode 100644 index 000000000..c321f04f0 --- /dev/null +++ b/crates/storage-postgres/tests/settings_read_in_transaction.rs @@ -0,0 +1,131 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 +//! Settings reads on a catalog store whose one connection is inside a +//! `READ ONLY` transaction its owner opened, as the session that `serve` +//! loads its keys on is. Neither read ends that transaction, makes it +//! writable or leaves its settings changed, and a bounded read that fails +//! behind a held lock leaves it usable. See `migrations_support` for the +//! database these tests need. + +mod migrations_support; + +use std::time::Duration; + +use extenddb_storage::management_store::SettingsStore; +use extenddb_storage::migrations::MigrationId; +use extenddb_storage_postgres::PostgresCatalogStore; +use migrations_support::{Scratch, base_conn, pool, skip}; +use sqlx::PgPool; + +/// The test's own deadline for one read. +const DEADLINE: Duration = Duration::from_secs(10); + +/// What the owner's transaction looks like: whether the session is inside a +/// transaction block, its start time, whether it is read-only, and the two +/// settings a bounded read sets. +async fn state(conn: &PgPool) -> (bool, String, String, String, String) { + sqlx::query_as( + "SELECT statement_timestamp() <> transaction_timestamp(), \ + transaction_timestamp()::text, current_setting('transaction_read_only'), \ + current_setting('statement_timeout'), current_setting('lock_timeout')", + ) + .fetch_one(conn) + .await + .expect("read the session state") +} + +/// A one-connection pool on the catalog whose connection is in a +/// `READ ONLY` transaction, and a store on it. +async fn read_only_store(url: &str) -> (PgPool, PostgresCatalogStore) { + let owner = pool(url, 1).await; + sqlx::raw_sql("BEGIN READ ONLY") + .execute(&owner) + .await + .expect("open the owner's transaction"); + let store = PostgresCatalogStore::new(owner.clone()); + (owner, store) +} + +#[tokio::test] +async fn reads_inside_a_read_only_transaction_leave_it_open_and_read_only() { + let Some(base) = base_conn() else { + return skip("settings read in a transaction"); + }; + let s = Scratch::new(&base, "pgm_settings_in_tx").await; + s.migrate_through(MigrationId::LATEST).await; + let writer = pool(&s.catalog_url(), 1).await; + PostgresCatalogStore::new(writer.clone()) + .set_setting("search_inequality_filters", "all") + .await + .expect("write the setting"); + + let (owner, store) = read_only_store(&s.catalog_url()).await; + let before = state(&owner).await; + assert!(before.0, "the owner's transaction is open: {before:?}"); + assert_eq!(before.2, "on"); + + let plain = tokio::time::timeout(DEADLINE, store.get_setting("search_inequality_filters")) + .await + .expect("the plain read ends"); + assert_eq!( + plain.expect("the plain read succeeds"), + Some("all".to_owned()) + ); + assert_eq!(state(&owner).await, before, "after the plain read"); + + let bounded = tokio::time::timeout( + DEADLINE, + store.get_setting_bounded("search_inequality_filters"), + ) + .await + .expect("the bounded read ends"); + assert_eq!( + bounded.expect("the bounded read succeeds"), + Some("all".to_owned()) + ); + assert_eq!(state(&owner).await, before, "after the bounded read"); + + let write = + sqlx::query("UPDATE settings SET value = 'off' WHERE key = 'search_inequality_filters'") + .execute(&owner) + .await; + assert!(write.is_err(), "the owner's transaction is still read-only"); + + owner.close().await; + writer.close().await; +} + +#[tokio::test] +async fn a_bounded_read_that_fails_inside_a_transaction_leaves_it_usable() { + let Some(base) = base_conn() else { + return skip("settings read in a transaction behind a lock"); + }; + let s = Scratch::new(&base, "pgm_settings_in_tx_lock").await; + s.migrate_through(MigrationId::LATEST).await; + let (owner, store) = read_only_store(&s.catalog_url()).await; + let before = state(&owner).await; + + let locker = pool(&s.catalog_url(), 1).await; + let mut lock = locker.begin().await.expect("begin the locking transaction"); + sqlx::query("LOCK TABLE settings IN ACCESS EXCLUSIVE MODE") + .execute(&mut *lock) + .await + .expect("lock the settings table"); + + let read = tokio::time::timeout( + DEADLINE, + store.get_setting_bounded("search_inequality_filters"), + ) + .await + .expect("a bounded read behind the lock ends before the test's deadline"); + assert!(read.is_err(), "a read behind the lock fails: {read:?}"); + assert_eq!( + state(&owner).await, + before, + "the owner's transaction is open, unaborted and unchanged" + ); + + lock.rollback().await.expect("release the lock"); + owner.close().await; + locker.close().await; +} From f160978e6a0808469e232ffab1c0494a2a24fdac Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:44:39 +0000 Subject: [PATCH 083/101] test(storage-postgres): read the session state of the transaction tests as a simple query The first column of the state, whether the session is inside a transaction block, is true outside one too when it is sent with the extended protocol, because Execute sets the statement's start again. It is now sent as a simple query. --- .../tests/settings_read_in_transaction.rs | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/storage-postgres/tests/settings_read_in_transaction.rs b/crates/storage-postgres/tests/settings_read_in_transaction.rs index c321f04f0..dcaf0363e 100644 --- a/crates/storage-postgres/tests/settings_read_in_transaction.rs +++ b/crates/storage-postgres/tests/settings_read_in_transaction.rs @@ -15,7 +15,7 @@ use extenddb_storage::management_store::SettingsStore; use extenddb_storage::migrations::MigrationId; use extenddb_storage_postgres::PostgresCatalogStore; use migrations_support::{Scratch, base_conn, pool, skip}; -use sqlx::PgPool; +use sqlx::{Executor, PgPool, Row}; /// The test's own deadline for one read. const DEADLINE: Duration = Duration::from_secs(10); @@ -24,14 +24,18 @@ const DEADLINE: Duration = Duration::from_secs(10); /// transaction block, its start time, whether it is read-only, and the two /// settings a bounded read sets. async fn state(conn: &PgPool) -> (bool, String, String, String, String) { - sqlx::query_as( - "SELECT statement_timestamp() <> transaction_timestamp(), \ - transaction_timestamp()::text, current_setting('transaction_read_only'), \ - current_setting('statement_timeout'), current_setting('lock_timeout')", - ) - .fetch_one(conn) - .await - .expect("read the session state") + // Sent as a simple query: the extended protocol sets the statement's + // start again at Execute, so the first column would be true outside a + // block too. + let row = conn + .fetch_one( + "SELECT statement_timestamp() <> transaction_timestamp(), \ + transaction_timestamp()::text, current_setting('transaction_read_only'), \ + current_setting('statement_timeout'), current_setting('lock_timeout')", + ) + .await + .expect("read the session state"); + (row.get(0), row.get(1), row.get(2), row.get(3), row.get(4)) } /// A one-connection pool on the catalog whose connection is in a From 3f8bc6b0d704c23afd1560949d55bcc000148065 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:16:39 +0000 Subject: [PATCH 084/101] test(storage-postgres): fail the vector search tests without a server when one is required CI sets EXTENDDB_TEST_PG_REQUIRED beside the connection string, so that a PostgreSQL test that cannot reach a server fails instead of skipping. The older PostgreSQL tests check it. The vector search filter fixture and the unit tests of the scan connection skipped whatever it said, so 11 of the 12 new tests passed with a SKIP line when no connection string reached them. Both skip sites now assert that the variable is unset or 0, with the message the other tests use. With EXTENDDB_TEST_PG_REQUIRED=1 and no connection string, the 12 tests of vector_search_filter, vector_search_filter_pages, settings_read_bound and vector_search_scan now fail; before, 11 passed and only settings_read_bound failed. --- crates/storage-postgres/src/vector_search_scan.rs | 11 ++++++++++- .../tests/common/vector_filter_fixture.rs | 10 ++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/storage-postgres/src/vector_search_scan.rs b/crates/storage-postgres/src/vector_search_scan.rs index 56611ba21..e66b86479 100644 --- a/crates/storage-postgres/src/vector_search_scan.rs +++ b/crates/storage-postgres/src/vector_search_scan.rs @@ -133,10 +133,19 @@ mod tests { use super::{ScanConnection, XACT_OF_THIS_BACKEND, cancel_if_in_transaction}; - /// A pool on the server's maintenance database, or `None` to skip. + /// A pool on the server's maintenance database, or `None` to skip. With + /// `EXTENDDB_TEST_PG_REQUIRED` set to any value but `0`, a job that must + /// reach a server fails here instead. async fn pool(max: u32) -> Option { let base = std::env::var("EXTENDDB_TEST_PG_CONNECTION_STRING").unwrap_or_default(); if base.trim().is_empty() { + let required = + std::env::var("EXTENDDB_TEST_PG_REQUIRED").is_ok_and(|v| !v.is_empty() && v != "0"); + assert!( + !required, + "EXTENDDB_TEST_PG_CONNECTION_STRING is not set, and EXTENDDB_TEST_PG_REQUIRED \ + says this job must reach a PostgreSQL server" + ); eprintln!("SKIP: EXTENDDB_TEST_PG_CONNECTION_STRING is not set"); return None; } diff --git a/crates/storage-postgres/tests/common/vector_filter_fixture.rs b/crates/storage-postgres/tests/common/vector_filter_fixture.rs index 351038789..3f6228347 100644 --- a/crates/storage-postgres/tests/common/vector_filter_fixture.rs +++ b/crates/storage-postgres/tests/common/vector_filter_fixture.rs @@ -57,9 +57,19 @@ impl VectorItemFilter for Matcher { } } +/// The server's base URL, or `None` to skip. With `EXTENDDB_TEST_PG_REQUIRED` +/// set to any value but `0`, a job that must reach a server fails here +/// instead. fn base() -> Option { let conn = std::env::var("EXTENDDB_TEST_PG_CONNECTION_STRING").unwrap_or_default(); if conn.trim().is_empty() { + let required = + std::env::var("EXTENDDB_TEST_PG_REQUIRED").is_ok_and(|v| !v.is_empty() && v != "0"); + assert!( + !required, + "EXTENDDB_TEST_PG_CONNECTION_STRING is not set, and EXTENDDB_TEST_PG_REQUIRED says \ + this job must reach a PostgreSQL server" + ); eprintln!("SKIP: EXTENDDB_TEST_PG_CONNECTION_STRING is not set"); return None; } From 4cce288f52828bab14e283ec1b7c9d3cca902295 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:16:50 +0000 Subject: [PATCH 085/101] docs(storage-postgres): state what the cancel check of a dropped vector scan covers The comment said that PostgreSQL signals the backend only while it is still inside the search transaction. The statement reads the backend status from pg_stat_activity, a copy taken once per transaction of the cancelling session, and pg_cancel_backend then signals the process id without looking at its transaction. A backend that ends the search transaction between the copy and the signal, and starts another client's, still gets the signal. The module comment and the doc of cancel_if_in_transaction now say that the check narrows that window and does not close it. Comment change only. --- .../src/vector_search_scan.rs | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/storage-postgres/src/vector_search_scan.rs b/crates/storage-postgres/src/vector_search_scan.rs index e66b86479..ebae2f66a 100644 --- a/crates/storage-postgres/src/vector_search_scan.rs +++ b/crates/storage-postgres/src/vector_search_scan.rs @@ -17,10 +17,16 @@ //! end on a connection nobody reads. //! //! The cancel names the backend by process id and by the start time of the -//! search transaction, and PostgreSQL signals it only while that backend is -//! still inside that transaction. A transaction-pooling proxy can hand the -//! backend to another client as soon as this one disconnects, and a process -//! id alone would then cancel that client's statement. +//! search transaction: it signals the backend only when `pg_stat_activity` +//! shows that backend in that transaction. A transaction-pooling proxy can +//! hand the backend to another client as soon as this one disconnects, and a +//! process id alone would then cancel that client's statement. The check +//! narrows that window and does not close it. `pg_stat_activity` is a copy +//! of the backend status taken once per transaction of the cancelling +//! session, and `pg_cancel_backend` signals the process id without looking +//! at its transaction, so a backend that ends the search transaction between +//! the copy and the signal, and starts another client's, still gets the +//! signal. use sqlx::pool::PoolConnection; use sqlx::{PgConnection, PgPool, Postgres}; @@ -109,8 +115,10 @@ const XACT_OF_THIS_BACKEND: &str = /// transaction that started at `xact_start`. Returns whether a cancel was /// sent. /// -/// No row matches once the backend has exited, has ended the transaction, or -/// serves another client's transaction; then nothing is signalled. +/// No row matches when the status copy shows the backend exited, out of the +/// transaction, or in another client's transaction; then nothing is +/// signalled. A backend that changes transaction after the copy is +/// signalled all the same. async fn cancel_if_in_transaction(pool: PgPool, (pid, xact_start): (i32, i64)) -> bool { sqlx::query_scalar::<_, bool>( "SELECT pg_cancel_backend(pid) FROM pg_stat_activity \ From eb8564daff138589f6a82a2f1c1101ffa6a47b3b Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:46:47 +0000 Subject: [PATCH 086/101] fix(build): turn the engine's search grammar off with the server's feature The server and the app each declared the search-inequality-filters feature as removable, but the server took the engine with its default features, so a server built without its feature still compiled the engine's grammar. It then installed no settings store and registered no search_inequality_filters key, and an engine with no installed store gives every account the extended grammar: such a binary served `>` and OR and answered `settings set search_inequality_filters off` with "Unknown setting". The app took the server with its defaults, so the app's feature switched nothing either, and the bin's entry only forwarded to the app. The workspace now takes extenddb-server without its default features (it already took the engine that way), and the server takes the engine with `partiql` only, so the server's feature turns on the engine's and the app's turns on the server's. The bin's entry, which switched nothing, is removed, and the compile-out script expects seven crates. The storage crates' comment states that their feature compiles their tests and turns on core's feature, which compiles core's grammar module for every crate of the build. Verified: `cargo tree -e features -i extenddb-engine` lists the engine's feature for the server and the app with their defaults and for the bin, and not for `-p extenddb-server --no-default-features` or `-p extenddb-app --no-default-features`; clippy 1.97.0 is clean on both without default features; `--check on` passes. --- .github/workflows/search-inequality-filters.yml | 9 +++++---- Cargo.toml | 2 +- crates/app/Cargo.toml | 6 ++++-- crates/bin/Cargo.toml | 8 +------- crates/engine/Cargo.toml | 5 +++-- crates/server/Cargo.toml | 10 +++++++--- crates/storage-postgres/Cargo.toml | 4 +++- crates/storage-sqlite/Cargo.toml | 4 +++- devtools/compile-out-search-inequality-filters | 14 ++++++++------ 9 files changed, 35 insertions(+), 27 deletions(-) diff --git a/.github/workflows/search-inequality-filters.yml b/.github/workflows/search-inequality-filters.yml index 6d7a65a72..a52e1c5d4 100644 --- a/.github/workflows/search-inequality-filters.yml +++ b/.github/workflows/search-inequality-filters.yml @@ -23,11 +23,12 @@ concurrency: # and as a list of accounts, and against the build with the feature compiled # out. # -# Most crates take their internal dependencies with default features, so no +# The storage crates and core are taken with their default features, so no # cargo command line compiles the feature out. The workspace takes -# extenddb-engine with its default features off, so extenddb-wasm-adapter, -# the browser build, names the feature for the engine, core and the SQLite -# backend itself. devtools/compile-out-search-inequality-filters removes the +# extenddb-engine and extenddb-server with their default features off: the +# server's feature turns on the engine's, the app's turns on the server's, +# and extenddb-wasm-adapter, the browser build, names the feature for the +# engine, core and the SQLite backend itself. devtools/compile-out-search-inequality-filters removes the # feature from the default list of every crate that declares it, which # compiles it out of the workspace, and checks that nothing enables it; with # `--check on` it checks that the browser build enables it on all three. diff --git a/Cargo.toml b/Cargo.toml index 90158cc0c..207911aac 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,7 +65,7 @@ extenddb-storage-mongodb = { path = "crates/storage-mongodb", version = "=1.0.0" extenddb-storage-postgres = { path = "crates/storage-postgres", version = "=1.0.0" } extenddb-storage-sqlite = { path = "crates/storage-sqlite", version = "=1.0.0" } extenddb-auth = { path = "crates/auth", version = "=1.0.0" } -extenddb-server = { path = "crates/server", version = "=1.0.0" } +extenddb-server = { path = "crates/server", version = "=1.0.0", default-features = false } extenddb-app = { path = "crates/app", version = "=1.0.0" } # Serialization diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index 2f773dc79..9254b73bb 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -23,8 +23,10 @@ backup-test-hooks = ["extenddb-server/backup-test-hooks"] # grammar (comparators, BETWEEN, IN, OR, NOT, attribute_exists and # attribute_not_exists) for the accounts the `search_inequality_filters` # runtime setting names, every account when it is absent. On by default. -# Removable: with this off, the grammar module is not compiled and -# SearchVectors accepts only an AND of equalities. +# The workspace takes the server without its default features, so this +# feature decides the server's: with it off, the server and the engine are +# built without it, SearchVectors accepts only an AND of equalities, and +# `settings` has no `search_inequality_filters` key. search-inequality-filters = ["extenddb-server/search-inequality-filters"] [dependencies] diff --git a/crates/bin/Cargo.toml b/crates/bin/Cargo.toml index 0f544cd84..23a47320e 100755 --- a/crates/bin/Cargo.toml +++ b/crates/bin/Cargo.toml @@ -18,7 +18,7 @@ name = "extenddb" path = "src/main.rs" [features] -default = ["postgres", "search-inequality-filters"] +default = ["postgres"] postgres = ["extenddb-storage-postgres"] cassandra = ["extenddb-storage-cassandra"] sqlite = ["extenddb-storage-sqlite"] @@ -38,12 +38,6 @@ mongodb-test-hooks = [ # fails (`main.rs` checks this at compile time). A production `sqlite` build # leaves it off. dev-mode = ["extenddb-app/dev-mode"] -# SearchVectors inequality filters: the extended SearchConditionExpression -# grammar for the accounts the `search_inequality_filters` runtime setting -# names, every account when it is absent. On by default, here and in every -# crate that declares it; with it off in all of them SearchVectors accepts -# only an AND of equalities. -search-inequality-filters = ["extenddb-app/search-inequality-filters"] [dependencies] extenddb-app = { workspace = true } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 6924322d6..b8eca3739 100755 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -24,8 +24,9 @@ partiql = ["extenddb-core/partiql"] # grammar (comparators, BETWEEN, IN, OR, NOT, attribute_exists and # attribute_not_exists) for the accounts the `search_inequality_filters` # runtime setting names, every account when it is absent. On by default. -# Removable: with this off, the grammar module is not compiled and -# SearchVectors accepts only an AND of equalities. +# With this off, SearchVectors accepts only an AND of equalities, whatever +# core's feature. With it on and no settings store installed, which only the +# server installs, every account gets the extended grammar. search-inequality-filters = ["extenddb-core/search-inequality-filters"] [dependencies] diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 0914d097e..2d04c35de 100755 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -26,15 +26,19 @@ backup-test-hooks = ["extenddb-engine/backup-test-hooks", "extenddb-storage/test # grammar (comparators, BETWEEN, IN, OR, NOT, attribute_exists and # attribute_not_exists) for the accounts the `search_inequality_filters` # runtime setting names, every account when it is absent. On by default. -# Removable: with this off, the grammar module is not compiled and -# SearchVectors accepts only an AND of equalities. +# This crate takes the engine without its default features, so with this off +# the engine's feature is off too unless another crate of the build turns it +# on: SearchVectors accepts only an AND of equalities, and the server has no +# `search_inequality_filters` key. Core's grammar module stays compiled while +# another crate of the build (a storage backend with its default features) +# turns core's feature on. search-inequality-filters = ["extenddb-core/search-inequality-filters", "extenddb-engine/search-inequality-filters"] [dependencies] extenddb-cache = { workspace = true } extenddb-core = { workspace = true } extenddb-config = { workspace = true } -extenddb-engine = { workspace = true, features = ["default"] } +extenddb-engine = { workspace = true, features = ["partiql"] } extenddb-storage = { workspace = true } extenddb-backup-store = { workspace = true } extenddb-auth = { workspace = true } diff --git a/crates/storage-postgres/Cargo.toml b/crates/storage-postgres/Cargo.toml index fcabb688a..4b08d9c7a 100755 --- a/crates/storage-postgres/Cargo.toml +++ b/crates/storage-postgres/Cargo.toml @@ -21,7 +21,9 @@ test-hooks = ["extenddb-storage/test-hooks"] test-util = ["extenddb-storage/test-util"] # The SearchVectors inequality filter tests, which evaluate the extended # grammar on this backend. On by default. The backend applies whatever filter -# the engine hands it, so the feature adds tests only. +# the engine hands it, so its own code does not change; the feature compiles +# those tests and turns on core's feature, which compiles core's grammar +# module for every crate of the build. search-inequality-filters = ["extenddb-core/search-inequality-filters"] [dev-dependencies] diff --git a/crates/storage-sqlite/Cargo.toml b/crates/storage-sqlite/Cargo.toml index b56608e10..26996205c 100644 --- a/crates/storage-sqlite/Cargo.toml +++ b/crates/storage-sqlite/Cargo.toml @@ -22,7 +22,9 @@ memory = [] test-hooks = ["extenddb-storage/test-hooks"] # The SearchVectors inequality filter tests, which evaluate the extended # grammar on this backend. On by default. The backend applies whatever filter -# the engine hands it, so the feature adds tests only. +# the engine hands it, so its own code does not change; the feature compiles +# those tests and turns on core's feature, which compiles core's grammar +# module for every crate of the build. search-inequality-filters = ["extenddb-core/search-inequality-filters"] [dependencies] diff --git a/devtools/compile-out-search-inequality-filters b/devtools/compile-out-search-inequality-filters index 99a7b574e..309481eb2 100755 --- a/devtools/compile-out-search-inequality-filters +++ b/devtools/compile-out-search-inequality-filters @@ -3,11 +3,13 @@ # SPDX-License-Identifier: Apache-2.0 """Remove the search-inequality-filters Cargo feature from every default list. -Each crate that declares the feature has it in its `default` list. Most -crates take their internal dependencies with default features, so no cargo -command line compiles it out. The workspace takes extenddb-engine with its -default features off, so the browser build's crate, extenddb-wasm-adapter, -names the feature for the engine, core and the SQLite backend itself. +Each crate that declares the feature has it in its `default` list. The +storage crates and core are taken with their default features, so no cargo +command line compiles it out. The workspace takes extenddb-engine and +extenddb-server with their default features off: the server's feature turns +on the engine's, the app's turns on the server's, and the browser build's +crate, extenddb-wasm-adapter, names the feature for the engine, core and the +SQLite backend itself. Removing the feature from every `default` list is how it is compiled out. This script reads every crates/*/Cargo.toml, refuses to edit any of them @@ -33,7 +35,7 @@ import sys from pathlib import Path FEATURE = "search-inequality-filters" -CRATES = 8 +CRATES = 7 BROWSER = "extenddb-wasm-adapter" BROWSER_CRATES = ("extenddb-core", "extenddb-engine", "extenddb-storage-sqlite") From cc39a313c851bea6a5c1bde9576b1f98ed9f661e Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:47:51 +0000 Subject: [PATCH 087/101] fix(devtools): check the browser build's feature state for wasm32 too devtools/compile-out-search-inequality-filters checked with cargo tree, which resolves the dependencies of the host target unless told otherwise, so a dependency that only wasm32 has and that turns the feature on passed both --check off and the check after compiling the feature out. The browser build is now checked for the host target and for wasm32-unknown-unknown, and the workspace check after the edits uses --target all. --- .../compile-out-search-inequality-filters | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/devtools/compile-out-search-inequality-filters b/devtools/compile-out-search-inequality-filters index 309481eb2..4cad81433 100755 --- a/devtools/compile-out-search-inequality-filters +++ b/devtools/compile-out-search-inequality-filters @@ -38,6 +38,7 @@ FEATURE = "search-inequality-filters" CRATES = 7 BROWSER = "extenddb-wasm-adapter" BROWSER_CRATES = ("extenddb-core", "extenddb-engine", "extenddb-storage-sqlite") +WASM = "wasm32-unknown-unknown" def feature_tree(root: Path, *args: str) -> str: @@ -50,13 +51,22 @@ def feature_tree(root: Path, *args: str) -> str: ).stdout +def host_target() -> str: + """The host's target triple, for which `cargo tree` resolves by default.""" + info = subprocess.run(["rustc", "-vV"], check=True, capture_output=True, text=True).stdout + return next(line.split(": ", 1)[1] for line in info.splitlines() if line.startswith("host: ")) + + def check_browser(root: Path, want: bool) -> list[str]: - """The crates of the browser build whose feature state is not `want`.""" + """The crates of the browser build whose feature state is not `want`, + built for the host or for wasm32, so a dependency that only one of the + two targets has is counted.""" wrong = [] for crate in BROWSER_CRATES: - tree = feature_tree(root, "-p", BROWSER, "-i", crate) - if (f'{crate} feature "{FEATURE}"' in tree) != want: - wrong.append(crate) + for target in (host_target(), WASM): + tree = feature_tree(root, "-p", BROWSER, "--target", target, "-i", crate) + if (f'{crate} feature "{FEATURE}"' in tree) != want: + wrong.append(f"{crate} ({target})") return wrong @@ -80,7 +90,7 @@ def compile_out(root: Path) -> int: return 1 for manifest, text in edits: manifest.write_text(text) - tree = feature_tree(root, "--workspace", "-i", "extenddb-core") + tree = feature_tree(root, "--workspace", "--target", "all", "-i", "extenddb-core") if f'feature "{FEATURE}"' in tree: print(f"error: the workspace still enables {FEATURE}:\n{tree}", file=sys.stderr) return 1 From f1f902f289ffa62e815a0b37f26eb20f1da30139 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:49:02 +0000 Subject: [PATCH 088/101] docs(devtools): state what run-tests does with the search setting unset or refused The help said that with EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS unset the setting is every account. run-tests then writes nothing, so a value an earlier run wrote stays: after a run with off, a run without the variable still gets the equality grammar. The help now says so. The error for a refused value named only a build without the feature. A build with it refuses a malformed value such as bogus or OFF the same way; the message names both causes and the values the key takes. --- devtools/run-tests | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/devtools/run-tests b/devtools/run-tests index 4a45553a0..0dd177660 100755 --- a/devtools/run-tests +++ b/devtools/run-tests @@ -134,7 +134,9 @@ Environment (--extenddb with an integration suite): EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS value for the search_inequality_filters setting, written before any suite starts (optional; - absent, the setting is every account) + unset, nothing is written and the server keeps + the value it has, which an earlier run may have + written) Environment (--real-dynamodb): EXTENDDB_TEST_ENDPOINT and EXTENDDB_ADMIN_PASSWORD unset; AWS credentials from the SDK's chain or AWS_ACCESS_KEY_ID. EOF @@ -428,7 +430,7 @@ if $NEEDS_INTEGRATION && [[ "$TARGET" != "real-dynamodb" ]]; then exit 1 fi if ! "$BINARY" settings --config "$CONFIG_FOR_SETTINGS" set search_inequality_filters "$EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS"; then - echo "error: the server refused search_inequality_filters=$EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS (a build without the search-inequality-filters feature refuses the key)." + echo "error: the server refused search_inequality_filters=$EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS: a build without the search-inequality-filters feature has no such key, and a build with it takes only an empty value, off, all, or a comma-separated list of 12-digit account IDs." exit 1 fi echo " ✓ search_inequality_filters set to $EXTENDDB_TEST_SEARCH_INEQUALITY_FILTERS" From 3abd4be351f0e9082736d33d4eb77c75ef636265 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:22:13 +0000 Subject: [PATCH 089/101] perf(search): check a SearchVectors request once DynamoDB makes the checks of a SearchVectors request that need no table before it authorizes the request. ExtendDB made them twice: the server ran them before the IAM decision, and the handler ran them again at dispatch, so a request that passed parsed its condition with both grammars twice. check_search_vectors_request now returns the checked request, and the server hands it to handle_checked_search_vectors at dispatch. The dispatch path through handle_search_vectors makes the checks itself, as before. The five SearchVectors and authorization wire modules give the same counts on a release SQLite server with the setting absent and off. --- crates/engine/src/lib.rs | 5 ++- crates/engine/src/search_vectors.rs | 40 ++++++++++++++++++--- crates/engine/src/search_vectors_request.rs | 14 ++++---- crates/server/src/handler.rs | 39 ++++++++++++-------- 4 files changed, 69 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 238933cd4..c4e254bcd 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -99,7 +99,10 @@ pub use put_item::handle_put_item; pub use query::handle_query; pub use request_limits::check_request_item_counts; pub use scan::handle_scan; -pub use search_vectors::{check_search_vectors_request, handle_search_vectors}; +pub use search_vectors::{ + CheckedSearchVectors, check_search_vectors_request, handle_checked_search_vectors, + handle_search_vectors, +}; #[cfg(all(feature = "search-inequality-filters", not(target_arch = "wasm32")))] pub use search_vectors_extended::{install_search_filter_settings, search_filter_settings_changed}; pub use streams::{SHARD_ITERATOR_EXPIRED_MESSAGE, ShardIteratorClass, classify_shard_iterator}; diff --git a/crates/engine/src/search_vectors.rs b/crates/engine/src/search_vectors.rs index fc6cd2afe..c9da12c61 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -46,11 +46,18 @@ struct SearchVectorsOutput { consumed_capacity: Option, } +/// A `SearchVectors` request whose checks that need no table passed, as +/// [`check_search_vectors_request`] returns it. The server hands it to +/// [`handle_checked_search_vectors`], so the checks, the search condition's +/// parse and the read of the `search_inequality_filters` setting run once +/// per request. +pub struct CheckedSearchVectors(request::Checked); + /// The checks of a `SearchVectors` request that need no table: the body, /// the backend's vector search, `IndexName`, `SearchVector`, `TopK`, the /// expression maps, the projection and the search condition. The service /// makes them before it authorizes the request, so the server calls this -/// ahead of the IAM decision. The handler makes them again. +/// ahead of the IAM decision. /// /// # Errors /// @@ -60,10 +67,10 @@ pub async fn check_search_vectors_request( storage: &std::sync::Arc, account_id: &str, limits: &extenddb_core::limits::LimitsConfig, -) -> Result<(), DynamoDbError> { +) -> Result { request::check(body, storage, account_id, limits) .await - .map(|_| ()) + .map(CheckedSearchVectors) } /// Handle a `SearchVectors` request. @@ -75,13 +82,36 @@ pub async fn check_search_vectors_request( pub async fn handle_search_vectors( body: Value, ctx: &OperationContext, +) -> Result { + let checked = request::check(&body, &ctx.storage, &ctx.account_id, &ctx.limits).await?; + search(checked, ctx).await +} + +/// Handle a `SearchVectors` request that [`check_search_vectors_request`] +/// checked for the account and storage engine of `ctx`. +/// +/// # Errors +/// +/// Returns `DynamoDbError` for missing tables/indexes, the checks that need +/// the index, or storage errors. +pub async fn handle_checked_search_vectors( + checked: CheckedSearchVectors, + ctx: &OperationContext, +) -> Result { + search(checked.0, ctx).await +} + +async fn search( + checked: request::Checked, + ctx: &OperationContext, ) -> Result { let request::Checked { input, query_vector, parsed, - vector_search, - } = request::check(&body, &ctx.storage, &ctx.account_id, &ctx.limits).await?; + } = checked; + let vector_search = + crate::vector_gate::ensure_search_supported(ctx.storage.as_vector_search())?; let key_info = ctx .table_key_info(&input.table_name) diff --git a/crates/engine/src/search_vectors_request.rs b/crates/engine/src/search_vectors_request.rs index 5c50d4a99..9e72e5bdb 100644 --- a/crates/engine/src/search_vectors_request.rs +++ b/crates/engine/src/search_vectors_request.rs @@ -12,7 +12,7 @@ use serde_json::Value; use extenddb_core::error::DynamoDbError; use extenddb_core::limits::LimitsConfig; use extenddb_core::types::{AttributeValue, ReturnConsumedCapacity}; -use extenddb_storage::{StorageEngine, VectorSearchEngine}; +use extenddb_storage::StorageEngine; use super::condition; @@ -46,11 +46,10 @@ pub(super) struct SearchVectorsInput { } /// A `SearchVectors` request whose checks that need no table passed. -pub(super) struct Checked<'s> { +pub(super) struct Checked { pub(super) input: SearchVectorsInput, pub(super) query_vector: Vec, pub(super) parsed: condition::Parsed, - pub(super) vector_search: &'s dyn VectorSearchEngine, } /// Check a `SearchVectors` request as far as the checks need no table. @@ -58,15 +57,15 @@ pub(super) struct Checked<'s> { /// # Errors /// /// Returns the error of the first failed check. -pub(super) async fn check<'s>( +pub(super) async fn check( body: &Value, - storage: &'s Arc, + storage: &Arc, account_id: &str, limits: &LimitsConfig, -) -> Result, DynamoDbError> { +) -> Result { let input = SearchVectorsInput::deserialize(body).map_err(crate::deserialize_error)?; - let vector_search = crate::vector_gate::ensure_search_supported(storage.as_vector_search())?; + crate::vector_gate::ensure_search_supported(storage.as_vector_search())?; // Request-shape validation runs before the table lookup, so a malformed // request against a missing table reports the validation error rather than @@ -123,7 +122,6 @@ pub(super) async fn check<'s>( input, query_vector, parsed, - vector_search, }) } diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 0fe017bd3..140bbd95e 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -136,27 +136,34 @@ pub(crate) async fn handle_request( // expression maps, the projection and the search condition. They run once // the table name passes `check_table_name_chars`; a table name outside // its pattern answers first, from `authorize_request`, and no length - // check applies to the table name here (#1462). + // check applies to the table name here (#1462). The checked request goes + // to the engine at dispatch, so the checks run once. + let mut checked_search = None; if operation == "SearchVectors" && crate::table_name_gate::check_table_name_chars(&operation, &input, &account_id).is_ok() - && let Err(e) = extenddb_engine::check_search_vectors_request( + { + match extenddb_engine::check_search_vectors_request( &input, &state.storage, &account_id, &state.limits, ) .await - { - let metric_table = metric_table_name(&operation, &input, &state.limits); - record_error_metrics( - &state.metrics, - &e, - &account_id, - metric_table.as_deref(), - &operation, - ); - state.metrics.record_request_count(&account_id, &operation); - return error_response(&e, &request_id); + { + Ok(checked) => checked_search = Some(checked), + Err(e) => { + let metric_table = metric_table_name(&operation, &input, &state.limits); + record_error_metrics( + &state.metrics, + &e, + &account_id, + metric_table.as_deref(), + &operation, + ); + state.metrics.record_request_count(&account_id, &operation); + return error_response(&e, &request_id); + } + } } // --- Authz segment --- @@ -295,8 +302,10 @@ pub(crate) async fn handle_request( // --- Dispatch segment --- let dispatch_start = std::time::Instant::now(); - let dispatch_result = - extenddb_engine::dispatch(&operation, input, &ctx, &state.server_addr).await; + let dispatch_result = match checked_search { + Some(checked) => extenddb_engine::handle_checked_search_vectors(checked, &ctx).await, + None => extenddb_engine::dispatch(&operation, input, &ctx, &state.server_addr).await, + }; #[allow(clippy::cast_precision_loss)] let dispatch_us = dispatch_start.elapsed().as_micros() as f64; // P120c: Record storage query metrics for the request's dispatch phase. From e0de13e3f26f391018a641cfb4e844ff0cd2fbca Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:49:47 +0000 Subject: [PATCH 090/101] fix(server): record the latency segments of a SearchVectors that fails its checks The server makes the checks of a SearchVectors request that need no table before the IAM decision. When they failed, it recorded the error and the request count but no latency segments, where a request that fails in the engine records all three: three searches with TopK 0 added no SearchVectors entry to `segments` in /metrics, where 1.0.0 added one with count 3, and three searches of a missing table added one. A failure there now records the latency segments too, the checks' time as the dispatch segment, so it is recorded as an engine error is. A wire test counts the SearchVectors segments of a new account after three searches with TopK 0 and after three searches of a missing table. --- crates/server/src/handler.rs | 29 +++++- tests/test_search_vectors_metrics.py | 128 +++++++++++++++++++++++++++ 2 files changed, 155 insertions(+), 2 deletions(-) create mode 100644 tests/test_search_vectors_metrics.py diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 140bbd95e..43c1a18d6 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -137,11 +137,15 @@ pub(crate) async fn handle_request( // the table name passes `check_table_name_chars`; a table name outside // its pattern answers first, from `authorize_request`, and no length // check applies to the table name here (#1462). The checked request goes - // to the engine at dispatch, so the checks run once. + // to the engine at dispatch, so the checks run once. A failure is recorded + // in the request metrics as an engine error is: the error, the request + // count and the latency segments, the checks' time as the dispatch + // segment. let mut checked_search = None; if operation == "SearchVectors" && crate::table_name_gate::check_table_name_chars(&operation, &input, &account_id).is_ok() { + let check_start = std::time::Instant::now(); match extenddb_engine::check_search_vectors_request( &input, &state.storage, @@ -152,6 +156,8 @@ pub(crate) async fn handle_request( { Ok(checked) => checked_search = Some(checked), Err(e) => { + #[allow(clippy::cast_precision_loss)] + let dispatch_us = check_start.elapsed().as_micros() as f64; let metric_table = metric_table_name(&operation, &input, &state.limits); record_error_metrics( &state.metrics, @@ -160,8 +166,27 @@ pub(crate) async fn handle_request( metric_table.as_deref(), &operation, ); + let response_start = std::time::Instant::now(); + let response = error_response(&e, &request_id); + #[allow(clippy::cast_precision_loss)] + let response_us = response_start.elapsed().as_micros() as f64; + #[allow(clippy::cast_precision_loss)] + let total_us = handler_start.elapsed().as_micros() as f64; state.metrics.record_request_count(&account_id, &operation); - return error_response(&e, &request_id); + state.metrics.record_segments( + &account_id, + &operation, + metric_table.as_deref(), + extenddb_core::metrics::LatencySegments { + auth_us, + authz_us: 0.0, + throttle_us: 0.0, + dispatch_us, + response_us, + total_us, + }, + ); + return response; } } } diff --git a/tests/test_search_vectors_metrics.py b/tests/test_search_vectors_metrics.py new file mode 100644 index 000000000..447225280 --- /dev/null +++ b/tests/test_search_vectors_metrics.py @@ -0,0 +1,128 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""The latency segments of a SearchVectors that fails its checks. + +The server makes the checks of a SearchVectors request that need no table +before the IAM decision. A request that fails them is recorded in the +request metrics as a request that fails in the engine is: the error, the +request count and one entry in the latency segments of ``/metrics``. The +test sends three searches with ``TopK`` 0, which fail those checks, and +three searches of a table that does not exist, which pass them on a backend +with vector search, as a new account, and reads the account's SearchVectors +segment count after each group. + +``/metrics`` is an ExtendDB endpoint, so the module runs only against +ExtendDB. + +Prerequisites: + - extenddb running on EXTENDDB_TEST_ENDPOINT + - Admin credentials in EXTENDDB_ADMIN_USER / EXTENDDB_ADMIN_PASSWORD +""" + +from __future__ import annotations + +import json +import os +import uuid + +import pytest +import requests +from botocore.auth import SigV4Auth +from botocore.awsrequest import AWSRequest +from botocore.credentials import Credentials + +from management_helpers import ManagementClient + +VECTOR = [{"N": "1"}, {"N": "0"}, {"N": "0"}, {"N": "0"}] + + +def _require_env() -> tuple[str, str, str]: + endpoint = os.environ.get("EXTENDDB_TEST_ENDPOINT", "").strip() + admin_user = os.environ.get("EXTENDDB_ADMIN_USER", "").strip() + admin_pass = os.environ.get("EXTENDDB_ADMIN_PASSWORD", "").strip() + if not endpoint or not admin_user or not admin_pass: + pytest.skip( + "The /metrics endpoint is ExtendDB's: the module needs " + "EXTENDDB_TEST_ENDPOINT, EXTENDDB_ADMIN_USER and " + "EXTENDDB_ADMIN_PASSWORD, which devtools/run-tests sets." + ) + return endpoint, admin_user, admin_pass + + +def _segment_count(env: tuple[str, str, str], account_id: str) -> int: + endpoint, admin_user, admin_pass = env + resp = requests.get( + f"{endpoint}/metrics", + params={"account_id": account_id}, + auth=(admin_user, admin_pass), + timeout=10, + verify=False, + ) + assert resp.status_code == 200, f"/metrics: {resp.status_code} {resp.text[:200]}" + return sum( + s["count"] for s in resp.json()["segments"] if s["operation"] == "SearchVectors" + ) + + +@pytest.fixture(scope="module") +def account(): + """A new account with a user that may call every DynamoDB action.""" + env = _require_env() + mgmt = ManagementClient(*env) + account_id = f"{uuid.uuid4().int % 10**12:012d}" + user = "search-metrics" + resp = mgmt.create_account(account_id, f"search-metrics-{account_id}") + assert resp.status_code == 201, resp.text + try: + resp = mgmt.create_user(account_id, user) + assert resp.status_code == 201, resp.text + resp = mgmt.create_access_key(account_id, user) + assert resp.status_code == 201, resp.text + creds = resp.json() + policy = { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "dynamodb:*", "Resource": "*"}], + } + resp = mgmt.put_user_policy(account_id, user, "full", policy) + assert resp.status_code == 204, resp.text + signer = SigV4Auth( + Credentials(creds["access_key_id"], creds["secret_access_key"]), + "dynamodb", + os.environ.get("AWS_DEFAULT_REGION", "us-east-1"), + ) + yield env, account_id, signer + finally: + mgmt.delete_user(account_id, user) + resp = mgmt.delete_account(account_id) + assert resp.status_code in (200, 204), resp.text + + +def _search(env: tuple[str, str, str], signer: SigV4Auth, table: str, top_k: int) -> str: + """The error type of a SearchVectors of ``table`` with ``top_k``.""" + body = json.dumps( + {"TableName": table, "IndexName": "vix", "SearchVector": VECTOR, "TopK": top_k} + ).encode() + headers = { + "X-Amz-Target": "DynamoDB_20120810.SearchVectors", + "Content-Type": "application/x-amz-json-1.0", + } + req = AWSRequest(method="POST", url=env[0], data=body, headers=headers) + signer.add_auth(req) + resp = requests.post( + env[0], data=body, headers=dict(req.headers), verify=False, timeout=30 + ) + assert resp.status_code == 400, resp.text + return resp.json()["__type"].rsplit("#", 1)[-1] + + +def test_a_search_that_fails_its_checks_adds_latency_segments(account): + env, account_id, signer = account + assert _segment_count(env, account_id) == 0 + codes = {_search(env, signer, "search-metrics-table", 0) for _ in range(3)} + assert codes == {"ValidationException"}, codes + assert _segment_count(env, account_id) == 3 + table = f"search-metrics-missing-{uuid.uuid4().hex[:8]}" + for _ in range(3): + _search(env, signer, table, 5) + assert _segment_count(env, account_id) == 6 From 242a5879ecf736055e98ed731f2d28f85fb97aaa Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:53:12 +0000 Subject: [PATCH 091/101] docs(storage): state where each backend applies the search item filter The storage comments said a backend calls the item filter on each candidate before ranking it, and the SearchVectors handler's module comment said the search takes an optional single-equality prefilter. PostgreSQL ranks the candidates in SQL and calls the filter on the rows in score order, page by page, until top_k rows match; SQLite calls it on each candidate before scoring it. ADR 0006 said the inline filters are evaluated in SQL so that LIMIT applies after filtering, which now holds for the equalities only. The comments of vector_filter.rs, VectorSearch::item_filter, the SQLite scan and the handler state what each backend does, ADR 0006 records the amendment under decision 3, and ADR 0030 names where the filter runs. --- crates/engine/src/search_vectors.rs | 8 +++++--- crates/storage-sqlite/src/vector_search.rs | 5 +++-- crates/storage/src/lib.rs | 5 +++-- crates/storage/src/vector_filter.rs | 7 +++++-- docs/adr/0006-pgvector-storage-and-scoring.md | 6 ++++++ docs/adr/0030-search-condition-grammar.md | 3 ++- 6 files changed, 24 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/search_vectors.rs b/crates/engine/src/search_vectors.rs index c9da12c61..282e801a3 100644 --- a/crates/engine/src/search_vectors.rs +++ b/crates/engine/src/search_vectors.rs @@ -4,9 +4,11 @@ //! `SearchVectors` operation handler. //! //! Runs a similarity search over a vector index: parses the query vector, an -//! optional single-equality prefilter, and an optional projection, calls the -//! storage layer for the top-k nearest neighbors, and returns each item with -//! its similarity score. +//! optional `SearchConditionExpression`, and an optional projection, calls +//! the storage layer for the top-k nearest neighbors that satisfy the +//! condition, and returns each item with its similarity score. The condition +//! reaches the storage layer as a HASH equality, inline-filter equalities and, +//! for the conditions those cannot express, an item filter. use std::collections::HashMap; diff --git a/crates/storage-sqlite/src/vector_search.rs b/crates/storage-sqlite/src/vector_search.rs index b2f69b213..04aac8dcf 100644 --- a/crates/storage-sqlite/src/vector_search.rs +++ b/crates/storage-sqlite/src/vector_search.rs @@ -274,8 +274,9 @@ impl VectorSearchEngine for SqliteEngine { .map_err(|e| StorageError::Internal(format!("stored item: {e}")))?; // Inline-filter attributes are applied here rather than in SQL, - // because they are item attributes rather than columns. Equality - // only, which is all the wire surface admits today. + // because they are item attributes rather than columns: the + // equality pairs first, then the item filter for the + // conditions the pairs cannot express. if !filters.is_empty() && !filters .iter() diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 7241b90ff..6dd949889 100755 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -194,8 +194,9 @@ pub struct VectorSearch<'a> { /// Every other condition of a search condition, a range, `IN`, `OR`, /// `NOT`, a function or a Number equality, arrives as `item_filter`. pub filters: &'a [(&'a str, &'a AttributeValue)], - /// A condition each candidate must satisfy before it is ranked, for a - /// search condition that `filters` cannot express. `None` means no + /// A condition each returned item must satisfy, for a search condition + /// that `filters` cannot express; the `top_k` cut applies to the items + /// that satisfy it. `None` means no /// condition beyond `hash_key` and `filters`. See [`VectorItemFilter`]. pub item_filter: Option>, } diff --git a/crates/storage/src/vector_filter.rs b/crates/storage/src/vector_filter.rs index cdeaa66e6..366d09bdb 100644 --- a/crates/storage/src/vector_filter.rs +++ b/crates/storage/src/vector_filter.rs @@ -5,8 +5,11 @@ //! //! The engine parses and validates a search condition, and a backend only //! evaluates it. A backend that serves vector search calls -//! [`VectorItemFilter::matches`] on each candidate before ranking it, so the -//! `top_k` cut applies to matching items only. +//! [`VectorItemFilter::matches`] on candidates and keeps only the items that +//! match, so the `top_k` cut applies to matching items only. SQLite calls it +//! on each candidate before scoring it. PostgreSQL ranks the candidates in +//! SQL and calls it on the rows in score order, page by page, until `top_k` +//! rows match. //! //! The engine sets [`crate::VectorSearch::item_filter`] only for a condition //! that the equality pairs of [`crate::VectorSearch::filters`] cannot express. diff --git a/docs/adr/0006-pgvector-storage-and-scoring.md b/docs/adr/0006-pgvector-storage-and-scoring.md index 938858fb4..0e0d7642c 100644 --- a/docs/adr/0006-pgvector-storage-and-scoring.md +++ b/docs/adr/0006-pgvector-storage-and-scoring.md @@ -58,6 +58,12 @@ exact path is verified would make a recall regression indistinguishable from a scan defect. The partition predicate and the inline filters are evaluated in SQL so that `LIMIT` applies after filtering rather than before. +Amended with ADR-0030: the partition predicate and the inline-filter equalities +are still evaluated in SQL. A search condition they cannot express, a range, +`IN`, `OR`, `NOT`, a function or a Number equality, is evaluated in ExtendDB on +the rows the SQL returns in score order, page by page, until `top_k` rows match, +so `top_k` still applies after filtering. + **4. A score that PostgreSQL cannot compute is bounded in SQL, not in Rust.** pgvector accumulates distances in single precision, so for vectors of ordinary diff --git a/docs/adr/0030-search-condition-grammar.md b/docs/adr/0030-search-condition-grammar.md index 22014f0de..37aced602 100644 --- a/docs/adr/0030-search-condition-grammar.md +++ b/docs/adr/0030-search-condition-grammar.md @@ -56,7 +56,8 @@ Option 2: the grammar has its own lexer, grammar and checks in `search-inequality-filters` Cargo feature and the `search_inequality_filters` runtime setting (default `all`); a condition the equality pairs cannot express reaches the backend as `VectorSearch::item_filter`, which the backend calls on -each candidate; SearchVectors sets no `dynamodb:Attributes` value. +candidates to keep the first `top_k` that match (SQLite on each candidate, +PostgreSQL on the rows its SQL returns in score order, page by page); SearchVectors sets no `dynamodb:Attributes` value. ## Rationale From d5086471bfdbc6571f29c952d4dffaef643e0a8b Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 07:54:10 +0000 Subject: [PATCH 092/101] docs(search): list every SearchVectors answer the grammar change moves The upgrade note covered the new forms and the Number comparison. It left out answers that also change for an upgraded client: names outside [A-Za-z0-9_] or starting with a digit or _ without ExpressionAttributeNames, whitespace other than space, tab, CR and LF, a condition longer than 4096 bytes, an ExpressionAttributeValues key longer than 255 bytes, a malformed ProjectionExpression answering ahead of the table, index and dimension checks, and the backend refusal ahead of the IAM decision. DynamoDB answers each of these as this release does (measured in eu-north-1, each request twice). It also said that an AND of string equalities never reads the setting and that every Number in the condition compares as binary64, and the usage guide said the setting limits only conditions other than an AND of equalities. The note now lists those answers, says which searches read the setting and that the HASH equality on a Number compares exactly, and names the error ServiceUnavailable (HTTP 503) as the admin guide row now does. The usage guide states what a condition is without the grammar. --- docs/manuals/03-usage-guide.md | 6 ++++-- docs/manuals/05-admin-guide.md | 2 +- docs/manuals/07-upgrade-manual.md | 18 ++++++++++++------ 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/docs/manuals/03-usage-guide.md b/docs/manuals/03-usage-guide.md index 983efbbd0..559844eb7 100755 --- a/docs/manuals/03-usage-guide.md +++ b/docs/manuals/03-usage-guide.md @@ -439,8 +439,10 @@ to 50 conditions, one `=` on the index's HASH attribute among them. A condition an inline filter attribute takes `=`, `<>`, `<`, `<=`, `>`, `>=`, `BETWEEN`, `IN`, `attribute_exists` or `attribute_not_exists`, and conditions combine with `AND`, `OR`, `NOT` and parentheses. The -`search_inequality_filters` runtime setting can limit the conditions other than -an AND of equalities to a list of accounts, or turn them off. +`search_inequality_filters` runtime setting can limit this grammar to a list of +accounts, or turn it off. Without it, a condition is an AND of at most 19 +equalities, one per attribute, each written as `attribute = :value`, and a Number +compares exactly. Four things are worth knowing before building on it. diff --git a/docs/manuals/05-admin-guide.md b/docs/manuals/05-admin-guide.md index af5d30d11..7002c2357 100755 --- a/docs/manuals/05-admin-guide.md +++ b/docs/manuals/05-admin-guide.md @@ -326,7 +326,7 @@ Managed via `extenddb settings set`. Changes take effect within 30 seconds witho | `log_level` | `info` | Log level: trace, debug, info, warn, error | | `control_plane_delay_seconds` | `0.25` | Delay for table status transitions, in seconds (0 = instant). PostgreSQL and SQLite write 0.25 into the catalog when it is created; MongoDB and Cassandra use 0.25 when the setting is absent. On PostgreSQL and SQLite a value below 1 makes DeleteTable remove the table in the request; on PostgreSQL, if a session holds a lock on the table's data (a reader, an open write transaction, an index build), DeleteTable returns `DELETING` instead (after at most about a second), the drop finishes in the background within about a second of that session's release, and a CreateTable of the same name is refused until then. | | `allow_credential_import` | `false` | Whether `import-access-key` is allowed. Only `true` enables it | -| `search_inequality_filters` | every account | The accounts whose `SearchVectors` requests accept the extended `SearchConditionExpression` grammar, which DynamoDB accepts on the accounts and regions measured (us-east-1, eu-north-1, ap-southeast-2): `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. A malformed value in the catalog, which the CLI and the management API refuse to write, is no account. With `off`, or for an account the list does not name, a search condition is an AND of equalities. A server reads the setting only for a search whose answer depends on the grammar, and at most once a second, so a change applies within about a second without a restart. When a read fails or does not end within two seconds, the server uses the value of its last read that answered; before any read has answered, such a search answers `ServiceUnavailableException` | +| `search_inequality_filters` | every account | The accounts whose `SearchVectors` requests accept the extended `SearchConditionExpression` grammar, which DynamoDB accepts on the accounts and regions measured (us-east-1, eu-north-1, ap-southeast-2): `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. A malformed value in the catalog, which the CLI and the management API refuse to write, is no account. With `off`, or for an account the list does not name, a search condition is an AND of equalities. A server reads the setting only for a search whose answer depends on the grammar, and at most once a second, so a change applies within about a second without a restart. When a read fails or does not end within two seconds, the server uses the value of its last read that answered; before any read has answered, such a search answers `ServiceUnavailable` (HTTP 503). The [upgrade manual](07-upgrade-manual.md) says which searches read it | | `vector_backfill_batch_delay_ms` | `0` | **Test-oriented.** Milliseconds to pause between batches while a vector index backfills. Zero in production. A test sets it so a write is guaranteed to land while the index is still building. The pause is outside the batch transaction, so writes are still accepted throughout, but it does extend the per-table propagation hold: no index on that table advances while the build runs, GSIs included, and the accepted range goes up to 60 s per batch. | | `vector_allocation_phase_delay_ms` | `0` | **Test-oriented.** Milliseconds to hold a new vector index in the resource-allocation phase (`CREATING` with `Backfilling: false`) before the scan starts. Zero in production. Without it the phase lasts only from the `UpdateTable` transaction, which inserts the row as `CREATING` with `Backfilling: false`, until the detached build task flips the flag, which is a window no client can time reliably rather than one that cannot exist. | diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 9eec107bf..42bf54ddd 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -390,23 +390,29 @@ deployment, even when no catalog migration is required. ### v1.1.0: SearchVectors serves the extended `SearchConditionExpression` grammar -**What changed.** A `SearchConditionExpression` takes the comparators `<>`, `<`, `<=`, `>` and `>=`, `BETWEEN`, `IN`, `OR`, `NOT`, parentheses, `attribute_exists` and `attribute_not_exists`, and more than one condition on an attribute, up to 50 conditions. DynamoDB accepts this grammar on the accounts and regions measured (us-east-1, eu-north-1, ap-southeast-2), although its API reference documents only `=`. Earlier releases accepted only an AND of equalities, at most 19, and refused the other forms with `ValidationException`. A Number in the condition now compares as the nearest binary64 value of each side, as on DynamoDB, so `9007199254740992` and `9007199254740993` are equal. Earlier releases compared Numbers in the condition exactly. +**What changed.** A `SearchConditionExpression` takes the comparators `<>`, `<`, `<=`, `>` and `>=`, `BETWEEN`, `IN`, `OR`, `NOT`, parentheses, `attribute_exists` and `attribute_not_exists`, and more than one condition on an attribute, up to 50 conditions. DynamoDB accepts this grammar on the accounts and regions measured (us-east-1, eu-north-1, ap-southeast-2), although its API reference documents only `=`. Earlier releases accepted only an AND of equalities, at most 19, and refused the other forms with `ValidationException`. A Number in a condition on an inline filter attribute now compares as the nearest binary64 value of each side, as on DynamoDB, so `9007199254740992` and `9007199254740993` are equal. The equality on a Number HASH attribute still compares exactly, as on DynamoDB: with an item whose HASH attribute and inline filter attribute are both `9007199254740992`, the HASH equality with `9007199254740993` returns no item, and the inline filter equality with `9007199254740993` returns it. Earlier releases compared every Number in the condition exactly. -The `search_inequality_filters` runtime setting selects the accounts that get the grammar: `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. With `off`, or for an account the list does not name, a search condition is an AND of equalities, compared as in earlier releases. A server reads the setting only for a search whose answer depends on the grammar, such as an inequality or a condition on a Number, and at most once a second, so a change applies within about a second without a restart. A search that both grammars answer alike, such as an AND of string equalities, never reads it. When a read fails or does not end within two seconds, the server uses the value of its last read that answered; before any read has answered, such a search answers `ServiceUnavailableException`. A malformed value in the catalog, which the CLI and the management API refuse to write, is logged once per change and enables no account. The [admin guide](05-admin-guide.md) lists the setting. +The `search_inequality_filters` runtime setting selects the accounts that get the grammar: `all`, `off`, or a comma-separated list of 12-digit account IDs. An absent or empty value is every account. With `off`, or for an account the list does not name, a search condition is an AND of equalities, compared as in earlier releases. A server reads the setting only for a search whose answer depends on the grammar, and at most once a second, so a change applies within about a second without a restart. A search depends on the grammar when one grammar refuses its condition and the other accepts it or refuses it with another message, or when both accept it and would give the backend different searches. An AND of equalities on String and Binary attributes, at most 19 and written as earlier releases accepted them, never reads it. Other ANDs of equalities do: one on a Number inline filter attribute, one in parentheses such as `(Country = :c) AND Cat = :s`, one with the value first such as `:s = Cat`, one with an attribute twice, and one of 20 or more conditions. Earlier releases refused all of these but the first, and an account the setting leaves out gets those refusals. When a read fails or does not end within two seconds, the server uses the value of its last read that answered; before any read has answered, such a search answers `ServiceUnavailable` (HTTP 503), which the AWS SDKs retry. A malformed value in the catalog, which the CLI and the management API refuse to write, is logged once per change and enables no account. The [admin guide](05-admin-guide.md) lists the setting. -**Who is affected.** A client that sent one of these forms got `ValidationException` and now gets the items the condition selects. A client whose condition compares Numbers that differ only after the 15th significant digit can get other items. To keep the earlier grammar, run `extenddb settings --config extenddb.toml set search_inequality_filters off` after the upgrade. MongoDB and Cassandra refuse SearchVectors, as before. No catalog migration is required. +For an account that gets the grammar, these requests that earlier releases served are now refused, as DynamoDB refuses them (measured 2026-11-25 in eu-north-1, each request twice): + +- A condition on an inline filter attribute whose name has a character outside `[A-Za-z0-9_]`, or starts with a digit or `_`, written without `ExpressionAttributeNames`: `Country = :c AND cat-x = :a` answers `Invalid SearchConditionExpression: Syntax error; token: "-", near: "cat-x"`, and `Catégorie`, `_cat` and `9lives` get the same kind of error. Through `ExpressionAttributeNames` the same names are served. +- Whitespace other than space, tab, CR and LF between tokens: a form feed, a vertical tab, U+00A0 or U+2003 answers a syntax error. +- A condition longer than 4096 bytes answers `Invalid SearchConditionExpression: Expression size has exceeded the maximum allowed size;`. + +**Who is affected.** A client that sent one of the new forms got `ValidationException` and now gets the items the condition selects. A client whose condition compares Numbers on an inline filter attribute that differ only after the 15th significant digit can get other items. A client that sent one of the refused forms above gets `ValidationException`. To keep the earlier grammar, run `extenddb settings --config extenddb.toml set search_inequality_filters off` after the upgrade; under `off` the requests above are served as before, and a search that depends on the grammar still reads the setting, so before any read has answered it can answer `ServiceUnavailable`. A build without the `search-inequality-filters` Cargo feature reads no setting. MongoDB and Cassandra refuse SearchVectors, as before, now ahead of the IAM decision (see below). No catalog migration is required. ### v1.1.0: SearchVectors refuses a malformed `ExpressionAttributeNames` map -**What changed.** SearchVectors refuses an `ExpressionAttributeNames` key that is not `#` followed by letters, digits and underscores, such as `n` or `##n`, with `ValidationException` `ExpressionAttributeNames contains invalid key: Syntax error; key: "n"`. It also refuses an empty map, a key longer than 255 bytes and an empty attribute name, with the messages GetItem gives. SearchVectors also refuses an empty key, an attribute name of 65536 bytes or more, an empty `ExpressionAttributeValues` map or a malformed key in it, either map without an expression that reads it, and a name that no expression uses. An empty attribute name or a name of 65536 bytes or more answers ahead of a bad key. These checks run after the `IndexName`, `SearchVector` and `TopK` checks and ahead of the table lookup. DynamoDB answers SearchVectors with the same messages in the same order. It answered an `IndexName` of two characters, an empty `SearchVector` and a `TopK` of 0 ahead of a bad key (measured 2026-11-21), and an empty or a too large attribute name ahead of a bad key (measured 2026-11-24). Earlier releases served such requests: a search with `ProjectionExpression` `#n` and the key `n` or `##n` returned the attribute the key named. `dynamodb:Attributes` did not hold that attribute, so a `Deny` on it did not refuse the search. +**What changed.** SearchVectors refuses an `ExpressionAttributeNames` key that is not `#` followed by letters, digits and underscores, such as `n` or `##n`, with `ValidationException` `ExpressionAttributeNames contains invalid key: Syntax error; key: "n"`. It also refuses an empty map, a key longer than 255 bytes and an empty attribute name, with the messages GetItem gives. SearchVectors also refuses an empty key, an `ExpressionAttributeValues` key longer than 255 bytes (`ExpressionAttributeValues contains invalid key: The expression attribute map contains a key that is too long;`, where earlier releases served a search with two 2102-byte keys), an attribute name of 65536 bytes or more, an empty `ExpressionAttributeValues` map or a malformed key in it, either map without an expression that reads it, and a name that no expression uses. An empty attribute name or a name of 65536 bytes or more answers ahead of a bad key. These checks run after the `IndexName`, `SearchVector` and `TopK` checks and ahead of the table lookup. DynamoDB answers SearchVectors with the same messages in the same order. It answered an `IndexName` of two characters, an empty `SearchVector` and a `TopK` of 0 ahead of a bad key (measured 2026-11-21), and an empty or a too large attribute name ahead of a bad key (measured 2026-11-24). Earlier releases served such requests: a search with `ProjectionExpression` `#n` and the key `n` or `##n` returned the attribute the key named. `dynamodb:Attributes` did not hold that attribute, so a `Deny` on it did not refuse the search. **Who is affected.** A client that sends SearchVectors with such a map gets `ValidationException`, as it does on the other operations that take the map. No catalog migration is required. ### v1.1.0: SearchVectors sets no `dynamodb:Attributes` value and checks its request before the policy -**What changed.** A `SearchVectors` request carries no `dynamodb:Attributes` value, whatever its `ProjectionExpression` and `SearchConditionExpression` name, as on DynamoDB. Earlier releases put the attributes in `ProjectionExpression` in the key. SearchVectors also makes the checks that need no table, of the request body, `IndexName`, `SearchVector`, `TopK`, the expression maps, `ProjectionExpression` and `SearchConditionExpression`, before the IAM decision, as DynamoDB does. A table name outside the pattern `[a-zA-Z0-9_.-]+` answers first, and no length check applies to the table name. Earlier releases made the IAM decision first. +**What changed.** A `SearchVectors` request carries no `dynamodb:Attributes` value, whatever its `ProjectionExpression` and `SearchConditionExpression` name, as on DynamoDB. Earlier releases put the attributes in `ProjectionExpression` in the key. SearchVectors also makes the checks that need no table, of the request body, `IndexName`, `SearchVector`, `TopK`, the expression maps, `ProjectionExpression` and `SearchConditionExpression`, before the IAM decision, as DynamoDB does. A table name outside the pattern `[a-zA-Z0-9_.-]+` answers first, and no length check applies to the table name. Earlier releases made the IAM decision first. Under every setting, a build without the feature included, a malformed `ProjectionExpression` now answers ahead of a missing table, a missing index and a `SearchVector` of the wrong dimension, as on DynamoDB (measured 2026-11-25 in eu-north-1, each request twice): `ProjectionExpression` `id,,Cat` on a missing table answers `Invalid ProjectionExpression` where earlier releases answered `ResourceNotFoundException`, `#nope` with no such name and `IndexName` `nope` answers that the name is not defined where they answered `The table does not have the specified index: nope`, and the reserved word `bucket` with a 2-element vector on a 4-dimension index answers `Attribute name is a reserved keyword; reserved keyword: bucket` where they answered `Input search vector dimension 2 does not match vector index dimension 4`. On a backend without vector search (MongoDB, Cassandra, and PostgreSQL without pgvector), the refusal `SearchVectors is not supported by this storage backend` also comes before the IAM decision. -**Who is affected.** A deployment with a policy that gates `SearchVectors` on `dynamodb:Attributes`. A `Deny` on an attribute no longer refuses a search that projects it, and a `Deny` gated on `Null` `true` refuses every search, a projected one included. DynamoDB answers both the same way (measured 2026-11-21). An `Allow` gated on `ForAllValues` now grants every search its `Action` covers, because the key is absent. A bare negated operator over the key, such as `StringNotEquals` `{"dynamodb:Attributes": "x"}`, now matches every search, as IAM matches one on an absent key: a `Deny` gated on it refuses every search, a projected one included, and an `Allow` gated on it grants every search its `Action` covers. Earlier releases matched it on no search. This answer follows from the two measurements above and was not sent to DynamoDB under such a policy. A caller that a policy denies and that sends a request failing one of the checks gets `ValidationException` where it got `AccessDeniedException`. No catalog migration is required. +**Who is affected.** A deployment with a policy that gates `SearchVectors` on `dynamodb:Attributes`. A `Deny` on an attribute no longer refuses a search that projects it, and a `Deny` gated on `Null` `true` refuses every search, a projected one included. DynamoDB answers both the same way (measured 2026-11-21). An `Allow` gated on `ForAllValues` now grants every search its `Action` covers, because the key is absent. A bare negated operator over the key, such as `StringNotEquals` `{"dynamodb:Attributes": "x"}`, now matches every search, as IAM matches one on an absent key: a `Deny` gated on it refuses every search, a projected one included, and an `Allow` gated on it grants every search its `Action` covers. Earlier releases matched it on no search. This answer follows from the two measurements above and was not sent to DynamoDB under such a policy. A caller that a policy denies and that sends a request failing one of the checks gets `ValidationException` where it got `AccessDeniedException`, and on a backend without vector search a denied caller gets that refusal where it got `AccessDeniedException`. No catalog migration is required. ### v1.0.0: Cassandra reads and writes at `LOCAL_QUORUM` From a56efa8c41e93b3f9ce49f60a338b20c25d5b3ac Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 08:00:20 +0000 Subject: [PATCH 093/101] test(server): read the SearchVectors segments of a new account when it has none /metrics leaves out `segments` when no entry exists, so the metrics test failed with a KeyError on the first read, before any search. The test now counts no entry as zero. --- tests/test_search_vectors_metrics.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_search_vectors_metrics.py b/tests/test_search_vectors_metrics.py index 447225280..701717298 100644 --- a/tests/test_search_vectors_metrics.py +++ b/tests/test_search_vectors_metrics.py @@ -60,8 +60,11 @@ def _segment_count(env: tuple[str, str, str], account_id: str) -> int: verify=False, ) assert resp.status_code == 200, f"/metrics: {resp.status_code} {resp.text[:200]}" + # The response leaves out `segments` when it has no entry. return sum( - s["count"] for s in resp.json()["segments"] if s["operation"] == "SearchVectors" + s["count"] + for s in resp.json().get("segments", []) + if s["operation"] == "SearchVectors" ) From df895be2a6dd9bb96b33445113b8cf9bd2cf649e Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 09:26:59 +0000 Subject: [PATCH 094/101] docs(adr): number the search condition grammar decision 0031 The search condition grammar decision was numbered 0030, a number another open change already gives to the optional allocator decision. It is now ADR-0031: the file name, its title, the index row and the amendment line of ADR-0006 name 0031. Verified with git grep: no file names ADR-0030 or the old file name. --- docs/adr/0006-pgvector-storage-and-scoring.md | 2 +- ...ch-condition-grammar.md => 0031-search-condition-grammar.md} | 2 +- docs/adr/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename docs/adr/{0030-search-condition-grammar.md => 0031-search-condition-grammar.md} (98%) diff --git a/docs/adr/0006-pgvector-storage-and-scoring.md b/docs/adr/0006-pgvector-storage-and-scoring.md index 0e0d7642c..9f109ed73 100644 --- a/docs/adr/0006-pgvector-storage-and-scoring.md +++ b/docs/adr/0006-pgvector-storage-and-scoring.md @@ -58,7 +58,7 @@ exact path is verified would make a recall regression indistinguishable from a scan defect. The partition predicate and the inline filters are evaluated in SQL so that `LIMIT` applies after filtering rather than before. -Amended with ADR-0030: the partition predicate and the inline-filter equalities +Amended with ADR-0031: the partition predicate and the inline-filter equalities are still evaluated in SQL. A search condition they cannot express, a range, `IN`, `OR`, `NOT`, a function or a Number equality, is evaluated in ExtendDB on the rows the SQL returns in score order, page by page, until `top_k` rows match, diff --git a/docs/adr/0030-search-condition-grammar.md b/docs/adr/0031-search-condition-grammar.md similarity index 98% rename from docs/adr/0030-search-condition-grammar.md rename to docs/adr/0031-search-condition-grammar.md index 37aced602..ee3d4e314 100644 --- a/docs/adr/0030-search-condition-grammar.md +++ b/docs/adr/0031-search-condition-grammar.md @@ -1,4 +1,4 @@ -# ADR-0030: SearchVectors serves the extended search condition grammar from its own parser, behind a feature and a setting +# ADR-0031: SearchVectors serves the extended search condition grammar from its own parser, behind a feature and a setting - Status: Proposed - Date: 2026-11-25 diff --git a/docs/adr/README.md b/docs/adr/README.md index 76cb8a42e..d7d13b1ef 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -55,7 +55,7 @@ decision, write a new ADR. | [0026](0026-credential-crypto-on-aws-lc.md) | Credential cryptography uses AWS-LC through aws-lc-rs | Accepted | | [0027](0027-cassandra-index-row-version-stamps.md) | Cassandra: index rows carry the base-row version as their write timestamp | Accepted | | [0029](0029-crates-io-packaging.md) | The workspace crates go to crates.io together, at one version with exact pins | Accepted | -| [0030](0030-search-condition-grammar.md) | SearchVectors serves the extended search condition grammar from its own parser, behind a feature and a setting | Proposed | +| [0031](0031-search-condition-grammar.md) | SearchVectors serves the extended search condition grammar from its own parser, behind a feature and a setting | Proposed | --- From bc19a591c3ef476356b3c51e978b6fe203adbfa7 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 09:26:59 +0000 Subject: [PATCH 095/101] docs(upgrade): list the unused-name answer to a parenthesised name DynamoDB returns the selected items for `Country = :c AND (#k) = :s` and `(#h) = :c AND (Cat) = :s` (eu-north-1, each request twice). Under `off`, for an account the setting leaves out, and in a build without the search-inequality-filters feature, ExtendDB now answers both with `Value provided in ExpressionAttributeNames unused in expressions`, naming `#k` or `#h`. Earlier releases answered `Invalid attribute: (#k)` and the HASH attribute message. Both are 400s, and the upgrade manual did not list the change. The expression map entry of the upgrade manual now states it. Verified on release SQLite servers, each request twice: main, the tip under `off` and the tip with the feature compiled out give the answers above, and the tip with the setting absent returns the item. --- docs/manuals/07-upgrade-manual.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/manuals/07-upgrade-manual.md b/docs/manuals/07-upgrade-manual.md index 42bf54ddd..2b45b800e 100755 --- a/docs/manuals/07-upgrade-manual.md +++ b/docs/manuals/07-upgrade-manual.md @@ -406,6 +406,8 @@ For an account that gets the grammar, these requests that earlier releases serve **What changed.** SearchVectors refuses an `ExpressionAttributeNames` key that is not `#` followed by letters, digits and underscores, such as `n` or `##n`, with `ValidationException` `ExpressionAttributeNames contains invalid key: Syntax error; key: "n"`. It also refuses an empty map, a key longer than 255 bytes and an empty attribute name, with the messages GetItem gives. SearchVectors also refuses an empty key, an `ExpressionAttributeValues` key longer than 255 bytes (`ExpressionAttributeValues contains invalid key: The expression attribute map contains a key that is too long;`, where earlier releases served a search with two 2102-byte keys), an attribute name of 65536 bytes or more, an empty `ExpressionAttributeValues` map or a malformed key in it, either map without an expression that reads it, and a name that no expression uses. An empty attribute name or a name of 65536 bytes or more answers ahead of a bad key. These checks run after the `IndexName`, `SearchVector` and `TopK` checks and ahead of the table lookup. DynamoDB answers SearchVectors with the same messages in the same order. It answered an `IndexName` of two characters, an empty `SearchVector` and a `TopK` of 0 ahead of a bad key (measured 2026-11-21), and an empty or a too large attribute name ahead of a bad key (measured 2026-11-24). Earlier releases served such requests: a search with `ProjectionExpression` `#n` and the key `n` or `##n` returned the attribute the key named. `dynamodb:Attributes` did not hold that attribute, so a `Deny` on it did not refuse the search. +Under `off`, for an account the setting leaves out, and in a build without the `search-inequality-filters` Cargo feature, a name written only inside parentheses in the `SearchConditionExpression` counts as unused. `Country = :c AND (#k) = :s` with `#k` naming `Cat` answers `Value provided in ExpressionAttributeNames unused in expressions: keys: {#k}`, where earlier releases answered `SearchConditionExpression must not contain any attributes that is not in SearchSchema. Invalid attribute: (#k)`. `(#h) = :c AND (Cat) = :s` with `#h` naming the HASH attribute answers the same message for `#h`, where earlier releases answered `SearchConditionExpression must have all HASH attributes in configured SearchSchema`. Both answers are `ValidationException`. With the extended grammar both searches return the items they select, as on DynamoDB (measured 2026-11-25 in eu-north-1, each request twice). + **Who is affected.** A client that sends SearchVectors with such a map gets `ValidationException`, as it does on the other operations that take the map. No catalog migration is required. ### v1.1.0: SearchVectors sets no `dynamodb:Attributes` value and checks its request before the policy From d1b8b312012f3273ea109387a3b0ccfb02d022be Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 17:17:33 +0000 Subject: [PATCH 096/101] fix(server): record a failed SearchVectors check into the bucketed segments When a SearchVectors request fails a check that runs before authorization, the server records the error, the request count and one latency segment entry, as it does for an error from the engine. Main now sums segments into fixed time buckets per account and operation, and record_segments no longer takes a table name. The pre-authorization path still passed the table name and the segments by value, so the merged tree did not build. The call now passes the segments by reference without the table name, as the dispatch path does, so the failure lands in the same buckets as every other request. Verified with the workspace build and with the SearchVectors metrics wire tests on SQLite and PostgreSQL. --- crates/server/src/handler.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/server/src/handler.rs b/crates/server/src/handler.rs index 2b4f91186..cac42ed59 100755 --- a/crates/server/src/handler.rs +++ b/crates/server/src/handler.rs @@ -176,8 +176,7 @@ pub(crate) async fn handle_request( state.metrics.record_segments( &account_id, &operation, - metric_table.as_deref(), - extenddb_core::metrics::LatencySegments { + &extenddb_core::metrics::LatencySegments { auth_us, authz_us: 0.0, throttle_us: 0.0, From 85cca829132f47b60f737cd25c031c2b188e4312 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 20:27:05 +0000 Subject: [PATCH 097/101] test(core): count a substituted name at each of its uses in the search size DynamoDB counts a name in ExpressionAttributeNames at each use when it sizes a SearchConditionExpression with its substitutions. One 65,533-byte name `#x0` in 17 conditions `#x0 = :s AND ...` (1,114,277 bytes) answers "Invalid SearchConditionExpression: Expression size has exceeded the maximum allowed size;", and in 15 conditions (983,185 bytes) answers ResourceNotFoundException on a table name that does not exist (us-east-1, 2026-11-25, each request twice with the same answer). ExtendDB already multiplied each name by its uses, but no test used a name more than once, so dropping the multiplication passed every test. This adds the two measured requests as rows: a core test of parse_search_filter and an engine test on a missing table, which also pins that the size check answers ahead of the table lookup. Verified: with `* uses` removed from the name sum, both new tests fail and the existing tests pass. --- .../search_filter/tests_operands.rs | 34 ++++++++++++++++++- .../engine/src/search_vectors_order_tests.rs | 34 ++++++++++++++++++- 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/crates/core/src/expression/search_filter/tests_operands.rs b/crates/core/src/expression/search_filter/tests_operands.rs index 56227db32..29c8e8746 100644 --- a/crates/core/src/expression/search_filter/tests_operands.rs +++ b/crates/core/src/expression/search_filter/tests_operands.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; use super::parse_search_filter; -use super::tests_support::{OK, n, p, s, used_values}; +use super::tests_support::{OK, message, n, p, s, used_values}; use crate::error::DynamoDbError; use crate::types::AttributeValue; @@ -291,6 +291,38 @@ fn the_combined_size_is_at_most_one_mebibyte() { } } +/// A name is counted at each of its uses. One 65,533-byte name `#x0` in +/// `#x0 = :s AND ...`: 17 conditions take 216 + 17 * 65,533 = 1,114,277 +/// bytes and 15 conditions 190 + 15 * 65,533 = 983,185. Measured on the live +/// service in us-east-1 on 2026-11-25 on a table name that does not exist, +/// each request twice with the same answer: 17 conditions answer the size +/// refusal and 15 answer ResourceNotFoundException, the answer of the table +/// lookup that follows a condition that passes. +#[test] +fn the_combined_size_counts_a_name_at_each_use() { + let names = HashMap::from([("#x0".to_owned(), "x".repeat(65_533))]); + let values = HashMap::from([(":s".to_owned(), s("US"))]); + for (conditions, served) in [(17, false), (15, true)] { + let expr = vec!["#x0 = :s"; conditions].join(" AND "); + let got = parse_search_filter( + &expr, + Some(&names), + Some(&values), + 50, + &crate::limits::LimitsConfig::default(), + ); + if served { + assert!(got.is_ok(), "{conditions}: {:?}", got.err()); + } else { + assert_eq!( + got.err().map(message), + Some(p("Expression size has exceeded the maximum allowed size;")), + "{conditions}" + ); + } + } +} + /// A function given the wrong number of operands, a function an update /// takes, and String bounds out of order. Measured on the service in /// eu-north-1 on 2026-11-25, each request twice, with the HASH equality diff --git a/crates/engine/src/search_vectors_order_tests.rs b/crates/engine/src/search_vectors_order_tests.rs index e36b754a6..43a569c37 100644 --- a/crates/engine/src/search_vectors_order_tests.rs +++ b/crates/engine/src/search_vectors_order_tests.rs @@ -8,7 +8,8 @@ //! `ExpressionAttributeValues` or `ExpressionAttributeNames` answers //! " must not be empty" against a missing table and with a two-element //! `SearchVector` on a four-dimension index; with valid maps the same -//! requests answer ResourceNotFoundException and the dimension message. +//! requests answer ResourceNotFoundException and the dimension message. The +//! combined size check answers ahead of a missing table too. use std::time::Duration; @@ -162,3 +163,34 @@ async fn an_empty_map_answers_before_a_dimension_mismatch() { "{mismatch:?}" ); } + +/// The combined size of the condition and its substitutions counts a name at +/// each use, and answers ahead of the table lookup. Measured on DynamoDB in +/// us-east-1 on 2026-11-25 on a table name that does not exist, each request +/// twice with the same answer: one 65,533-byte name `#x0` in 17 conditions +/// `#x0 = :s AND ...` (1,114,277 bytes) answers the size refusal, and in 15 +/// conditions (983,185 bytes) ResourceNotFoundException. +#[tokio::test] +async fn the_size_counts_a_name_at_each_use_before_a_missing_table() { + let dir = TempDir::new().unwrap(); + let ctx = context(&dir).await; + let body = |conditions: usize| { + let mut body = request("missing", 4, us(), Some(json!({"#x0": "x".repeat(65_533)}))); + body["ExpressionAttributeValues"] = json!({":s": {"S": "US"}}); + body["SearchConditionExpression"] = json!(vec!["#x0 = :s"; conditions].join(" AND ")); + body + }; + let refused = answer(&ctx, body(17)).await; + assert!( + validation( + "Invalid SearchConditionExpression: Expression size has exceeded the maximum \ + allowed size;" + )(&refused), + "{refused:?}" + ); + let missing = answer(&ctx, body(15)).await; + assert!( + matches!(missing, DynamoDbError::ResourceNotFoundException(_)), + "{missing:?}" + ); +} From a3a9533d6e2e54464d3e78f7e39083e7542dd297 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 20:27:05 +0000 Subject: [PATCH 098/101] fix(core): saturate the combined size of a search condition The combined size of a SearchConditionExpression and its substitutions, counted at each use, is at most 1,048,576 bytes. ExtendDB summed each substitution's size times its uses in plain `usize` arithmetic. On a 32-bit target, the browser build, a 4 MiB value used 1,024 times (ten IN lists of 100 operands and one of 24, inside the expression, operator and condition limits) adds exactly 2^32 bytes, which wraps to 0 in a release build and passes the check. The products and sums now saturate, so such a request answers the size refusal on every target. A new test sends that request; it runs natively and, on wasm32 under Node, in the core step of devtools/run-wasm-step, which now lists it. Verified: on wasm32 the test fails with the plain arithmetic restored and passes with this change; natively it passes with either, since a 64-bit `usize` does not wrap at that size. --- .../search_filter/tests_operands.rs | 31 +++++++++++++++++++ .../core/src/expression/search_filter/walk.rs | 18 ++++++----- devtools/run-wasm-step | 7 +++-- 3 files changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/core/src/expression/search_filter/tests_operands.rs b/crates/core/src/expression/search_filter/tests_operands.rs index 29c8e8746..f7ef35e0a 100644 --- a/crates/core/src/expression/search_filter/tests_operands.rs +++ b/crates/core/src/expression/search_filter/tests_operands.rs @@ -323,6 +323,37 @@ fn the_combined_size_counts_a_name_at_each_use() { } } +/// A 4 MiB value used 1,024 times adds 2^32 bytes, which a 32-bit `usize` +/// cannot hold: the sum saturates instead of wrapping to 0. The uses are ten +/// `IN` lists of 100 operands and one of 24, inside the 4,096-byte, operator +/// and condition limits. Runs as a native `#[test]` and, on `wasm32`, where +/// `usize` is 32 bits, as a `wasm_bindgen_test` under Node. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn the_combined_size_saturates_instead_of_wrapping() { + let list = |uses: usize| format!("a IN ({})", vec![":v"; uses].join(",")); + let mut conditions = vec!["Country = :h".to_owned()]; + conditions.extend((0..10).map(|_| list(100))); + conditions.push(list(24)); + let expr = conditions.join(" AND "); + assert!(expr.len() <= 4_096, "{}", expr.len()); + let values = HashMap::from([ + (":h".to_owned(), s("US")), + (":v".to_owned(), s(&"x".repeat(4 << 20))), + ]); + let got = parse_search_filter( + &expr, + None, + Some(&values), + 50, + &crate::limits::LimitsConfig::default(), + ); + assert_eq!( + got.err().map(message), + Some(p("Expression size has exceeded the maximum allowed size;")) + ); +} + /// A function given the wrong number of operands, a function an update /// takes, and String bounds out of order. Measured on the service in /// eu-north-1 on 2026-11-25, each request twice, with the HASH equality diff --git a/crates/core/src/expression/search_filter/walk.rs b/crates/core/src/expression/search_filter/walk.rs index c80c1b1b3..5a7934afc 100644 --- a/crates/core/src/expression/search_filter/walk.rs +++ b/crates/core/src/expression/search_filter/walk.rs @@ -445,13 +445,15 @@ pub(super) fn combined_bytes(src: &str, node: &Node, maps: &Maps<'_>) -> usize { }, |_| {}, ); - let names: usize = names + // Saturating: on a 32-bit target a 4 MiB value used 1,024 times is 2^32 + // bytes, which plain arithmetic would wrap to 0. + let names = names.into_iter().fold(0usize, |sum, (n, uses)| { + sum.saturating_add(maps.name(n).map_or(0, str::len).saturating_mul(uses)) + }); + values .into_iter() - .map(|(n, uses)| maps.name(n).map_or(0, str::len) * uses) - .sum(); - let values: usize = values - .into_iter() - .map(|(v, uses)| maps.value(v).map_or(0, crate::types::attribute_value_size) * uses) - .sum(); - src.len() + names + values + .fold(src.len().saturating_add(names), |sum, (v, uses)| { + let size = maps.value(v).map_or(0, crate::types::attribute_value_size); + sum.saturating_add(size.saturating_mul(uses)) + }) } diff --git a/devtools/run-wasm-step b/devtools/run-wasm-step index 6bbb26f2d..4aa458278 100755 --- a/devtools/run-wasm-step +++ b/devtools/run-wasm-step @@ -287,8 +287,10 @@ case "$step" in core) # extenddb-core's wasm32 unit tests, under Node: the cases of # src/crypto.rs, which on wasm32 run its RustCrypto backend (natively - # they run AWS-LC), and the test of limits::page_size in - # src/limits/mod.rs, which on wasm32 runs with a 32-bit usize. + # they run AWS-LC), and the tests of limits::page_size in + # src/limits/mod.rs and of the combined size of a search condition in + # src/expression/search_filter/tests_operands.rs, which on wasm32 run + # with a 32-bit usize. # # TESTS names every wasm test of the suite as the runner reports it, # and the step fails unless the run reports each of them ok and no @@ -305,6 +307,7 @@ case "$step" in crypto::tests::open_rejects_wrong_aad_wrong_key_and_tampering crypto::tests::seal_open_round_trip_with_fresh_nonce crypto::tests::sha256_known_vector + expression::search_filter::tests_operands::the_combined_size_saturates_instead_of_wrapping limits::tests::page_size_is_at_least_one_and_never_below_the_limit_it_can_hold ) run_suite core From 1316c01f6af596b9a17eb882c2bf6fcab08953a5 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 20:27:05 +0000 Subject: [PATCH 099/101] docs(core): drop a stray line from the between_bounds_fault comment The rustdoc of between_bounds_fault opened with the first line of the format_attribute_value comment, which has its own comment further down. This removes the line. --- crates/core/src/expression/evaluator.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/core/src/expression/evaluator.rs b/crates/core/src/expression/evaluator.rs index ef41ae1b3..f2df2ccc5 100755 --- a/crates/core/src/expression/evaluator.rs +++ b/crates/core/src/expression/evaluator.rs @@ -404,7 +404,6 @@ fn evaluate_size<'a>( Ok(Some(Cow::Owned(AttributeValue::N(sz.to_string())))) } -/// Format an `AttributeValue` for error messages (e.g. `N:5`, `S:hello`). /// The fault of two BETWEEN bounds that are both values, without the /// expression prefix: bounds of different types, then a lower bound above the /// upper bound. Numbers compare exactly, whatever the precision of the From 148d209d7ef1146886255b4a8947fb268ae184fd Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Wed, 25 Nov 2026 23:51:38 +0000 Subject: [PATCH 100/101] test(engine): run the per-use size row only with the extended grammar The equality-only grammar, which a build without the search-inequality-filters feature serves, refuses a repeated attribute before it sizes the condition, so the 17-condition row answered "must only contain one condition per attribute" in the compiled-out CI job. The row now runs only with the feature, as the other extended-grammar tests do. --- crates/engine/src/search_vectors_order_tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/search_vectors_order_tests.rs b/crates/engine/src/search_vectors_order_tests.rs index 43a569c37..d4343475a 100644 --- a/crates/engine/src/search_vectors_order_tests.rs +++ b/crates/engine/src/search_vectors_order_tests.rs @@ -169,7 +169,10 @@ async fn an_empty_map_answers_before_a_dimension_mismatch() { /// us-east-1 on 2026-11-25 on a table name that does not exist, each request /// twice with the same answer: one 65,533-byte name `#x0` in 17 conditions /// `#x0 = :s AND ...` (1,114,277 bytes) answers the size refusal, and in 15 -/// conditions (983,185 bytes) ResourceNotFoundException. +/// conditions (983,185 bytes) ResourceNotFoundException. The equality-only +/// grammar refuses a repeated attribute first, so the test runs only with the +/// extended grammar. +#[cfg(feature = "search-inequality-filters")] #[tokio::test] async fn the_size_counts_a_name_at_each_use_before_a_missing_table() { let dir = TempDir::new().unwrap(); From 8620a604dea684495af25c2d09a612e9573df718 Mon Sep 17 00:00:00 2001 From: Deepthi Mohan Date: Thu, 26 Nov 2026 16:26:35 +0000 Subject: [PATCH 101/101] fix(storage-postgres): pass the filtered search SQL to sqlx 0.9 in AssertSqlSafe sqlx 0.9 takes a SQL string that is not a &'static str only through sqlx::AssertSqlSafe. Main moved to sqlx 0.9.1, and the filtered SearchVectors path built its page, item and embedding statements at run time and passed them as &str, so storage-postgres did not compile. The page statement also passed a borrowed &'q str into the query, which sqlx 0.9 rejects as borrowed data escaping the method. Each of these calls now wraps its SQL, with no change to the SQL text or the bound values. In vector_search_filtered.rs the embedding statement is used once, so the query takes the owned String. The page statements are reused on every page and the item statement on every batch, so the query copies them. The two pg_sleep statements in the vector_search_scan tests copy their String. The test fixtures create and drop their databases and delete rows of a vector table through the owned format! result. The SQL names are a UUID the test generates, the database names the fixture creates, and the vector table name the server reports. Verified: clippy 1.97.0 --workspace --all-targets -D warnings is clean. --- crates/storage-postgres/src/vector_search_filtered.rs | 6 +++--- crates/storage-postgres/src/vector_search_scan.rs | 10 +++++++--- .../tests/common/vector_filter_fixture.rs | 10 ++++++---- .../tests/vector_search_filter_pages.rs | 4 ++-- 4 files changed, 18 insertions(+), 12 deletions(-) diff --git a/crates/storage-postgres/src/vector_search_filtered.rs b/crates/storage-postgres/src/vector_search_filtered.rs index b251ee98f..3cb37c86f 100644 --- a/crates/storage-postgres/src/vector_search_filtered.rs +++ b/crates/storage-postgres/src/vector_search_filtered.rs @@ -119,7 +119,7 @@ impl ScanStatement { limit: i64, after: Option<(f64, String)>, ) -> QueryAs<'q, Postgres, (f64, String), PgArguments> { - let mut query = sqlx::query_as::<_, (f64, String)>(sql) + let mut query = sqlx::query_as::<_, (f64, String)>(sqlx::AssertSqlSafe(sql)) .bind(self.vector.clone()) .bind(self.partition.clone()) .bind(limit) @@ -156,7 +156,7 @@ async fn offer_page( ); for batch in page.chunks(ITEM_BATCH) { let rids: Vec<&str> = batch.iter().map(|(_, rid)| rid.as_str()).collect(); - let mut items = sqlx::query_as::<_, (i64, Json)>(&sql) + let mut items = sqlx::query_as::<_, (i64, Json)>(sqlx::AssertSqlSafe(sql.as_str())) .bind(rids) .fetch(scan.connection()); let mut position = 0usize; @@ -263,7 +263,7 @@ async fn read_embeddings( "SELECT ctid::text, embedding FROM {} WHERE ctid = ANY($1::text[]::tid[])", statement.vec_table ); - let rows: Vec<(String, Vector)> = sqlx::query_as(&sql) + let rows: Vec<(String, Vector)> = sqlx::query_as(sqlx::AssertSqlSafe(sql)) .bind(rids) .fetch_all(scan.connection()) .await diff --git a/crates/storage-postgres/src/vector_search_scan.rs b/crates/storage-postgres/src/vector_search_scan.rs index ebae2f66a..cc9bb20a7 100644 --- a/crates/storage-postgres/src/vector_search_scan.rs +++ b/crates/storage-postgres/src/vector_search_scan.rs @@ -196,7 +196,7 @@ mod tests { let scan_query = query.clone(); let search = async { let mut scan = ScanConnection::begin(&pool).await.expect("begin"); - sqlx::query(&scan_query) + sqlx::query(sqlx::AssertSqlSafe(scan_query.as_str())) .execute(scan.connection()) .await .expect("the statement"); @@ -294,8 +294,12 @@ mod tests { uuid::Uuid::new_v4().simple() ); let statement = query.clone(); - let sleeper = - tokio::spawn(async move { sqlx::query(&statement).execute(&mut *conn).await.is_ok() }); + let sleeper = tokio::spawn(async move { + sqlx::query(sqlx::AssertSqlSafe(statement.as_str())) + .execute(&mut *conn) + .await + .is_ok() + }); let start = std::time::Instant::now(); while !still_running(&observer, &query, Duration::ZERO).await { assert!( diff --git a/crates/storage-postgres/tests/common/vector_filter_fixture.rs b/crates/storage-postgres/tests/common/vector_filter_fixture.rs index 3f6228347..baaa64c5b 100644 --- a/crates/storage-postgres/tests/common/vector_filter_fixture.rs +++ b/crates/storage-postgres/tests/common/vector_filter_fixture.rs @@ -94,7 +94,7 @@ where .expect("connect to the server"); let outcome = AssertUnwindSafe(async { for db in [&catalog, &data] { - sqlx::query(&format!("CREATE DATABASE \"{db}\"")) + sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE \"{db}\""))) .execute(&admin) .await .expect("create the database"); @@ -108,9 +108,11 @@ where for db in [&catalog, &data] { // FORCE ends the engine's pooled connections, which a panic leaves // open. - let dropped = sqlx::query(&format!("DROP DATABASE IF EXISTS \"{db}\" WITH (FORCE)")) - .execute(&admin) - .await; + let dropped = sqlx::query(sqlx::AssertSqlSafe(format!( + "DROP DATABASE IF EXISTS \"{db}\" WITH (FORCE)" + ))) + .execute(&admin) + .await; if let Err(e) = dropped { eprintln!("could not drop {db}: {e}"); } diff --git a/crates/storage-postgres/tests/vector_search_filter_pages.rs b/crates/storage-postgres/tests/vector_search_filter_pages.rs index 83a292506..4b7e8a773 100644 --- a/crates/storage-postgres/tests/vector_search_filter_pages.rs +++ b/crates/storage-postgres/tests/vector_search_filter_pages.rs @@ -183,10 +183,10 @@ async fn delete_rows(url: &str, ids: &[&str]) { .await .expect("find the vector table"); assert_eq!(tables.len(), 1, "{tables:?}"); - let deleted = sqlx::query(&format!( + let deleted = sqlx::query(sqlx::AssertSqlSafe(format!( "DELETE FROM \"{}\" WHERE item_data -> 'id' ->> 'S' = ANY($1)", tables[0] - )) + ))) .bind(ids) .execute(&pool) .await